updated plasmic package to work with new hooks + added example

This commit is contained in:
dswbx
2024-12-18 08:41:11 +01:00
parent 1631bbb754
commit c4138ef823
34 changed files with 491 additions and 334 deletions

View File

@@ -0,0 +1,255 @@
import type { CodeComponentMeta } from "@plasmicapp/host";
import registerComponent, { type ComponentMeta } from "@plasmicapp/host/registerComponent";
// biome-ignore lint/style/useImportType: <explanation>
import React from "react";
//import { PlasmicCanvasContext } from "@plasmicapp/loader-react";
import { useContext, useEffect, useRef, useState } from "react";
type PlasmicImageProps = {
asset: {
aspectRatio?: any;
dataUri: string;
name: string;
type: string;
uid: number;
uuid: string;
width: number;
height: number;
};
uid: number;
};
type ImageProps = {
className?: string;
src?: string | PlasmicImageProps;
alt?: string;
width?: number | string;
height?: number | string;
ratio?: number;
backgroundColor?: string;
forceLoad?: boolean;
transformations?: string;
transitionSpeed?: number;
loadTreshold?: number;
};
function numeric(value: number | string): number {
return typeof value === "number" ? value : Number.parseFloat(value);
}
function getDimensionDefaults(
width: number | string | undefined,
height: number | string | undefined,
ratio: number | undefined
) {
let _width = width;
let _height = height;
let _ratio = ratio;
if (_width && ratio) {
_height = (1 / ratio) * numeric(_width);
} else if (_height && ratio) {
_width = ratio * numeric(_height);
}
if (_width && _height && !_ratio) {
_ratio = numeric(_width) / numeric(_height);
}
return { width: _width, height: _height, ratio: _ratio };
}
function getPlaceholderStyle(
width: number | string | undefined,
height: number | string | undefined,
ratio: number | undefined
) {
let paddingBottom = 0;
if (width && height) {
paddingBottom = (1 / (numeric(width) / numeric(height))) * 100;
//paddingBottom = `${numeric(width)}px / ${numeric(height)}px * 100%}`;
//
} else if (ratio) {
paddingBottom = (1 / ratio) * 100;
}
return {
paddingBottom: paddingBottom + "%"
};
}
export const Image: React.FC<ImageProps> = ({
className,
src,
alt = "",
width,
height,
ratio,
backgroundColor = "rgba(225, 225, 225, 0.2)",
forceLoad = false,
transformations = "",
transitionSpeed = 200,
loadTreshold = 0.1,
...rest
}) => {
const inEditor = false; // !!useContext(PlasmicCanvasContext);
const [loaded, setLoaded] = useState(false);
const [isInView, setIsInView] = useState(inEditor ?? forceLoad);
const [transitioned, setTransitioned] = useState(forceLoad);
const imgRef = useRef<any>(null);
if (src) {
if (typeof src === "object") {
src = src.asset.dataUri;
}
if (/cloudinary/.test(src)) {
if (transformations) {
src = src.replace("/upload", "/upload/" + transformations);
}
}
}
//console.log("after:src", src);
useEffect(() => {
if (forceLoad) {
setIsInView(true);
return;
}
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setIsInView(true);
observer.disconnect();
}
});
},
{ threshold: loadTreshold }
);
if (imgRef.current) {
observer.observe(imgRef.current);
}
return () => {
observer.disconnect();
};
}, [forceLoad]);
const onLoad = () => {
setTimeout(() => {
setLoaded(true);
}, 0);
setTimeout(() => {
setTransitioned(true);
}, transitionSpeed);
};
const {
width: _width,
height: _height,
ratio: _ratio
} = getDimensionDefaults(width, height, ratio);
const imgStyle: any = {
objectFit: "cover",
transition: `opacity ${transitionSpeed}ms linear`,
position: "relative",
maxWidth: "100%",
maxHeight: "100%",
width: _width || "100%",
height: "auto",
//height: _height || "auto",
//height: !transitioned ? _height || "auto" : "auto",
opacity: forceLoad || loaded ? 1 : 0
};
const placeholderStyle: any = {
position: "absolute",
maxWidth: "100%",
maxHeight: "100%",
backgroundColor,
width: _width || "100%",
height: 0,
//height: transitioned ? "auto" : 0,
...getPlaceholderStyle(_width, _height, _ratio)
};
const wrapperStyle: any = {
position: "relative",
width: _width,
...getPlaceholderStyle(_width, _height, _ratio),
height: 0,
margin: 0,
lineHeight: 0,
//height: _height,
maxWidth: "100%",
maxHeight: "100%"
};
if (loaded) {
wrapperStyle.height = "auto";
wrapperStyle.paddingBottom = 0;
}
if (!src) return <div className={className} style={wrapperStyle} ref={imgRef} />;
return (
<div className={className} style={wrapperStyle} ref={imgRef}>
<div style={placeholderStyle} />
{isInView && (
<img
src={src}
alt={alt}
onLoad={onLoad}
style={imgStyle}
width={_width}
height={_height}
{...rest}
/>
)}
</div>
);
};
export function registerImage(
loader?: { registerComponent: typeof registerComponent },
customMeta?: ComponentMeta<ImageProps>
) {
if (loader) {
loader.registerComponent(Image, customMeta ?? ImageMeta);
} else {
registerComponent(Image, customMeta ?? ImageMeta);
}
}
export const ImageMeta: CodeComponentMeta<ImageProps> = {
name: "ImageLazy",
importPath: "@bknd/plasmic",
props: {
src: {
type: "imageUrl",
displayName: "Image"
},
alt: "string",
width: "number",
height: "number",
ratio: "number",
forceLoad: "boolean",
transformations: "string",
//backgroundColor: "color",
transitionSpeed: {
type: "number",
helpText: "How fast image should fade in. Default is 200 (ms)."
},
loadTreshold: {
type: "number",
displayName: "Treshold",
//defaultValue: 0.1,
helpText:
"Number between 0 and 1. Default is 0.1. Determines how much of the image must be in viewport before it gets loaded"
}
}
};

View File

@@ -0,0 +1,125 @@
import type { CodeComponentMeta } from "@plasmicapp/host";
import registerComponent, { type ComponentMeta } from "@plasmicapp/host/registerComponent";
// biome-ignore lint/style/useImportType: <explanation>
import React from "react";
import { useEffect, useRef, useState } from "react";
interface LazyRenderProps {
className?: string;
forceLoad?: boolean;
forceFallback?: boolean;
threshold?: number;
fallback?: React.ReactNode;
delay?: number;
children?: React.ReactNode;
onBecomesVisible?: () => void;
}
const DefaultFallback = () => <div style={{ height: 50 }}>asdf</div>;
export const LazyRender: React.FC<LazyRenderProps> = ({
className = "",
children,
forceLoad = false,
forceFallback = false,
threshold = 0.1,
delay = 0,
fallback = <DefaultFallback />,
onBecomesVisible
}) => {
const [isVisible, setIsVisible] = useState(forceLoad);
const ref = useRef<HTMLDivElement>(null);
/* console.log("props", {
delay,
threshold,
fallback,
isVisible,
forceLoad,
forceFallback,
children,
}); */
useEffect(() => {
if (forceLoad || forceFallback) {
setIsVisible(true);
return;
}
const observerOptions: IntersectionObserverInit = {
threshold: threshold < 1 ? threshold : 0.1
};
const observerCallback: IntersectionObserverCallback = (entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting && !isVisible) {
setTimeout(() => {
setIsVisible(true);
onBecomesVisible?.();
if (ref.current) observer.unobserve(ref.current);
}, delay);
}
});
};
const observer = new IntersectionObserver(observerCallback, observerOptions);
if (ref.current) observer.observe(ref.current);
return () => {
if (ref.current) observer.unobserve(ref.current);
};
}, [forceLoad, threshold, forceFallback, delay]);
return (
<div className={className} ref={ref}>
{isVisible && !forceFallback ? children : fallback}
</div>
);
};
export function registerLazyRender(
loader?: { registerComponent: typeof registerComponent },
customMeta?: ComponentMeta<LazyRenderProps>
) {
if (loader) {
loader.registerComponent(LazyRender, customMeta ?? LazyRenderMeta);
} else {
registerComponent(LazyRender, customMeta ?? LazyRenderMeta);
}
}
export const LazyRenderMeta: CodeComponentMeta<LazyRenderProps> = {
name: "LazyRender",
importPath: "@bknd/plasmic",
props: {
forceLoad: {
type: "boolean",
defaultValue: false
},
forceFallback: {
type: "boolean",
defaultValue: false
},
threshold: {
type: "number",
defaultValue: 0.1
},
fallback: {
type: "slot"
//allowedComponents: ["*"],
},
delay: {
type: "number",
defaultValue: 0
},
onBecomesVisible: {
type: "code",
lang: "javascript"
},
children: {
type: "slot"
//allowedComponents: ["*"],
}
}
};

View File

@@ -0,0 +1,343 @@
import { DataProvider, usePlasmicCanvasContext } from "@plasmicapp/host";
import registerComponent, { type ComponentMeta } from "@plasmicapp/host/registerComponent";
import { usePlasmicQueryData } from "@plasmicapp/query";
import { useApi, useEntityQuery } from "bknd/client";
import type { RepoQuery } from "bknd/data";
// biome-ignore lint/style/useImportType: <explanation>
import React from "react";
import { usePlasmicBkndContext } from "../../contexts/BkndContext";
type BkndDataProps = {
children?: React.ReactNode;
loading?: React.ReactNode;
error?: React.ReactNode;
empty?: React.ReactNode;
setControlContextData?: (ctxData: {
entities: string[];
fields: string[];
references: string[];
}) => void;
className?: string;
limit?: number;
offset?: number;
withRefs?: string[];
joinRefs?: string[];
dataName?: string;
entityId?: number;
entity?: string;
select?: string[];
sortBy: string;
sortDir: "asc" | "desc";
where?: string;
mode?: "fetch" | "swr";
noLayout?: boolean;
preview?: boolean;
previewSlot?: "loading" | "error" | "empty";
};
const LoadingComponent = ({ loading }: { loading?: React.ReactNode }) => {
return loading ? <>{loading}</> : <>Loading...</>;
};
const ErrorComponent = ({ error }: { error?: React.ReactNode }) => {
return error ? <>{error}</> : <>Error</>;
};
const EmptyComponent = ({ empty }: { empty?: React.ReactNode }) => {
return empty ? <>{empty}</> : <>No data</>;
};
export function BkndData({
children,
loading,
error,
empty,
entity,
setControlContextData,
dataName,
limit,
offset,
entityId,
where,
withRefs,
joinRefs,
sortBy = "id",
sortDir = "asc",
mode = "fetch",
select = [],
noLayout,
preview,
previewSlot,
...props
}: BkndDataProps) {
//console.log("--bknd data");
const inEditor = !!usePlasmicCanvasContext();
const plasmicContext = usePlasmicBkndContext();
if (inEditor && preview) {
let Component: React.ReactNode;
switch (previewSlot) {
case "loading":
Component = <LoadingComponent loading={loading} />;
break;
case "error":
Component = <ErrorComponent error={error} />;
break;
case "empty":
Component = <EmptyComponent empty={empty} />;
break;
}
if (Component) {
return noLayout ? Component : <div className={props.className}>{Component}</div>;
}
}
let _where: any = undefined;
if (where) {
if (typeof where === "string") {
try {
_where = JSON.parse(where);
} catch (e) {}
} else {
_where = where;
}
}
const query = {
select: select.length > 0 ? select : undefined,
limit: entityId ? undefined : limit,
offset: entityId ? undefined : offset,
where: _where,
sort: { by: sortBy, dir: sortDir },
with: withRefs,
join: joinRefs
};
//console.log("---context", plasmicContext);
if (plasmicContext.appConfig?.data?.entities) {
const { entities, relations } = plasmicContext.appConfig.data;
console.log("entities", entities);
//setControlContextData?.({ entities, fields: ["id"] });
let fields: string[] = ["id"];
let references: string[] = [];
if (entity && entity in entities) {
fields = Object.keys(entities[entity].fields!);
if (relations) {
const rels = Object.values(relations).filter(
// biome-ignore lint/suspicious/noDoubleEquals: <explanation>
(r: any) => r.source == entity
);
// @ts-ignore
references = rels?.map((r) => r.config?.mappedBy ?? r.target);
//console.log("relations", relations, references);
}
}
setControlContextData?.({ entities: Object.keys(entities), fields, references });
}
if (!entity) {
return <div>Select an entity</div>;
}
const modeProps: ModeProps = {
loading,
error,
empty,
dataName: dataName ?? entity ?? "data",
entityId,
entity,
query,
children
};
const Component = mode === "swr" ? <ModeSWR {...modeProps} /> : <ModeFetch {...modeProps} />;
return noLayout ? Component : <div className={props.className}>{Component}</div>;
}
type ModeProps = {
entity: string;
dataName: string;
children?: React.ReactNode;
loading?: React.ReactNode;
error?: React.ReactNode;
empty?: React.ReactNode;
entityId?: number;
query?: Partial<RepoQuery>;
};
const ModeFetch = ({
children,
loading,
error,
empty,
dataName,
entityId,
entity,
query
}: ModeProps) => {
const api = useApi();
const endpoint = entityId
? api.data.readOne(entity, entityId, query)
: api.data.readMany(entity, query);
const {
data,
error: hasError,
isLoading
} = usePlasmicQueryData(endpoint.key(), async () => {
const res = await endpoint.execute();
return res.data;
});
if (isLoading) {
return <LoadingComponent loading={loading} />;
}
if (hasError) {
return <ErrorComponent error={error} />;
}
if (data.length === 0) {
return <EmptyComponent empty={empty} />;
}
return (
<DataProvider name={dataName ?? entity ?? "data"} data={data}>
{children}
</DataProvider>
);
};
const ModeSWR = ({ children, loading, error, dataName, entityId, empty, entity }: ModeProps) => {
const $q = useEntityQuery(entity, entityId);
if ($q.isLoading) {
return <LoadingComponent loading={loading} />;
}
if ($q.error) {
return <ErrorComponent error={error} />;
}
if (!$q.data) {
return <EmptyComponent empty={empty} />;
}
return (
<DataProvider name={dataName ?? entity ?? "data"} data={$q.data}>
{children}
</DataProvider>
);
};
export function registerBkndData(
loader?: { registerComponent: typeof registerComponent },
customMeta?: ComponentMeta<BkndDataProps>
) {
if (loader) {
loader.registerComponent(BkndData, customMeta ?? BkndDataMeta);
} else {
registerComponent(BkndData, customMeta ?? BkndDataMeta);
}
}
export const BkndDataMeta: ComponentMeta<BkndDataProps> = {
name: "BKND Data",
section: "BKND",
importPath: "@bknd/plasmic",
providesData: true,
props: {
entity: {
type: "choice",
options: (props, ctx) => ctx?.entities ?? []
},
dataName: {
type: "string"
},
entityId: {
type: "number"
},
select: {
type: "choice",
options: (props, ctx) => ctx?.fields ?? []
},
limit: {
type: "number",
defaultValue: 10,
// @ts-ignore
hidden: (props) => !!props.entityId,
min: 0
},
offset: {
type: "number",
defaultValue: 0,
// @ts-ignore
hidden: (props) => !!props.entityId,
min: 0
},
withRefs: {
displayName: "With",
type: "choice",
multiSelect: true,
options: (props, ctx) => ctx?.references ?? []
},
joinRefs: {
displayName: "Join",
type: "choice",
multiSelect: true,
options: (props, ctx) => ctx?.references ?? []
},
where: {
type: "code",
lang: "json"
},
sortBy: {
type: "choice",
options: (props, ctx) => ctx?.fields ?? []
},
sortDir: {
type: "choice",
options: ["asc", "desc"],
defaultValue: "asc"
},
children: {
type: "slot"
},
loading: {
type: "slot"
},
error: {
type: "slot"
},
empty: {
type: "slot"
},
mode: {
type: "choice",
options: ["fetch", "swr"],
defaultValue: "fetch",
advanced: true
},
noLayout: {
type: "boolean",
defaultValue: true,
advanced: true
},
preview: {
type: "boolean",
defaultValue: false,
advanced: true
},
previewSlot: {
type: "choice",
options: ["loading", "error", "empty"],
hidden: (props: any) => props.preview !== true,
advanced: true
}
}
};

View File

@@ -0,0 +1,3 @@
export { BkndData, BkndDataMeta } from "./data/BkndData";
export { Image, ImageMeta } from "./Image";
export { LazyRender, LazyRenderMeta } from "./LazyRender";

View File

@@ -0,0 +1,147 @@
import { DataProvider, GlobalActionsProvider, usePlasmicCanvasContext } from "@plasmicapp/host";
import registerGlobalContext, {
type GlobalContextMeta
} from "@plasmicapp/host/registerGlobalContext";
import type { AppConfig } from "bknd";
// @ts-ignore
import { ClientProvider, useApi, useAuth, useBaseUrl } from "bknd/client";
// biome-ignore lint/style/useImportType: <explanation>
import React from "react";
import { createContext, useContext, useEffect, useMemo, useState } from "react";
// Users will be able to set these props in Studio.
interface BkndGlobalContextProps {
// You might use this to override the auth URL to a test or local URL.
baseUrl?: string;
appConfig?: AppConfig;
auth: any; // @todo: add typings
}
type BkndContextProps = {
baseUrl?: string;
initialAuth?: any;
};
const BkndContextContext = createContext<BkndGlobalContextProps>({} as any);
// @todo: it's an issue that we need auth, so we cannot make baseurl adjustable (maybe add an option to useAuth with a specific base url?)
export const BkndContext = ({
children,
baseUrl,
initialAuth
}: React.PropsWithChildren<BkndContextProps>) => {
const auth = useAuth();
const baseurl = baseUrl ?? useBaseUrl();
const api = useApi({ host: baseurl });
const [data, setData] = useState<BkndGlobalContextProps>({
baseUrl: baseurl,
auth: auth ?? initialAuth,
appConfig: undefined
});
const inEditor = !!usePlasmicCanvasContext();
useEffect(() => {
setData((prev) => ({ ...prev, auth: auth }));
}, [auth.user]);
useEffect(() => {
(async () => {
if (inEditor) {
const result = await api.system.readConfig();
/*const res = await fetch(`${baseurl}/api/system/config`);
const result = (await res.json()) as BkndGlobalContextProps["appConfig"];*/
console.log("appconfig", result);
setData((prev) => ({ ...prev, appConfig: result }));
}
})();
}, [inEditor]);
const actions = useMemo(
() => ({
login: async (data: any) => {
console.log("login", data);
const result = await auth.login(data);
console.log("login:result", result);
if (result.res.ok && "user" in result.data) {
//result.data.
return result.data;
} else {
console.log("login failed", result);
}
return false;
},
register: async (data: any) => {
console.log("register", data);
const result = await auth.register(data);
console.log("register:result", result);
if (result.res.ok && "user" in result.data) {
//result.data.
return result.data;
}
return false;
},
logout: async () => {
await auth.logout();
console.log("logged out");
return true;
},
setToken: auth.setToken
}),
[baseUrl]
);
console.log("plasmic.bknd.context", { baseUrl });
return (
<GlobalActionsProvider contextName="BkndContext" actions={actions}>
<BkndContextContext.Provider value={data}>
<DataProvider name="bknd" data={data}>
<ClientProvider baseUrl={data.baseUrl}>{children}</ClientProvider>
</DataProvider>
</BkndContextContext.Provider>
</GlobalActionsProvider>
);
};
export function usePlasmicBkndContext() {
const context = useContext(BkndContextContext);
return context;
}
export function registerBkndContext(
loader?: { registerGlobalContext: typeof registerGlobalContext },
customMeta?: GlobalContextMeta<BkndContextProps>
) {
if (loader) {
loader.registerGlobalContext(BkndContext, customMeta ?? BkndContextMeta);
} else {
registerGlobalContext(BkndContext, customMeta ?? BkndContextMeta);
}
}
export const BkndContextMeta: GlobalContextMeta<BkndContextProps> = {
name: "BkndContext",
importPath: "@bknd/plasmic",
props: { baseUrl: { type: "string" }, initialAuth: { type: "object" } },
providesData: true,
globalActions: {
login: {
parameters: [{ name: "data", type: "object" }]
},
register: {
parameters: [{ name: "data", type: "object" }]
},
logout: {
parameters: []
},
setToken: {
parameters: [{ name: "token", type: "string" }]
},
sayHi: {
parameters: [{ name: "message", type: "string" }]
}
}
};

View File

@@ -0,0 +1 @@
export { BkndContext, BkndContextMeta } from "./BkndContext";

View File

@@ -0,0 +1,17 @@
import type { registerComponent, registerGlobalContext } from "@plasmicapp/host";
import { registerImage } from "./components/Image";
import { registerLazyRender } from "./components/LazyRender";
import { registerBkndData } from "./components/data/BkndData";
import { registerBkndContext } from "./contexts/BkndContext";
export function registerAll(loader?: {
registerComponent: typeof registerComponent;
registerGlobalContext: typeof registerGlobalContext;
}) {
registerBkndData(loader);
registerBkndContext(loader);
registerImage(loader);
registerLazyRender(loader);
}
export { registerBkndData, registerBkndContext };