public commit

This commit is contained in:
dswbx
2024-11-16 12:01:47 +01:00
commit 90f80c4280
582 changed files with 49291 additions and 0 deletions

View File

@@ -0,0 +1,243 @@
"use client";
import type { CodeComponentMeta } from "@plasmicapp/host";
//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 const ImageMeta: CodeComponentMeta<React.ComponentType<ImageProps>> = {
name: "ImageLazy",
importPath: import.meta.dir,
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,111 @@
import type { CodeComponentMeta } from "@plasmicapp/host";
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 const LazyRenderMeta: CodeComponentMeta<React.ComponentType<LazyRenderProps>> = {
name: "LazyRender",
importPath: import.meta.dir,
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,23 @@
import type { CodeComponentMeta } from "@plasmicapp/host";
import { Link } from "wouter";
export function WouterLink({ href, className, children, ...props }) {
return (
<Link href={href ?? "#"} className={className} {...props}>
{children}
</Link>
);
}
export const WouterLinkMeta: CodeComponentMeta<any> = {
name: "WouterLink",
importPath: import.meta.dir,
props: {
href: {
type: "href",
},
children: {
type: "slot",
},
},
};

View File

@@ -0,0 +1,385 @@
import { type CodeComponentMeta, DataProvider, usePlasmicCanvasContext } from "@plasmicapp/host";
import type { RepoQuery } from "bknd/data";
import { useEntities, useEntity } from "bknd/ui";
import { encodeSearch } from "bknd/utils";
import { useContext, useEffect, useState } from "react";
import { usePlasmicBkndContext } from "../../contexts/BkndContext";
type BkndEntitiesProps = {
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;
sortBy: string;
sortDir: "asc" | "desc";
where?: string;
mode?: "fetch" | "react-query";
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",
noLayout,
preview,
previewSlot,
...props
}: BkndEntitiesProps) {
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 = {
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 === "react-query" ? <ModeReactQuery {...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 [data, setData] = useState<any[]>([]);
const [isLoading, setLoading] = useState(true);
const [hasError, setError] = useState<string>();
const plasmicContext = usePlasmicBkndContext();
const basepath = "/api/data";
const path = entityId ? `${basepath}/${entity}/${entityId}` : `${basepath}/${entity}`;
console.log("query", path, query);
const url = `${plasmicContext.baseUrl}${path}?${encodeSearch(query)}`;
useEffect(() => {
(async () => {
try {
const res = await fetch(url);
const result = (await res.json()) as any;
//console.log("result", result);
setData(result.data);
setLoading(false);
setError(undefined);
} catch (e) {
console.error(e);
setError(String(e));
setLoading(false);
}
})();
}, [url]);
console.log("--data", { name: dataName ?? entity ?? "data", data, isLoading, hasError });
if (isLoading) {
return <LoadingComponent loading={loading} />;
}
if (hasError) {
return <ErrorComponent error={error} />;
}
if (data.length === 0) {
return <EmptyComponent empty={empty} />;
}
console.log("--here1");
return (
<DataProvider name={dataName ?? entity ?? "data"} data={data}>
{children}
</DataProvider>
);
};
const ModeReactQuery = (props: ModeProps) => {
return props.entityId ? (
<ModeReactQuerySingle {...props} />
) : (
<ModeReactQueryMultiple {...props} />
);
};
const ModeReactQuerySingle = ({
children,
loading,
error,
dataName,
entityId,
empty,
entity
}: ModeProps) => {
const container = useEntity(entity, entityId);
const { isLoading, isError } = container.status.fetch;
if (isLoading) {
return <LoadingComponent loading={loading} />;
}
if (isError) {
return <ErrorComponent error={error} />;
}
if (!container.data) {
return <EmptyComponent empty={empty} />;
}
return (
<DataProvider name={dataName ?? entity ?? "data"} data={container.data}>
{children}
</DataProvider>
);
};
const ModeReactQueryMultiple = ({
children,
loading,
error,
empty,
dataName,
entity,
query
}: ModeProps) => {
const container = useEntities(entity, query);
const { isLoading, isError } = container.status.fetch;
if (isLoading) {
return <LoadingComponent loading={loading} />;
}
if (isError) {
return <ErrorComponent error={error} />;
}
if (!container.data || container.data.length === 0) {
return <EmptyComponent empty={empty} />;
}
return (
<DataProvider name={dataName ?? entity ?? "data"} data={container.data}>
{children}
</DataProvider>
);
};
export const BkndDataMeta: CodeComponentMeta<React.ComponentType<BkndEntitiesProps>> = {
name: "BKND Data",
section: "BKND",
importPath: import.meta.dir,
providesData: true,
props: {
entity: {
type: "choice",
options: (props, ctx) => ctx.entities
},
dataName: {
type: "string"
},
entityId: {
type: "number"
},
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", "react-query"],
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,4 @@
export { BkndData, BkndDataMeta } from "./data/BkndData";
export { WouterLink, WouterLinkMeta } from "./WouterLink";
export { Image, ImageMeta } from "./Image";
export { LazyRender, LazyRenderMeta } from "./LazyRender";