made the creation of an entity more accessible and obvious

This commit is contained in:
dswbx
2025-01-17 11:24:24 +01:00
parent ac3c7316ff
commit 1625a0c7c0
12 changed files with 176 additions and 138 deletions

View File

@@ -12,6 +12,7 @@ import {
} from "data/data-schema"; } from "data/data-schema";
import { useBknd } from "ui/client/bknd"; import { useBknd } from "ui/client/bknd";
import type { TSchemaActions } from "ui/client/schema/actions"; import type { TSchemaActions } from "ui/client/schema/actions";
import { bkndModals } from "ui/modals";
export function useBkndData() { export function useBkndData() {
const { config, app, schema, actions: bkndActions } = useBknd(); const { config, app, schema, actions: bkndActions } = useBknd();
@@ -62,7 +63,8 @@ export function useBkndData() {
} }
}; };
const $data = { const $data = {
entity: (name: string) => entities[name] entity: (name: string) => entities[name],
modals
}; };
return { return {
@@ -75,6 +77,15 @@ export function useBkndData() {
}; };
} }
const modals = {
createAny: () => bkndModals.open(bkndModals.ids.dataCreate, {}),
createEntity: () =>
bkndModals.open(bkndModals.ids.dataCreate, {
initialPath: ["entities", "entity"],
initialState: { action: "entity" }
})
};
function entityFieldActions(bkndActions: TSchemaActions, entityName: string) { function entityFieldActions(bkndActions: TSchemaActions, entityName: string) {
return { return {
add: async (name: string, field: TAppDataField) => { add: async (name: string, field: TAppDataField) => {

View File

@@ -1,33 +1,33 @@
import { Button } from "../buttons/Button"; import { twMerge } from "tailwind-merge";
import { Button, type ButtonProps } from "../buttons/Button";
export type EmptyProps = { export type EmptyProps = {
Icon?: any; Icon?: any;
title?: string; title?: string;
description?: string; description?: string;
buttonText?: string; primary?: ButtonProps;
buttonOnClick?: () => void; secondary?: ButtonProps;
className?: string;
}; };
export const Empty: React.FC<EmptyProps> = ({ export const Empty: React.FC<EmptyProps> = ({
Icon = undefined, Icon = undefined,
title = undefined, title = undefined,
description = "Check back later my friend.", description = "Check back later my friend.",
buttonText, primary,
buttonOnClick secondary,
className
}) => ( }) => (
<div className="flex flex-col h-full w-full justify-center items-center"> <div className={twMerge("flex flex-col h-full w-full justify-center items-center", className)}>
<div className="flex flex-col gap-3 items-center max-w-80"> <div className="flex flex-col gap-3 items-center max-w-80">
{Icon && <Icon size={48} className="opacity-50" stroke={1} />} {Icon && <Icon size={48} className="opacity-50" stroke={1} />}
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-1">
{title && <h3 className="text-center text-lg font-bold">{title}</h3>} {title && <h3 className="text-center text-lg font-bold">{title}</h3>}
<p className="text-center text-primary/60">{description}</p> <p className="text-center text-primary/60">{description}</p>
</div> </div>
{buttonText && ( <div className="mt-1.5 flex flex-row gap-2">
<div className="mt-1.5"> {secondary && <Button variant="default" {...secondary} />}
<Button variant="primary" onClick={buttonOnClick}> {primary && <Button variant="primary" {...primary} />}
{buttonText} </div>
</Button>
</div>
)}
</div> </div>
</div> </div>
); );

View File

@@ -10,6 +10,7 @@ import {
export type TStepsProps = { export type TStepsProps = {
children: any; children: any;
initialPath?: string[]; initialPath?: string[];
initialState?: any;
lastBack?: () => void; lastBack?: () => void;
[key: string]: any; [key: string]: any;
}; };
@@ -19,13 +20,14 @@ type TStepContext<T = any> = {
stepBack: () => void; stepBack: () => void;
close: () => void; close: () => void;
state: T; state: T;
path: string[];
setState: Dispatch<SetStateAction<T>>; setState: Dispatch<SetStateAction<T>>;
}; };
const StepContext = createContext<TStepContext>(undefined as any); const StepContext = createContext<TStepContext>(undefined as any);
export function Steps({ children, initialPath = [], lastBack }: TStepsProps) { export function Steps({ children, initialPath = [], initialState = {}, lastBack }: TStepsProps) {
const [state, setState] = useState<any>({}); const [state, setState] = useState<any>(initialState);
const [path, setPath] = useState<string[]>(initialPath); const [path, setPath] = useState<string[]>(initialPath);
const steps: any[] = Children.toArray(children).filter( const steps: any[] = Children.toArray(children).filter(
(child: any) => child.props.disabled !== true (child: any) => child.props.disabled !== true
@@ -46,7 +48,7 @@ export function Steps({ children, initialPath = [], lastBack }: TStepsProps) {
const current = steps.find((step) => step.props.id === path[path.length - 1]) || steps[0]; const current = steps.find((step) => step.props.id === path[path.length - 1]) || steps[0];
return ( return (
<StepContext.Provider value={{ nextStep, stepBack, state, setState, close: lastBack! }}> <StepContext.Provider value={{ nextStep, stepBack, state, path, setState, close: lastBack! }}>
{current} {current}
</StepContext.Provider> </StepContext.Provider>
); );

View File

@@ -1,8 +1,8 @@
import type { ModalProps } from "@mantine/core"; import type { ModalProps } from "@mantine/core";
import { modals as $modals, ModalsProvider, closeModal, openContextModal } from "@mantine/modals"; import { modals as $modals, ModalsProvider, closeModal, openContextModal } from "@mantine/modals";
import { transformObject } from "core/utils";
import type { ComponentProps } from "react"; import type { ComponentProps } from "react";
import { OverlayModal } from "ui/modals/debug/OverlayModal"; import { OverlayModal } from "ui/modals/debug/OverlayModal";
import { CreateModal } from "ui/modules/data/components/schema/create-modal/CreateModal";
import { DebugModal } from "./debug/DebugModal"; import { DebugModal } from "./debug/DebugModal";
import { SchemaFormModal } from "./debug/SchemaFormModal"; import { SchemaFormModal } from "./debug/SchemaFormModal";
import { TestModal } from "./debug/TestModal"; import { TestModal } from "./debug/TestModal";
@@ -11,7 +11,8 @@ const modals = {
test: TestModal, test: TestModal,
debug: DebugModal, debug: DebugModal,
form: SchemaFormModal, form: SchemaFormModal,
overlay: OverlayModal overlay: OverlayModal,
dataCreate: CreateModal
}; };
declare module "@mantine/modals" { declare module "@mantine/modals" {
@@ -54,10 +55,9 @@ function close<Modal extends keyof typeof modals>(modal: Modal) {
} }
export const bkndModals = { export const bkndModals = {
ids: transformObject(modals, (key) => key) as unknown as Record< ids: Object.fromEntries(Object.keys(modals).map((key) => [key, key])) as {
keyof typeof modals, [K in keyof typeof modals]: K;
keyof typeof modals },
>,
open, open,
close, close,
closeAll: $modals.closeAll closeAll: $modals.closeAll

View File

@@ -1,15 +1,9 @@
import { type Static, StringEnum, StringIdentifier, Type, transformObject } from "core/utils"; import type { ModalProps } from "@mantine/core";
import { FieldClassMap } from "data"; import type { ContextModalProps } from "@mantine/modals";
import { type Static, StringEnum, StringIdentifier, Type } from "core/utils";
import { entitiesSchema, fieldsSchema, relationsSchema } from "data/data-schema"; import { entitiesSchema, fieldsSchema, relationsSchema } from "data/data-schema";
import { omit } from "lodash-es"; import { useState } from "react";
import { forwardRef, useState } from "react"; import { type Modal2Ref, ModalBody, ModalFooter, ModalTitle } from "ui/components/modal/Modal2";
import {
Modal2,
type Modal2Ref,
ModalBody,
ModalFooter,
ModalTitle
} from "ui/components/modal/Modal2";
import { Step, Steps, useStepContext } from "ui/components/steps/Steps"; import { Step, Steps, useStepContext } from "ui/components/steps/Steps";
import { StepCreate } from "ui/modules/data/components/schema/create-modal/step.create"; import { StepCreate } from "ui/modules/data/components/schema/create-modal/step.create";
import { StepEntity } from "./step.entity"; import { StepEntity } from "./step.entity";
@@ -67,48 +61,59 @@ const createModalSchema = Type.Object(
); );
export type TCreateModalSchema = Static<typeof createModalSchema>; export type TCreateModalSchema = Static<typeof createModalSchema>;
export const CreateModal = forwardRef<CreateModalRef>(function CreateModal(props, ref) { export function CreateModal({
const [path, setPath] = useState<string[]>([]); context,
id,
innerProps: { initialPath = [], initialState }
}: ContextModalProps<{ initialPath?: string[]; initialState?: TCreateModalSchema }>) {
const [path, setPath] = useState<string[]>(initialPath);
console.log("...", initialPath, initialState);
function close() { function close() {
// @ts-ignore context.closeModal(id);
ref?.current?.close();
} }
return ( return (
<Modal2 ref={ref}> <Steps path={path} lastBack={close} initialPath={initialPath} initialState={initialState}>
<Steps path={path} lastBack={close}> <Step id="select">
<Step id="select"> <ModalTitle path={["Create New"]} onClose={close} />
<ModalTitle path={["Create New"]} onClose={close} /> <StepSelect />
<StepSelect /> </Step>
</Step> <Step id="entity" path={["action"]}>
<Step id="entity" path={["action"]}> <ModalTitle path={["Create New", "Entity"]} onClose={close} />
<ModalTitle path={["Create New", "Entity"]} onClose={close} /> <StepEntity />
<StepEntity /> </Step>
</Step> <Step id="entity-fields" path={["action", "entity"]}>
<Step id="entity-fields" path={["action", "entity"]}> <ModalTitle path={["Create New", "Entity", "Fields"]} onClose={close} />
<ModalTitle path={["Create New", "Entity", "Fields"]} onClose={close} /> <StepEntityFields />
<StepEntityFields /> </Step>
</Step> <Step id="relation" path={["action"]}>
<Step id="relation" path={["action"]}> <ModalTitle path={["Create New", "Relation"]} onClose={close} />
<ModalTitle path={["Create New", "Relation"]} onClose={close} /> <StepRelation />
<StepRelation /> </Step>
</Step> <Step id="create" path={["action"]}>
<Step id="create" path={["action"]}> <ModalTitle path={["Create New", "Creation"]} onClose={close} />
<ModalTitle path={["Create New", "Creation"]} onClose={close} /> <StepCreate />
<StepCreate /> </Step>
</Step>
{/* Templates */} {/* Templates */}
{Templates.map(([Component, meta]) => ( {Templates.map(([Component, meta]) => (
<Step key={meta.id} id={meta.id} path={["action"]}> <Step key={meta.id} id={meta.id} path={["action"]}>
<ModalTitle path={["Create New", "Template", meta.title]} onClose={close} /> <ModalTitle path={["Create New", "Template", meta.title]} onClose={close} />
<Component /> <Component />
</Step> </Step>
))} ))}
</Steps> </Steps>
</Modal2>
); );
}); }
CreateModal.defaultTitle = undefined;
CreateModal.modalProps = {
withCloseButton: false,
size: "xl",
padding: 0,
classNames: {
root: "bknd-admin"
}
} satisfies Partial<ModalProps>;
export { ModalBody, ModalFooter, ModalTitle, useStepContext, relationsSchema }; export { ModalBody, ModalFooter, ModalTitle, useStepContext, relationsSchema };

View File

@@ -12,7 +12,7 @@ import {
import Templates from "./templates/register"; import Templates from "./templates/register";
export function StepSelect() { export function StepSelect() {
const { nextStep, stepBack, state, setState } = useStepContext<TCreateModalSchema>(); const { nextStep, stepBack, state, path, setState } = useStepContext<TCreateModalSchema>();
const selected = state.action ?? null; const selected = state.action ?? null;
function handleSelect(action: TSchemaAction) { function handleSelect(action: TSchemaAction) {
@@ -74,6 +74,7 @@ export function StepSelect() {
}} }}
prev={{ onClick: stepBack }} prev={{ onClick: stepBack }}
prevLabel="Cancel" prevLabel="Cancel"
debug={{ state, path }}
/> />
</> </>
); );

View File

@@ -1,8 +1,10 @@
import { SegmentedControl } from "@mantine/core"; import { SegmentedControl, Tooltip } from "@mantine/core";
import { IconDatabase } from "@tabler/icons-react"; import { IconDatabase } from "@tabler/icons-react";
import type { Entity, TEntityType } from "data"; import type { Entity, TEntityType } from "data";
import { TbDatabasePlus } from "react-icons/tb";
import { twMerge } from "tailwind-merge"; import { twMerge } from "tailwind-merge";
import { useBknd } from "ui/client/bknd"; import { useBkndData } from "ui/client/schema/data/use-bknd-data";
import { IconButton } from "ui/components/buttons/IconButton";
import { Empty } from "ui/components/display/Empty"; import { Empty } from "ui/components/display/Empty";
import { Link } from "ui/components/wouter/Link"; import { Link } from "ui/components/wouter/Link";
import { useBrowserTitle } from "ui/hooks/use-browser-title"; import { useBrowserTitle } from "ui/hooks/use-browser-title";
@@ -11,9 +13,7 @@ import { routes, useNavigate } from "ui/lib/routes";
export function DataRoot({ children }) { export function DataRoot({ children }) {
// @todo: settings routes should be centralized // @todo: settings routes should be centralized
const { const { entities, $data } = useBkndData();
app: { entities }
} = useBknd();
const entityList: Record<TEntityType, Entity[]> = { const entityList: Record<TEntityType, Entity[]> = {
regular: [], regular: [],
generated: [], generated: [],
@@ -22,7 +22,7 @@ export function DataRoot({ children }) {
const [navigate] = useNavigate(); const [navigate] = useNavigate();
const context = window.location.href.match(/\/schema/) ? "schema" : "data"; const context = window.location.href.match(/\/schema/) ? "schema" : "data";
for (const entity of entities) { for (const entity of Object.values(entities)) {
entityList[entity.getType()].push(entity); entityList[entity.getType()].push(entity);
} }
@@ -52,14 +52,19 @@ export function DataRoot({ children }) {
<AppShell.Sidebar> <AppShell.Sidebar>
<AppShell.SectionHeader <AppShell.SectionHeader
right={ right={
<SegmentedControl <>
data={[ <SegmentedControl
{ value: "data", label: "Data" }, data={[
{ value: "schema", label: "Schema" } { value: "data", label: "Data" },
]} { value: "schema", label: "Schema" }
value={context} ]}
onChange={handleSegmentChange} value={context}
/> onChange={handleSegmentChange}
/>
<Tooltip label="New Entity">
<IconButton Icon={TbDatabasePlus} onClick={$data.modals.createEntity} />
</Tooltip>
</>
} }
> >
Entities Entities
@@ -70,7 +75,7 @@ export function DataRoot({ children }) {
<SearchInput placeholder="Search entities" /> <SearchInput placeholder="Search entities" />
</div>*/} </div>*/}
<EntityLinkList entities={entityList.regular} context={context} /> <EntityLinkList entities={entityList.regular} context={context} suggestCreate />
<EntityLinkList entities={entityList.system} context={context} title="System" /> <EntityLinkList entities={entityList.system} context={context} title="System" />
<EntityLinkList <EntityLinkList
entities={entityList.generated} entities={entityList.generated}
@@ -88,9 +93,22 @@ export function DataRoot({ children }) {
const EntityLinkList = ({ const EntityLinkList = ({
entities, entities,
title, title,
context context,
}: { entities: Entity[]; title?: string; context: "data" | "schema" }) => { suggestCreate = false
if (entities.length === 0) return null; }: { entities: Entity[]; title?: string; context: "data" | "schema"; suggestCreate?: boolean }) => {
const { $data } = useBkndData();
if (entities.length === 0) {
return suggestCreate ? (
<Empty
className="py-10"
description="Create your first entity to get started."
secondary={{
children: "Create entity",
onClick: () => $data.modals.createEntity()
}}
/>
) : null;
}
return ( return (
<nav <nav
@@ -119,9 +137,9 @@ const EntityLinkList = ({
export function DataEmpty() { export function DataEmpty() {
useBrowserTitle(["Data"]); useBrowserTitle(["Data"]);
const [navigate] = useNavigate(); const [navigate] = useNavigate();
const { $data } = useBkndData();
function handleButtonClick() { function handleButtonClick() {
//navigate(routes.settings.path(["data", "entities"]), { absolute: true });
navigate(routes.data.schema.root()); navigate(routes.data.schema.root());
} }
@@ -130,8 +148,14 @@ export function DataEmpty() {
Icon={IconDatabase} Icon={IconDatabase}
title="No entity selected" title="No entity selected"
description="Please select an entity from the left sidebar or create a new one to continue." description="Please select an entity from the left sidebar or create a new one to continue."
buttonText="Go to schema" secondary={{
buttonOnClick={handleButtonClick} children: "Go to schema",
onClick: handleButtonClick
}}
primary={{
children: "Create entity",
onClick: $data.modals.createEntity
}}
/> />
); );
} }

View File

@@ -37,22 +37,20 @@ export function DataSchemaEntity({ params }) {
<> <>
<AppShell.SectionHeader <AppShell.SectionHeader
right={ right={
<> <Dropdown
<Dropdown items={[
items={[ {
{ label: "Settings",
label: "Settings", onClick: () =>
onClick: () => navigate(routes.settings.path(["data", "entities", entity.name]), {
navigate(routes.settings.path(["data", "entities", entity.name]), { absolute: true
absolute: true })
}) }
} ]}
]} position="bottom-end"
position="bottom-end" >
> <IconButton Icon={TbDots} />
<IconButton Icon={TbDots} /> </Dropdown>
</Dropdown>
</>
} }
className="pl-3" className="pl-3"
> >
@@ -74,12 +72,11 @@ export function DataSchemaEntity({ params }) {
<Empty <Empty
title="Relations" title="Relations"
description="This will soon be available here. Meanwhile, check advanced settings." description="This will soon be available here. Meanwhile, check advanced settings."
buttonText="Advanced Settings" primary={{
buttonOnClick={() => children: "Advanced Settings",
navigate(routes.settings.path(["data", "relations"]), { onClick: () =>
absolute: true navigate(routes.settings.path(["data", "relations"]), { absolute: true })
}) }}
}
/> />
</AppShell.SectionHeaderAccordionItem> </AppShell.SectionHeaderAccordionItem>
<AppShell.SectionHeaderAccordionItem <AppShell.SectionHeaderAccordionItem
@@ -91,12 +88,13 @@ export function DataSchemaEntity({ params }) {
<Empty <Empty
title="Indices" title="Indices"
description="This will soon be available here. Meanwhile, check advanced settings." description="This will soon be available here. Meanwhile, check advanced settings."
buttonText="Advanced Settings" primary={{
buttonOnClick={() => children: "Advanced Settings",
navigate(routes.settings.path(["data", "indices"]), { onClick: () =>
absolute: true navigate(routes.settings.path(["data", "indices"]), {
}) absolute: true
} })
}}
/> />
</AppShell.SectionHeaderAccordionItem> </AppShell.SectionHeaderAccordionItem>
</div> </div>

View File

@@ -1,10 +1,7 @@
import { Suspense, lazy, useRef } from "react"; import { Suspense, lazy } from "react";
import { import { useBkndData } from "ui/client/schema/data/use-bknd-data";
CreateModal, import { Button } from "ui/components/buttons/Button";
type CreateModalRef import * as AppShell from "ui/layouts/AppShell/AppShell";
} from "ui/modules/data/components/schema/create-modal/CreateModal";
import { Button } from "../../components/buttons/Button";
import * as AppShell from "../../layouts/AppShell/AppShell";
const DataSchemaCanvas = lazy(() => const DataSchemaCanvas = lazy(() =>
import("ui/modules/data/components/canvas/DataSchemaCanvas").then((m) => ({ import("ui/modules/data/components/canvas/DataSchemaCanvas").then((m) => ({
@@ -13,18 +10,12 @@ const DataSchemaCanvas = lazy(() =>
); );
export function DataSchemaIndex() { export function DataSchemaIndex() {
const createModalRef = useRef<CreateModalRef>(null); const { $data } = useBkndData();
return ( return (
<> <>
<CreateModal ref={createModalRef} />
<AppShell.SectionHeader <AppShell.SectionHeader
right={ right={
<Button <Button type="button" variant="primary" onClick={$data.modals.createAny}>
type="button"
variant="primary"
onClick={() => createModalRef.current?.open()}
>
Create new Create new
</Button> </Button>
} }

View File

@@ -20,8 +20,10 @@ export function MediaRoot({ children }) {
Icon={IconPhoto} Icon={IconPhoto}
title="Media not enabled" title="Media not enabled"
description="Please enable media in the settings to continue." description="Please enable media in the settings to continue."
buttonText="Manage Settings" primary={{
buttonOnClick={() => navigate(app.getSettingsPath(["media"]))} children: "Manage Settings",
onClick: () => navigate(app.getSettingsPath(["media"]))
}}
/> />
); );
} }

View File

@@ -175,7 +175,10 @@ export function Setting<Schema extends TObject = any>({
<Empty <Empty
title="Not found" title="Not found"
description={`Configuration at path ${path.join(".")} doesn't exist.`} description={`Configuration at path ${path.join(".")} doesn't exist.`}
buttonText="Go back" primary={{
children: "Go back",
onClick: () => goBack()
}}
/> />
); );
} }

View File

@@ -52,6 +52,7 @@
"noSwitchDeclarations": "warn" "noSwitchDeclarations": "warn"
}, },
"complexity": { "complexity": {
"noUselessFragments": "warn",
"noStaticOnlyClass": "off", "noStaticOnlyClass": "off",
"noForEach": "off", "noForEach": "off",
"useLiteralKeys": "warn", "useLiteralKeys": "warn",