From bde362a52bb95a591dd4e13aac6466371f34ba54 Mon Sep 17 00:00:00 2001 From: Maik Groten Date: Wed, 11 Nov 2026 21:08:47 +0100 Subject: [PATCH 1/2] feat(plugins): let a plugin form hold a list the admin grows, folds and reorders A plugin's admin form is a fixed set of fields. A plugin whose settings are a list, such as named groups of folders, had to show every entry it could hold as a section of its own. A form section can now be one slot of a list (add_group, add_label in the plugin SDK). The form shows the first slot and every slot up to the last one that holds a value other than its fields' defaults, then a button that reveals the next. Each slot folds with a click on its header, also in forms that open their sections, shows the value of a leading text field in its header, and has arrows that trade its values with the slot before or after it. The v2 API passes add_group and add_label through on plugin form sections. The slots' fields stay ordinary config keys, so stored config and what plugins read do not change. Other collapsible sections keep their Hide/Show button. The SDK replace in go.mod points at a fork commit until the SDK change is released. AI disclosure: written with Claude Fable 5.2 in Claude Code. The plugin and v2 Go tests, the v2 contract checks and the admin web tests pass locally. golangci-lint was not run, and the form was not checked in a browser by the author. Co-Authored-By: Claude Fable 5.2 --- contracts/api/v2/openapi.json | 8 + go.mod | 2 +- go.sum | 4 +- internal/apiv2/admin_plugin_installations.go | 4 +- internal/plugins/config_schema_view.go | 5 + web/src/api/types.ts | 4 + web/src/api/v2/schema.ts | 4 + .../admin/plugins/SchemaForm.test.tsx | 63 +++++++ .../components/admin/plugins/SchemaForm.tsx | 174 ++++++++++++++++-- .../admin/plugins/schemaFormUtils.test.ts | 56 ++++++ .../admin/plugins/schemaFormUtils.ts | 77 ++++++++ 11 files changed, 381 insertions(+), 20 deletions(-) diff --git a/contracts/api/v2/openapi.json b/contracts/api/v2/openapi.json index e5929e3cc5..b60517de3e 100644 --- a/contracts/api/v2/openapi.json +++ b/contracts/api/v2/openapi.json @@ -16919,6 +16919,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..c3e8f485a5 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.20261111200612-fee6f26ddfbc diff --git a/go.sum b/go.sum index 99418f9da4..af4d0e39e7 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.20261111200612-fee6f26ddfbc h1:ws6voWvn5wihAoD7skTI9gt2cun39Dp/BC+5hq+SC58= +github.com/grtn91/silo-plugin-sdk v0.32.2-0.20261111200612-fee6f26ddfbc/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..d5b9839aab 100644 --- a/internal/apiv2/admin_plugin_installations.go +++ b/internal/apiv2/admin_plugin_installations.go @@ -108,6 +108,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"` @@ -302,7 +304,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..f9918ad0e6 100644 --- a/internal/plugins/config_schema_view.go +++ b/internal/plugins/config_schema_view.go @@ -70,6 +70,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 { @@ -134,6 +138,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..bd3447ff73 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 { diff --git a/web/src/api/v2/schema.ts b/web/src/api/v2/schema.ts index a62d831a87..ad88cf5b61 100644 --- a/web/src/api/v2/schema.ts +++ b/web/src/api/v2/schema.ts @@ -19941,6 +19941,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/SchemaForm.test.tsx b/web/src/components/admin/plugins/SchemaForm.test.tsx index 7e05c6df1e..034b66ec6e 100644 --- a/web/src/components/admin/plugins/SchemaForm.test.tsx +++ b/web/src/components/admin/plugins/SchemaForm.test.tsx @@ -281,3 +281,66 @@ 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("shows a slot that already holds a value", () => { + render(); + expect(screen.getByText("Second name")).toBeInTheDocument(); + }); +}); diff --git a/web/src/components/admin/plugins/SchemaForm.tsx b/web/src/components/admin/plugins/SchemaForm.tsx index 46563e7282..2bad40aa94 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 } 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"; @@ -19,8 +25,10 @@ import { Switch } from "@/components/ui/switch"; import { useT } from "@/i18n"; import { + addSlots, effectiveValue, evaluateShowWhen, + swapSlotValues, validateSchemaValues, type SchemaOption, } from "./schemaFormUtils"; @@ -121,6 +129,9 @@ function SchemaFormSection({ forceOpen, expanded, renderFields, + addButton, + onMoveUp, + onMoveDown, }: { section: PluginAdminFormSection; values: Record; @@ -128,6 +139,11 @@ 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; }) { // 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 +154,106 @@ 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 +272,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) { @@ -438,6 +541,40 @@ 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)); + } + const sections = descriptor.sections ?? []; const groupedKeys = new Set(); for (const section of sections) { @@ -458,7 +595,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)} /> ))}
diff --git a/web/src/components/admin/plugins/schemaFormUtils.test.ts b/web/src/components/admin/plugins/schemaFormUtils.test.ts index 3376e024b2..b74fb7b5ba 100644 --- a/web/src/components/admin/plugins/schemaFormUtils.test.ts +++ b/web/src/components/admin/plugins/schemaFormUtils.test.ts @@ -3,6 +3,7 @@ import type { PluginAdminForm, PluginAdminFormField } from "@/api/types"; import { describe, expect, it } from "vitest"; import { + addSlots, buildSchemaValues, coerceFieldValue, parseFieldTypes, @@ -297,3 +298,58 @@ 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); + }); +}); diff --git a/web/src/components/admin/plugins/schemaFormUtils.ts b/web/src/components/admin/plugins/schemaFormUtils.ts index 9363b63ac1..d964b10a79 100644 --- a/web/src/components/admin/plugins/schemaFormUtils.ts +++ b/web/src/components/admin/plugins/schemaFormUtils.ts @@ -271,6 +271,83 @@ 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; +} + export type BuildSchemaValuesOptions = { /** * Send an emptied non-secret field as an explicit clear ("" for a string From ed9f1ee4f079209a89d93d0f9e1a8ad46f18cbdd Mon Sep 17 00:00:00 2001 From: Maik Groten Date: Wed, 11 Nov 2026 23:10:29 +0100 Subject: [PATCH 2/2] feat(plugins): order a plugin form's multi-select by dragging and remove a list slot Two gaps in plugin forms that hold a list: A multi-select showed its options as toggles and stored the values in the order they were clicked, so a plugin that reads them as a sequence gave the admin no way to see or change that order. A multi-select the plugin marks as ordered (plugin SDK) now shows its chosen values as a numbered list. Rows are dragged, or moved with the keyboard on the handle, with the sortable list hook the other lists use. Options not chosen yet are buttons that add to the end. Other multi-selects keep their toggles. A slot of a list section could be emptied but not removed. Its header now has a delete button: the slots after it move up and the list shows one slot fewer. The v2 API passes the ordered flag through on plugin form fields. No new strings: the buttons reuse "Delete" and "Drag to reorder". The SDK replace in go.mod points at a fork commit until the SDK change is released. AI disclosure: written with Claude Fable 5.2 in Claude Code. The plugin and v2 Go tests, the v2 contract checks and the admin web tests pass locally. golangci-lint was not run, and the form was not checked in a browser by the author. Co-Authored-By: Claude Fable 5.2 --- contracts/api/v2/openapi.json | 4 + go.mod | 2 +- go.sum | 4 +- internal/apiv2/admin_plugin_installations.go | 3 +- internal/plugins/config_schema_view.go | 4 +- web/src/api/types.ts | 2 + web/src/api/v2/schema.ts | 2 + .../admin/plugins/OrderedMultiSelect.tsx | 143 ++++++++++++++++++ .../admin/plugins/SchemaForm.test.tsx | 53 +++++++ .../components/admin/plugins/SchemaForm.tsx | 44 +++++- .../admin/plugins/schemaFormUtils.test.ts | 34 +++++ .../admin/plugins/schemaFormUtils.ts | 25 +++ 12 files changed, 314 insertions(+), 6 deletions(-) create mode 100644 web/src/components/admin/plugins/OrderedMultiSelect.tsx diff --git a/contracts/api/v2/openapi.json b/contracts/api/v2/openapi.json index b60517de3e..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" }, diff --git a/go.mod b/go.mod index c3e8f485a5..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.20261111200612-fee6f26ddfbc +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 af4d0e39e7..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.20261111200612-fee6f26ddfbc h1:ws6voWvn5wihAoD7skTI9gt2cun39Dp/BC+5hq+SC58= -github.com/grtn91/silo-plugin-sdk v0.32.2-0.20261111200612-fee6f26ddfbc/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 d5b9839aab..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"` @@ -287,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 { diff --git a/internal/plugins/config_schema_view.go b/internal/plugins/config_schema_view.go index f9918ad0e6..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 { @@ -126,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())) diff --git a/web/src/api/types.ts b/web/src/api/types.ts index bd3447ff73..6a029542f8 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -3957,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 ad88cf5b61..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 */ 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 034b66ec6e..546c9f6896 100644 --- a/web/src/components/admin/plugins/SchemaForm.test.tsx +++ b/web/src/components/admin/plugins/SchemaForm.test.tsx @@ -339,8 +339,61 @@ describe("SchemaForm add groups", () => { 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 2bad40aa94..bdd22bdabb 100644 --- a/web/src/components/admin/plugins/SchemaForm.tsx +++ b/web/src/components/admin/plugins/SchemaForm.tsx @@ -1,6 +1,6 @@ import { useEffect, useMemo, useRef, useState } from "react"; -import { ArrowDown, ArrowUp, Loader2, Plus } from "lucide-react"; +import { ArrowDown, ArrowUp, Loader2, Plus, Trash2 } from "lucide-react"; import type { PluginAdminForm, PluginAdminFormField, PluginAdminFormSection } from "@/api/types"; import { @@ -24,10 +24,12 @@ 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, @@ -132,6 +134,7 @@ function SchemaFormSection({ addButton, onMoveUp, onMoveDown, + onRemove, }: { section: PluginAdminFormSection; values: Record; @@ -144,6 +147,8 @@ function SchemaFormSection({ /** 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. @@ -191,6 +196,17 @@ function SchemaFormSection({ >