Merge pull request #51 from bknd-io/feat/admin-data-improve

Admin UI improvements
This commit is contained in:
dswbx
2025-01-17 13:46:38 +01:00
committed by GitHub
26 changed files with 352 additions and 175 deletions

View File

@@ -157,8 +157,12 @@ export abstract class Field<
return this.config.virtual ?? false; return this.config.virtual ?? false;
} }
getLabel(): string { getLabel(options?: { fallback?: boolean }): string | undefined {
return this.config.label ?? snakeToPascalWithSpaces(this.name); return this.config.label
? this.config.label
: options?.fallback !== false
? snakeToPascalWithSpaces(this.name)
: undefined;
} }
getDescription(): string | undefined { getDescription(): string | undefined {

View File

@@ -33,6 +33,7 @@ export function BkndProvider({
useState<Pick<BkndContext, "version" | "schema" | "config" | "permissions">>(); useState<Pick<BkndContext, "version" | "schema" | "config" | "permissions">>();
const [fetched, setFetched] = useState(false); const [fetched, setFetched] = useState(false);
const errorShown = useRef<boolean>(); const errorShown = useRef<boolean>();
const [local_version, set_local_version] = useState(0);
const api = useApi(); const api = useApi();
async function reloadSchema() { async function reloadSchema() {
@@ -80,6 +81,7 @@ export function BkndProvider({
setSchema(schema); setSchema(schema);
setWithSecrets(_includeSecrets); setWithSecrets(_includeSecrets);
setFetched(true); setFetched(true);
set_local_version((v) => v + 1);
}); });
} }
@@ -98,7 +100,10 @@ export function BkndProvider({
const actions = getSchemaActions({ api, setSchema, reloadSchema }); const actions = getSchemaActions({ api, setSchema, reloadSchema });
return ( return (
<BkndContext.Provider value={{ ...schema, actions, requireSecrets, app, adminOverride }}> <BkndContext.Provider
value={{ ...schema, actions, requireSecrets, app, adminOverride }}
key={local_version}
>
{children} {children}
</BkndContext.Provider> </BkndContext.Provider>
); );

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,35 @@ export function useBkndData() {
}; };
} }
const modals = {
createAny: () => bkndModals.open(bkndModals.ids.dataCreate, {}),
createEntity: () =>
bkndModals.open(bkndModals.ids.dataCreate, {
initialPath: ["entities", "entity"],
initialState: { action: "entity" }
}),
createRelation: (rel: { source?: string; target?: string; type?: string }) =>
bkndModals.open(bkndModals.ids.dataCreate, {
initialPath: ["entities", "relation"],
initialState: {
action: "relation",
relations: {
create: [rel as any]
}
}
}),
createMedia: (entity?: string) =>
bkndModals.open(bkndModals.ids.dataCreate, {
initialPath: ["entities", "template-media"],
initialState: {
action: "template-media",
initial: {
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

@@ -4,15 +4,15 @@ import { twMerge } from "tailwind-merge";
import { Link } from "ui/components/wouter/Link"; import { Link } from "ui/components/wouter/Link";
const sizes = { const sizes = {
small: "px-2 py-1.5 rounded-md gap-1.5 text-sm", small: "px-2 py-1.5 rounded-md gap-1 text-sm",
default: "px-3 py-2.5 rounded-md gap-2.5", default: "px-3 py-2.5 rounded-md gap-1.5",
large: "px-4 py-3 rounded-md gap-3 text-lg" large: "px-4 py-3 rounded-md gap-2.5 text-lg"
}; };
const iconSizes = { const iconSizes = {
small: 15, small: 12,
default: 18, default: 16,
large: 22 large: 20
}; };
const styles = { const styles = {

View File

@@ -10,9 +10,9 @@ export type IconType =
const styles = { const styles = {
xs: { className: "p-0.5", size: 13 }, xs: { className: "p-0.5", size: 13 },
sm: { className: "p-0.5", size: 16 }, sm: { className: "p-0.5", size: 15 },
md: { className: "p-1", size: 20 }, md: { className: "p-1", size: 18 },
lg: { className: "p-1.5", size: 24 } lg: { className: "p-1.5", size: 22 }
} as const; } as const;
interface IconButtonProps extends ComponentPropsWithoutRef<"button"> { interface IconButtonProps extends ComponentPropsWithoutRef<"button"> {

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}
</Button>
</div> </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

@@ -0,0 +1,32 @@
import { useEffect, useRef } from "react";
export function useEffectOnce(effect: () => void | (() => void | undefined), deps: any[]): void {
const hasRunRef = useRef(false);
const savedDepsRef = useRef<any[] | undefined>(deps);
useEffect(() => {
const depsChanged = !hasRunRef.current || !areDepsEqual(savedDepsRef.current, deps);
if (depsChanged) {
hasRunRef.current = true;
savedDepsRef.current = deps;
return effect();
}
}, [deps]);
}
function areDepsEqual(prevDeps: any[] | undefined, nextDeps: any[]): boolean {
if (prevDeps && prevDeps.length === 0 && nextDeps.length === 0) {
return true;
}
if (!prevDeps && nextDeps.length === 0) {
return true;
}
if (!prevDeps || !nextDeps || prevDeps.length !== nextDeps.length) {
return false;
}
return prevDeps.every((dep, index) => Object.is(dep, nextDeps[index]));
}

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

@@ -9,6 +9,7 @@ import { useBknd } from "ui/client/bknd";
import { Button } from "ui/components/buttons/Button"; import { Button } from "ui/components/buttons/Button";
import * as Formy from "ui/components/form/Formy"; import * as Formy from "ui/components/form/Formy";
import { Popover } from "ui/components/overlay/Popover"; import { Popover } from "ui/components/overlay/Popover";
import { Link } from "ui/components/wouter/Link";
import { routes } from "ui/lib/routes"; import { routes } from "ui/lib/routes";
import { useLocation } from "wouter"; import { useLocation } from "wouter";
import { EntityTable } from "../EntityTable"; import { EntityTable } from "../EntityTable";
@@ -82,7 +83,9 @@ export function EntityRelationalFormField({
return ( return (
<Formy.Group> <Formy.Group>
<Formy.Label htmlFor={fieldApi.name}>{field.getLabel()}</Formy.Label> <Formy.Label htmlFor={fieldApi.name}>
{field.getLabel({ fallback: false }) ?? entity.label}
</Formy.Label>
<div <div
data-disabled={fetching || disabled ? 1 : undefined} data-disabled={fetching || disabled ? 1 : undefined}
className="data-[disabled]:opacity-70 data-[disabled]:pointer-events-none" className="data-[disabled]:opacity-70 data-[disabled]:pointer-events-none"
@@ -152,9 +155,11 @@ export function EntityRelationalFormField({
); );
})} })}
</div> </div>
<Button IconLeft={TbEye} onClick={handleViewItem} size="small"> <Link to={routes.data.entity.edit(entity.name, _value.id as any)}>
<Button IconLeft={TbEye} size="small">
View View
</Button> </Button>
</Link>
</> </>
) : ( ) : (
<div className="pl-2">- Select -</div> <div className="pl-2">- Select -</div>

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";
@@ -45,6 +39,7 @@ export type TFieldCreate = Static<typeof createFieldSchema>;
const createModalSchema = Type.Object( const createModalSchema = Type.Object(
{ {
action: schemaAction, action: schemaAction,
initial: Type.Optional(Type.Any()),
entities: Type.Optional( entities: Type.Optional(
Type.Object({ Type.Object({
create: Type.Optional(Type.Array(entitySchema)) create: Type.Optional(Type.Array(entitySchema))
@@ -67,17 +62,20 @@ 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 />
@@ -107,8 +105,16 @@ export const CreateModal = forwardRef<CreateModalRef>(function CreateModal(props
</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

@@ -10,6 +10,7 @@ import { ucFirst } from "core/utils";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { TbCirclesRelation, TbSettings } from "react-icons/tb"; import { TbCirclesRelation, TbSettings } 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 { useBkndData } from "ui/client/schema/data/use-bknd-data";
import { IconButton, type IconType } from "ui/components/buttons/IconButton"; import { IconButton, type IconType } from "ui/components/buttons/IconButton";
import { JsonViewer } from "ui/components/code/JsonViewer"; import { JsonViewer } from "ui/components/code/JsonViewer";
@@ -26,6 +27,7 @@ export function StepCreate() {
const [states, setStates] = useState<(boolean | string)[]>([]); const [states, setStates] = useState<(boolean | string)[]>([]);
const [submitting, setSubmitting] = useState(false); const [submitting, setSubmitting] = useState(false);
const $data = useBkndData(); const $data = useBkndData();
const b = useBknd();
const items: ActionItem[] = []; const items: ActionItem[] = [];
if (state.entities?.create) { if (state.entities?.create) {
@@ -90,7 +92,8 @@ export function StepCreate() {
states.every((s) => s === true) states.every((s) => s === true)
); );
if (items.length === states.length && states.every((s) => s === true)) { if (items.length === states.length && states.every((s) => s === true)) {
close(); b.actions.reload().then(close);
//close();
} else { } else {
setSubmitting(false); setSubmitting(false);
} }

View File

@@ -9,12 +9,15 @@ import {
registerCustomTypeboxKinds registerCustomTypeboxKinds
} from "core/utils"; } from "core/utils";
import { ManyToOneRelation, type RelationType, RelationTypes } from "data"; import { ManyToOneRelation, type RelationType, RelationTypes } from "data";
import { type ReactNode, useEffect } from "react"; import { type ReactNode, startTransition, useEffect } from "react";
import { type Control, type FieldValues, type UseFormRegister, useForm } from "react-hook-form"; import { type Control, type FieldValues, type UseFormRegister, useForm } from "react-hook-form";
import { TbRefresh } from "react-icons/tb";
import { useBknd } from "ui/client/bknd"; import { useBknd } from "ui/client/bknd";
import { Button } from "ui/components/buttons/Button";
import { MantineNumberInput } from "ui/components/form/hook-form-mantine/MantineNumberInput"; import { MantineNumberInput } from "ui/components/form/hook-form-mantine/MantineNumberInput";
import { MantineSelect } from "ui/components/form/hook-form-mantine/MantineSelect"; import { MantineSelect } from "ui/components/form/hook-form-mantine/MantineSelect";
import { useStepContext } from "ui/components/steps/Steps"; import { useStepContext } from "ui/components/steps/Steps";
import { useEvent } from "ui/hooks/use-event";
import { ModalBody, ModalFooter, type TCreateModalSchema } from "./CreateModal"; import { ModalBody, ModalFooter, type TCreateModalSchema } from "./CreateModal";
// @todo: check if this could become an issue // @todo: check if this could become an issue
@@ -63,7 +66,7 @@ type ComponentCtx<T extends FieldValues = FieldValues> = {
export function StepRelation() { export function StepRelation() {
const { config } = useBknd(); const { config } = useBknd();
const entities = config.data.entities; const entities = config.data.entities;
const { nextStep, stepBack, state, setState } = useStepContext<TCreateModalSchema>(); const { nextStep, stepBack, state, path, setState } = useStepContext<TCreateModalSchema>();
const { const {
register, register,
handleSubmit, handleSubmit,
@@ -93,6 +96,22 @@ export function StepRelation() {
} }
} }
const flip = useEvent(() => {
const { source, target } = data;
if (source && target) {
setValue("source", target);
setValue("target", source);
} else {
if (source) {
setValue("target", source);
setValue("source", null as any);
} else {
setValue("source", target);
setValue("target", null as any);
}
}
});
return ( return (
<> <>
<form onSubmit={handleSubmit(handleNext)}> <form onSubmit={handleSubmit(handleNext)}>
@@ -109,6 +128,7 @@ export function StepRelation() {
disabled: data.target === name disabled: data.target === name
}))} }))}
/> />
<div className="flex flex-col gap-1">
<MantineSelect <MantineSelect
control={control} control={control}
name="type" name="type"
@@ -117,6 +137,14 @@ export function StepRelation() {
data={Relations.map((r) => ({ value: r.type, label: r.label }))} data={Relations.map((r) => ({ value: r.type, label: r.label }))}
allowDeselect={false} allowDeselect={false}
/> />
{data.type && (
<div className="flex justify-center mt-1">
<Button size="small" IconLeft={TbRefresh} onClick={flip}>
Flip entities
</Button>
</div>
)}
</div>
<MantineSelect <MantineSelect
control={control} control={control}
allowDeselect={false} allowDeselect={false}
@@ -146,7 +174,7 @@ export function StepRelation() {
onClick: handleNext onClick: handleNext
}} }}
prev={{ onClick: stepBack }} prev={{ onClick: stepBack }}
debug={{ state, data }} debug={{ state, path, data }}
/> />
</form> </form>
</> </>

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

@@ -31,7 +31,7 @@ const schema = Type.Object({
type TCreateModalMediaSchema = Static<typeof schema>; type TCreateModalMediaSchema = Static<typeof schema>;
export function TemplateMediaComponent() { export function TemplateMediaComponent() {
const { stepBack, setState, state, nextStep } = useStepContext<TCreateModalSchema>(); const { stepBack, setState, state, path, nextStep } = useStepContext<TCreateModalSchema>();
const { const {
register, register,
handleSubmit, handleSubmit,
@@ -41,7 +41,7 @@ export function TemplateMediaComponent() {
control control
} = useForm({ } = useForm({
resolver: typeboxResolver(schema), resolver: typeboxResolver(schema),
defaultValues: Default(schema, {}) as TCreateModalMediaSchema defaultValues: Default(schema, state.initial ?? {}) as TCreateModalMediaSchema
}); });
const { config } = useBknd(); const { config } = useBknd();
@@ -134,7 +134,7 @@ export function TemplateMediaComponent() {
prev={{ prev={{
onClick: stepBack onClick: stepBack
}} }}
debug={{ state, data }} debug={{ state, path, data }}
/> />
</form> </form>
</> </>

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,6 +52,7 @@ export function DataRoot({ children }) {
<AppShell.Sidebar> <AppShell.Sidebar>
<AppShell.SectionHeader <AppShell.SectionHeader
right={ right={
<>
<SegmentedControl <SegmentedControl
data={[ data={[
{ value: "data", label: "Data" }, { value: "data", label: "Data" },
@@ -60,6 +61,10 @@ export function DataRoot({ children }) {
value={context} value={context}
onChange={handleSegmentChange} 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

@@ -41,6 +41,7 @@ export function DataEntityUpdate({ params }) {
with: local_relation_refs with: local_relation_refs
}, },
{ {
keepPreviousData: false,
revalidateOnFocus: false, revalidateOnFocus: false,
shouldRetryOnError: false shouldRetryOnError: false
} }
@@ -95,8 +96,7 @@ export function DataEntityUpdate({ params }) {
); );
} }
const makeKey = (key: string | number = "") => const makeKey = (key: string | number = "") => `${entity.name}_${entityId}_${String(key)}`;
`${params.entity.name}_${entityId}_${String(key)}`;
const fieldsDisabled = $q.isLoading || $q.isValidating || Form.state.isSubmitting; const fieldsDisabled = $q.isLoading || $q.isValidating || Form.state.isSubmitting;

View File

@@ -40,8 +40,8 @@ export function DataEntityList({ params }) {
useBrowserTitle(["Data", entity?.label ?? params.entity]); useBrowserTitle(["Data", entity?.label ?? params.entity]);
const [navigate] = useNavigate(); const [navigate] = useNavigate();
const search = useSearch(searchSchema, { const search = useSearch(searchSchema, {
select: entity?.getSelect(undefined, "table") ?? [], select: undefined,
sort: entity?.getDefaultSort() sort: undefined
}); });
const $q = useApiQuery( const $q = useApiQuery(
@@ -50,7 +50,7 @@ export function DataEntityList({ params }) {
select: search.value.select, select: search.value.select,
limit: search.value.perPage, limit: search.value.perPage,
offset: (search.value.page - 1) * search.value.perPage, offset: (search.value.page - 1) * search.value.perPage,
sort: search.value.sort sort: `${search.value.sort.dir === "asc" ? "" : "-"}${search.value.sort.by}`
}), }),
{ {
enabled: !!entity, enabled: !!entity,
@@ -94,6 +94,14 @@ export function DataEntityList({ params }) {
items={[ items={[
{ {
label: "Settings", label: "Settings",
onClick: () => navigate(routes.data.schema.entity(entity.name))
},
{
label: "Data Schema",
onClick: () => navigate(routes.data.schema.root())
},
{
label: "Advanced Settings",
onClick: () => onClick: () =>
navigate(routes.settings.path(["data", "entities", entity.name]), { navigate(routes.settings.path(["data", "entities", entity.name]), {
absolute: true absolute: true
@@ -123,7 +131,7 @@ export function DataEntityList({ params }) {
<EntityTable2 <EntityTable2
data={data ?? null} data={data ?? null}
entity={entity} entity={entity}
/*select={search.value.select}*/ select={search.value.select}
onClickRow={handleClickRow} onClickRow={handleClickRow}
page={search.value.page} page={search.value.page}
sort={search.value.sort} sort={search.value.sort}

View File

@@ -8,11 +8,12 @@ import { isDebug } from "core";
import type { Entity } from "data"; import type { Entity } from "data";
import { cloneDeep } from "lodash-es"; import { cloneDeep } from "lodash-es";
import { useRef, useState } from "react"; import { useRef, useState } from "react";
import { TbDots } from "react-icons/tb"; import { TbCirclesRelation, TbDots, TbPhoto, TbPlus } from "react-icons/tb";
import { useBkndData } from "ui/client/schema/data/use-bknd-data"; import { useBkndData } from "ui/client/schema/data/use-bknd-data";
import { Button } from "ui/components/buttons/Button"; import { Button } from "ui/components/buttons/Button";
import { IconButton } from "ui/components/buttons/IconButton"; import { IconButton } from "ui/components/buttons/IconButton";
import { Empty } from "ui/components/display/Empty"; import { Empty } from "ui/components/display/Empty";
import { Message } from "ui/components/display/Message";
import { JsonSchemaForm, type JsonSchemaFormRef } from "ui/components/form/json-schema"; import { JsonSchemaForm, type JsonSchemaFormRef } from "ui/components/form/json-schema";
import { Dropdown } from "ui/components/overlay/Dropdown"; import { Dropdown } from "ui/components/overlay/Dropdown";
import * as AppShell from "ui/layouts/AppShell/AppShell"; import * as AppShell from "ui/layouts/AppShell/AppShell";
@@ -24,7 +25,6 @@ import { EntityFieldsForm, type EntityFieldsFormRef } from "./forms/entity.field
export function DataSchemaEntity({ params }) { export function DataSchemaEntity({ params }) {
const { $data } = useBkndData(); const { $data } = useBkndData();
const [value, setValue] = useState("fields"); const [value, setValue] = useState("fields");
const fieldsRef = useRef<EntityFieldsFormRef>(null);
function toggle(value) { function toggle(value) {
return () => setValue(value); return () => setValue(value);
@@ -32,6 +32,9 @@ export function DataSchemaEntity({ params }) {
const [navigate] = useNavigate(); const [navigate] = useNavigate();
const entity = $data.entity(params.entity as string)!; const entity = $data.entity(params.entity as string)!;
if (!entity) {
return <Message.NotFound description={`Entity "${params.entity}" doesn't exist.`} />;
}
return ( return (
<> <>
@@ -41,7 +44,14 @@ export function DataSchemaEntity({ params }) {
<Dropdown <Dropdown
items={[ items={[
{ {
label: "Settings", label: "Data",
onClick: () =>
navigate(routes.data.root() + routes.data.entity.list(entity.name), {
absolute: true
})
},
{
label: "Advanced Settings",
onClick: () => onClick: () =>
navigate(routes.settings.path(["data", "entities", entity.name]), { navigate(routes.settings.path(["data", "entities", entity.name]), {
absolute: true absolute: true
@@ -52,6 +62,27 @@ export function DataSchemaEntity({ params }) {
> >
<IconButton Icon={TbDots} /> <IconButton Icon={TbDots} />
</Dropdown> </Dropdown>
<Dropdown
items={[
{
icon: TbCirclesRelation,
label: "Add relation",
onClick: () =>
$data.modals.createRelation({
target: entity.name,
type: "n:1"
})
},
{
icon: TbPhoto,
label: "Add media",
onClick: () => $data.modals.createMedia(entity.name)
}
]}
position="bottom-end"
>
<Button IconRight={TbPlus}>Add</Button>
</Dropdown>
</> </>
} }
className="pl-3" className="pl-3"
@@ -74,12 +105,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 +121,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",
onClick: () =>
navigate(routes.settings.path(["data", "indices"]), { navigate(routes.settings.path(["data", "indices"]), {
absolute: true 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

@@ -55,8 +55,10 @@ export function FlowsEmpty() {
title="No flow selected" title="No flow selected"
description="Please select a flow from the left sidebar or create a new one description="Please select a flow from the left sidebar or create a new one
to continue." to continue."
buttonText="Create Flow" primary={{
buttonOnClick={() => navigate(app.getSettingsPath(["flows"]))} children: "Create Flow",
onClick: () => navigate(app.getSettingsPath(["flows"]))
}}
/> />
</main> </main>
</> </>

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

@@ -1,17 +1,18 @@
import { IconHome } from "@tabler/icons-react"; import { IconHome } from "@tabler/icons-react";
import { useEffect } from "react"; import { useEffect } from "react";
import { useAuth } from "ui/client"; import { useAuth } from "ui/client";
import { useEffectOnce } from "ui/hooks/use-effect";
import { Empty } from "../components/display/Empty"; import { Empty } from "../components/display/Empty";
import { useBrowserTitle } from "../hooks/use-browser-title"; import { useBrowserTitle } from "../hooks/use-browser-title";
import * as AppShell from "../layouts/AppShell/AppShell"; import * as AppShell from "../layouts/AppShell/AppShell";
import { useNavigate } from "../lib/routes"; import { useNavigate } from "../lib/routes";
export const Root = ({ children }) => { export const Root = ({ children }) => {
const { verify } = useAuth(); const { verify, user } = useAuth();
useEffect(() => { useEffectOnce(() => {
verify(); verify();
}, []); }, [user?.id]);
return ( return (
<AppShell.Root> <AppShell.Root>

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

@@ -7,12 +7,11 @@ import { StorageLocalAdapter } from "./src/media/storage/adapters/StorageLocalAd
registries.media.register("local", StorageLocalAdapter); registries.media.register("local", StorageLocalAdapter);
const run_example: string | boolean = false; const example = import.meta.env.VITE_EXAMPLE;
//run_example = "ex-admin-rich";
const credentials = run_example const credentials = example
? { ? {
url: `file:.configs/${run_example}.db` url: `file:.configs/${example}.db`
//url: ":memory:" //url: ":memory:"
} }
: { : {
@@ -26,10 +25,8 @@ if (!credentials.url) {
const connection = new LibsqlConnection(createClient(credentials)); const connection = new LibsqlConnection(createClient(credentials));
let initialConfig: any = undefined; let initialConfig: any = undefined;
if (run_example) { if (example) {
const { version, ...config } = JSON.parse( const { version, ...config } = JSON.parse(await readFile(`.configs/${example}.json`, "utf-8"));
await readFile(`.configs/${run_example}.json`, "utf-8")
);
initialConfig = config; initialConfig = config;
} }

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",