diff --git a/contracts/api/v2/openapi.json b/contracts/api/v2/openapi.json index e5929e3cc5..40913861b7 100644 --- a/contracts/api/v2/openapi.json +++ b/contracts/api/v2/openapi.json @@ -16879,6 +16879,10 @@ }, "type": "array" }, + "ordered": { + "description": "The order of a multi-select's values matters. The form shows the chosen values as a list that can be put in order.", + "type": "boolean" + }, "placeholder": { "type": "string" }, @@ -16919,6 +16923,14 @@ "AdminPluginFormSection": { "additionalProperties": false, "properties": { + "add_group": { + "description": "Sections with the same add_group are the slots of one list. The form shows the slots in use and a button that reveals the next.", + "type": "string" + }, + "add_label": { + "description": "The text of the button that reveals the next slot.", + "type": "string" + }, "collapsed_default": { "type": "boolean" }, diff --git a/go.mod b/go.mod index 5a058f05ed..517bb734f7 100644 --- a/go.mod +++ b/go.mod @@ -175,4 +175,4 @@ require ( replace github.com/zishang520/webtransport-go => ./internal/compat/zishang520-webtransport-go -replace github.com/Silo-Server/silo-plugin-sdk => github.com/grtn91/silo-plugin-sdk v0.32.2-0.20261111162054-6349f38bd415 +replace github.com/Silo-Server/silo-plugin-sdk => github.com/grtn91/silo-plugin-sdk v0.32.2-0.20261111220705-65c53aada4d3 diff --git a/go.sum b/go.sum index 99418f9da4..e77ac240ac 100644 --- a/go.sum +++ b/go.sum @@ -151,8 +151,8 @@ github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aN github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk= github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs= -github.com/grtn91/silo-plugin-sdk v0.32.2-0.20261111162054-6349f38bd415 h1:Hd76ckWisVLd+q/+SCyVKACQrq128i+gQS1b+p3IyyE= -github.com/grtn91/silo-plugin-sdk v0.32.2-0.20261111162054-6349f38bd415/go.mod h1:+r4X2TAiB9Gk22sUj1gFWUj65lll1P1/dMS+Ncvy3Y0= +github.com/grtn91/silo-plugin-sdk v0.32.2-0.20261111220705-65c53aada4d3 h1:Hm3wz12BcA9RxImughmC1VLmu5fGJ8JAV2gsshyIGUA= +github.com/grtn91/silo-plugin-sdk v0.32.2-0.20261111220705-65c53aada4d3/go.mod h1:+r4X2TAiB9Gk22sUj1gFWUj65lll1P1/dMS+Ncvy3Y0= github.com/h2non/bimg v1.1.9 h1:WH20Nxko9l/HFm4kZCA3Phbgu2cbHvYzxwxn9YROEGg= github.com/h2non/bimg v1.1.9/go.mod h1:R3+UiYwkK4rQl6KVFTOFJHitgLbZXBZNFh2cv3AEbp8= github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k= diff --git a/internal/apiv2/admin_plugin_installations.go b/internal/apiv2/admin_plugin_installations.go index 8b0e3b86b2..a7b1133eff 100644 --- a/internal/apiv2/admin_plugin_installations.go +++ b/internal/apiv2/admin_plugin_installations.go @@ -99,6 +99,7 @@ type AdminPluginFormField struct { ShowWhen []AdminFormCondition `json:"show_when"` Validation *AdminPluginFormValidation `json:"validation,omitempty"` ExclusiveGroupField string `json:"exclusive_group_field,omitempty"` + Ordered bool `json:"ordered,omitempty" doc:"The order of a multi-select's values matters. The form shows the chosen values as a list that can be put in order."` } type AdminPluginFormSection struct { Key string `json:"key"` @@ -108,6 +109,8 @@ type AdminPluginFormSection struct { CollapsedDefault bool `json:"collapsed_default"` FieldKeys []string `json:"field_keys"` ShowWhen []AdminFormCondition `json:"show_when"` + AddGroup string `json:"add_group,omitempty" doc:"Sections with the same add_group are the slots of one list. The form shows the slots in use and a button that reveals the next."` + AddLabel string `json:"add_label,omitempty" doc:"The text of the button that reveals the next slot."` } type AdminPluginForm struct { Fields []AdminPluginFormField `json:"fields"` @@ -285,7 +288,7 @@ func adminPluginFormOf(f *plugins.AdminFormView) (*AdminPluginForm, error) { } out := &AdminPluginForm{Fields: make([]AdminPluginFormField, 0, len(f.Fields)), SubmitLabel: f.SubmitLabel, Sections: make([]AdminPluginFormSection, 0, len(f.Sections))} for _, fld := range f.Fields { - item := AdminPluginFormField{Key: fld.Key, Label: fld.Label, Description: fld.Description, Control: fld.Control, Placeholder: fld.Placeholder, Required: fld.Required, Secret: fld.Secret, Multiline: fld.Multiline, Options: make([]AdminFormOption, 0, len(fld.Options)), Rows: fld.Rows, DynamicOptions: fld.DynamicOptions, ShowWhen: adminPluginFormConditionsOf(fld.ShowWhen), ExclusiveGroupField: fld.ExclusiveGroupField} + item := AdminPluginFormField{Key: fld.Key, Label: fld.Label, Description: fld.Description, Control: fld.Control, Placeholder: fld.Placeholder, Required: fld.Required, Secret: fld.Secret, Multiline: fld.Multiline, Options: make([]AdminFormOption, 0, len(fld.Options)), Rows: fld.Rows, DynamicOptions: fld.DynamicOptions, ShowWhen: adminPluginFormConditionsOf(fld.ShowWhen), ExclusiveGroupField: fld.ExclusiveGroupField, Ordered: fld.Ordered} if fld.DefaultValue != nil { raw, err := json.Marshal(fld.DefaultValue) if err != nil { @@ -302,7 +305,7 @@ func adminPluginFormOf(f *plugins.AdminFormView) (*AdminPluginForm, error) { out.Fields = append(out.Fields, item) } for _, s := range f.Sections { - out.Sections = append(out.Sections, AdminPluginFormSection{Key: s.Key, Title: s.Title, Description: s.Description, Collapsible: s.Collapsible, CollapsedDefault: s.CollapsedDefault, FieldKeys: NonNil(s.FieldKeys), ShowWhen: adminPluginFormConditionsOf(s.ShowWhen)}) + out.Sections = append(out.Sections, AdminPluginFormSection{Key: s.Key, Title: s.Title, Description: s.Description, Collapsible: s.Collapsible, CollapsedDefault: s.CollapsedDefault, FieldKeys: NonNil(s.FieldKeys), ShowWhen: adminPluginFormConditionsOf(s.ShowWhen), AddGroup: s.AddGroup, AddLabel: s.AddLabel}) } return out, nil } diff --git a/internal/plugins/config_schema_view.go b/internal/plugins/config_schema_view.go index c788d8807c..a02c8a11b0 100644 --- a/internal/plugins/config_schema_view.go +++ b/internal/plugins/config_schema_view.go @@ -39,6 +39,8 @@ type AdminFormFieldView struct { ShowWhen []AdminFormConditionView `json:"show_when,omitempty"` Validation *AdminFormValidationView `json:"validation,omitempty"` ExclusiveGroupField string `json:"exclusive_group_field,omitempty"` + // Ordered says the order of a multi-select's values matters. + Ordered bool `json:"ordered,omitempty"` } type AdminFormOptionView struct { @@ -70,6 +72,10 @@ type AdminFormSectionView struct { CollapsedDefault bool `json:"collapsed_default"` FieldKeys []string `json:"field_keys"` ShowWhen []AdminFormConditionView `json:"show_when,omitempty"` + // AddGroup names the list this section is one slot of, and AddLabel the + // button that reveals the next slot. Empty for an ordinary section. + AddGroup string `json:"add_group,omitempty"` + AddLabel string `json:"add_label,omitempty"` } func ConfigSchemaViews(schemas []*pluginv1.ConfigSchema) []ConfigSchemaView { @@ -122,7 +128,7 @@ func AdminFormViewFromProto(form *pluginv1.AdminFormDescriptor) *AdminFormView { Placeholder: field.GetPlaceholder(), Required: field.GetRequired(), Secret: field.GetSecret(), Multiline: field.GetMultiline(), DefaultValue: defaultValue, Options: options, Rows: field.GetRows(), DynamicOptions: field.GetDynamicOptions(), ShowWhen: adminFormConditionViews(field.GetShowWhen()), - Validation: validation, ExclusiveGroupField: field.GetExclusiveGroupField(), + Validation: validation, ExclusiveGroupField: field.GetExclusiveGroupField(), Ordered: field.GetOrdered(), }) } sections := make([]AdminFormSectionView, 0, len(form.GetSections())) @@ -134,6 +140,7 @@ func AdminFormViewFromProto(form *pluginv1.AdminFormDescriptor) *AdminFormView { Key: section.GetKey(), Title: section.GetTitle(), Description: section.GetDescription(), Collapsible: section.GetCollapsible(), CollapsedDefault: section.GetCollapsedDefault(), FieldKeys: append([]string(nil), section.GetFieldKeys()...), ShowWhen: adminFormConditionViews(section.GetShowWhen()), + AddGroup: section.GetAddGroup(), AddLabel: section.GetAddLabel(), }) } return &AdminFormView{Fields: fields, SubmitLabel: form.GetSubmitLabel(), Sections: sections} diff --git a/web/src/api/types.ts b/web/src/api/types.ts index 179b506527..6a029542f8 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -3935,6 +3935,10 @@ export interface PluginAdminFormSection { collapsed_default: boolean; field_keys: string[]; show_when?: PluginAdminFormCondition[]; + /** Sections with the same add_group are the slots of one list the admin grows. */ + add_group?: string; + /** The text of the button that reveals the next slot. */ + add_label?: string; } export interface PluginAdminFormField { @@ -3953,6 +3957,8 @@ export interface PluginAdminFormField { show_when?: PluginAdminFormCondition[]; validation?: PluginAdminFormValidation; exclusive_group_field?: string; + /** The order of a multi-select's values matters; the form lets the admin arrange them. */ + ordered?: boolean; /** * Names a host-known value this field can be populated from in one click. * Used by autoscan source config so a path field can be filled from Silo's diff --git a/web/src/api/v2/schema.ts b/web/src/api/v2/schema.ts index a62d831a87..30860c36dc 100644 --- a/web/src/api/v2/schema.ts +++ b/web/src/api/v2/schema.ts @@ -19932,6 +19932,8 @@ export interface components { label: string; multiline: boolean; options: components["schemas"]["AdminFormOption"][]; + /** @description The order of a multi-select's values matters. The form shows the chosen values as a list that can be put in order. */ + ordered?: boolean; placeholder?: string; required: boolean; /** Format: int32 */ @@ -19941,6 +19943,10 @@ export interface components { validation?: components["schemas"]["AdminPluginFormValidation"]; }; AdminPluginFormSection: { + /** @description Sections with the same add_group are the slots of one list. The form shows the slots in use and a button that reveals the next. */ + add_group?: string; + /** @description The text of the button that reveals the next slot. */ + add_label?: string; collapsed_default: boolean; collapsible: boolean; description?: string; diff --git a/web/src/components/admin/plugins/OrderedMultiSelect.tsx b/web/src/components/admin/plugins/OrderedMultiSelect.tsx new file mode 100644 index 0000000000..88f87e5a0f --- /dev/null +++ b/web/src/components/admin/plugins/OrderedMultiSelect.tsx @@ -0,0 +1,143 @@ +import { DndContext } from "@dnd-kit/core"; +import { SortableContext, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable"; +import { CSS } from "@dnd-kit/utilities"; +import { GripVertical, Plus, X } from "lucide-react"; + +import { Button } from "@/components/ui/button"; +import { useSortableList } from "@/hooks/useSortableList"; +import { useT } from "@/i18n"; + +import type { SchemaOption } from "./schemaFormUtils"; + +function identity(value: string): string { + return value; +} + +function SortableValue({ + value, + label, + position, + disabled, + onRemove, +}: { + value: string; + label: string; + position: number; + disabled: boolean; + onRemove: () => void; +}) { + const t = useT(); + const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ + id: value, + disabled, + }); + const style: React.CSSProperties = { + transform: CSS.Transform.toString(transform), + transition, + opacity: isDragging ? 0.4 : 1, + }; + return ( +
  • + + {position} + {label} + +
  • + ); +} + +/** + * A multi-select whose order matters. The chosen values are a list that can + * be put in order by dragging, or with the keyboard on a row's handle; the + * options not chosen yet are buttons that add to the end of it. + */ +export function OrderedMultiSelect({ + options, + selected, + onChange, + disabled = false, + describedBy, +}: { + options: SchemaOption[]; + selected: string[]; + onChange: (next: string[]) => void; + disabled?: boolean; + describedBy?: string; +}) { + const { sensors, collisionDetection, handleDragEnd } = useSortableList( + selected, + identity, + onChange, + ); + // A chosen value the options no longer list keeps its place, shown as it is stored. + const labels = new Map(options.map((option) => [option.value, option.label])); + const unchosen = options.filter((option) => !selected.includes(option.value)); + + return ( +
    + {selected.length > 0 ? ( + + +
      + {selected.map((value, index) => ( + onChange(selected.filter((other) => other !== value))} + /> + ))} +
    +
    +
    + ) : null} + {unchosen.length > 0 ? ( +
    + {unchosen.map((option) => ( + + ))} +
    + ) : null} +
    + ); +} diff --git a/web/src/components/admin/plugins/SchemaForm.test.tsx b/web/src/components/admin/plugins/SchemaForm.test.tsx index 7e05c6df1e..546c9f6896 100644 --- a/web/src/components/admin/plugins/SchemaForm.test.tsx +++ b/web/src/components/admin/plugins/SchemaForm.test.tsx @@ -281,3 +281,119 @@ describe("SchemaForm empty-string select options", () => { expect(onChange).toHaveBeenLastCalledWith({ prompt: "" }); }); }); + +describe("SchemaForm add groups", () => { + const slotted: PluginAdminForm = { + fields: [ + field("slot_1_name", "First name", "TEXT"), + field("slot_2_name", "Second name", "TEXT"), + ], + sections: [1, 2].map((n) => ({ + key: `slot_${n}`, + title: `Slot ${n}`, + collapsible: false, + collapsed_default: false, + field_keys: [`slot_${n}_name`], + add_group: "slots", + add_label: "Add slot", + })), + }; + + it("reveals the next slot with the add button, then drops the button", () => { + render(); + expect(screen.getByText("First name")).toBeInTheDocument(); + expect(screen.queryByText("Second name")).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Add slot" })); + expect(screen.getByText("Second name")).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Add slot" })).not.toBeInTheDocument(); + }); + + it("moves a slot's values up and down", () => { + const onChange = vi.fn(); + render( + , + ); + expect(screen.getByText("Slot 1: one")).toBeInTheDocument(); + const up = screen.getAllByRole("button", { name: "Move up" }); + const down = screen.getAllByRole("button", { name: "Move down" }); + expect(up[0]).toBeDisabled(); + expect(down[1]).toBeDisabled(); + fireEvent.click(down[0]!); + expect(onChange).toHaveBeenCalledWith({ slot_1_name: "two", slot_2_name: "one" }); + }); + + it("folds a slot with a click on its header, even when the form opens its sections", () => { + const foldable: PluginAdminForm = { + ...slotted, + sections: slotted.sections!.map((section) => ({ ...section, collapsible: true })), + }; + render(); + expect(screen.getByText("First name")).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Slot 1" })); + expect(screen.queryByText("First name")).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Slot 1" })); + expect(screen.getByText("First name")).toBeInTheDocument(); + }); + + it("removes a slot: the ones after it move up and the list gets shorter", () => { + const onChange = vi.fn(); + const { rerender } = render( + , + ); + fireEvent.click(screen.getAllByRole("button", { name: "Delete" })[0]!); + expect(onChange).toHaveBeenCalledWith({ slot_1_name: "two" }); + rerender( + , + ); + expect(screen.queryByText("Second name")).not.toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Add slot" })).toBeInTheDocument(); + }); + + it("shows a slot that already holds a value", () => { + render(); + expect(screen.getByText("Second name")).toBeInTheDocument(); + }); +}); + +describe("SchemaForm ordered multi-select", () => { + const ordered: PluginAdminForm = { + fields: [ + field("folders", "Folders", "MULTI_SELECT", { + ordered: true, + options: [ + { value: "/a", label: "Disk A" }, + { value: "/b", label: "Disk B" }, + { value: "/c", label: "Disk C" }, + ], + }), + ], + }; + + it("lists the chosen values in their order and adds a value at the end", () => { + const onChange = vi.fn(); + render( + , + ); + const rows = screen.getAllByRole("listitem").map((row) => row.textContent); + expect(rows).toEqual(["1Disk C", "2Disk A"]); + fireEvent.click(screen.getByRole("button", { name: "Disk B" })); + expect(onChange).toHaveBeenCalledWith({ folders: ["/c", "/a", "/b"] }); + }); + + it("removes a chosen value", () => { + const onChange = vi.fn(); + render( + , + ); + fireEvent.click(screen.getAllByRole("button", { name: "Delete" })[0]!); + expect(onChange).toHaveBeenCalledWith({ folders: ["/a"] }); + }); +}); diff --git a/web/src/components/admin/plugins/SchemaForm.tsx b/web/src/components/admin/plugins/SchemaForm.tsx index 46563e7282..bdd22bdabb 100644 --- a/web/src/components/admin/plugins/SchemaForm.tsx +++ b/web/src/components/admin/plugins/SchemaForm.tsx @@ -1,8 +1,14 @@ import { useEffect, useMemo, useRef, useState } from "react"; -import { Loader2 } from "lucide-react"; +import { ArrowDown, ArrowUp, Loader2, Plus, Trash2 } from "lucide-react"; import type { PluginAdminForm, PluginAdminFormField, PluginAdminFormSection } from "@/api/types"; +import { + Accordion, + AccordionContent, + AccordionItem, + AccordionTrigger, +} from "@/components/ui/accordion"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -18,9 +24,13 @@ import { Skeleton } from "@/components/ui/skeleton"; import { Switch } from "@/components/ui/switch"; import { useT } from "@/i18n"; +import { OrderedMultiSelect } from "./OrderedMultiSelect"; import { + addSlots, effectiveValue, evaluateShowWhen, + removeSlotValues, + swapSlotValues, validateSchemaValues, type SchemaOption, } from "./schemaFormUtils"; @@ -121,6 +131,10 @@ function SchemaFormSection({ forceOpen, expanded, renderFields, + addButton, + onMoveUp, + onMoveDown, + onRemove, }: { section: PluginAdminFormSection; values: Record; @@ -128,6 +142,13 @@ function SchemaFormSection({ forceOpen: boolean; expanded: boolean; renderFields: (keys: string[]) => React.ReactNode; + /** The button that reveals the next slot, when this is a list's last shown one. */ + addButton?: React.ReactNode; + /** Trade places with the slot before or after; set only for a list's slots that have one. */ + onMoveUp?: () => void; + onMoveDown?: () => void; + /** Remove this slot from its list; set only for a list's slots. */ + onRemove?: () => void; }) { // null = operator hasn't toggled; fall back to collapsed_default. forceOpen // (the section has unresolved errors) always wins so setup can't be hidden. @@ -138,25 +159,117 @@ function SchemaFormSection({ return null; } - const collapsible = section.collapsible && !expanded; + // A list's slots stay collapsible in a form that opens its sections: a + // long list is the reason to fold them. + const isSlot = Boolean(section.add_group); + const collapsible = section.collapsible && (!expanded || isSlot); + // A slot whose first field is its name shows the name in its header, so a + // folded slot can be told from the others. + const first = isSlot ? fields.find((field) => field.key === section.field_keys[0]) : undefined; + const firstValue = first?.control === "TEXT" ? values[first.key] : undefined; + const slotName = typeof firstValue === "string" ? firstValue.trim() : ""; + const heading = slotName ? `${section.title}: ${slotName}` : section.title; const open = forceOpen || (userOpen ?? !section.collapsed_default); const showFields = collapsible ? open : true; + const moveButtons = isSlot ? ( + <> + + + + + ) : null; + + // A list's slot folds as an accordion: the whole header is the trigger. + // The move buttons sit beside the trigger, since a button cannot hold one. + if (isSlot && collapsible) { + return ( + <> +
    + setUserOpen(value === section.key)} + > + +
    + + + {heading} + {section.description ? ( + + {section.description} + + ) : null} + + + {moveButtons} +
    + + {renderFields(section.field_keys)} + +
    +
    +
    + {addButton} + + ); + } + return ( -
    -
    -
    - - + <> +
    +
    +
    + + +
    +
    + {moveButtons} + {collapsible ? ( + + ) : null} +
    - {collapsible ? ( - - ) : null} -
    - {showFields ? renderFields(section.field_keys) : null} -
    + {showFields ? renderFields(section.field_keys) : null} + + {addButton} + ); } @@ -175,6 +288,12 @@ export function SchemaForm({ }: Props) { const t = useT(); const hidden = useMemo(() => new Set(hiddenKeys), [hiddenKeys]); + // How many slots of each add group the admin has asked for with its button. + const [revealedSlots, setRevealedSlots] = useState>({}); + const slots = useMemo( + () => addSlots(descriptor, values, revealedSlots), + [descriptor, values, revealedSlots], + ); const byKey = useMemo(() => { const map = new Map(); for (const field of descriptor.fields) { @@ -276,6 +395,17 @@ export function SchemaForm({ } const current = effectiveValue(field, values); const selected = Array.isArray(current) ? current.map((v) => String(v)) : []; + if (field.ordered && (options.length > 0 || selected.length > 0)) { + return ( + setField(field.key, next)} + disabled={locked} + describedBy={describedBy} + /> + ); + } if (options.length === 0) { return (

    @@ -438,6 +568,54 @@ export function SchemaForm({ return

    {nodes}
    ; } + // The button after a list's last shown slot. It reveals the next one. + function renderAddButton(section: PluginAdminFormSection): React.ReactNode { + const add = slots.addAfter.get(section.key); + if (!add) return null; + const shown = (descriptor.sections ?? []).filter( + (candidate) => candidate.add_group === add.group && !slots.hidden.has(candidate.key), + ).length; + return ( +
    + +
    + ); + } + + // Trades a slot's values with the shown slot before (-1) or after (+1) it + // in its list. Undefined when there is none. + function slotMover(section: PluginAdminFormSection, step: -1 | 1): (() => void) | undefined { + if (!section.add_group) return undefined; + const shown = (descriptor.sections ?? []).filter( + (candidate) => candidate.add_group === section.add_group && !slots.hidden.has(candidate.key), + ); + const other = shown[shown.indexOf(section) + step]; + if (!other) return undefined; + return () => onChange(swapSlotValues(section, other, values)); + } + + // Removes a slot from its list: the shown slots after it move up, and the + // list shows one slot fewer unless this was its only one. + function slotRemover(section: PluginAdminFormSection): (() => void) | undefined { + const group = section.add_group; + if (!group) return undefined; + const shown = (descriptor.sections ?? []).filter( + (candidate) => candidate.add_group === group && !slots.hidden.has(candidate.key), + ); + return () => { + setRevealedSlots((current) => ({ ...current, [group]: Math.max(1, shown.length - 1) })); + onChange(removeSlotValues(shown, shown.indexOf(section), values)); + }; + } + const sections = descriptor.sections ?? []; const groupedKeys = new Set(); for (const section of sections) { @@ -458,7 +636,9 @@ export function SchemaForm({
    {ungroupedFields.length > 0 ? renderFieldList(ungroupedFields) : null} {sections - .filter((section) => resolveKeys(section.field_keys).length > 0) + .filter( + (section) => resolveKeys(section.field_keys).length > 0 && !slots.hidden.has(section.key), + ) .map((section) => ( mergedErrors[key] != null)} expanded={expandSections} renderFields={(keys) => renderFieldList(resolveKeys(keys))} + addButton={renderAddButton(section)} + onMoveUp={slotMover(section, -1)} + onMoveDown={slotMover(section, 1)} + onRemove={slotRemover(section)} /> ))}
    diff --git a/web/src/components/admin/plugins/schemaFormUtils.test.ts b/web/src/components/admin/plugins/schemaFormUtils.test.ts index 3376e024b2..e69782dc9b 100644 --- a/web/src/components/admin/plugins/schemaFormUtils.test.ts +++ b/web/src/components/admin/plugins/schemaFormUtils.test.ts @@ -3,6 +3,9 @@ import type { PluginAdminForm, PluginAdminFormField } from "@/api/types"; import { describe, expect, it } from "vitest"; import { + addSlots, + removeSlotValues, + swapSlotValues, buildSchemaValues, coerceFieldValue, parseFieldTypes, @@ -297,3 +300,90 @@ describe("buildSchemaValues explicit clears", () => { }); }); }); + +describe("addSlots", () => { + const slotSection = (n: number) => ({ + key: `group_${n}`, + title: `Group ${n}`, + collapsible: false, + collapsed_default: false, + field_keys: [`group_${n}_name`, `group_${n}_folders`, `group_${n}_mode`], + add_group: "groups", + add_label: "Add group", + }); + const slotFields = (n: number): PluginAdminFormField[] => [ + field(`group_${n}_name`, "Name", "TEXT"), + field(`group_${n}_folders`, "Folders", "MULTI_SELECT", { dynamic_options: true }), + field(`group_${n}_mode`, "Mode", "SELECT", { + default_value: "in_order", + options: [ + { value: "in_order", label: "In order" }, + { value: "distribute", label: "Most free space" }, + ], + }), + ]; + const slotted: PluginAdminForm = { + fields: [1, 2, 3].flatMap(slotFields), + sections: [1, 2, 3].map(slotSection), + }; + + it("shows only the first slot of an empty list, followed by the add button", () => { + const slots = addSlots(slotted, {}); + expect([...slots.hidden]).toEqual(["group_2", "group_3"]); + expect(slots.addAfter.get("group_1")).toEqual({ group: "groups", label: "Add group" }); + }); + + it("shows every slot up to the last one in use", () => { + const slots = addSlots(slotted, { group_2_folders: ["/a"] }); + expect([...slots.hidden]).toEqual(["group_3"]); + expect([...slots.addAfter.keys()]).toEqual(["group_2"]); + }); + + it("does not count a default value or an empty one as use", () => { + const slots = addSlots(slotted, { + group_2_mode: "in_order", + group_3_name: " ", + group_3_folders: [], + }); + expect([...slots.hidden]).toEqual(["group_2", "group_3"]); + }); + + it("shows the slots the admin asked for and drops the button on the last", () => { + expect([...addSlots(slotted, {}, { groups: 2 }).hidden]).toEqual(["group_3"]); + const all = addSlots(slotted, {}, { groups: 3 }); + expect(all.hidden.size).toBe(0); + expect(all.addAfter.size).toBe(0); + }); +}); + +describe("slot values", () => { + const slots = [1, 2, 3].map((n) => ({ field_keys: [`g${n}_name`, `g${n}_folders`] })); + const values = { + g1_name: "one", + g1_folders: ["/a"], + g2_name: "two", + g3_name: "three", + g3_folders: ["/c"], + other: true, + }; + + it("trades two slots' values by field position", () => { + expect(swapSlotValues(slots[0]!, slots[1]!, values)).toEqual({ + ...values, + g1_name: "two", + g1_folders: undefined, + g2_name: "one", + g2_folders: ["/a"], + }); + }); + + it("removes a slot by moving the later ones up and emptying the last", () => { + expect(removeSlotValues(slots, 1, values)).toEqual({ + g1_name: "one", + g1_folders: ["/a"], + g2_name: "three", + g2_folders: ["/c"], + other: true, + }); + }); +}); diff --git a/web/src/components/admin/plugins/schemaFormUtils.ts b/web/src/components/admin/plugins/schemaFormUtils.ts index 9363b63ac1..29ebc5868f 100644 --- a/web/src/components/admin/plugins/schemaFormUtils.ts +++ b/web/src/components/admin/plugins/schemaFormUtils.ts @@ -271,6 +271,108 @@ export function fieldIsVisible( ); } +export type AddSlots = { + /** Keys of the slot sections the form does not show yet. */ + hidden: Set; + /** The slot section each list's add button follows, by section key. */ + addAfter: Map; +}; + +function slotInUse( + descriptor: PluginAdminForm, + fieldKeys: string[], + values: Record, +): boolean { + return fieldKeys.some((key) => { + const value = values[key]; + if (isEmpty(value)) return false; + const field = descriptor.fields.find((candidate) => candidate.key === key); + return stringify(value) !== stringify(field?.default_value); + }); +} + +/** + * Which slots of the form's add groups show. Sections with the same + * `add_group` are the slots of one list. A list shows its first slot, every + * slot up to the last one holding a value other than its fields' defaults, + * and as many as `revealed` says the admin asked for. While a slot is left, + * the last shown one is followed by the add button. + */ +export function addSlots( + descriptor: PluginAdminForm, + values: Record, + revealed: Record = {}, +): AddSlots { + const groups = new Map>(); + for (const section of descriptor.sections ?? []) { + if (!section.add_group) continue; + const slots = groups.get(section.add_group) ?? []; + slots.push(section); + groups.set(section.add_group, slots); + } + const out: AddSlots = { hidden: new Set(), addAfter: new Map() }; + for (const [group, slots] of groups) { + let shown = Math.max(1, revealed[group] ?? 0); + slots.forEach((slot, index) => { + if (slotInUse(descriptor, slot.field_keys, values)) shown = Math.max(shown, index + 1); + }); + shown = Math.min(shown, slots.length); + for (const slot of slots.slice(shown)) out.hidden.add(slot.key); + const last = slots[shown - 1]; + if (last && shown < slots.length) { + out.addAfter.set(last.key, { group, label: last.add_label || "+" }); + } + } + return out; +} + +/** + * The values after two slots of a list trade places. Slots declare the same + * fields in the same order, so each field's value moves to the field at the + * same position in the other slot. + */ +export function swapSlotValues( + a: { field_keys: string[] }, + b: { field_keys: string[] }, + values: Record, +): Record { + const next = { ...values }; + const count = Math.min(a.field_keys.length, b.field_keys.length); + for (let i = 0; i < count; i++) { + const keyA = a.field_keys[i]; + const keyB = b.field_keys[i]; + if (keyA === undefined || keyB === undefined) continue; + next[keyA] = values[keyB]; + next[keyB] = values[keyA]; + } + return next; +} + +/** + * The values after one slot of a list is removed. `slots` are the list's + * shown slots in order. The slots after the removed one move up a place, by + * the position of their fields as in swapSlotValues, and the last shown slot + * is emptied, which leaves its fields on their defaults. + */ +export function removeSlotValues( + slots: { field_keys: string[] }[], + index: number, + values: Record, +): Record { + const next = { ...values }; + for (let i = index; i < slots.length; i++) { + const slot = slots[i]; + const following = slots[i + 1]; + if (!slot) continue; + slot.field_keys.forEach((key, position) => { + const from = following?.field_keys[position]; + if (from === undefined) delete next[key]; + else next[key] = values[from]; + }); + } + return next; +} + export type BuildSchemaValuesOptions = { /** * Send an emptied non-secret field as an explicit clear ("" for a string