Compare commits

..

2 Commits

Author SHA1 Message Date
dswbx 66959fe789 extended data canvas and init indices management 2025-05-03 17:58:58 +02:00
dswbx 6694c63990 admin: data/auth route-driven settings and collapsible components (#168)
introduced `useRoutePathState` for managing active states via routes, added `CollapsibleList` for reusable collapsible UI, and updated various components to leverage route awareness for improved navigation state handling. Also adjusted routing for entities, strategies, and schema to support optional sub-paths.
2025-05-03 11:05:38 +02:00
24 changed files with 674 additions and 233 deletions
+1 -1
View File
@@ -218,7 +218,7 @@ export function objectCleanEmpty<Obj extends { [key: string]: any }>(obj: Obj):
* @param object
* @param sources
*/
export function mergeObject(object, ...sources) {
export function mergeObject<R = unknown>(object, ...sources): R {
for (const source of sources) {
for (const [key, value] of Object.entries(source)) {
if (value === undefined) {
+2 -3
View File
@@ -6,6 +6,7 @@ import {
type EntityManager,
constructEntity,
constructRelation,
constructIndex,
} from "data";
import { Module } from "modules/Module";
import { DataController } from "./api/DataController";
@@ -35,9 +36,7 @@ export class AppData extends Module<typeof dataConfigSchema> {
);
const indices = transformObject(_indices, (index, name) => {
const entity = _entity(index.entity)!;
const fields = index.fields.map((f) => entity.field(f)!);
return new EntityIndex(entity, fields, index.unique, name);
return constructIndex(index, _entity, name);
});
for (const entity of Object.values(entities)) {
+1
View File
@@ -68,6 +68,7 @@ export const indicesSchema = tb.Type.Object(
additionalProperties: false,
},
);
export type TAppDataIndex = Static<(typeof indicesSchema)[number]>;
export const dataConfigSchema = tb.Type.Object(
{
+1 -1
View File
@@ -17,7 +17,7 @@ export {
export { KyselyPluginRunner } from "./plugins/KyselyPluginRunner";
export { constructEntity, constructRelation } from "./schema/constructor";
export { constructEntity, constructRelation, constructIndex } from "./schema/constructor";
export const DatabaseEvents = {
...MutatorEvents,
+23 -2
View File
@@ -1,6 +1,13 @@
import { transformObject } from "core/utils";
import { Entity, type Field } from "data";
import { FIELDS, RELATIONS, type TAppDataEntity, type TAppDataRelation } from "data/data-schema";
import { Entity, EntityIndex, type Field } from "data";
import {
FIELDS,
RELATIONS,
type TAppDataEntity,
type TAppDataField,
type TAppDataIndex,
type TAppDataRelation,
} from "data/data-schema";
export function constructEntity(name: string, entityConfig: TAppDataEntity) {
const fields = transformObject(entityConfig.fields ?? {}, (fieldConfig, name) => {
@@ -32,3 +39,17 @@ export function constructRelation(
relationConfig.config,
);
}
export function constructIndex(
indexConfig: TAppDataIndex,
resolver: (name: Entity | string) => Entity,
name: string,
) {
const entity = resolver(indexConfig.entity);
return new EntityIndex(
entity,
entity.fields.filter((f) => indexConfig.fields.includes(f.name)),
indexConfig.unique,
name,
);
}
@@ -70,6 +70,7 @@ export function useBkndData() {
};
const $data = {
entity: (name: string) => entities[name],
indicesOf: (name: string) => app.indices.filter((i) => i.entity.name === name),
modals,
system: (name: string) => ({
any: entities[name]?.type === "system",
@@ -82,6 +83,7 @@ export function useBkndData() {
$data,
entities,
relations: app.relations,
indices: app.indices,
config: config.data,
schema: schema.data,
actions,
+17 -1
View File
@@ -1,5 +1,12 @@
import type { App } from "App";
import { type Entity, type EntityRelation, constructEntity, constructRelation } from "data";
import {
type Entity,
type EntityIndex,
type EntityRelation,
constructEntity,
constructRelation,
constructIndex,
} from "data";
import { RelationAccessor } from "data/relations/RelationAccessor";
import { Flow, TaskMap } from "flows";
import type { BkndAdminOptions } from "ui/client/BkndProvider";
@@ -14,6 +21,7 @@ export class AppReduced {
// @todo: change to record
private _entities: Entity[] = [];
private _relations: EntityRelation[] = [];
private _indices: EntityIndex[] = [];
private _flows: Flow[] = [];
constructor(
@@ -30,6 +38,10 @@ export class AppReduced {
return constructRelation(relation, this.entity.bind(this));
});
this._indices = Object.entries(this.appJson.data.indices ?? {}).map(([name, index]) => {
return constructIndex(index, this.entity.bind(this), name);
});
for (const [name, obj] of Object.entries(this.appJson.flows.flows ?? {})) {
// @ts-ignore
// @todo: fix constructing flow
@@ -58,6 +70,10 @@ export class AppReduced {
return new RelationAccessor(this._relations);
}
get indices(): EntityIndex[] {
return this._indices;
}
get flows(): Flow[] {
return this._flows;
}
+23 -5
View File
@@ -13,13 +13,15 @@ import {
import { type ReactNode, useCallback, useEffect, useState } from "react";
import { useTheme } from "ui/client/use-theme";
type CanvasProps = ReactFlowProps & {
export type CanvasProps = Omit<ReactFlowProps, "onNodesChange" | "onEdgesChange"> & {
externalProvider?: boolean;
backgroundStyle?: "lines" | "dots";
minimap?: boolean | MiniMapProps;
children?: Element | ReactNode;
onDropNewNode?: (base: any) => any;
onDropNewEdge?: (base: any) => any;
onNodesChange?: (changes: any) => void;
onEdgesChange?: (changes: any) => void;
};
export function Canvas({
@@ -33,8 +35,8 @@ export function Canvas({
onDropNewEdge,
...props
}: CanvasProps) {
const [nodes, setNodes, onNodesChange] = useNodesState(_nodes ?? []);
const [edges, setEdges, onEdgesChange] = useEdgesState(_edges ?? []);
const [nodes, setNodes, _onNodesChange] = useNodesState(_nodes ?? []);
const [edges, setEdges, _onEdgesChange] = useEdgesState(_edges ?? []);
const { screenToFlowPosition } = useReactFlow();
const { theme } = useTheme();
@@ -42,6 +44,22 @@ export function Canvas({
const [isSpacePressed, setIsSpacePressed] = useState(false);
const [isPointerPressed, setIsPointerPressed] = useState(false);
const onNodesChange = useCallback(
(changes) => {
_onNodesChange(changes);
props.onNodesChange?.(changes);
},
[_onNodesChange, props.onNodesChange],
);
const onEdgesChange = useCallback(
(changes) => {
_onEdgesChange(changes);
props.onEdgesChange?.(changes);
},
[_onEdgesChange, props.onEdgesChange],
);
const handleKeyDown = (event: KeyboardEvent) => {
if (event.metaKey) {
setIsCommandPressed(true);
@@ -173,8 +191,6 @@ export function Canvas({
snapToGrid
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
nodesConnectable={false}
/*panOnDrag={isSpacePressed}*/
panOnDrag={true}
@@ -183,6 +199,8 @@ export function Canvas({
zoomOnDoubleClick={false}
selectionOnDrag={!isSpacePressed}
{...props}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
>
{backgroundStyle === "lines" && (
<Background
@@ -13,7 +13,7 @@ export function DefaultNode({ selected, children, className, ...props }: TDefaul
{...props}
className={twMerge(
"relative w-80 shadow-lg rounded-lg bg-background",
selected && "outline outline-blue-500/25",
selected && "ring-4 ring-blue-400/50",
className,
)}
>
@@ -246,7 +246,6 @@ export const Switch = forwardRef<
props.disabled && "opacity-50 !cursor-not-allowed",
)}
onCheckedChange={(bool) => {
console.log("setting", bool);
props.onChange?.({ target: { value: bool } });
}}
{...(props as any)}
@@ -272,7 +271,7 @@ export const Switch = forwardRef<
export const Select = forwardRef<
HTMLSelectElement,
React.ComponentProps<"select"> & {
options?: { value: string; label: string }[] | (string | number)[];
options?: { value: string; label: string; disabled?: boolean }[] | (string | number)[];
}
>(({ children, options, ...props }, ref) => (
<div className="flex w-full relative">
@@ -297,7 +296,7 @@ export const Select = forwardRef<
return o;
})
.map((opt) => (
<option key={opt.value} value={opt.value}>
<option key={opt.value} value={opt.value} disabled={opt.disabled}>
{opt.label}
</option>
))}
@@ -78,6 +78,7 @@ const ArrayItem = memo(({ path, index, schema }: any) => {
return (
<div key={itemPath} className="flex flex-row gap-2">
<FieldComponent
required={schema.minItems > 0}
name={itemPath}
schema={subschema!}
value={value}
@@ -0,0 +1,62 @@
import type { ReactNode } from "react";
import { twMerge } from "tailwind-merge";
export interface CollapsibleListRootProps extends React.HTMLAttributes<HTMLDivElement> {}
const Root = ({ className, ...props }: CollapsibleListRootProps) => (
<div className={twMerge("flex flex-col gap-2 max-w-4xl", className)} {...props} />
);
export interface CollapsibleListItemProps extends React.HTMLAttributes<HTMLDivElement> {
hasError?: boolean;
disabled?: boolean;
}
const Item = ({ className, hasError, disabled, ...props }: CollapsibleListItemProps) => (
<div
className={twMerge(
"flex flex-col border border-muted rounded bg-background",
hasError && "border-error",
className,
)}
{...props}
/>
);
export interface CollapsibleListPreviewProps extends React.HTMLAttributes<HTMLDivElement> {
left?: ReactNode;
right?: ReactNode;
}
const Preview = ({ className, left, right, children, ...props }: CollapsibleListPreviewProps) => (
<div
{...props}
className={twMerge("flex flex-row justify-between p-3 gap-3 items-center", className)}
>
{left && <div className="flex flex-row items-center p-2 bg-primary/5 rounded">{left}</div>}
<div className="font-mono flex-grow flex flex-row gap-3">{children}</div>
{right && <div className="flex flex-row gap-4 items-center">{right}</div>}
</div>
);
export interface CollapsibleListDetailProps extends React.HTMLAttributes<HTMLDivElement> {
open?: boolean;
}
const Detail = ({ className, open, ...props }: CollapsibleListDetailProps) =>
open && (
<div
{...props}
className={twMerge(
"flex flex-col border-t border-t-muted px-4 pt-3 pb-4 bg-lightest/50 gap-4",
className,
)}
/>
);
export const CollapsibleList = {
Root,
Item,
Preview,
Detail,
};
+93
View File
@@ -0,0 +1,93 @@
import { use, createContext, useEffect } from "react";
import { useState } from "react";
import { useLocation, useParams } from "wouter";
// extract path segment from path, e.g. /auth/strategies/:strategy? -> "strategy"
function extractPathSegment(path: string): string {
const match = path.match(/:(\w+)\??/);
return match?.[1] ?? "";
}
// get url by replacing path segment with identifier
// e.g. /auth/strategies/:strategy? -> /auth/strategies/x
function getPath(path: string, identifier?: string) {
if (!identifier) {
return path.replace(/\/:\w+\??/, "");
}
return path.replace(/:\w+\??/, identifier);
}
export function useRoutePathState(_path?: string, identifier?: string) {
const ctx = useRoutePathContext(_path ?? "");
const path = _path ?? ctx?.path ?? "";
const segment = extractPathSegment(path);
const routeIdentifier = useParams()[segment];
const [localActive, setLocalActive] = useState(routeIdentifier === identifier);
const active = ctx ? identifier === ctx.activeIdentifier : localActive;
const [, navigate] = useLocation();
function toggle(_open?: boolean) {
const open = _open ?? !active;
if (ctx) {
ctx.setActiveIdentifier(open ? identifier! : "");
}
if (path) {
if (open) {
navigate(getPath(path, identifier));
} else {
navigate(getPath(path));
}
} else {
setLocalActive(open);
}
}
useEffect(() => {
if (!ctx && _path && identifier) {
setLocalActive(routeIdentifier === identifier);
}
}, [routeIdentifier, identifier, _path]);
return {
active,
toggle,
};
}
type RoutePathStateContextType = {
defaultIdentifier?: string;
path: string;
activeIdentifier: string;
setActiveIdentifier: (identifier: string) => void;
};
const RoutePathStateContext = createContext<RoutePathStateContextType>(undefined!);
export function RoutePathStateProvider({
children,
defaultIdentifier,
path,
}: Pick<RoutePathStateContextType, "path" | "defaultIdentifier"> & { children: React.ReactNode }) {
const segment = extractPathSegment(path);
const routeIdentifier = useParams()[segment];
const [activeIdentifier, setActiveIdentifier] = useState(
routeIdentifier ?? defaultIdentifier ?? "",
);
return (
<RoutePathStateContext.Provider
value={{ defaultIdentifier, path, activeIdentifier, setActiveIdentifier }}
>
{children}
</RoutePathStateContext.Provider>
);
}
function useRoutePathContext(path?: string) {
const ctx = use(RoutePathStateContext);
if (ctx && (!path || ctx.path === path)) {
return ctx;
}
return undefined;
}
+24 -8
View File
@@ -13,6 +13,7 @@ import {
import type { IconType } from "react-icons";
import { twMerge } from "tailwind-merge";
import { IconButton } from "ui/components/buttons/IconButton";
import { useRoutePathState } from "ui/hooks/use-route-path-state";
import { AppShellProvider, useAppShell } from "ui/layouts/AppShell/use-appshell";
import { appShellStore } from "ui/store";
import { useLocation } from "wouter";
@@ -376,6 +377,15 @@ export function Scrollable({
);
}
type SectionHeaderAccordionItemProps = {
title: string;
open: boolean;
toggle: () => void;
ActiveIcon?: any;
children?: React.ReactNode;
renderHeaderRight?: (props: { open: boolean }) => React.ReactNode;
};
export const SectionHeaderAccordionItem = ({
title,
open,
@@ -383,14 +393,7 @@ export const SectionHeaderAccordionItem = ({
ActiveIcon = IconChevronUp,
children,
renderHeaderRight,
}: {
title: string;
open: boolean;
toggle: () => void;
ActiveIcon?: any;
children?: React.ReactNode;
renderHeaderRight?: (props: { open: boolean }) => React.ReactNode;
}) => (
}: SectionHeaderAccordionItemProps) => (
<div
style={{ minHeight: 49 }}
className={twMerge(
@@ -422,6 +425,19 @@ export const SectionHeaderAccordionItem = ({
</div>
);
export const RouteAwareSectionHeaderAccordionItem = ({
routePattern,
identifier,
...props
}: Omit<SectionHeaderAccordionItemProps, "open" | "toggle"> & {
// it's optional because it could be provided using the context
routePattern?: string;
identifier: string;
}) => {
const { active, toggle } = useRoutePathState(routePattern, identifier);
return <SectionHeaderAccordionItem {...props} open={active} toggle={toggle} />;
};
export const Separator = ({ className, ...props }: ComponentPropsWithoutRef<"hr">) => (
<hr {...props} className={twMerge("border-muted my-3", className)} />
);
+1 -1
View File
@@ -10,7 +10,7 @@ import { useClipboard } from "@mantine/hooks";
import { ButtonLink } from "ui/components/buttons/Button";
import { routes } from "ui/lib/routes";
import { useBkndMedia } from "ui/client/schema/media/use-bknd-media";
import { JsonViewer } from "ui";
import { JsonViewer } from "ui/components/code/JsonViewer";
export type MediaInfoModalProps = {
file: FileState;
@@ -1,17 +1,43 @@
import { MarkerType, type Node, Position, ReactFlowProvider } from "@xyflow/react";
import type { AppDataConfig, TAppDataEntity } from "data/data-schema";
import { MarkerType, type Node, Position, ReactFlowProvider, useReactFlow } from "@xyflow/react";
import type { AppDataConfig, TAppDataEntity, TAppDataField } from "data/data-schema";
import { useBknd } from "ui/client/BkndProvider";
import { Canvas } from "ui/components/canvas/Canvas";
import { Canvas, type CanvasProps } from "ui/components/canvas/Canvas";
import { layoutWithDagre } from "ui/components/canvas/layouts";
import { Panels } from "ui/components/canvas/panels";
import { EntityTableNode } from "./EntityTableNode";
import { useTheme } from "ui/client/use-theme";
import { useCallback } from "react";
import { mergeObject, transformObject } from "core/utils";
export interface TCanvasEntityField extends TAppDataField {
name: string;
indexed?: boolean;
}
export interface TCanvasEntity extends TAppDataEntity {
label: string;
fields: Record<string, TCanvasEntityField>;
[key: string]: any;
}
function entitiesToNodes(
entities: AppDataConfig["entities"],
indices?: AppDataConfig["indices"],
): Node<TCanvasEntity>[] {
const indexed_fields = Object.entries(indices ?? {}).flatMap(([, index]) => index.fields);
function entitiesToNodes(entities: AppDataConfig["entities"]): Node<TAppDataEntity>[] {
return Object.entries(entities ?? {}).map(([name, entity]) => {
return {
id: name,
data: { label: name, ...entity },
data: {
...entity,
label: name,
fields: transformObject(entity.fields ?? {}, (f, name) => ({
...f,
name,
indexed: indexed_fields.includes(name),
})),
},
type: "entity",
dragHandle: ".drag-handle",
position: { x: 0, y: 0 },
@@ -65,24 +91,29 @@ const nodeTypes = {
entity: EntityTableNode.Component,
} as const;
const getEdgeStyle = (theme: string) => ({
stroke: theme === "light" ? "#ccc" : "#666",
});
const getMarkerEndStyle = (theme: string) => ({
type: MarkerType.Arrow,
width: 20,
height: 20,
color: theme === "light" ? "#aaa" : "#777",
});
export function DataSchemaCanvas() {
const {
config: { data },
} = useBknd();
const { theme } = useTheme();
const nodes = entitiesToNodes(data.entities);
const nodes = entitiesToNodes(data.entities, data.indices);
console.log(nodes);
const edges = relationsToEdges(data.relations).map((e) => ({
...e,
style: {
stroke: theme === "light" ? "#ccc" : "#666",
},
style: getEdgeStyle(theme),
type: "smoothstep",
markerEnd: {
type: MarkerType.Arrow,
width: 20,
height: 20,
color: theme === "light" ? "#aaa" : "#777",
},
markerEnd: getMarkerEndStyle(theme),
}));
const nodeLayout = layoutWithDagre({
@@ -107,7 +138,7 @@ export function DataSchemaCanvas() {
return (
<ReactFlowProvider>
<Canvas
<ActualCanvas
nodes={nodes}
edges={edges}
nodeTypes={nodeTypes}
@@ -119,7 +150,49 @@ export function DataSchemaCanvas() {
}}
>
<Panels zoom minimap />
</Canvas>
</ActualCanvas>
</ReactFlowProvider>
);
}
function toRecord(nodes: Node<TAppDataEntity>[]): Record<string, Node<TAppDataEntity>> {
return Object.fromEntries(nodes.map((n) => [n.id, n]));
}
function ActualCanvas(props: CanvasProps) {
const flow = useReactFlow();
const { theme } = useTheme();
const onNodesChange = useCallback((changes: any) => {
const nodes = mergeObject<Record<string, Node<TAppDataEntity>>>(
toRecord(flow.getNodes()),
toRecord(changes),
);
const selected = Object.values(nodes).filter((n) => n.selected);
const selected_names = selected.map((n) => n.id);
flow.setEdges((edges) =>
edges.map((edge) => {
if (selected_names.includes(edge.source) || selected_names.includes(edge.target)) {
return {
...edge,
animated: true,
style: { stroke: "#6495c6" },
markerEnd: {
...getMarkerEndStyle(theme),
color: "#6495c6",
},
};
}
return {
...edge,
style: getEdgeStyle(theme),
animated: false,
markerEnd: getMarkerEndStyle(theme),
};
}),
);
}, []);
return <Canvas {...props} onNodesChange={onNodesChange as any} />;
}
@@ -1,26 +1,21 @@
import { Handle, type Node, type NodeProps, Position } from "@xyflow/react";
import { Handle, type Node, type NodeProps, Position, useReactFlow } from "@xyflow/react";
import type { TAppDataEntity } from "data/data-schema";
import { useState } from "react";
import { TbDiamonds, TbKey } from "react-icons/tb";
import { useEffect, useState } from "react";
import { TbBolt, TbDiamonds, TbKey } from "react-icons/tb";
import { twMerge } from "tailwind-merge";
import { DefaultNode } from "ui/components/canvas/components/nodes/DefaultNode";
import { useTheme } from "ui/client/use-theme";
import { useNavigate } from "ui/lib/routes";
import type { TCanvasEntity, TCanvasEntityField } from "./DataSchemaCanvas";
export type TableProps = {
name: string;
type?: string;
fields: TableField[];
};
export type TableField = {
name: string;
type: string;
primary?: boolean;
foreign?: boolean;
indexed?: boolean;
fields: TCanvasEntityField[];
};
function NodeComponent(props: NodeProps<Node<TAppDataEntity & { label: string }>>) {
const [hovered, setHovered] = useState(false);
function NodeComponent(props: NodeProps<Node<TCanvasEntity>>) {
const { data } = props;
const fields = props.data.fields ?? {};
const field_count = Object.keys(fields).length;
@@ -32,10 +27,11 @@ function NodeComponent(props: NodeProps<Node<TAppDataEntity & { label: string }>
{Object.entries(fields).map(([name, field], index) => (
<TableRow
key={index}
field={{ name, ...field }}
field={field}
table={data.label}
index={index}
last={field_count === index + 1}
selected={props.selected && ["relation", "primary"].includes(field.type)}
/>
))}
</div>
@@ -53,13 +49,16 @@ const TableRow = ({
index,
onHover,
last,
selected,
}: {
field: TableField;
field: TCanvasEntityField;
table: string;
index: number;
last?: boolean;
selected?: boolean;
onHover?: (hovered: boolean) => void;
}) => {
const [navigate] = useNavigate();
const handleTop = HEIGHTS.header + HEIGHTS.row * index + HEIGHTS.row / 2;
const handles = true;
const handleId = `${table}:${field.name}`;
@@ -67,10 +66,12 @@ const TableRow = ({
return (
<div
className={twMerge(
"flex flex-row w-full justify-between font-mono py-1.5 px-2.5 border-b border-primary/15 border-l border-r cursor-auto",
"flex flex-row w-full justify-between font-mono py-1.5 px-2.5 border-b border-primary/15 border-l border-r cursor-pointer",
last && "rounded-bl-lg rounded-br-lg",
selected && "bg-primary/5",
"hover:bg-primary/5",
)}
onClick={() => navigate(`/entity/${table}/fields/${field.name}`)}
>
{handles && (
<Handle
@@ -86,7 +87,12 @@ const TableRow = ({
{field.type === "primary" && <TbKey className="text-yellow-700" />}
{field.type === "relation" && <TbDiamonds className="text-sky-700" />}
</div>
<div className="flex flex-grow">{field.name}</div>
<div className="flex flex-grow items-center gap-1">
<span className={field.config?.required ? "font-bold" : "opacity-90"}>
{field.name}
</span>{" "}
{field.indexed && <TbBolt className="text-warning-foreground/50" />}
</div>
<div className="flex opacity-60">{field.type}</div>
{handles && (
+33 -39
View File
@@ -1,6 +1,6 @@
import { isDebug } from "core";
import { autoFormatString } from "core/utils";
import { type ChangeEvent, useState } from "react";
import type { ChangeEvent } from "react";
import {
TbAt,
TbBrandAppleFilled,
@@ -13,7 +13,6 @@ import {
TbBrandX,
TbSettings,
} from "react-icons/tb";
import { twMerge } from "tailwind-merge";
import { useBknd } from "ui/client/bknd";
import { useBkndAuth } from "ui/client/schema/auth/use-bknd-auth";
import { Button } from "ui/components/buttons/Button";
@@ -33,6 +32,8 @@ import {
} from "ui/components/form/json-schema-form";
import { useBrowserTitle } from "ui/hooks/use-browser-title";
import * as AppShell from "../../layouts/AppShell/AppShell";
import { CollapsibleList } from "ui/components/list/CollapsibleList";
import { useRoutePathState } from "ui/hooks/use-route-path-state";
export function AuthStrategiesList(props) {
useBrowserTitle(["Auth", "Strategies"]);
@@ -104,7 +105,7 @@ function AuthStrategiesListInternal() {
<p className="opacity-70">
Allow users to sign in or sign up using different strategies.
</p>
<div className="flex flex-col gap-2 max-w-4xl">
<CollapsibleList.Root>
<Strategy type="password" name="password" />
<Strategy type="oauth" name="google" />
<Strategy type="oauth" name="github" />
@@ -113,7 +114,7 @@ function AuthStrategiesListInternal() {
<Strategy type="oauth" name="instagram" unavailable />
<Strategy type="oauth" name="apple" unavailable />
<Strategy type="oauth" name="discord" unavailable />
</div>
</CollapsibleList.Root>
</div>
<FormDebug />
</AppShell.Scrollable>
@@ -138,47 +139,40 @@ const Strategy = ({ type, name, unavailable }: StrategyProps) => {
]),
);
const schema = schemas[type];
const [open, setOpen] = useState(false);
const { active, toggle } = useRoutePathState("/strategies/:strategy?", name);
if (!schema) return null;
return (
<FormContextOverride schema={schema} prefix={name}>
<div
className={twMerge(
"flex flex-col border border-muted rounded bg-background",
unavailable && "opacity-20 pointer-events-none cursor-not-allowed",
errors.length > 0 && "border-red-500",
)}
<CollapsibleList.Item
hasError={errors.length > 0}
className={
unavailable ? "opacity-20 pointer-events-none cursor-not-allowed" : undefined
}
>
<div className="flex flex-row justify-between p-3 gap-3 items-center">
<div className="flex flex-row items-center p-2 bg-primary/5 rounded">
<StrategyIcon type={type} provider={name} />
</div>
<div className="font-mono flex-grow flex flex-row gap-3">
<span className="leading-none">{autoFormatString(name)}</span>
</div>
<div className="flex flex-row gap-4 items-center">
<StrategyToggle type={type} />
<IconButton
Icon={TbSettings}
size="lg"
iconProps={{ strokeWidth: 1.5 }}
variant={open ? "primary" : "ghost"}
onClick={() => setOpen((o) => !o)}
/>
</div>
</div>
{open && (
<div
className={twMerge(
"flex flex-col border-t border-t-muted px-4 pt-3 pb-4 bg-lightest/50 gap-4",
)}
>
<StrategyForm type={type} name={name} />
</div>
)}
</div>
<CollapsibleList.Preview
left={<StrategyIcon type={type} provider={name} />}
right={
<>
<StrategyToggle type={type} />
<IconButton
Icon={TbSettings}
size="lg"
iconProps={{ strokeWidth: 1.5 }}
variant={active ? "primary" : "ghost"}
onClick={() => toggle(!active)}
/>
</>
}
>
<span className="leading-none">{autoFormatString(name)}</span>
</CollapsibleList.Preview>
<CollapsibleList.Detail open={active}>
<StrategyForm type={type} name={name} />
</CollapsibleList.Detail>
</CollapsibleList.Item>
</FormContextOverride>
);
};
+1 -1
View File
@@ -14,7 +14,7 @@ export default function AuthRoutes() {
<Route path="/users" component={AuthUsersList} />
<Route path="/roles" component={AuthRolesList} />
<Route path="/roles/edit/:role" component={AuthRolesEdit} />
<Route path="/strategies" component={AuthStrategiesList} />
<Route path="/strategies/:strategy?" component={AuthStrategiesList} />
<Route path="/settings" component={AuthSettings} />
</AuthRoot>
);
-4
View File
@@ -83,10 +83,6 @@ export function DataRoot({ children }) {
</AppShell.SectionHeader>
<AppShell.Scrollable initialOffset={96}>
<div className="flex flex-col flex-grow py-3 gap-3">
{/*<div className="pt-3 px-3">
<SearchInput placeholder="Search entities" />
</div>*/}
<EntityLinkList entities={entityList.regular} context={context} suggestCreate />
<EntityLinkList entities={entityList.system} context={context} title="System" />
<EntityLinkList
+135 -120
View File
@@ -30,14 +30,12 @@ import { routes, useNavigate } from "ui/lib/routes";
import { fieldSpecs } from "ui/modules/data/components/fields-specs";
import { extractSchema } from "../settings/utils/schema";
import { EntityFieldsForm, type EntityFieldsFormRef } from "./forms/entity.fields.form";
import { RoutePathStateProvider } from "ui/hooks/use-route-path-state";
import { EntityIndicesForm } from "./forms/entity.indices.form";
import type { TAppDataIndex } from "data/data-schema";
export function DataSchemaEntity({ params }) {
const { $data } = useBkndData();
const [value, setValue] = useState("fields");
function toggle(value) {
return () => setValue(value);
}
const [navigate] = useNavigate();
const entity = $data.entity(params.entity as string)!;
@@ -47,115 +45,103 @@ export function DataSchemaEntity({ params }) {
return (
<>
<AppShell.SectionHeader
right={
<>
<Dropdown
items={[
{
label: "Data",
onClick: () =>
navigate(routes.data.root() + routes.data.entity.list(entity.name), {
absolute: true,
}),
},
{
label: "Advanced Settings",
onClick: () =>
navigate(routes.settings.path(["data", "entities", entity.name]), {
absolute: true,
}),
},
]}
position="bottom-end"
>
<IconButton Icon={TbDots} />
</Dropdown>
<Dropdown
items={[
{
icon: TbCirclesRelation,
label: "Add relation",
onClick: () => $data.modals.createRelation(entity.name),
},
{
icon: TbPhoto,
label: "Add media",
onClick: () => $data.modals.createMedia(entity.name),
},
() => <div className="h-px my-1 w-full bg-primary/5" />,
{
icon: TbDatabasePlus,
label: "Create Entity",
onClick: () => $data.modals.createEntity(),
},
]}
position="bottom-end"
>
<Button IconRight={TbPlus}>Add</Button>
</Dropdown>
</>
}
className="pl-3"
<RoutePathStateProvider
path={`/entity/${entity.name}/:setting?`}
defaultIdentifier="fields"
>
<div className="flex flex-row gap-4">
<Breadcrumbs2
path={[{ label: "Schema", href: "/" }, { label: entity.label }]}
backTo="/"
/>
<Link to="/" className="hidden md:inline">
<Button IconLeft={TbSitemap}>Overview</Button>
</Link>
</div>
</AppShell.SectionHeader>
<div className="flex flex-col h-full" key={entity.name}>
<Fields entity={entity} open={value === "fields"} toggle={toggle("fields")} />
<AppShell.SectionHeader
right={
<>
<Dropdown
items={[
{
label: "Data",
onClick: () =>
navigate(
routes.data.root() + routes.data.entity.list(entity.name),
{
absolute: true,
},
),
},
{
label: "Advanced Settings",
onClick: () =>
navigate(routes.settings.path(["data", "entities", entity.name]), {
absolute: true,
}),
},
]}
position="bottom-end"
>
<IconButton Icon={TbDots} />
</Dropdown>
<Dropdown
items={[
{
icon: TbCirclesRelation,
label: "Add relation",
onClick: () => $data.modals.createRelation(entity.name),
},
{
icon: TbPhoto,
label: "Add media",
onClick: () => $data.modals.createMedia(entity.name),
},
() => <div className="h-px my-1 w-full bg-primary/5" />,
{
icon: TbDatabasePlus,
label: "Create Entity",
onClick: () => $data.modals.createEntity(),
},
]}
position="bottom-end"
>
<Button IconRight={TbPlus}>Add</Button>
</Dropdown>
</>
}
className="pl-3"
>
<div className="flex flex-row gap-4">
<Breadcrumbs2
path={[{ label: "Schema", href: "/" }, { label: entity.label }]}
backTo="/"
/>
<Link to="/" className="hidden md:inline">
<Button IconLeft={TbSitemap}>Overview</Button>
</Link>
</div>
</AppShell.SectionHeader>
<div className="flex flex-col h-full" key={entity.name}>
<Fields entity={entity} />
<BasicSettings entity={entity} open={value === "2"} toggle={toggle("2")} />
<AppShell.SectionHeaderAccordionItem
title="Relations"
open={value === "3"}
toggle={toggle("3")}
ActiveIcon={IconCirclesRelation}
>
<Empty
<BasicSettings entity={entity} />
<AppShell.RouteAwareSectionHeaderAccordionItem
identifier="relations"
title="Relations"
description="This will soon be available here. Meanwhile, check advanced settings."
primary={{
children: "Advanced Settings",
onClick: () =>
navigate(routes.settings.path(["data", "relations"]), { absolute: true }),
}}
/>
</AppShell.SectionHeaderAccordionItem>
<AppShell.SectionHeaderAccordionItem
title="Indices"
open={value === "4"}
toggle={toggle("4")}
ActiveIcon={IconBolt}
>
<Empty
title="Indices"
description="This will soon be available here. Meanwhile, check advanced settings."
primary={{
children: "Advanced Settings",
onClick: () =>
navigate(routes.settings.path(["data", "indices"]), {
absolute: true,
}),
}}
/>
</AppShell.SectionHeaderAccordionItem>
</div>
ActiveIcon={IconCirclesRelation}
>
<Empty
title="Relations"
description="This will soon be available here. Meanwhile, check advanced settings."
primary={{
children: "Advanced Settings",
onClick: () =>
navigate(routes.settings.path(["data", "relations"]), {
absolute: true,
}),
}}
/>
</AppShell.RouteAwareSectionHeaderAccordionItem>
<Indices entity={entity} />
</div>
</RoutePathStateProvider>
</>
);
}
const Fields = ({
entity,
open,
toggle,
}: { entity: Entity; open: boolean; toggle: () => void }) => {
const Fields = ({ entity }: { entity: Entity }) => {
const [submitting, setSubmitting] = useState(false);
const [updates, setUpdates] = useState(0);
const { actions, $data } = useBkndData();
@@ -174,10 +160,9 @@ const Fields = ({
const initialFields = Object.fromEntries(entity.fields.map((f) => [f.name, f.toJSON()])) as any;
return (
<AppShell.SectionHeaderAccordionItem
<AppShell.RouteAwareSectionHeaderAccordionItem
identifier="fields"
title="Fields"
open={open}
toggle={toggle}
ActiveIcon={IconAlignJustified}
renderHeaderRight={({ open }) =>
open ? (
@@ -192,6 +177,7 @@ const Fields = ({
<div className="animate-fade-in absolute w-full h-full top-0 bottom-0 left-0 right-0 bg-background/65 z-50" />
)}
<EntityFieldsForm
routePattern={`/entity/${entity.name}/fields/:sub?`}
fields={initialFields}
ref={ref}
key={String(updates)}
@@ -237,15 +223,11 @@ const Fields = ({
</div>
)}
</div>
</AppShell.SectionHeaderAccordionItem>
</AppShell.RouteAwareSectionHeaderAccordionItem>
);
};
const BasicSettings = ({
entity,
open,
toggle,
}: { entity: Entity; open: boolean; toggle: () => void }) => {
const BasicSettings = ({ entity }: { entity: Entity }) => {
const d = useBkndData();
const config = d.entities?.[entity.name]?.config;
const formRef = useRef<JsonSchemaFormRef>(null);
@@ -271,10 +253,9 @@ const BasicSettings = ({
}
return (
<AppShell.SectionHeaderAccordionItem
<AppShell.RouteAwareSectionHeaderAccordionItem
identifier="settings"
title="Settings"
open={open}
toggle={toggle}
ActiveIcon={IconSettings}
renderHeaderRight={({ open }) =>
open ? (
@@ -293,6 +274,40 @@ const BasicSettings = ({
className="legacy hide-required-mark fieldset-alternative mute-root"
/>
</div>
</AppShell.SectionHeaderAccordionItem>
</AppShell.RouteAwareSectionHeaderAccordionItem>
);
};
const Indices = ({ entity }: { entity: Entity }) => {
const [navigate] = useNavigate();
const [data, setData] = useState<Record<string, TAppDataIndex>>({});
const d = useBkndData();
const [submitting, setSubmitting] = useState(false);
async function handleUpdate() {
console.log("update", data);
return;
/*if (submitting) return;
setSubmitting(true);
await d.actions.entity.patch(entity.name).indices.set(data);
setSubmitting(false);*/
}
return (
<AppShell.RouteAwareSectionHeaderAccordionItem
identifier="indices"
title="Indices"
ActiveIcon={IconBolt}
renderHeaderRight={({ open }) =>
open ? (
<Button variant="primary" disabled={!open || submitting} onClick={handleUpdate}>
Update
</Button>
) : null
}
>
<div className="flex flex-col flex-grow py-3 px-4 max-w-4xl gap-3 relative">
<EntityIndicesForm entity={entity} onChange={setData} />
</div>
</AppShell.RouteAwareSectionHeaderAccordionItem>
);
};
@@ -27,6 +27,7 @@ import { Popover } from "ui/components/overlay/Popover";
import { type TFieldSpec, fieldSpecs } from "ui/modules/data/components/fields-specs";
import { dataFieldsUiSchema } from "../../settings/routes/data.settings";
import * as tbbox from "@sinclair/typebox";
import { useRoutePathState } from "ui/hooks/use-route-path-state";
const { Type } = tbbox;
const fieldsSchemaObject = originalFieldsSchemaObject;
@@ -63,6 +64,7 @@ export type EntityFieldsFormProps = {
onChange?: (formData: TAppDataEntityFields) => void;
sortable?: boolean;
additionalFieldTypes?: (TFieldSpec & { onClick: () => void })[];
routePattern?: string;
};
export type EntityFieldsFormRef = {
@@ -74,7 +76,10 @@ export type EntityFieldsFormRef = {
};
export const EntityFieldsForm = forwardRef<EntityFieldsFormRef, EntityFieldsFormProps>(
function EntityFieldsForm({ fields: _fields, sortable, additionalFieldTypes, ...props }, ref) {
function EntityFieldsForm(
{ fields: _fields, sortable, additionalFieldTypes, routePattern, ...props },
ref,
) {
const entityFields = Object.entries(_fields).map(([name, field]) => ({
name,
field,
@@ -166,6 +171,7 @@ export const EntityFieldsForm = forwardRef<EntityFieldsFormRef, EntityFieldsForm
errors={errors}
remove={remove}
dnd={dnd}
routePattern={routePattern}
/>
)}
/>
@@ -179,6 +185,7 @@ export const EntityFieldsForm = forwardRef<EntityFieldsFormRef, EntityFieldsForm
form={formProps}
errors={errors}
remove={remove}
routePattern={routePattern}
/>
))}
</div>
@@ -273,6 +280,7 @@ function EntityField({
remove,
errors,
dnd,
routePattern,
}: {
field: FieldArrayWithId<TFieldsFormSchema, "fields", "id">;
index: number;
@@ -283,11 +291,12 @@ function EntityField({
remove: (index: number) => void;
errors: any;
dnd?: SortableItemProps;
routePattern?: string;
}) {
const [opened, handlers] = useDisclosure(false);
const prefix = `fields.${index}.field` as const;
const type = field.field.type;
const name = watch(`fields.${index}.name`);
const { active, toggle } = useRoutePathState(routePattern ?? "", name);
const fieldSpec = fieldSpecs.find((s) => s.type === type)!;
const specificData = omit(field.field.config, commonProps);
const disabled = fieldSpec.disabled || [];
@@ -300,9 +309,11 @@ function EntityField({
return () => {
if (name.length === 0) {
remove(index);
return;
toggle();
} else if (window.confirm(`Sure to delete "${name}"?`)) {
remove(index);
toggle();
}
window.confirm(`Sure to delete "${name}"?`) && remove(index);
};
}
//console.log("register", register(`${prefix}.config.required`));
@@ -313,7 +324,7 @@ function EntityField({
key={field.id}
className={twMerge(
"flex flex-col border border-muted rounded bg-background mb-2",
opened && "mb-6",
active && "mb-6",
hasErrors && "border-red-500 ",
)}
{...dndProps}
@@ -371,13 +382,13 @@ function EntityField({
Icon={TbSettings}
disabled={is_primary}
iconProps={{ strokeWidth: 1.5 }}
onClick={handlers.toggle}
variant={opened ? "primary" : "ghost"}
onClick={() => toggle()}
variant={active ? "primary" : "ghost"}
/>
</div>
</div>
</div>
{opened && (
{active && (
<div className="flex flex-col border-t border-t-muted px-3 py-2 bg-lightest/50">
{/*<pre>{JSON.stringify(field, null, 2)}</pre>*/}
<Tabs defaultValue="general">
@@ -0,0 +1,118 @@
import { TbBolt, TbTrash } from "react-icons/tb";
import type { Entity } from "data/entities";
import { IconButton } from "ui/components/buttons/IconButton";
import { useBkndData } from "ui/client/schema/data/use-bknd-data";
import { CollapsibleList } from "ui/components/list/CollapsibleList";
import { EntityIndex } from "data";
import { Button } from "ui/components/buttons/Button";
import { useEffect, useState } from "react";
import { JsonViewer } from "ui/components/code/JsonViewer";
import type { TAppDataIndex } from "data/data-schema";
import * as Formy from "ui/components/form/Formy";
export interface EntityIndicesFormProps {
entity: Entity;
onChange?: (indices: Record<string, TAppDataIndex>) => void;
}
export function EntityIndicesForm({ entity, onChange }: EntityIndicesFormProps) {
const { $data } = useBkndData();
const [indices, setIndices] = useState<EntityIndex[]>($data.indicesOf(entity.name));
const [create, setCreate] = useState<TAppDataIndex>({
entity: entity.name,
fields: [],
unique: false,
});
const indexed_fields = indices.flatMap((i) => i.fields).map((f) => f.name);
const required_fields = indices
.flatMap((i) => i.fields)
.filter((f) => f.isRequired())
.map((f) => f.name);
const fields = entity.fields.filter(
(f) => !["primary", "relation", "media"].includes(f.type) && !indexed_fields.includes(f.name),
);
useEffect(() => {
onChange?.(Object.fromEntries(indices.map((i) => [i.name, i.toJSON()])));
}, [indices]);
function handleAdd() {
setIndices((prev) => [
...prev,
new EntityIndex(
entity,
create.fields.map((f) => entity.fields.find((f2) => f2.name === f)!),
create.unique,
),
]);
}
//console.log("indices", { indices, schema, config });
return (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
{indices.map((index) => (
<CollapsibleList.Item key={index.name} title={index.name}>
<CollapsibleList.Preview
left={<TbBolt />}
right={<IconButton size="lg" Icon={TbTrash} />}
>
<span>{index.fields.map((f) => f.name).join(", ")}</span>
<span className="opacity-50">{index.name}</span>
</CollapsibleList.Preview>
</CollapsibleList.Item>
))}
</div>
<div className="flex flex-row gap-7 items-center">
<span className="font-bold">Add Index</span>
<div className="flex flex-row gap-2">
<Formy.Label className="opacity-70">Unique</Formy.Label>
<Formy.Switch
checked={create.unique}
size="sm"
onCheckedChange={(checked) => {
setCreate((prev) => ({
...prev,
unique: checked,
fields: prev.fields.some((f) => required_fields.includes(f))
? prev.fields
: [],
}));
}}
/>
</div>
<div className="flex flex-row flex-wrap gap-2 items-center">
<Formy.Label className="opacity-70">Field</Formy.Label>
<div className="min-w-0">
<Formy.Select
className="h-9 py-1.5 pl-3 pr-8"
options={fields.map((f) => ({
label: f.getLabel()!,
value: f.name,
disabled: create.unique && !required_fields.includes(f.name),
}))}
value={create.fields[0]}
onChange={(e) => {
setCreate((prev) => ({ ...prev, fields: [e.target.value] }));
}}
/>
</div>
</div>
<div className="flex flex-grow" />
<Button variant="primary" disabled={create.fields.length === 0} onClick={handleAdd}>
Add
</Button>
</div>
<div>
<JsonViewer
json={{
create,
data: Object.fromEntries(indices.map((i) => [i.name, i.toJSON()])),
}}
expand={9}
/>
</div>
</div>
);
}
+1 -1
View File
@@ -17,7 +17,7 @@ export default function DataRoutes() {
<Route path="/schema" nest>
<Route path="/" component={DataSchemaIndex} />
<Route path="/entity/:entity" component={DataSchemaEntity} />
<Route path="/entity/:entity/:setting?/:sub?" component={DataSchemaEntity} />
</Route>
</Switch>
</DataRoot>