added easier access points to modify schema + added relation flip in dialog

This commit is contained in:
dswbx
2025-01-17 13:17:09 +01:00
parent 1625a0c7c0
commit a723d6f618
13 changed files with 157 additions and 48 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

@@ -83,6 +83,26 @@ const modals = {
bkndModals.open(bkndModals.ids.dataCreate, { bkndModals.open(bkndModals.ids.dataCreate, {
initialPath: ["entities", "entity"], initialPath: ["entities", "entity"],
initialState: { action: "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
}
}
}) })
}; };

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

@@ -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)}>
View <Button IconLeft={TbEye} size="small">
</Button> View
</Button>
</Link>
</> </>
) : ( ) : (
<div className="pl-2">- Select -</div> <div className="pl-2">- Select -</div>

View File

@@ -39,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))

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,14 +128,23 @@ export function StepRelation() {
disabled: data.target === name disabled: data.target === name
}))} }))}
/> />
<MantineSelect <div className="flex flex-col gap-1">
control={control} <MantineSelect
name="type" control={control}
onChange={() => setValue("config", {})} name="type"
label="Relation Type" onChange={() => setValue("config", {})}
data={Relations.map((r) => ({ value: r.type, label: r.label }))} label="Relation Type"
allowDeselect={false} data={Relations.map((r) => ({ value: r.type, label: r.label }))}
/> 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

@@ -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

@@ -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

@@ -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

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,25 +32,58 @@ 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 (
<> <>
<AppShell.SectionHeader <AppShell.SectionHeader
right={ right={
<Dropdown <>
items={[ <Dropdown
{ items={[
label: "Settings", {
onClick: () => label: "Data",
navigate(routes.settings.path(["data", "entities", entity.name]), { onClick: () =>
absolute: true navigate(routes.data.root() + routes.data.entity.list(entity.name), {
}) absolute: true
} })
]} },
position="bottom-end" {
> label: "Advanced Settings",
<IconButton Icon={TbDots} /> onClick: () =>
</Dropdown> 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({
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"
> >

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>
</> </>