diff --git a/.changeset/37087-console-reads-form-items.md b/.changeset/37087-console-reads-form-items.md new file mode 100644 index 00000000000..8bbd154cbaa --- /dev/null +++ b/.changeset/37087-console-reads-form-items.md @@ -0,0 +1,15 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/console': patch +'@object-ui/i18n': patch +--- + +feat(console): the console reads and edits forms as `form` items (objectstack#37087, ADR-0159) + +- **Setup → Public forms** lists and switches `form` items: the list is the `form` read, a switch saves the `form` item (its body with `sharing.enabled` set, without the `data` an old-shape form is served with), and "Restore package original" resets the `form` override. What the page shows is unchanged: every public form, on and off, its address and preview; a form its installed app ships switched off reads as off. A form whose app's own document cannot be read now offers no switch. +- **Studio's form editor**: the public form designer is the `form` type's editor (`EditPage` and `CreatePage`), with list columns for name, label, object, public address and status. It reads and writes the `form` item, whose body is at the top level, and has no switch: every save and publish writes `sharing.enabled` and `sharing.allowAnonymous` as they are stored at that moment, so a publish never opens a form Setup switched off. A form an installed app ships is saved as a declared override in the app's customization package. When the server refuses a save or publish because another form already uses the address, the editor says the address is taken, not that a draft is pending. The `form` type stays out of Studio's menu for now. +- **The console's own form page** (the signed-in one an action of type `form` opens) reads `GET /api/v1/meta/form/NAME`. The anonymous form route is unchanged. +- New `engine.studio.publicForms.*` and `engine.list.col.publicAddress` / `engine.list.col.publicState` strings in `./namespaces/studio` (en, zh). + +Clause-②: yes +Metadata-protocol: none diff --git a/ui/apps/console/src/__tests__/formPageRequiredMarker-10178.test.tsx b/ui/apps/console/src/__tests__/formPageRequiredMarker-10178.test.tsx index 6d6cd139cd2..7886d7e1aad 100644 --- a/ui/apps/console/src/__tests__/formPageRequiredMarker-10178.test.tsx +++ b/ui/apps/console/src/__tests__/formPageRequiredMarker-10178.test.tsx @@ -59,12 +59,11 @@ const OBJECT_SCHEMA = { }, }; -const VIEW_ENVELOPE = { +const FORM_ITEM = { name: 'showcase_task.intake', object: 'showcase_task', - viewKind: 'form', label: 'Task intake', - config: { + ...{ type: 'simple', sections: [{ label: 'Task', fields: ['title', 'freeform', 'agree', 'optin'] }], }, @@ -89,7 +88,7 @@ async function renderForm() { vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, ]), ); diff --git a/ui/apps/console/src/__tests__/internalFormShell.test.tsx b/ui/apps/console/src/__tests__/internalFormShell.test.tsx index 564f073e0c6..55ba3cfef98 100644 --- a/ui/apps/console/src/__tests__/internalFormShell.test.tsx +++ b/ui/apps/console/src/__tests__/internalFormShell.test.tsx @@ -146,9 +146,8 @@ import { App } from '../App'; const INTERNAL_VIEW = { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Log Time', - config: { type: 'simple', sections: [{ fields: ['title'] }] }, + ...{ type: 'simple', sections: [{ fields: ['title'] }] }, }; const OBJECT_SCHEMA = { name: 'showcase_task', fields: { title: { type: 'text', label: 'Title' } } }; const PUBLIC_FORM = { @@ -163,7 +162,7 @@ beforeEach(() => { vi.stubGlobal( 'fetch', vi.fn(async (url: string) => { - const body = String(url).includes('/meta/view/') + const body = String(url).includes('/meta/form/') ? INTERNAL_VIEW : String(url).includes('/meta/object/') ? OBJECT_SCHEMA diff --git a/ui/apps/console/src/components/FormPage.conditionalRules.test.tsx b/ui/apps/console/src/components/FormPage.conditionalRules.test.tsx index 62ccc876f07..9b832c69bbe 100644 --- a/ui/apps/console/src/components/FormPage.conditionalRules.test.tsx +++ b/ui/apps/console/src/components/FormPage.conditionalRules.test.tsx @@ -76,14 +76,13 @@ function withRules(rules: Record>) { return { ...BASE_SCHEMA, fields }; } -/** Wrap sections in the `/meta/view/:name` envelope the internal route reads. */ -function viewEnvelope(sections: unknown[]) { +/** Wrap sections in the `/meta/form/:name` item the internal route reads. */ +function formItem(sections: unknown[]) { return { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Task', - config: { type: 'simple', sections }, + ...{ type: 'simple', sections }, }; } @@ -134,7 +133,7 @@ function renderInternal(sections: unknown[], opts: RenderOpts = {}) { vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: viewEnvelope(sections) }, + { match: '/meta/form/', body: formItem(sections) }, { match: '/meta/object/', body: opts.objectSchema ?? BASE_SCHEMA }, ...(opts.extraRoutes ?? []), ]), diff --git a/ui/apps/console/src/components/FormPage.externalWriteRefusal-30334.test.tsx b/ui/apps/console/src/components/FormPage.externalWriteRefusal-30334.test.tsx index ccac444b655..556ada25067 100644 --- a/ui/apps/console/src/components/FormPage.externalWriteRefusal-30334.test.tsx +++ b/ui/apps/console/src/components/FormPage.externalWriteRefusal-30334.test.tsx @@ -56,9 +56,8 @@ function stubInternal(refusal: { status: number; body: unknown }) { const view = { name: 'spare_parts.form', object: 'spare_parts', - viewKind: 'form', label: 'Spare part', - config: { type: 'simple', sections: [{ fields: ['name'] }] }, + ...{ type: 'simple', sections: [{ fields: ['name'] }] }, }; const object = { name: 'spare_parts', label: 'Spare part', fields: FIELDS }; vi.stubGlobal( @@ -68,7 +67,7 @@ function stubInternal(refusal: { status: number; body: unknown }) { posts += 1; return answer(false, refusal.status, refusal.body); } - if (String(url).includes('/meta/view/')) return answer(true, 200, view); + if (String(url).includes('/meta/form/')) return answer(true, 200, view); if (String(url).includes('/meta/object/')) return answer(true, 200, object); throw new Error(`unstubbed fetch: ${url}`); }), diff --git a/ui/apps/console/src/components/FormPage.fieldSpan-37559.test.tsx b/ui/apps/console/src/components/FormPage.fieldSpan-37559.test.tsx index 31afb8e56fa..5760d5ab08b 100644 --- a/ui/apps/console/src/components/FormPage.fieldSpan-37559.test.tsx +++ b/ui/apps/console/src/components/FormPage.fieldSpan-37559.test.tsx @@ -41,13 +41,12 @@ const OBJECT_SCHEMA = { }, }; -function viewEnvelope(fields: unknown[], columns: number) { +function formItem(fields: unknown[], columns: number) { return { name: 'showcase_task.intake', object: 'showcase_task', - viewKind: 'form', label: 'Task intake', - config: { type: 'simple', sections: [{ label: 'Task', columns, fields }] }, + ...{ type: 'simple', sections: [{ label: 'Task', columns, fields }] }, }; } @@ -72,7 +71,7 @@ function renderForm(fields: unknown[], columns = 2) { vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: viewEnvelope(fields, columns) }, + { match: '/meta/form/', body: formItem(fields, columns) }, { match: '/meta/object/', body: OBJECT_SCHEMA }, ]), ); diff --git a/ui/apps/console/src/components/FormPage.fieldSpec.test.ts b/ui/apps/console/src/components/FormPage.fieldSpec.test.ts index 779f226f1f2..5cfc2f2bbd5 100644 --- a/ui/apps/console/src/components/FormPage.fieldSpec.test.ts +++ b/ui/apps/console/src/components/FormPage.fieldSpec.test.ts @@ -15,7 +15,7 @@ * The measurement that chose the route: the console's copy was a strict subset * — 9 of the shared type's 26 keys, every one of them identical, none of them * console-only — sitting in a position that describes an **authored document** - * (`FormSectionSpec.fields`, read straight off `/meta/view/:name`), not a + * (`FormSectionSpec.fields`, read straight off `/meta/form/:name`), not a * narrower thing this app authors. The narrow, renderer-honoured shape is a * separate type that already exists here, `RenderableField`. So the two names * were one contract, and the console's copy simply described it wrongly: legal diff --git a/ui/apps/console/src/components/FormPage.formViewChrome-26843.test.tsx b/ui/apps/console/src/components/FormPage.formViewChrome-26843.test.tsx index 9d805433666..d691f84e9c6 100644 --- a/ui/apps/console/src/components/FormPage.formViewChrome-26843.test.tsx +++ b/ui/apps/console/src/components/FormPage.formViewChrome-26843.test.tsx @@ -34,25 +34,24 @@ const OBJECT_SCHEMA = { }, }; -function viewBody(form: Record) { - return { - name: 'showcase_inquiry.intake', - object: 'showcase_inquiry', - viewKind: 'form', - label: 'Intake', - config: { type: 'simple', sections: [{ fields: ['title', 'channel'] }], ...form }, - }; +function formBody(form: Record) { + return { type: 'simple', sections: [{ fields: ['title', 'channel'] }], ...form }; +} + +/** The `form` item `/meta/form/:name` serves: identity and body at the top level. */ +function formItem(form: Record) { + return { name: 'showcase_inquiry.intake', object: 'showcase_inquiry', label: 'Intake', ...formBody(form) }; } function stubFetch(form: Record) { return vi.fn(async (url: string) => { const path = String(url); - const body = path.includes('/meta/view/') - ? viewBody(form) + const body = path.includes('/meta/form/') + ? formItem(form) : path.includes('/meta/object/') ? OBJECT_SCHEMA : path.includes('/forms/intake') - ? { slug: 'intake', object: 'showcase_inquiry', form: viewBody(form).config, objectSchema: OBJECT_SCHEMA } + ? { slug: 'intake', object: 'showcase_inquiry', form: formBody(form), objectSchema: OBJECT_SCHEMA } : path.includes('/data/showcase_inquiry/r1') ? { record: { id: 'r1', title: 'Stored', channel: 'email' } } : null; diff --git a/ui/apps/console/src/components/FormPage.inAppShell-13433.test.tsx b/ui/apps/console/src/components/FormPage.inAppShell-13433.test.tsx index a57ad8a3df9..b2e3c88a2c1 100644 --- a/ui/apps/console/src/components/FormPage.inAppShell-13433.test.tsx +++ b/ui/apps/console/src/components/FormPage.inAppShell-13433.test.tsx @@ -32,16 +32,14 @@ import { appRoutes } from '../AppContent'; vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); /** A container's default form: no view label, no form `title` — what Log Time opens. */ -const UNLABELLED_VIEW = { - name: 'showcase_task.form', - object: 'showcase_task', - viewKind: 'form', - config: { - type: 'simple', - sections: [{ name: 'task', label: 'Task details', fields: ['title'] }], - }, +const UNLABELLED_BODY = { + type: 'simple', + sections: [{ name: 'task', label: 'Task details', fields: ['title'] }], }; +/** A `form` item that names itself nowhere: no `label`, no `title`. */ +const UNLABELLED_VIEW = { name: 'showcase_task.form', object: 'showcase_task', ...UNLABELLED_BODY }; + const OBJECT_SCHEMA = { name: 'showcase_task', label: 'Task', @@ -65,7 +63,7 @@ function stubFetch(view: unknown = UNLABELLED_VIEW) { const method = (init?.method ?? 'GET').toUpperCase(); const u = String(url); let body: unknown; - if (u.includes('/meta/view/')) body = view; + if (u.includes('/meta/form/')) body = view; else if (u.includes('/meta/object/')) body = OBJECT_SCHEMA; else if (method === 'GET' && u.includes('/data/showcase_task/task-42')) body = GET_RESPONSE; else if (method === 'POST' && u.includes('/data/showcase_task')) body = POST_RESPONSE; @@ -127,14 +125,14 @@ describe('the heading of an internal form (objectui#13433)', () => { }); it('an authored form `title` heads the form', async () => { - vi.stubGlobal('fetch', stubFetch({ ...UNLABELLED_VIEW, config: { ...UNLABELLED_VIEW.config, title: 'Log time' } })); + vi.stubGlobal('fetch', stubFetch({ ...UNLABELLED_VIEW, title: 'Log time' })); renderInternal({ url: '/forms/showcase_task.form' }); expect(await screen.findByRole('heading', { level: 1 })).toHaveTextContent(/^Log time$/); }); it('control: the view’s own label still wins', async () => { - vi.stubGlobal('fetch', stubFetch({ ...UNLABELLED_VIEW, label: 'Quick edit', config: { ...UNLABELLED_VIEW.config, title: 'Log time' } })); + vi.stubGlobal('fetch', stubFetch({ ...UNLABELLED_VIEW, label: 'Quick edit', title: 'Log time' })); renderInternal({ url: '/forms/showcase_task.form' }); expect(await screen.findByRole('heading', { level: 1 })).toHaveTextContent(/^Quick edit$/); @@ -191,7 +189,7 @@ describe('Cancel on an internal form (objectui#13433)', () => { ok: true, status: 200, statusText: 'OK', - json: async () => ({ object: 'showcase_task', form: UNLABELLED_VIEW.config, objectSchema: OBJECT_SCHEMA }), + json: async () => ({ object: 'showcase_task', form: UNLABELLED_BODY, objectSchema: OBJECT_SCHEMA }), text: async () => '', }) as unknown as Response), ); diff --git a/ui/apps/console/src/components/FormPage.inlineLocaleEntry-13380.test.tsx b/ui/apps/console/src/components/FormPage.inlineLocaleEntry-13380.test.tsx index 8e8d19148d6..2f1dc316964 100644 --- a/ui/apps/console/src/components/FormPage.inlineLocaleEntry-13380.test.tsx +++ b/ui/apps/console/src/components/FormPage.inlineLocaleEntry-13380.test.tsx @@ -98,12 +98,11 @@ const FORM = { const PUBLIC_PAYLOAD = { slug: 'support', object: API_NAME, form: FORM, objectSchema: CASE_SCHEMA }; -const VIEW_ENVELOPE = { +const FORM_ITEM = { name: 'support_case.intake', object: API_NAME, - viewKind: 'form', label: 'Support', - config: FORM, + ...FORM, }; // ─── Harness ────────────────────────────────────────────────────────────── @@ -136,7 +135,7 @@ function renderSurface(surface: Surface, lang: Lang) { surface === 'public' ? [{ match: '/forms/support', body: PUBLIC_PAYLOAD }] : [ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: CASE_SCHEMA }, // The signed-in visitor's bundle, answered empty: the authored copy // is what renders. diff --git a/ui/apps/console/src/components/FormPage.loadRefusal-29186.test.tsx b/ui/apps/console/src/components/FormPage.loadRefusal-29186.test.tsx index 064ed963256..b2d3156c389 100644 --- a/ui/apps/console/src/components/FormPage.loadRefusal-29186.test.tsx +++ b/ui/apps/console/src/components/FormPage.loadRefusal-29186.test.tsx @@ -27,9 +27,8 @@ vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); const VIEW = { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Log Time', - config: { type: 'simple', sections: [{ fields: ['title', 'hours'] }] }, + ...{ type: 'simple', sections: [{ fields: ['title', 'hours'] }] }, }; const OBJECT = { @@ -80,7 +79,7 @@ function openEdit(refusal: { status: number; body: unknown }) { writes += 1; return answer(true, 200, {}); } - if (String(url).includes('/meta/view/')) return answer(true, 200, VIEW); + if (String(url).includes('/meta/form/')) return answer(true, 200, VIEW); if (String(url).includes('/meta/object/')) return answer(true, 200, OBJECT); if (String(url).includes(`/data/showcase_task/${RECORD_ID}`)) { return answer(false, refusal.status, refusal.body); diff --git a/ui/apps/console/src/components/FormPage.maxLength.test.tsx b/ui/apps/console/src/components/FormPage.maxLength.test.tsx index a678aeb4a8a..a3d163bebd1 100644 --- a/ui/apps/console/src/components/FormPage.maxLength.test.tsx +++ b/ui/apps/console/src/components/FormPage.maxLength.test.tsx @@ -63,14 +63,13 @@ const OBJECT_SCHEMA = { }, }; -/** Wrap a section's fields in the `/meta/view/:name` envelope this route reads. */ -function viewEnvelope(fields: unknown[]) { +/** Wrap a section's fields in the `/meta/form/:name` item this route reads. */ +function formItem(fields: unknown[]) { return { name: 'showcase_task.intake', object: 'showcase_task', - viewKind: 'form', label: 'Task intake', - config: { type: 'simple', sections: [{ label: 'Task', fields }] }, + ...{ type: 'simple', sections: [{ label: 'Task', fields }] }, }; } @@ -96,7 +95,7 @@ function renderForm(fields: unknown[]) { vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: viewEnvelope(fields) }, + { match: '/meta/form/', body: formItem(fields) }, { match: '/meta/object/', body: OBJECT_SCHEMA }, ]), ); diff --git a/ui/apps/console/src/components/FormPage.notFound-27446.test.tsx b/ui/apps/console/src/components/FormPage.notFound-27446.test.tsx index 834cfcbc507..ce5fbc138dd 100644 --- a/ui/apps/console/src/components/FormPage.notFound-27446.test.tsx +++ b/ui/apps/console/src/components/FormPage.notFound-27446.test.tsx @@ -27,7 +27,7 @@ vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); /** Answers the `/meta/view` read with `status`; nothing else is reachable. */ function stubViewRead(status: number) { return vi.fn(async (url: string) => { - if (!String(url).includes('/meta/view/no_such_form')) throw new Error(`unstubbed fetch: ${url}`); + if (!String(url).includes('/meta/form/no_such_form')) throw new Error(`unstubbed fetch: ${url}`); const body = { error: { code: 'RESOURCE_NOT_FOUND', message: 'Metadata item not found or access denied.' } }; return { ok: status >= 200 && status < 300, diff --git a/ui/apps/console/src/components/FormPage.optionLabelLocale-26452.test.tsx b/ui/apps/console/src/components/FormPage.optionLabelLocale-26452.test.tsx index 5fee21f1492..bbf7460f6cb 100644 --- a/ui/apps/console/src/components/FormPage.optionLabelLocale-26452.test.tsx +++ b/ui/apps/console/src/components/FormPage.optionLabelLocale-26452.test.tsx @@ -46,12 +46,11 @@ import { FormPage } from './FormPage'; vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); -const VIEW_ENVELOPE = { +const FORM_ITEM = { name: 'showcase_task.form', object: 'showcase_task', - viewKind: 'form', label: 'Task', - config: { + ...{ type: 'simple', sections: [{ label: 'Task', fields: ['title', 'status', 'priority'] }], }, @@ -106,7 +105,7 @@ function json(body: unknown): Response { function stubServer(record: Record) { return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input instanceof Request ? input.url : input); - if (url.includes('/meta/view/')) return json(VIEW_ENVELOPE); + if (url.includes('/meta/form/')) return json(FORM_ITEM); if (url.includes('/meta/object/')) { const lang = new Headers(init?.headers).get('Accept-Language'); seenLanguages.push(lang); diff --git a/ui/apps/console/src/components/FormPage.predicateScope.test.tsx b/ui/apps/console/src/components/FormPage.predicateScope.test.tsx index 17664d205d5..aacfb5050bd 100644 --- a/ui/apps/console/src/components/FormPage.predicateScope.test.tsx +++ b/ui/apps/console/src/components/FormPage.predicateScope.test.tsx @@ -147,13 +147,12 @@ function withRules(rules: Record>) { return { ...BASE_SCHEMA, fields }; } -function viewEnvelope(sections: unknown[]) { +function formItem(sections: unknown[]) { return { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Task', - config: { type: 'simple', sections }, + ...{ type: 'simple', sections }, }; } @@ -188,7 +187,7 @@ function renderInternalWithScope( vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: viewEnvelope(sections) }, + { match: '/meta/form/', body: formItem(sections) }, { match: '/meta/object/', body: objectSchema }, ]), ); @@ -398,8 +397,8 @@ describe('#6110 hop 1 — `/forms/:name` publishes the SESSION principal', () => 'fetch', stubFetch([ { - match: '/meta/view/', - body: viewEnvelope([ + match: '/meta/form/', + body: formItem([ { label: 'Basics', fields: ['priority'] }, { label: 'Compensation', visibleWhen: GATE, fields: ['notes'] }, ]), diff --git a/ui/apps/console/src/components/FormPage.recordId.test.tsx b/ui/apps/console/src/components/FormPage.recordId.test.tsx index 256df603402..7face78183e 100644 --- a/ui/apps/console/src/components/FormPage.recordId.test.tsx +++ b/ui/apps/console/src/components/FormPage.recordId.test.tsx @@ -51,13 +51,12 @@ import { FormPage } from './FormPage'; vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); -/** The FormView metadata `/meta/view/:name` serves — `showcase_task.edit`. */ -const VIEW_ENVELOPE = { +/** The FormView metadata `/meta/form/:name` serves — `showcase_task.edit`. */ +const FORM_ITEM = { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Log Time', - config: { + ...{ type: 'simple', sections: [{ label: 'Task', fields: ['title', 'hours'] }], }, @@ -158,7 +157,7 @@ function renderInternal(query = '') { /** The happy-path route table: metadata + object schema + the record read. */ function editRoutes(extra: Parameters[0] = []) { return stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, { match: '/data/showcase_task/task-42', body: GET_RESPONSE }, { method: 'PATCH', match: '/data/showcase_task/task-42', body: PATCH_RESPONSE }, @@ -239,7 +238,7 @@ describe('?recordId= makes the internal form an EDIT (ruling point 1)', () => { vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, { match: '/data/showcase_task/task-42', body: GET_RESPONSE }, { @@ -280,7 +279,7 @@ describe('a recordId this route cannot honour FAILS CLOSED (ruling point 2)', () vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, { match: '/data/showcase_task/', status: 404, statusText: 'Not Found' }, ]), @@ -299,7 +298,7 @@ describe('a recordId this route cannot honour FAILS CLOSED (ruling point 2)', () vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, { match: '/data/showcase_task/', status: 403, statusText: 'Forbidden' }, ]), @@ -312,7 +311,7 @@ describe('a recordId this route cannot honour FAILS CLOSED (ruling point 2)', () vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, { match: '/data/showcase_task/', @@ -336,7 +335,7 @@ describe('a recordId this route cannot honour FAILS CLOSED (ruling point 2)', () vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, { match: '/data/showcase_task/', status: 404, statusText: 'Not Found' }, ]), @@ -383,7 +382,7 @@ describe('control: no recordId ⇒ the create path is unchanged', () => { vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, { method: 'POST', diff --git a/ui/apps/console/src/components/FormPage.recordObject.test.tsx b/ui/apps/console/src/components/FormPage.recordObject.test.tsx index 16ab9997b70..06e14824d1d 100644 --- a/ui/apps/console/src/components/FormPage.recordObject.test.tsx +++ b/ui/apps/console/src/components/FormPage.recordObject.test.tsx @@ -56,17 +56,17 @@ import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; import { createI18n } from '@object-ui/i18n'; +import { ActionRunner } from '@object-ui/core'; import { FormPage } from './FormPage'; vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); /** `showcase_task.edit` — the FormView the mis-scoped action targets. */ -const VIEW_ENVELOPE = { +const FORM_ITEM = { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Log Time', - config: { + ...{ type: 'simple', sections: [{ label: 'Task', fields: ['title', 'hours'] }], }, @@ -152,7 +152,7 @@ function renderInternal(query = '') { /** The happy-path route table: metadata + object schema + the record read. */ function editRoutes(extra: Parameters[0] = []) { return stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, { match: '/data/showcase_task/42', body: GET_RESPONSE }, { @@ -210,7 +210,7 @@ describe('a recordObject naming another object FAILS CLOSED (#4292)', () => { // is compared against, so it cannot be known any earlier. Everything after // that point is skipped, including the object schema. expect(calls.filter((c) => c.url.includes('/data/'))).toHaveLength(0); - expect(calls.map((c) => c.url).filter((u) => u.includes('/meta/view/'))).toHaveLength(1); + expect(calls.map((c) => c.url).filter((u) => u.includes('/meta/form/'))).toHaveLength(1); }); it('and no write can follow, since there is no form to submit', async () => { @@ -280,7 +280,7 @@ describe('control: recordId with NO recordObject keeps #4278 behaviour', () => { vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, { match: '/data/showcase_task/42', @@ -333,3 +333,41 @@ describe('control: the PUBLIC /f/:slug path ignores recordObject too', () => { expect(screen.queryByText(/Refusing to open it/)).not.toBeInTheDocument(); }); }); + +/** + * objectstack#37087 (ADR-0159 D9) — an action of type `form` opens its form, + * read as a `form` item. The real `ActionRunner` produces the URL a record's + * Log Time button navigates to; this route, mounted where the console mounts + * it, reads the form at `GET /api/v1/meta/form/NAME` (never `/meta/view`), + * renders it with the record's values, and submits. + */ +describe('an action of type `form` opens its form through the `form` read (#37087)', () => { + it('Log Time on a task: /meta/form/NAME is read, the form renders the record, and the submit writes it', async () => { + const runner = new ActionRunner({ record: { id: '42' }, objectName: 'showcase_task' }); + let to = ''; + runner.setNavigationHandler((url) => { + to = url; + }); + await runner.execute({ type: 'form', target: 'showcase_task.edit' }); + expect(to).toBe('/forms/showcase_task.edit?recordId=42&recordObject=showcase_task'); + + vi.stubGlobal('fetch', editRoutes()); + render( + + + } /> + record page} /> + + , + ); + + expect(await screen.findByLabelText(/Title/)).toHaveValue('Write the report'); + const metaReads = calls.filter((c) => c.method === 'GET' && c.url.includes('/meta/')).map((c) => c.url); + expect(metaReads.filter((u) => u.endsWith('/api/v1/meta/form/showcase_task.edit'))).toHaveLength(1); + expect(metaReads.filter((u) => u.includes('/meta/view'))).toHaveLength(0); + + await userEvent.click(screen.getByRole('button', { name: /Submit/ })); + await waitFor(() => expect(calls.some((c) => c.method === 'PATCH')).toBe(true)); + expect(calls.find((c) => c.method === 'PATCH')!.url).toContain('/data/showcase_task/42'); + }); +}); diff --git a/ui/apps/console/src/components/FormPage.redirect.test.tsx b/ui/apps/console/src/components/FormPage.redirect.test.tsx index 8ec3d1993ba..a29256d8e23 100644 --- a/ui/apps/console/src/components/FormPage.redirect.test.tsx +++ b/ui/apps/console/src/components/FormPage.redirect.test.tsx @@ -55,13 +55,12 @@ vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); /** The console mount the framework CLI configures for an embedded deployment. */ const MOUNT = '/_console'; -function viewEnvelope(submitBehavior: unknown) { +function formItem(submitBehavior: unknown) { return { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Log Time', - config: { + ...{ type: 'simple', sections: [{ label: 'Task', fields: ['title'] }], submitBehavior, @@ -170,7 +169,7 @@ describe('a ruled relative url is an in-shell route', () => { vi.stubGlobal( 'fetch', stubFetch({ - '/meta/view/': viewEnvelope({ kind: 'redirect', url: '/thanks' }), + '/meta/form/': formItem({ kind: 'redirect', url: '/thanks' }), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task': CREATE_RESPONSE, }), @@ -217,7 +216,7 @@ describe('a ruled relative url is an in-shell route', () => { vi.stubGlobal( 'fetch', stubFetch({ - '/meta/view/': viewEnvelope({ kind: 'redirect', url: '/thanks?ref={{record.id}}' }), + '/meta/form/': formItem({ kind: 'redirect', url: '/thanks?ref={{record.id}}' }), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task': CREATE_RESPONSE, }), @@ -237,7 +236,7 @@ describe('a ruled relative url is an in-shell route', () => { vi.stubGlobal( 'fetch', stubFetch({ - '/meta/view/': viewEnvelope({ kind: 'redirect', url: '/t/{{record.slug}}' }), + '/meta/form/': formItem({ kind: 'redirect', url: '/t/{{record.slug}}' }), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task': { ...CREATE_RESPONSE, @@ -282,7 +281,7 @@ describe('a ruled relative url is an in-shell route', () => { vi.stubGlobal( 'fetch', stubFetch({ - '/meta/view/': viewEnvelope({ kind: 'redirect', url: '/thanks', delayMs: 60 }), + '/meta/form/': formItem({ kind: 'redirect', url: '/thanks', delayMs: 60 }), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task': CREATE_RESPONSE, }), @@ -306,7 +305,7 @@ describe('an out-of-contract destination is refused, not followed', () => { vi.stubGlobal( 'fetch', stubFetch({ - '/meta/view/': viewEnvelope({ kind: 'redirect', url: 'https://example.com/thanks' }), + '/meta/form/': formItem({ kind: 'redirect', url: 'https://example.com/thanks' }), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task': CREATE_RESPONSE, }), diff --git a/ui/apps/console/src/components/FormPage.refusalMarks-27417.test.tsx b/ui/apps/console/src/components/FormPage.refusalMarks-27417.test.tsx index 95db4a078ab..488144c6881 100644 --- a/ui/apps/console/src/components/FormPage.refusalMarks-27417.test.tsx +++ b/ui/apps/console/src/components/FormPage.refusalMarks-27417.test.tsx @@ -95,9 +95,8 @@ function stubInternal(refusal: { status: number; body: unknown }) { const view = { name: 'showcase_inquiry.contact', object: 'showcase_inquiry', - viewKind: 'form', label: 'Contact', - config: { type: 'simple', sections: [{ fields: ['name', 'email', 'company'] }] }, + ...{ type: 'simple', sections: [{ fields: ['name', 'email', 'company'] }] }, }; const object = { name: 'showcase_inquiry', label: 'Inquiry', fields: FIELDS }; vi.stubGlobal( @@ -115,7 +114,7 @@ function stubInternal(refusal: { status: number; body: unknown }) { posts += 1; return answer(false, refusal.status, refusal.body); } - if (String(url).includes('/meta/view/')) return answer(true, 200, view); + if (String(url).includes('/meta/form/')) return answer(true, 200, view); if (String(url).includes('/meta/object/')) return answer(true, 200, object); throw new Error(`unstubbed fetch: ${url}`); }), diff --git a/ui/apps/console/src/components/FormPage.refusalText-29019.test.tsx b/ui/apps/console/src/components/FormPage.refusalText-29019.test.tsx index d57aa5b3747..c5215005d2f 100644 --- a/ui/apps/console/src/components/FormPage.refusalText-29019.test.tsx +++ b/ui/apps/console/src/components/FormPage.refusalText-29019.test.tsx @@ -64,9 +64,8 @@ function stubInternal(refusal: Refusal) { const view = { name: 'qar8_fsb.form', object: 'qar8_fsb', - viewKind: 'form', label: 'Feedback', - config: { type: 'simple', sections: [{ fields: ['name', 'email'] }] }, + ...{ type: 'simple', sections: [{ fields: ['name', 'email'] }] }, }; const object = { name: 'qar8_fsb', label: 'Feedback', fields: FIELDS }; vi.stubGlobal( @@ -76,7 +75,7 @@ function stubInternal(refusal: Refusal) { posts += 1; return answer(false, refusal.status, refusal.body); } - if (String(url).includes('/meta/view/')) return answer(true, 200, view); + if (String(url).includes('/meta/form/')) return answer(true, 200, view); if (String(url).includes('/meta/object/')) return answer(true, 200, object); throw new Error(`unstubbed fetch: ${url}`); }), diff --git a/ui/apps/console/src/components/FormPage.retiredFieldType-10176.test.tsx b/ui/apps/console/src/components/FormPage.retiredFieldType-10176.test.tsx index 78b8344dced..4557555fbce 100644 --- a/ui/apps/console/src/components/FormPage.retiredFieldType-10176.test.tsx +++ b/ui/apps/console/src/components/FormPage.retiredFieldType-10176.test.tsx @@ -108,13 +108,12 @@ const ROUTES = [ render: () => { stubFetch([ { - match: '/meta/view/', + match: '/meta/form/', body: { name: 'probe.form', object: 'probe', - viewKind: 'form', label: 'Probe', - config: { type: 'simple', sections: [{ label: 'Probe', fields: FIELD_NAMES }] }, + ...{ type: 'simple', sections: [{ label: 'Probe', fields: FIELD_NAMES }] }, }, }, { match: '/meta/object/', body: OBJECT_SCHEMA }, diff --git a/ui/apps/console/src/components/FormPage.retiredWidget-10471.test.tsx b/ui/apps/console/src/components/FormPage.retiredWidget-10471.test.tsx index 01c789c5c85..2b83e94c730 100644 --- a/ui/apps/console/src/components/FormPage.retiredWidget-10471.test.tsx +++ b/ui/apps/console/src/components/FormPage.retiredWidget-10471.test.tsx @@ -109,13 +109,12 @@ const ROUTES = [ render: () => { stubFetch([ { - match: '/meta/view/', + match: '/meta/form/', body: { name: 'probe.form', object: 'probe', - viewKind: 'form', label: 'Probe', - config: { type: 'simple', sections: [{ label: 'Probe', fields: SECTION_FIELDS }] }, + ...{ type: 'simple', sections: [{ label: 'Probe', fields: SECTION_FIELDS }] }, }, }, { match: '/meta/object/', body: OBJECT_SCHEMA }, diff --git a/ui/apps/console/src/components/FormPage.richTextHints-12110.test.tsx b/ui/apps/console/src/components/FormPage.richTextHints-12110.test.tsx index f3ac22bd9e9..be3cb7720f1 100644 --- a/ui/apps/console/src/components/FormPage.richTextHints-12110.test.tsx +++ b/ui/apps/console/src/components/FormPage.richTextHints-12110.test.tsx @@ -100,7 +100,7 @@ function stubFetch(routes: Array<{ match: string; body: unknown }>) { /** * Render one of the two routes over the same object and the same section: * the anonymous `/f/:slug` page (`GET /forms/:slug`), or the authed internal - * `/forms/:name` page (`GET /meta/view/:name` + `GET /meta/object/:name`). + * `/forms/:name` page (`GET /meta/form/:name` + `GET /meta/object/:name`). */ function renderSurface(surface: Surface) { if (surface === 'public') { @@ -135,13 +135,12 @@ function renderSurface(surface: Surface) { 'fetch', stubFetch([ { - match: '/meta/view/', + match: '/meta/form/', body: { name: 'hc_case.intake', object: 'hc_case', - viewKind: 'form', label: 'Case intake', - config: { type: 'simple', sections: [{ label: 'Request', fields: SECTION_FIELDS }] }, + ...{ type: 'simple', sections: [{ label: 'Request', fields: SECTION_FIELDS }] }, }, }, { match: '/meta/object/', body: OBJECT_SCHEMA }, diff --git a/ui/apps/console/src/components/FormPage.sectionGroup.test.tsx b/ui/apps/console/src/components/FormPage.sectionGroup.test.tsx index 8f29489ae82..f842f84793f 100644 --- a/ui/apps/console/src/components/FormPage.sectionGroup.test.tsx +++ b/ui/apps/console/src/components/FormPage.sectionGroup.test.tsx @@ -134,13 +134,12 @@ function renderInternal(sections: unknown[], type = 'simple') { 'fetch', stubFetch([ { - match: '/meta/view/', + match: '/meta/form/', body: { name: 'ticket.edit', object: 'ticket', - viewKind: 'form', label: 'Ticket', - config: { type, sections }, + ...{ type, sections }, }, }, { match: '/meta/object/', body: TICKET }, diff --git a/ui/apps/console/src/components/FormPage.serverDefaults.test.tsx b/ui/apps/console/src/components/FormPage.serverDefaults.test.tsx index ea585c844bd..a2215ae5e48 100644 --- a/ui/apps/console/src/components/FormPage.serverDefaults.test.tsx +++ b/ui/apps/console/src/components/FormPage.serverDefaults.test.tsx @@ -107,13 +107,12 @@ const OBJECT_SCHEMA = { const FIELD_NAMES = ['title', 'status', 'owner', 'remind_at', 'priority', 'stage']; -function viewEnvelope() { +function formItem() { return { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Task', - config: { type: 'simple', sections: [{ label: 'Task', fields: FIELD_NAMES }] }, + ...{ type: 'simple', sections: [{ label: 'Task', fields: FIELD_NAMES }] }, }; } @@ -184,7 +183,7 @@ function renderPublic() { } const CREATE_ROUTES = { - '/meta/view/': viewEnvelope(), + '/meta/form/': formItem(), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task': CREATE_RESPONSE, }; @@ -338,7 +337,7 @@ describe('counter-probes — what the filter must NOT eat', () => { vi.stubGlobal( 'fetch', stubFetch({ - '/meta/view/': viewEnvelope(), + '/meta/form/': formItem(), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task/task-7': STORED_RECORD, }), diff --git a/ui/apps/console/src/components/FormPage.sharedFieldResolver-10179.test.tsx b/ui/apps/console/src/components/FormPage.sharedFieldResolver-10179.test.tsx index 7916488d934..4b8558ab669 100644 --- a/ui/apps/console/src/components/FormPage.sharedFieldResolver-10179.test.tsx +++ b/ui/apps/console/src/components/FormPage.sharedFieldResolver-10179.test.tsx @@ -71,13 +71,12 @@ vi.mock('@object-ui/fields', async (importOriginal) => { function renderForm(objectFields: Record, viewFields: unknown[]) { const routes: Array<{ match: string; body: unknown }> = [ { - match: '/meta/view/', + match: '/meta/form/', body: { name: 'probe.form', object: 'probe', - viewKind: 'form', label: 'Probe', - config: { type: 'simple', sections: [{ label: 'Probe', fields: viewFields }] }, + ...{ type: 'simple', sections: [{ label: 'Probe', fields: viewFields }] }, }, }, { match: '/meta/object/', body: { name: 'probe', label: 'Probe', fields: objectFields } }, diff --git a/ui/apps/console/src/components/FormPage.sharedWidgets-10179.test.tsx b/ui/apps/console/src/components/FormPage.sharedWidgets-10179.test.tsx index d70861c5fb3..dd86817c0e7 100644 --- a/ui/apps/console/src/components/FormPage.sharedWidgets-10179.test.tsx +++ b/ui/apps/console/src/components/FormPage.sharedWidgets-10179.test.tsx @@ -98,13 +98,12 @@ let writes: Array<{ method: string; body: Record }> = []; function stubFetch() { const routes: Array<{ match: string; body: unknown }> = [ { - match: '/meta/view/', + match: '/meta/form/', body: { name: 'showcase_order.intake', object: 'showcase_order', - viewKind: 'form', label: 'Order intake', - config: { type: 'simple', sections: [{ label: 'Order', fields: FIELD_NAMES }] }, + ...{ type: 'simple', sections: [{ label: 'Order', fields: FIELD_NAMES }] }, }, }, { match: '/meta/object/', body: OBJECT_SCHEMA }, diff --git a/ui/apps/console/src/components/FormPage.submit.test.tsx b/ui/apps/console/src/components/FormPage.submit.test.tsx index e126f348728..8bb40382fec 100644 --- a/ui/apps/console/src/components/FormPage.submit.test.tsx +++ b/ui/apps/console/src/components/FormPage.submit.test.tsx @@ -36,14 +36,13 @@ import { FormPage } from './FormPage'; vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); -/** The FormView metadata `/meta/view/:name` serves for the internal path. */ -function viewEnvelope(submitBehavior?: unknown) { +/** The FormView metadata `/meta/form/:name` serves for the internal path. */ +function formItem(submitBehavior?: unknown) { return { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Log Time', - config: { + ...{ type: 'simple', sections: [{ label: 'Task', fields: ['title'] }], ...(submitBehavior ? { submitBehavior } : {}), @@ -158,7 +157,7 @@ describe('internal submit — default behaviour (ruling point 2)', () => { vi.stubGlobal( 'fetch', stubFetch({ - '/meta/view/': viewEnvelope(), + '/meta/form/': formItem(), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task': CREATE_RESPONSE, }), @@ -192,7 +191,7 @@ describe('internal submit — default behaviour (ruling point 2)', () => { vi.stubGlobal( 'fetch', stubFetch({ - '/meta/view/': viewEnvelope(), + '/meta/form/': formItem(), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task': { object: 'showcase_task', record: { title: 'x' } }, }), @@ -212,7 +211,7 @@ describe('an explicitly declared submitBehavior still wins (ruling point 3)', () vi.stubGlobal( 'fetch', stubFetch({ - '/meta/view/': viewEnvelope({ kind: 'thank-you', title: 'Logged', message: 'Time saved.' }), + '/meta/form/': formItem({ kind: 'thank-you', title: 'Logged', message: 'Time saved.' }), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task': CREATE_RESPONSE, }), diff --git a/ui/apps/console/src/components/FormPage.tabbedLayout-26843.test.tsx b/ui/apps/console/src/components/FormPage.tabbedLayout-26843.test.tsx index 24b63d10300..43dfa4ab8fe 100644 --- a/ui/apps/console/src/components/FormPage.tabbedLayout-26843.test.tsx +++ b/ui/apps/console/src/components/FormPage.tabbedLayout-26843.test.tsx @@ -48,13 +48,12 @@ function stubFetch(form: Record, objectSchema: unknown = OBJECT if (init?.method === 'POST') { submits.push({ url: path, body: JSON.parse(String(init.body)) }); } - const body = path.includes('/meta/view/') + const body = path.includes('/meta/form/') ? { name: 'showcase_ticket.intake', object: 'showcase_ticket', - viewKind: 'form', label: 'Intake', - config: { type: 'tabbed', sections: THREE_SECTIONS, ...form }, + ...{ type: 'tabbed', sections: THREE_SECTIONS, ...form }, } : path.includes('/meta/object/') ? objectSchema diff --git a/ui/apps/console/src/components/FormPage.test.ts b/ui/apps/console/src/components/FormPage.test.ts index ec73e2024fe..7ffba17e08e 100644 --- a/ui/apps/console/src/components/FormPage.test.ts +++ b/ui/apps/console/src/components/FormPage.test.ts @@ -689,121 +689,56 @@ describe('readLoadedRecord', () => { }); /** - * objectui#2208 — the server's `/meta/view/:name` returns the flattened - * ExpandedViewItem envelope `{ name, object, viewKind, label, config }`; - * the form spec lives under `config`. Pre-fix the loader read sections off - * the envelope itself → every internal form rendered zero fields + a bare - * Submit that "succeeded". List views reaching the forms route (the - * framework#2554 collision fallout) rendered the same false positive - * instead of an actionable error. + * objectstack#37087 (ADR-0159) — the internal route reads `/meta/form/:name`, + * which serves a `form` item: identity and form body at the top level (no + * `config` wrapper, ruled question 5), an old-shape form included (the + * server's projection, D5). objectui#2208's false positive (zero fields and a + * bare Submit) cannot come back through a `config` hop, because there is none; + * a list name answers `404` on the `form` read (`FormPage.notFound-27446`). */ describe('resolveInternalForm', () => { - const envelope = { + const formItem = { name: 'showcase_task.tabbed', object: 'showcase_task', - viewKind: 'form', label: 'Tabbed', - scope: 'package', - config: { - type: 'tabbed', - data: { provider: 'object', object: 'showcase_task' }, - sections: [{ name: 'overview', label: 'Overview', fields: ['title', 'status'] }], - }, + type: 'tabbed', + sections: [{ name: 'overview', label: 'Overview', fields: ['title', 'status'] }], }; - it('unwraps the ExpandedViewItem envelope: form spec comes from config', () => { - const out = resolveInternalForm('showcase_task.tabbed', envelope); + it('reads the form body, the object and the label off the `form` item itself', () => { + const out = resolveInternalForm('showcase_task.tabbed', formItem); expect(out.form.type).toBe('tabbed'); expect(out.form.sections).toHaveLength(1); expect(out.label).toBe('Tabbed'); expect(out.object).toBe('showcase_task'); }); - it('accepts the { item: envelope } wrapper', () => { - const out = resolveInternalForm('showcase_task.tabbed', { item: envelope }); + it('accepts the { item } wrapper', () => { + const out = resolveInternalForm('showcase_task.tabbed', { item: formItem }); expect(out.form.sections).toHaveLength(1); expect(out.object).toBe('showcase_task'); }); - // objectui#13433 — no fallback to the view NAME: a form that names itself + // objectui#13433 — no fallback to the form NAME: a form that names itself // nowhere is headed by its object's label, resolved by `FormPage` at render - // (`FormPage.inAppShell-13433.test.tsx`). The raw qualified name was what - // the showcase's Log Time page was headed by. - it('answers no label when neither envelope nor config carry one, rather than the view name', () => { - const { label: _l, ...noLabel } = envelope; - const out = resolveInternalForm('showcase_task.tabbed', noLabel); - expect(out.label).toBeUndefined(); - }); - - it('reads the form config’s `title` when the envelope carries no label', () => { - const { label: _l, ...noLabel } = envelope; - const out = resolveInternalForm('showcase_task.tabbed', { - ...noLabel, - config: { ...noLabel.config, title: 'Tabbed edit' }, - }); - expect(out.label).toBe('Tabbed edit'); - }); - - it('throws an actionable error for a non-form view instead of rendering an empty form', () => { - const listView = { - name: 'showcase_task.default', - object: 'showcase_task', - viewKind: 'list', - label: 'All Tasks', - config: { type: 'grid', data: { provider: 'object', object: 'showcase_task' }, columns: ['title'] }, - }; - expect(() => resolveInternalForm('showcase_task.default', listView)).toThrow(/list view, not a form view/); - }); - - it('throws for a flattened runtime-overlay list row that lost its viewKind (framework#2555 fallout)', () => { - // A personalization PUT persisted the raw config at the top level; the - // pre-heal server returns it with name/object/label but NO viewKind and - // NO config envelope. It must not pass for a legacy bare form spec. - const pollutedOverlay = { - name: 'showcase_task.default', - object: 'showcase_task', - label: 'All Tasks', - type: 'grid', - data: { provider: 'object', object: 'showcase_task' }, - columns: [{ field: 'title' }], - sort: [{ id: '29200fa8-c416-471e-9ca3-913f9308ad89', field: 'estimate_hours', order: 'desc' }], - }; - expect(() => resolveInternalForm('showcase_task.default', pollutedOverlay)).toThrow(/grid view, not a form view/); - }); - - it('throws for a flattened list body whose viewKind sits at the top level (healed overlay row)', () => { - const healedOverlay = { - name: 'showcase_task.default', - object: 'showcase_task', - viewKind: 'list', - label: 'All Tasks', - type: 'grid', - data: { provider: 'object', object: 'showcase_task' }, - columns: [{ field: 'title' }], - }; - expect(() => resolveInternalForm('showcase_task.default', healedOverlay)).toThrow(/list view, not a form view/); - }); - - it('still accepts a bare legacy form spec (no envelope)', () => { - const bare = { - type: 'simple', - label: 'Quick Edit', - data: { provider: 'object', object: 'task' }, - sections: [{ label: 'Main', fields: ['title'] }], - }; - const out = resolveInternalForm('task.quick', bare); - expect(out.form).toBe(bare as any); - expect(out.label).toBe('Quick Edit'); - // object resolved from the spec's data binding - expect(out.object).toBe('task'); - }); - - it('accepts the legacy { item: { spec } } wrapper', () => { - const out = resolveInternalForm('task.quick', { - item: { spec: { type: 'simple', object: 'task', sections: [] } }, - }); - expect(out.object).toBe('task'); - expect(out.form.type).toBe('simple'); + // (`FormPage.inAppShell-13433.test.tsx`). + it('answers no label when the item carries neither label nor title, rather than the name', () => { + const { label: _l, ...noLabel } = formItem; + expect(resolveInternalForm('showcase_task.tabbed', noLabel).label).toBeUndefined(); + }); + + it('reads the form’s `title` when the item carries no label, and the label before the title', () => { + const { label: _l, ...noLabel } = formItem; + expect(resolveInternalForm('showcase_task.tabbed', { ...noLabel, title: 'Tabbed edit' }).label).toBe('Tabbed edit'); + expect(resolveInternalForm('showcase_task.tabbed', { ...formItem, title: 'Tabbed edit' }).label).toBe('Tabbed'); + }); + + it('reads the object from the item’s `object` binding only — a `config` wrapper is not unwrapped', () => { + // The old `view` envelope: nothing is read from under `config`. + const old = { name: 'showcase_task.tabbed', viewKind: 'form', config: { type: 'tabbed', data: { provider: 'object', object: 'showcase_task' }, sections: [] } }; + const out = resolveInternalForm('showcase_task.tabbed', old); + expect(out.object).toBeUndefined(); + expect(out.form.sections).toBeUndefined(); }); }); diff --git a/ui/apps/console/src/components/FormPage.tsx b/ui/apps/console/src/components/FormPage.tsx index 9b116902d44..d9153e9e07f 100644 --- a/ui/apps/console/src/components/FormPage.tsx +++ b/ui/apps/console/src/components/FormPage.tsx @@ -3,7 +3,7 @@ /** * FormPage — single component that renders a FormView either as a public * anonymous form (`/f/:slug` → backend `GET/POST /api/v1/forms/:slug`) or - * as an authed internal form (`/forms/:name` → `GET /api/v1/meta/view/:name` + * as an authed internal form (`/forms/:name` → `GET /api/v1/meta/form/:name` * + `POST /api/v1/data/:object`). * * Both modes share the same renderer; the difference is only in how the @@ -286,36 +286,22 @@ interface ObjectFieldDef { } /** - * The form layouts a form view declares (FormViewSpec.type) — `simple`, - * `tabbed` and `wizard` since ADR-0050 (#27155 / #27159): `split`, `drawer` - * and `modal` left the enum, and the spec refuses each at parse. - */ -const FORM_SPEC_TYPES = new Set(['simple', 'tabbed', 'wizard']); - -/** - * The form CONFIG plus the view identity that travels beside it (objectui#5596). + * The form body plus the identity label that travels beside it (objectui#5596). * * {@link FormViewSpec} is the converged form contract and carries no `label`: * `@objectstack/spec`'s `FormViewSchema` REJECTS that key outright - * (`unrecognized_keys`, measured against the installed 17.0.0) — a form config + * (`unrecognized_keys`, measured against the installed 17.0.0) — a form body * says `title`, not `label`. Until #5596 this file's hand copy declared `label` * on the form type, which read as "a FormView may be labelled" and is not true. * - * The value those reads actually find is the VIEW's identity label, and both - * bodies this renderer accepts carry it one way or another: - * - * - the `ExpandedViewItem` envelope (#2208) puts it beside `config`, and - * {@link resolveInternalForm} already reads it from there; - * - a FLATTENED runtime overlay has no envelope at all — the config and the - * identity share one object, which is exactly what the spec publishes as - * `VIEW_METADATA_MEMBERS.formOverlay` (`FormViewSchema` extended with - * `label` / `object` / `viewKind` / ...). On that branch `form === body`, so - * the label is reachable through the form variable. + * The value that read finds is the form's identity label: a `form` item + * (ADR-0159 D2) carries `label` beside its body at the top level, its name in + * lists, so the body {@link resolveInternalForm} hands the renderer carries it. * * So the key is declared HERE, on the body this renderer unwraps, and not on the * form contract shared with `packages/app-shell`. Narrowed to `string` because - * every read below assigns it into a `string` slot; the spec's own overlay types - * it `I18nLabel`, whose inline locale-map arm this renderer resolves for a field + * every read below assigns it into a `string` slot; the spec types it + * `I18nLabel`, whose inline locale-map arm this renderer resolves for a field * entry's copy ({@link buildSections}, objectui#13380) but not for this label. */ type FormViewBody = FormViewSpec & { label?: string }; @@ -1788,77 +1774,49 @@ async function loadPublicForm(slug: string): Promise { } /** - * Unwrap a `/meta/view/:name` response into the {@link FormViewBody} the renderer - * consumes. Since the ADR-0017 registrar the server returns the flattened - * ExpandedViewItem envelope — `{ name, object, viewKind, label, config: - * { type, sections, … } }` — with the actual form spec nested under - * `config`. Pre-fix, this loader read `sections`/`label` off the envelope - * itself and rendered every internal form as zero fields plus a bare - * Submit that "succeeded" (objectui#2208). Older servers / seeded rows may - * still serve `{ item: { spec } }` or the bare spec, so all shapes are - * accepted. - * - * Also rejects non-form views loudly: a list-view name reaching this route - * (e.g. an action target hit by the framework#2554 key collision) used to - * render as that same empty-form false positive. + * Unwrap a `/meta/form/:name` response into the {@link FormViewBody} the + * renderer consumes (ADR-0159, objectstack#37087). The `form` read serves a + * `form` item: its identity (`name`, `object`, `label`) and its form body at + * the top level (ADR-0159 ruled question 5: no `config` wrapper). An old-shape + * form (a container's `form`, a `formViews` entry, a `viewKind: 'form'` item) + * is served in the same shape, through the server's one projection + * (ADR-0159 D5), so this page reads one shape only. The read answers the + * item bare or as `{ item }`. + * + * A name that is no form (a list view's, an action target that names a list) + * answers `404` on the `form` read, so it reaches the not-found state, never an + * empty form (objectui#2208's false positive). */ export function resolveInternalForm( - name: string, - viewBody: unknown, + // The name the page was opened with: the `form` read already answered for it. + _name: string, + formBody: unknown, ): { label: string | undefined; object?: string; form: FormViewBody } { - const body = viewBody as Record | null; - const item = body?.item ?? body; - const spec = item?.spec ?? item; - const isEnvelope = - spec && typeof spec === 'object' - && spec.config && typeof spec.config === 'object' - && ('viewKind' in spec || 'object' in spec); - // viewKind may sit on the envelope OR on a flattened list-view body - // (runtime personalization overlays are persisted with the config at the - // top level), so read it wherever it is. - const viewKind: string | undefined = - spec && typeof spec === 'object' ? spec.viewKind : undefined; - if (viewKind && viewKind !== 'form') { - throw new Error( - `View "${name}" is a ${viewKind} view, not a form view — check the action or link that targets it.`, - ); - } - const form: FormViewBody = isEnvelope ? spec.config : spec; - // A flattened list config carries no viewKind at all but declares a grid/ - // kanban/… visualization type no form renderer understands — same false - // positive, same loud failure. - if (!viewKind && form && typeof form === 'object' && typeof form.type === 'string' - && !FORM_SPEC_TYPES.has(form.type)) { - throw new Error( - `View "${name}" is a ${form.type} view, not a form view — check the action or link that targets it.`, - ); - } + const body = formBody as Record | null; + const form: FormViewBody = body?.item ?? body; return { - // The view's identity label, then the form config's `title` — the same - // order `loadPublicForm` reads the public payload in (objectui#8408), and - // for the same reason: `title` is the spec-legal key naming a form, and - // `form.label` (a flattened overlay's identity label) must not outrank it. + // The form's own label (its name in lists), then its `title` — the + // identity label first, as the page read it off the view item before + // (objectui#8408). // // No fallback to `name` (objectui#13433). A container's default form — // `showcase_task.form`, what the showcase's Log Time opens — carries - // neither key, and the page was headed by that raw qualified view name. + // neither key, and the page was headed by that raw qualified name. // Undefined here means "names itself nowhere"; `FormPage` heads it with // the object's label instead, as the public route does. - label: (isEnvelope ? spec.label : undefined) ?? form?.title ?? form?.label, - // `data.object` is a declared FormView key since objectui#5596, so this no - // longer needs `as any` — only a narrowing to the one arm that carries an - // object name (`ViewDataSchema`'s `provider: 'object'`), read defensively - // because the body itself is untrusted. - object: (isEnvelope ? spec.object : undefined) - ?? (form?.data as { object?: string } | undefined)?.object - ?? spec?.object, + label: (form as { label?: string } | null)?.label ?? form?.title, + // The form's one binding (ADR-0159 D2), read defensively because the body + // itself is untrusted. + object: typeof (form as { object?: unknown } | null)?.object === 'string' + ? (form as { object: string }).object + : undefined, form, }; } /** * "No such form" on either route (objectstack-ai/objectstack#27446, #27756): - * the internal `/meta/view` read or the public `/forms/:slug` resolver + * the internal `/meta/form` read or the public `/forms/:slug` resolver * answered 404. Both answer 404 for a form that does not exist and for one the * caller may not read, on purpose, so the page says the one thing both mean — * nothing here by that name. @@ -1913,13 +1871,13 @@ async function loadInternalForm( recordObject?: string | null, channel?: ApiFetch, ): Promise { - const viewRes = await apiFetch(`/meta/view/${encodeURIComponent(name)}`, undefined, channel); - if (viewRes.status === 404) throw new FormNotFoundError(`Form metadata not found: view/${name}`); - if (!viewRes.ok) { - throw new Error(`Could not load form metadata (${viewRes.status}): view/${name}`); + const formRes = await apiFetch(`/meta/form/${encodeURIComponent(name)}`, undefined, channel); + if (formRes.status === 404) throw new FormNotFoundError(`Form metadata not found: form/${name}`); + if (!formRes.ok) { + throw new Error(`Could not load form metadata (${formRes.status}): form/${name}`); } - const viewBody = await viewRes.json(); - const { label, object: objectName, form } = resolveInternalForm(name, viewBody); + const formBody = await formRes.json(); + const { label, object: objectName, form } = resolveInternalForm(name, formBody); if (!objectName) { throw new Error(`FormView "${name}" is missing an "object" target`); } diff --git a/ui/apps/console/src/components/FormPage.upfrontWriteRefusal-29187.test.tsx b/ui/apps/console/src/components/FormPage.upfrontWriteRefusal-29187.test.tsx index cdecde24f66..f8621c0368a 100644 --- a/ui/apps/console/src/components/FormPage.upfrontWriteRefusal-29187.test.tsx +++ b/ui/apps/console/src/components/FormPage.upfrontWriteRefusal-29187.test.tsx @@ -55,9 +55,8 @@ beforeEach(() => { const view = { name: `${OBJECT}.form`, object: OBJECT, - viewKind: 'form', label: 'Feedback', - config: { type: 'simple', sections: [{ fields: ['name', 'email'] }] }, + ...{ type: 'simple', sections: [{ fields: ['name', 'email'] }] }, }; const publicPayload = { slug: 'feedback', @@ -74,7 +73,7 @@ beforeEach(() => { posts += 1; return answer(403, { error: 'denied', code: 'PERMISSION_DENIED' }); } - if (u.includes('/meta/view/')) return answer(200, view); + if (u.includes('/meta/form/')) return answer(200, view); if (u.includes('/meta/object/')) return answer(200, { name: OBJECT, label: 'Feedback', fields: FIELDS }); if (u.includes(`/data/${OBJECT}/r1`)) { return answer(200, { object: OBJECT, id: 'r1', record: { id: 'r1', name: 'Ada', email: 'ada@example.com' } }); diff --git a/ui/apps/console/src/components/FormPage.viewSpec.test.ts b/ui/apps/console/src/components/FormPage.viewSpec.test.ts index 1101a5c16bf..e1fe7b2a4d5 100644 --- a/ui/apps/console/src/components/FormPage.viewSpec.test.ts +++ b/ui/apps/console/src/components/FormPage.viewSpec.test.ts @@ -152,9 +152,9 @@ export function formContainerContractPins(): void { // ── PIN G — `label` did not follow the form contract. It was on this file's // removed `FormViewSpec`, and `@objectstack/spec`'s `FormViewSchema` REJECTS - // it (`unrecognized_keys` — a form config is titled, not labelled). It is view - // IDENTITY: it arrives on the `ExpandedViewItem` envelope, or beside the - // config on a flattened runtime overlay. So it lives on `FormPage.tsx`'s own + // it (`unrecognized_keys` — a form body is titled, not labelled). It is form + // IDENTITY: a `form` item carries it beside its body at the top level + // (ADR-0159 D2). So it lives on `FormPage.tsx`'s own // `FormViewBody`, which is what `resolveInternalForm` returns — NOT on the // contract shared with `packages/app-shell`. type ResolvedBody = ReturnType['form']; @@ -200,29 +200,15 @@ describe('objectui#5596 — the console renders the shared container specs', () expect(asString[0].columns).toBe(3); }); - it('reads the view label off the body, not off the form config', () => { - // Envelope branch: identity sits beside `config` (objectui#2208). - const envelope = resolveInternalForm('contact_form', { - name: 'contact_form', + it('reads the form label off the `form` item, beside its body', () => { + const item = resolveInternalForm('contact.contact_form', { + name: 'contact.contact_form', object: 'contact', - viewKind: 'form', label: 'Contact us', - config: { type: 'simple', sections: [{ fields: ['name'] }] }, - }); - expect(envelope.label).toBe('Contact us'); - expect(envelope.object).toBe('contact'); - - // Flattened-overlay branch: no envelope at all, so the identity keys and the - // form config share one object — the shape `@objectstack/spec` publishes as - // `VIEW_METADATA_MEMBERS.formOverlay`. This is the branch the removed - // `FormViewSpec.label` key was really describing. - const flattened = resolveInternalForm('contact_form', { type: 'simple', - label: 'Contact us', - data: { provider: 'object', object: 'contact' }, sections: [{ fields: ['name'] }], }); - expect(flattened.label).toBe('Contact us'); - expect(flattened.object).toBe('contact'); + expect(item.label).toBe('Contact us'); + expect(item.object).toBe('contact'); }); }); diff --git a/ui/apps/console/src/components/FormPage.visibleWhen.test.tsx b/ui/apps/console/src/components/FormPage.visibleWhen.test.tsx index a0ec8edf53c..aff6bdbe8a6 100644 --- a/ui/apps/console/src/components/FormPage.visibleWhen.test.tsx +++ b/ui/apps/console/src/components/FormPage.visibleWhen.test.tsx @@ -97,14 +97,13 @@ const OBJECT_SCHEMA = { }, }; -/** Wrap a section's fields in the `/meta/view/:name` envelope this route reads. */ -function viewEnvelope(fields: unknown[]) { +/** Wrap a section's fields in the `/meta/form/:name` item this route reads. */ +function formItem(fields: unknown[]) { return { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Task', - config: { type: 'simple', sections: [{ label: 'Task', fields }] }, + ...{ type: 'simple', sections: [{ label: 'Task', fields }] }, }; } @@ -147,7 +146,7 @@ function renderInternal(fields: unknown[], query = '', extraRoutes: Parameters = [ { method: 'GET', - match: '/meta/view/', + match: '/meta/form/', body: { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Task', - config: { type: 'simple', sections }, + ...{ type: 'simple', sections }, }, }, { method: 'GET', match: '/meta/object/', body: objectSchema }, diff --git a/ui/apps/console/src/components/FormPage.widgetDegrade-10472.test.tsx b/ui/apps/console/src/components/FormPage.widgetDegrade-10472.test.tsx index e325c98c6b6..b87913f7e49 100644 --- a/ui/apps/console/src/components/FormPage.widgetDegrade-10472.test.tsx +++ b/ui/apps/console/src/components/FormPage.widgetDegrade-10472.test.tsx @@ -51,13 +51,12 @@ const UNREGISTERED = 'no_such_widget'; function renderForm(objectFields: Record, viewFields: unknown[]) { const routes: Array<{ match: string; body: unknown }> = [ { - match: '/meta/view/', + match: '/meta/form/', body: { name: 'probe.form', object: 'probe', - viewKind: 'form', label: 'Probe', - config: { type: 'simple', sections: [{ label: 'Probe', fields: viewFields }] }, + ...{ type: 'simple', sections: [{ label: 'Probe', fields: viewFields }] }, }, }, { match: '/meta/object/', body: { name: 'probe', label: 'Probe', fields: objectFields } }, diff --git a/ui/apps/console/src/components/FormPage.wizardSteps-27224.test.tsx b/ui/apps/console/src/components/FormPage.wizardSteps-27224.test.tsx index b5ace36fe15..810456b2b3d 100644 --- a/ui/apps/console/src/components/FormPage.wizardSteps-27224.test.tsx +++ b/ui/apps/console/src/components/FormPage.wizardSteps-27224.test.tsx @@ -53,13 +53,12 @@ function stubFetch(form: Record, objectSchema: unknown = OBJECT if (init?.method === 'POST') { submits.push({ url: path, body: JSON.parse(String(init.body)) }); } - const body = path.includes('/meta/view/') + const body = path.includes('/meta/form/') ? { name: 'showcase_ticket.intake', object: 'showcase_ticket', - viewKind: 'form', label: 'Intake', - config: { type: 'wizard', sections: THREE_SECTIONS, ...form }, + ...{ type: 'wizard', sections: THREE_SECTIONS, ...form }, } : path.includes('/meta/object/') ? objectSchema diff --git a/ui/packages/app-shell/src/services/builtinComponents.tsx b/ui/packages/app-shell/src/services/builtinComponents.tsx index a2217604194..633e78723c9 100644 --- a/ui/packages/app-shell/src/services/builtinComponents.tsx +++ b/ui/packages/app-shell/src/services/builtinComponents.tsx @@ -19,6 +19,7 @@ import { lazy, Suspense } from 'react'; import { registerAppComponent } from './componentRegistry.js'; import { lazyPage, LazyPageFallback as MetadataAdminFallback } from './lazyPage.js'; import { registerMetadataResource } from '../views/metadata-admin/registry.js'; +import { FORM_LIST_COLUMNS } from '../views/studio-design/publicForm/formListColumns.js'; import { CONNECTOR_CREDENTIALS_REF } from '../views/setup/connectorCredentials.js'; import { CONNECTOR_CONNECTIONS_REF } from '../views/setup/connectorConnections.js'; import { PERMISSION_SET_ASSIGNMENT_REF, POSITION_HOLDERS_REF } from '../views/setup/peopleAssignments.js'; @@ -453,6 +454,26 @@ registerMetadataResource({ listFilter: (item) => !isAggregatedViewContainer(item), }); +// objectstack#37087 (ADR-0159 D9) — the `form` type: its list's columns and +// its own editor, Studio's form designer (`studio-design/publicForm/`), on +// the item and on `…/form/new`. The editor loads the first time a form opens. +// `form` stays out of Studio's menu (`studioMenuPlacement.ts`). +const FormItemEditPage = lazyPage('form', () => + import('../views/studio-design/publicForm/PublicFormsDesigner.js').then((m) => m.FormItemEditPage), +); +const FormItemCreatePage = lazyPage('form', () => + import('../views/studio-design/publicForm/PublicFormsDesigner.js').then((m) => m.FormItemCreatePage), +); +registerMetadataResource({ + type: 'form', + domain: 'ui', + searchableFields: ['name', 'label', 'title', 'object'], + // `/meta/types` serves no list layout for `form`: these are the console's own. + listColumns: FORM_LIST_COLUMNS, + EditPage: FormItemEditPage, + CreatePage: FormItemCreatePage, +}); + registerMetadataResource({ type: 'dashboard', label: 'Dashboards', diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts index 9d40e9949ee..54021b522ce 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts @@ -55,8 +55,10 @@ import { overrideDraftBody } from './studio-design/customizeOverride.js'; * `PageSchema`) joins the original three (#1541): a record page is edited in * the browser and staged/published through the same `/meta` draft model. * objectstack#37359 — `mapping`, a shared import mapping saved from the import - * wizard, is created the same way: into a package of the app, published at once. */ -export type RuntimeArtifactType = 'view' | 'report' | 'dashboard' | 'page' | 'mapping'; + * wizard, is created the same way: into a package of the app, published at once. + * objectstack#37087 — `form` (ADR-0159), the public form Setup switches and + * Studio's form editor saves, through the same package targets. */ +export type RuntimeArtifactType = 'view' | 'report' | 'dashboard' | 'page' | 'mapping' | 'form'; /** * The metadata `name` (the `:name` in `/meta/page/:name`) for an object's @@ -318,7 +320,9 @@ function invalidateViewCaches( name: string, ctx: RuntimePersistCtx, ): void { - if (type !== 'view') return; + // [#37087] A `form` save over an old shape removes the old-shape `view` row + // at that address (ADR-0159 card ②), so the object's cached views are stale too. + if (type !== 'view' && type !== 'form') return; const objectName = ctx.objectName; if (!objectName || !name) return; const invalidate = ctx.dataSource?.invalidateViewKeys; diff --git a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx index e6bcc341241..3197c24781c 100644 --- a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx +++ b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx @@ -15,6 +15,8 @@ import { MemoryRouter } from 'react-router-dom'; const fake = vi.hoisted(() => ({ items: [] as unknown[], + listed: [] as string[], + layeredTypes: [] as string[], listFails: null as string | null, layered: (_name: string, _packageId?: string): { code?: unknown; effective?: unknown; draft?: unknown } => ({}), packages: new Map(), @@ -35,7 +37,8 @@ vi.mock('../../providers/AdapterProvider.js', () => { const adapter = { getClient: () => ({ meta: { - getItems: async () => { + getItems: async (type: string) => { + fake.listed.push(type); if (fake.listFails) throw new Error(fake.listFails); return { items: fake.items }; }, @@ -50,7 +53,10 @@ vi.mock('@object-ui/react', async (importOriginal) => ({ })); vi.mock('../metadata-admin/useMetadata.js', async (importOriginal) => { const client = { - layered: async (_type: string, name: string, options?: { packageId?: string }) => fake.layered(name, options?.packageId), + layered: async (type: string, name: string, options?: { packageId?: string }) => { + fake.layeredTypes.push(type); + return fake.layered(name, options?.packageId); + }, save: (...args: unknown[]) => fake.save(...args), publish: async () => ({}), reset: async () => ({}), @@ -70,13 +76,14 @@ const sharing = (enabled?: boolean) => ({ allowAnonymous: true, publicLink: 'contact-us', }); +/** A `form` item (ADR-0159): its body at the top level. */ const form = (enabled: boolean | undefined, extra: Record = {}) => ({ name: 'web_to_lead', object: 'crm_lead', - viewKind: 'form', label: 'Contact us', _packageId: 'crm', - config: { title: 'Contact us', data: { object: 'crm_lead' }, sharing: sharing(enabled) }, + title: 'Contact us', + sharing: sharing(enabled), ...extra, }); @@ -107,6 +114,8 @@ const ADMIN = ['manage_platform_settings', 'manage_metadata']; beforeEach(() => { fake.items = []; + fake.listed = []; + fake.layeredTypes = []; fake.listFails = null; fake.layered = () => ({}); fake.packages = new Map(); @@ -129,6 +138,8 @@ describe('PublicFormsSetupPage', () => { fake.packages.set('crm', { writable: true, manifest: { id: 'crm' } }); render(, { wrapper: host(['manage_platform_settings']) }); expect(await screen.findByTestId('public-form-row-web_to_lead')).toHaveAttribute('data-on', 'true'); + // [#37087] The list is the effective `form` read. + expect(fake.listed).toEqual(['form']); expect(screen.getByTestId('public-forms-no-switch')).toHaveTextContent('«publicFormsSetup.noSwitchPermission»'); expect(screen.getByTestId('public-form-switch-web_to_lead')).toBeDisabled(); }); @@ -146,12 +157,14 @@ describe('PublicFormsSetupPage', () => { expect(row).toHaveAttribute('data-shipped-off', 'true'); expect(screen.getByTestId('public-form-shipped-off-web_to_lead')).toHaveTextContent('«publicFormsSetup.shippedOff»'); expect(screen.getByTestId('public-form-switch-web_to_lead')).toBeDisabled(); + // [#37087] The app's own document is the `form` layered read's. + expect(fake.layeredTypes.every((type) => type === 'form')).toBe(true); }); } it('a list read that fails says so in business words, never the server\'s own message', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); - fake.listFails = 'GET /api/v1/meta/view failed: ECONNRESET upstream'; + fake.listFails = 'GET /api/v1/meta/form failed: ECONNRESET upstream'; render(, { wrapper: host(ADMIN) }); const alert = await screen.findByTestId('public-forms-load-failed'); expect(alert).toHaveTextContent('«publicFormsSetup.loadFailed»'); @@ -170,6 +183,8 @@ describe('PublicFormsSetupPage', () => { await waitFor(() => expect(row).toHaveAttribute('data-unknown', 'true')); expect(row).toHaveAttribute('data-on', 'false'); expect(screen.getByTestId('public-form-unknown-web_to_lead')).toHaveTextContent('«publicFormsSetup.statusUnknown»'); + // Not knowing whether it is live, the page offers no switch: Refresh reads it again. + expect(screen.getByTestId('public-form-switch-web_to_lead')).toBeDisabled(); }); it('a switch over a pending draft says so and does not read as done', async () => { @@ -197,7 +212,7 @@ describe('PublicFormsSetupPage', () => { ] as const) { (fake.toast.error as ReturnType).mockClear(); fake.save = async () => { - throw Object.assign(new Error('Capability manage_metadata required for PUT /meta/view/web_to_lead'), { status }); + throw Object.assign(new Error('Capability manage_metadata required for PUT /meta/form/web_to_lead'), { status }); }; const { unmount } = render(, { wrapper: host(ADMIN) }); fireEvent.click(await screen.findByTestId('public-form-switch-web_to_lead')); diff --git a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx index 169a0eda27c..2f942e20b6e 100644 --- a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx +++ b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx @@ -129,7 +129,7 @@ function PublicFormsSetupBody() { (async () => { try { if (!client?.meta?.getItems) throw new Error('meta.getItems is not available on this client'); - const answer = await client.meta.getItems('view'); + const answer = await client.meta.getItems('form'); const rows = await markShippedOff(publicFormRowsOf(answer), metadataClient as any); if (live) setRead({ kind: 'ready', rows }); } catch (err) { @@ -277,7 +277,7 @@ function PublicFormsSetupBody() {
void flip(row, next)} aria-label={t(row.on ? 'publicFormsSetup.switchOffLabel' : 'publicFormsSetup.switchOnLabel', { name: row.title, diff --git a/ui/packages/app-shell/src/views/setup/publicForms.test.ts b/ui/packages/app-shell/src/views/setup/publicForms.test.ts index 0bc794c30ed..70e1b14597d 100644 --- a/ui/packages/app-shell/src/views/setup/publicForms.test.ts +++ b/ui/packages/app-shell/src/views/setup/publicForms.test.ts @@ -24,15 +24,20 @@ const sharing = (enabled: boolean, extra: Record = {}) => ({ ...extra, }); +/** A served `form` item (ADR-0159): its body at the top level. */ const formItem = (overrides: Record = {}, enabled = true) => ({ name: 'web_to_lead', object: 'crm_lead', - viewKind: 'form', label: 'Contact us', _packageId: 'crm', - config: { title: 'Contact us', data: { object: 'crm_lead' }, sharing: sharing(enabled), sections: [] }, + title: 'Contact us', + sharing: sharing(enabled), + sections: [], ...overrides, }); +/** The same form as the effective read projects an app's old view shape (ADR-0159 D5). */ +const projectedItem = (overrides: Record = {}, enabled = true) => + formItem({ data: { provider: 'object', object: 'crm_lead' }, _formDefinedIn: 'view', ...overrides }, enabled); describe('publicFormRowOf', () => { it('lists a form open to anonymous intake as on', () => { @@ -51,26 +56,29 @@ describe('publicFormRowOf', () => { }); it('does not list an internal form: not anonymous, or no address', () => { - const notAnonymous = formItem({ config: { title: 'x', sharing: { enabled: true, allowAnonymous: false, publicLink: 'x' } } }); - const noLink = formItem({ config: { title: 'x', sharing: { enabled: true, allowAnonymous: true } } }); - const noSharing = formItem({ config: { title: 'x' } }); + const notAnonymous = formItem({ sharing: { enabled: true, allowAnonymous: false, publicLink: 'x' } }); + const noLink = formItem({ sharing: { enabled: true, allowAnonymous: true } }); + const noSharing = formItem({ sharing: undefined }); expect(publicFormRowOf(notAnonymous)).toBeNull(); expect(publicFormRowOf(noLink)).toBeNull(); expect(publicFormRowOf(noSharing)).toBeNull(); }); - it('does not list a view that is not a form, or one with no config', () => { - expect(publicFormRowOf(formItem({ viewKind: 'list' }))).toBeNull(); - expect(publicFormRowOf(formItem({ config: null }))).toBeNull(); + it('lists a form an app still ships as an old view shape, as the effective read projects it', () => { + expect(publicFormRowOf(projectedItem())).toEqual(publicFormRowOf(formItem())); + }); + + it('does not list an item with no name, or nothing', () => { + expect(publicFormRowOf(formItem({ name: '' }))).toBeNull(); expect(publicFormRowOf(null)).toBeNull(); }); it('names a form by its served label, else its title, else its first section, else its name; a package-less item has none', () => { expect(publicFormRowOf(formItem({ label: undefined }))?.title).toBe('Contact us'); - const sectioned = { sharing: sharing(true), sections: [{ name: 'contact_us', label: 'Get in touch', fields: [] }] }; - expect(publicFormRowOf(formItem({ label: undefined, config: sectioned }))?.title).toBe('Get in touch'); - expect(publicFormRowOf(formItem({ label: '', config: { sharing: sharing(true) } }))?.title).toBe('web_to_lead'); - expect(publicFormRowOf(formItem({ name: 'crm_lead.web_to_lead', label: '', config: { sharing: sharing(true) } }))?.title).toBe( + const sectioned = { title: undefined, sections: [{ name: 'contact_us', label: 'Get in touch', fields: [] }] }; + expect(publicFormRowOf(formItem({ label: undefined, ...sectioned }))?.title).toBe('Get in touch'); + expect(publicFormRowOf(formItem({ label: '', title: undefined }))?.title).toBe('web_to_lead'); + expect(publicFormRowOf(formItem({ name: 'crm_lead.web_to_lead', label: '', title: undefined }))?.title).toBe( 'web_to_lead', ); expect(publicFormRowOf(formItem({ _packageId: undefined }))?.packageId).toBeNull(); @@ -81,7 +89,7 @@ describe('publicFormRowsOf', () => { it('reads `{ items }` or a bare array, drops internal forms and sorts by the name shown', () => { const b = formItem({ name: 'b_form', label: 'Beta' }); const a = formItem({ name: 'a_form', label: 'Alpha' }); - const list = formItem({ name: 'all', viewKind: 'list' }); + const list = formItem({ name: 'all', sharing: undefined }); expect(publicFormRowsOf({ items: [b, list, a] }).map((r) => r.name)).toEqual(['a_form', 'b_form']); expect(publicFormRowsOf([b, a]).map((r) => r.name)).toEqual(['a_form', 'b_form']); expect(publicFormRowsOf(undefined)).toEqual([]); @@ -94,6 +102,10 @@ describe('overrideHoldsOnlySwitch', () => { const override = { ...formItem({}, false), _layer: 'custom', overrides: { package: 'crm', basedOn: '3.0.0' } }; expect(overrideHoldsOnlySwitch(override, base)).toBe(true); }); + it('[#37087] is true over an old-shape base: its projection\'s `data` binding and marker are not design', () => { + const override = { ...stripped(formItem({}, false)), overrides: { package: 'crm', basedOn: '3.0.0' } }; + expect(overrideHoldsOnlySwitch(override, projectedItem())).toBe(true); + }); it('is false when the override also changes the design', () => { const override = { ...formItem({ label: 'Talk to us' }, false), @@ -130,10 +142,11 @@ describe('switchPublicForm', () => { expect(out).toBe('published'); expect(client.save).toHaveBeenCalledTimes(1); const [type, name, body, options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; - expect([type, name]).toEqual(['view', 'web_to_lead']); + expect([type, name]).toEqual(['form', 'web_to_lead']); expect(options).toMatchObject({ mode: 'draft', ifNoneMatch: '*', packageId: 'crm' }); - expect(body).toEqual({ ...stripped(doc), config: { ...doc.config, sharing: sharing(false) } }); - expect(client.publish).toHaveBeenCalledWith('view', 'web_to_lead', { packageId: 'crm' }); + expect(body).toEqual({ ...stripped(doc), sharing: sharing(false) }); + expect(client.publish).toHaveBeenCalledWith('form', 'web_to_lead', { packageId: 'crm' }); + expect(client.layered).toHaveBeenCalledWith('form', 'web_to_lead', { packageId: 'crm' }); expect(invalidateViewKeys).toHaveBeenCalledWith('crm_lead', 'web_to_lead'); }); @@ -147,9 +160,9 @@ describe('switchPublicForm', () => { const [, , body, options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; expect(options).toMatchObject({ packageId: 'crm.custom' }); expect(body.overrides).toEqual({ package: 'crm', basedOn: '3.0.0' }); - expect(body.config.sharing).toEqual(sharing(false)); + expect(body.sharing).toEqual(sharing(false)); expect(body._packageId).toBeUndefined(); - expect(client.publish).toHaveBeenCalledWith('view', 'web_to_lead', { packageId: 'crm.custom' }); + expect(client.publish).toHaveBeenCalledWith('form', 'web_to_lead', { packageId: 'crm.custom' }); expect(client.reset).not.toHaveBeenCalled(); }); @@ -158,10 +171,10 @@ describe('switchPublicForm', () => { const client = clientOf((_n, pkg) => (pkg === 'crm' ? { code: doc, effective: doc } : { code: null, effective: null })); const doors = listed({ crm: { writable: false, version: '3.0.0' }, 'crm.custom': { writable: true, version: '0.0.0' } }); await switchPublicForm(row, false, client, {}, doors); - expect(client.layered).toHaveBeenNthCalledWith(1, 'view', 'web_to_lead', { packageId: 'crm.custom' }); - expect(client.layered).toHaveBeenNthCalledWith(2, 'view', 'web_to_lead', { packageId: 'crm' }); + expect(client.layered).toHaveBeenNthCalledWith(1, 'form', 'web_to_lead', { packageId: 'crm.custom' }); + expect(client.layered).toHaveBeenNthCalledWith(2, 'form', 'web_to_lead', { packageId: 'crm' }); const [, , body] = client.save.mock.calls[0] as unknown as [string, string, any]; - expect(body.config.sharing).toEqual(sharing(false)); + expect(body.sharing).toEqual(sharing(false)); }); it('switching back on restores the app\'s own form when the override held nothing but the switch', async () => { @@ -173,7 +186,7 @@ describe('switchPublicForm', () => { const out = await switchPublicForm(row, true, client, { dataSource: { invalidateViewKeys } as any }, doors); expect(out).toBe('restored'); expect(client.reset).toHaveBeenCalledTimes(1); - expect(client.reset).toHaveBeenCalledWith('view', 'web_to_lead', { packageId: 'crm.custom' }); + expect(client.reset).toHaveBeenCalledWith('form', 'web_to_lead', { packageId: 'crm.custom' }); expect(client.save).not.toHaveBeenCalled(); expect(invalidateViewKeys).toHaveBeenCalledWith('crm_lead', 'web_to_lead'); }); @@ -189,7 +202,7 @@ describe('switchPublicForm', () => { const [, , body, options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; expect(options).toMatchObject({ packageId: 'crm.custom' }); expect(body.label).toBe('Talk to us'); - expect(body.config.sharing).toEqual(sharing(true)); + expect(body.sharing).toEqual(sharing(true)); expect(body.overrides).toEqual({ package: 'crm', basedOn: '3.0.0' }); }); @@ -203,7 +216,7 @@ describe('switchPublicForm', () => { expect(out).toEqual({ kind: 'earlier-version', basedOn: '2.0.0' }); expect(client.reset).not.toHaveBeenCalled(); const [, , body] = client.save.mock.calls[0] as unknown as [string, string, any]; - expect(body.config.sharing).toEqual(sharing(true)); + expect(body.sharing).toEqual(sharing(true)); // The override keeps the version it declared: re-basing is a person's call. expect(body.overrides).toEqual({ package: 'crm', basedOn: '2.0.0' }); }); @@ -220,13 +233,14 @@ describe('switchPublicForm', () => { describe('a form the installed app ships switched off', () => { const shippedOff = { 'enabled: false': formItem({}, false), - 'no enabled': formItem({ config: { title: 'Contact us', data: { object: 'crm_lead' }, sharing: { allowAnonymous: true, publicLink: 'contact-us' } } }), + 'no enabled': formItem({ sharing: { allowAnonymous: true, publicLink: 'contact-us' } }), + 'enabled: false, as an old shape': projectedItem({}, false), }; const doors = () => listed({ crm: { writable: false, version: '3.0.0' }, 'crm.custom': { writable: true, version: '0.0.0' } }); for (const [how, base] of Object.entries(shippedOff)) { it(`(${how}) is never switched on: nothing is written, and the refusal says the app ships it off`, async () => { - expect(baseShipsFormOff(base, 'web_to_lead')).toBe(true); + expect(baseShipsFormOff(base)).toBe(true); // No override yet: the list serves the app's own document. const fresh = clientOf(() => ({ code: base, effective: base })); const freshDoors = doors(); @@ -257,9 +271,9 @@ describe('switchPublicForm', () => { } it('(allowAnonymous: false) the routes\' own rule: an app that ships the form closed to anonymous visitors withdraws it, even once an override opens it', async () => { - const base = formItem({ config: { title: 'Contact us', data: { object: 'crm_lead' }, sharing: sharing(true, { allowAnonymous: false }) } }); + const base = formItem({ sharing: sharing(true, { allowAnonymous: false }) }); const override = { ...stripped(formItem()), overrides: { package: 'crm', basedOn: '3.0.0' } }; - expect(baseShipsFormOff(base, 'web_to_lead', override)).toBe(true); + expect(baseShipsFormOff(base)).toBe(true); // The served override reads on, by the candidates rule alone. const served = publicFormRowOf({ ...override, _packageId: 'crm' })!; expect(served.on).toBe(true); @@ -280,9 +294,26 @@ describe('switchPublicForm', () => { expect(marked.shippedOff).toBeUndefined(); }); + it('[#37087] does not read a form as on when the read answers no document of the app\'s own', async () => { + const client = clientOf(() => ({ code: null, effective: formItem() })); + const [marked] = await markShippedOff([publicFormRowOf(formItem())!], client, doors()); + expect(marked).toMatchObject({ on: false, unknown: true }); + // …and switching it on writes nothing. + await expect(switchPublicForm(row, true, client, {}, doors())).rejects.toMatchObject({ reason: 'load-failed' }); + expect(client.save).not.toHaveBeenCalled(); + }); + + it('[#37087] withdraws by the form\'s name whatever slug the served override declares (ADR-0159 D6 rule 6)', async () => { + const base = formItem({}, false); + const elsewhere = { ...stripped(formItem({ sharing: sharing(true, { publicLink: 'elsewhere' }) })), overrides: { package: 'crm', basedOn: '3.0.0' } }; + const client = clientOf(() => ({ code: base, effective: elsewhere })); + const [marked] = await markShippedOff([publicFormRowOf({ ...elsewhere, _packageId: 'crm' })!], client, doors()); + expect(marked).toMatchObject({ on: false, shippedOff: true }); + }); + it('leaves a form the app ships on, a writable package\'s form and a form with no package as listed', async () => { const on = formItem(); - expect(baseShipsFormOff(on, 'web_to_lead')).toBe(false); + expect(baseShipsFormOff(on)).toBe(false); const client = clientOf((name) => ({ code: name === 'own' ? formItem({}, false) : on, effective: on })); const listedDoors = listed({ crm: { writable: false, version: '3.0.0' }, mine: { writable: true } }); const rows = [ @@ -335,12 +366,22 @@ describe('switchPublicForm', () => { for (const c of [ok, unreadable]) expect(c.save).not.toHaveBeenCalled(); }); + it('[#37087] saves an old shape\'s switch as a `form` item: no `data`, no projection marker', async () => { + const doc = projectedItem(); + const client = clientOf(() => ({ code: doc, effective: doc })); + await switchPublicForm(row, false, client, {}, listed({ crm: { writable: true } })); + const [type, , body] = client.save.mock.calls[0] as unknown as [string, string, any]; + expect(type).toBe('form'); + expect(body).toEqual({ ...stripped(formItem()), sharing: sharing(false) }); + expect('data' in body).toBe(false); + }); + it('saves a form that names no package where it lives', async () => { const doc = formItem({ _packageId: undefined }); const client = clientOf(() => ({ code: doc, effective: doc })); const out = await switchPublicForm({ ...row, packageId: null }, false, client, {}, listed({})); expect(out).toBe('published'); - expect(client.layered).toHaveBeenCalledWith('view', 'web_to_lead', {}); + expect(client.layered).toHaveBeenCalledWith('form', 'web_to_lead', {}); const [, , , options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; expect(options).toEqual({ mode: 'draft', ifNoneMatch: '*' }); }); diff --git a/ui/packages/app-shell/src/views/setup/publicForms.ts b/ui/packages/app-shell/src/views/setup/publicForms.ts index 44496fc6d31..0c70321c873 100644 --- a/ui/packages/app-shell/src/views/setup/publicForms.ts +++ b/ui/packages/app-shell/src/views/setup/publicForms.ts @@ -8,8 +8,8 @@ * * ## Which forms are listed, and which are on * - * A public form is a form view item whose form the server's one rule - * (`anonymousFormIntakeCandidates`, `@objectstack/spec/ui`) opens to anonymous + * A public form is a `form` item (ADR-0159) whose `sharing` the server's one + * rule (`anonymousFormIntakeSlug`, `@objectstack/spec/ui`) opens to anonymous * intake. The rule reads three keys of its `sharing`: the switch `enabled`, * `allowAnonymous` and the `publicLink` slug. This module reads none of them * itself (the routes and this page must never disagree, objectui#11545): @@ -20,9 +20,13 @@ * whose author never made it anonymous or gave it no address is an internal * form, and is not listed. * - * The list read is the effective one (`GET /meta/view`, ADR-0146 D8): an + * The list read is the effective one (`GET /meta/form`, ADR-0146 D8): an * installed app's form switched off in its customization package is served - * switched off, so it lists as off. + * switched off, so it lists as off. A form an app still ships as an old view + * shape is served there as its projection (ADR-0159 D5, marked + * `_formDefinedIn: 'view'`), and every read and write below names `form`: + * a switch saved over an old shape is a `form` item ({@link authorableForm}), + * which supersedes the old shape at that address (card ②'s write rule). * * ## Where a switch is saved * @@ -44,15 +48,17 @@ * * ## A form the app ships switched off * - * An installed app whose own document keeps a form's address but switches it - * off (`enabled: false` or `allowAnonymous: false`, matched by slot or by - * slug) WITHDRAWS it: the anonymous routes judge the app's own document as a - * kill switch that no override re-opens (`anonymousFormIntakeWithdrawnIn`, - * pinned in `packages/rest/src/public-form-withdrawal-effective-read.test.ts`). - * This page judges it with that same function, imported from the spec. A - * switch the app's document omits counts as off too, as the stack schema - * parses it (`enabled` defaults to `false`). Such a form is listed, never as - * on ({@link markShippedOff}), and switching it on writes nothing and says the + * An installed app whose own document of a form keeps its address but switches + * it off (`enabled: false` or `allowAnonymous: false`) WITHDRAWS it: the + * anonymous routes judge the app's own document as a kill switch that no + * override re-opens, by the form's name whatever slug either side declares + * (`formExplicitlyWithdraws` in the doors' layer, `formIntakeLayer`, ADR-0159 D6 + * rule 6). This page judges it with that same function, imported from the + * spec, on the app's own document as the `form` layered read serves it (its + * `code`, the projection of an old shape included). A switch the app's + * document omits counts as off too, as the stack schema parses it (`enabled` + * defaults to `false`). Such a form is listed, never as on + * ({@link markShippedOff}), and switching it on writes nothing and says the * app ships it switched off. * * A switch is refused, and nothing is written, over a draft already pending @@ -64,7 +70,7 @@ * nothing to read. */ -import { anonymousFormIntakeCandidates, anonymousFormIntakeWithdrawnIn, anonymousFormObjectName } from '@objectstack/spec/ui'; +import { anonymousFormIntakeSlug, formExplicitlyWithdraws } from '@objectstack/spec/ui'; import { emitMetadataRefresh } from '../../assistant/assistantBus.js'; import { resolveDashboardEditTarget, @@ -84,7 +90,7 @@ const isDoc = (v: unknown): v is FormDoc => !!v && typeof v === 'object' && !Arr /** One public form, as the list read serves it. */ export interface PublicFormRow { - /** The form view item's name: the metadata address every write names. */ + /** The `form` item's name: the metadata address every write names. */ name: string; /** What the page shows as its name ({@link shownName}). */ title: string; @@ -118,46 +124,45 @@ const text = (v: unknown): string | undefined => (typeof v === 'string' && v.tri /** * The name a form is shown by, in the words its author gave it: the served - * (translated) label, else the form's title or label, else the label of its - * first section (what the form's own page heads it with), else its name - * without the object prefix (`crm_lead.web_to_lead` → `web_to_lead`). + * (translated) label, else the form's title, else the label of its first + * section (what the form's own page heads it with), else its name without + * the object prefix (`crm_lead.web_to_lead` → `web_to_lead`). */ function shownName(item: FormDoc): string { - const config: FormDoc = isDoc(item.config) ? item.config : {}; - const first = Array.isArray(config.sections) ? config.sections.find(isDoc) : undefined; + const first = Array.isArray(item.sections) ? item.sections.find(isDoc) : undefined; const dot = item.name.lastIndexOf('.'); return ( text(item.label) ?? - text(config.title) ?? - text(config.label) ?? + text(item.title) ?? text(first?.label) ?? (dot >= 0 && dot < item.name.length - 1 ? item.name.slice(dot + 1) : item.name) ); } +/** The slug the rule opens `form` at, or `null`. */ +const openSlug = (form: FormDoc): string | null => anonymousFormIntakeSlug(form.sharing); + /** - * The public form a served view item carries, or `null` (module header): a - * `viewKind: 'form'` item whose `config` the rule opens once its switch is on. - * The list serves view ITEMS only, so a form is its item's `config`. + * The public form a served `form` item is, or `null` (module header): an item + * whose `sharing` the rule opens once its switch is on. A `form` item carries + * its body at the top level, the projection of an old shape included. */ export function publicFormRowOf(item: unknown): PublicFormRow | null { - if (!isDoc(item) || item.viewKind !== 'form' || !isDoc(item.config) || typeof item.name !== 'string') return null; - const switchedOn = anonymousFormIntakeCandidates({ ...item, config: withSwitch(item.config, true) }); - const listed = switchedOn.find((c) => c.key === item.name); - if (!listed) return null; - const on = anonymousFormIntakeCandidates(item).some((c) => c.key === item.name); + if (!isDoc(item) || typeof item.name !== 'string' || !item.name) return null; + const slug = openSlug(withSwitch(item, true)); + if (slug === null) return null; const packageId = typeof item._packageId === 'string' && item._packageId ? item._packageId : null; return { name: item.name, title: shownName(item), - object: anonymousFormObjectName(item, item.config), - slug: listed.slug, - on, + ...(typeof item.object === 'string' && item.object ? { object: item.object } : {}), + slug, + on: openSlug(item) !== null, packageId, }; } -/** Every public form of a `GET /meta/view` answer (`{ items }`, or a bare array), sorted by name shown. */ +/** Every public form of a `GET /meta/form` answer (`{ items }`, or a bare array), sorted by name shown. */ export function publicFormRowsOf(answer: unknown): PublicFormRow[] { const items: unknown[] = Array.isArray(answer) ? answer : isDoc(answer) && Array.isArray(answer.items) ? answer.items : []; const rows: PublicFormRow[] = []; @@ -198,10 +203,15 @@ export class PublicFormSwitchRefusal extends Error { } } -/** A document without the read's `_` decorations. */ -function authored(doc: FormDoc): FormDoc { +/** + * A served form as a `form` item a save takes: without the read's `_` + * decorations (the projection's `_formDefinedIn` included) and without + * `data`, the old shape's binding, which a `form` item never carries: it is + * bound by its `object` (ADR-0159 D2; the save refuses `data` by name). + */ +export function authorableForm(doc: FormDoc): FormDoc { const out: FormDoc = {}; - for (const [key, value] of Object.entries(doc)) if (!key.startsWith('_')) out[key] = value; + for (const [key, value] of Object.entries(doc)) if (!key.startsWith('_') && key !== 'data') out[key] = value; return out; } @@ -219,34 +229,26 @@ function canonical(value: unknown): string { */ export function overrideHoldsOnlySwitch(override: FormDoc, base: FormDoc): boolean { const strip = (doc: FormDoc) => { - const out = authored(doc); + const out = withSwitch(authorableForm(doc), true); delete out.overrides; - if (isDoc(out.config)) out.config = withSwitch(out.config, true); return out; }; return canonical(strip(override)) === canonical(strip(base)); } /** - * Whether an installed app's own document `base` of the form `name` ships it - * switched off (module header), judged by the routes' own rule: `base` - * withdraws the form `served` carries (the effective item, an override - * included; `base` itself when omitted), matched by slot or by slug - * (`anonymousFormIntakeWithdrawnIn`). The served form is judged with its switch - * on, the state a switch-on would leave it in. A switch the app's document - * omits counts as off as well, as the stack schema parses it, so the console - * fails closed where the routes do. + * Whether an installed app's own document `base` of a form ships it switched + * off (module header), judged by the routes' own rule: the doors close a form + * whose name's body explicitly withdraws it (`formExplicitlyWithdraws`), + * whatever slug the served form declares (ADR-0159 D6 rule 6). A switch the + * app's document omits counts as off as well, as the stack schema parses it, + * so the console fails closed where the routes do. */ -export function baseShipsFormOff(base: unknown, name: string, served?: unknown): boolean { - if (!isDoc(base) || !isDoc(base.config)) return false; - const named = { ...base, name }; - const view: FormDoc = isDoc(served) ? { ...served, name } : named; - const probe = isDoc(view.config) ? { ...view, config: withSwitch(view.config, true) } : view; - const candidates = anonymousFormIntakeCandidates(probe).filter((c) => c.key === name); - if (candidates.some((c) => anonymousFormIntakeWithdrawnIn([named], probe, c))) return true; +export function baseShipsFormOff(base: unknown): boolean { + if (!isDoc(base)) return false; + if (formExplicitlyWithdraws(base) !== undefined) return true; // An omitted switch: the app's document would open the form switched on, but does not as written. - const wouldOpen = anonymousFormIntakeCandidates({ ...named, config: withSwitch(base.config, true) }).some((c) => c.key === name); - return wouldOpen && !anonymousFormIntakeCandidates(named).some((c) => c.key === name); + return openSlug(withSwitch(base, true)) !== null && openSlug(base) === null; } type FormLayers = { code?: unknown; effective?: unknown; draft?: unknown }; @@ -264,10 +266,10 @@ async function readFormLayers(name: string, target: ResolvedTarget, client: Pick : target.kind === 'package' ? { packageId: target.packageId } : { packageId: target.pair ?? target.base }; - const layers = await client.layered('view', name, at); + const layers = await client.layered('form', name, at); // A listed pair that does not hold the form yet holds nothing: its base's document is read. if (target.kind === 'customization' && target.pair && !isDoc(layers.effective) && !isDoc(layers.code)) { - return client.layered('view', name, { packageId: target.base }); + return client.layered('form', name, { packageId: target.base }); } return layers; } @@ -296,8 +298,9 @@ export async function markShippedOff( if (target.kind !== 'customization') return row; try { const layers = await readFormLayers(row.name, target, client); - const served = isDoc(layers.effective) ? layers.effective : layers.code; - return baseShipsFormOff(layers.code, row.name, served) ? { ...row, on: false, shippedOff: true } : row; + // No document of the app's own: whether the routes serve the form is not known. + if (!isDoc(layers.code)) return { ...row, on: false, unknown: true }; + return baseShipsFormOff(layers.code) ? { ...row, on: false, shippedOff: true } : row; } catch { return { ...row, on: false, unknown: true }; } @@ -328,25 +331,27 @@ export async function switchPublicForm( throw new PublicFormSwitchRefusal('load-failed', err instanceof Error ? err.message : String(err)); } const effective = isDoc(layers.effective) ? layers.effective : isDoc(layers.code) ? layers.code : null; - if (!effective || !isDoc(effective.config)) throw new PublicFormSwitchRefusal('load-failed', row.name); - const switched = { ...authored(effective), config: withSwitch(effective.config, on) }; + if (!effective) throw new PublicFormSwitchRefusal('load-failed', row.name); + const switched = withSwitch(authorableForm(effective), on); - if (target.kind === 'unbound') return saveAndPublishRuntimeMetadata('view', row.name, switched, persist); - if (target.kind === 'package') return saveAndPublishInPackage('view', row.name, switched, target.packageId, persist); + if (target.kind === 'unbound') return saveAndPublishRuntimeMetadata('form', row.name, switched, persist); + if (target.kind === 'package') return saveAndPublishInPackage('form', row.name, switched, target.packageId, persist); // An installed app: this environment's customization, in the app's pair. const declared = declaredOverrideOf(effective, target.base); const override = declared ? effective : null; const base = isDoc(layers.code) ? layers.code : null; // The app ships the form switched off: no override re-opens it, so nothing is written. - if (on && baseShipsFormOff(base, row.name, effective)) throw new PublicFormSwitchRefusal('shipped-off', target.base); - if (on && override && base && isDoc(base.config)) { - const baseOn = anonymousFormIntakeCandidates({ ...base, name: row.name }).some((c) => c.key === row.name); + // No document of the app's own: nothing tells whether it ships the form switched off. + if (on && !base) throw new PublicFormSwitchRefusal('load-failed', row.name); + if (on && baseShipsFormOff(base)) throw new PublicFormSwitchRefusal('shipped-off', target.base); + if (on && override && base) { + const baseOn = openSlug(base) !== null; if (baseOn && overrideHoldsOnlySwitch(override, base) && target.pair) { // A draft pending over the override is its saver's: nothing is removed under it. if (isDoc(layers.draft)) return 'pending-draft'; // "Restore package original": the pair's row of the form is removed. - await client.reset('view', row.name, { packageId: target.pair }); + await client.reset('form', row.name, { packageId: target.pair }); if (row.object) persist.dataSource?.invalidateViewKeys?.(row.object, row.name); emitMetadataRefresh(); return 'restored'; @@ -356,7 +361,7 @@ export async function switchPublicForm( if (body === null) throw new PublicFormSwitchRefusal('no-version', target.base); const saveTarget = await ensureDashboardSaveTarget(target, doors); if (saveTarget.kind !== 'customization') throw new PublicFormSwitchRefusal('no-package', target.base); - const outcome = await saveAndPublishInPackage('view', row.name, body, saveTarget.packageId, persist); + const outcome = await saveAndPublishInPackage('form', row.name, body, saveTarget.packageId, persist); // Switched on over an override taken from an earlier version of the app: the form stays on that version. if (on && outcome === 'published' && declared && target.basedOn && declared.basedOn !== target.basedOn) { return { kind: 'earlier-version', basedOn: declared.basedOn }; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx b/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx index 5fbec23127f..b31aa9c6419 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx @@ -64,6 +64,7 @@ import { StudioBundleItemEditor } from './StudioBundleItemEditor.js'; import { AutomationsPillar } from './AutomationsPillar.js'; import { DataPillar } from './DataPillar.js'; import { StudioPermissionSetPage } from './StudioPermissionSetPage.js'; +import { FormItemPage } from './publicForm/PublicFormsDesigner.js'; import { BUNDLE_MEMBER_PARAM, getMetadataResource } from '../metadata-admin/registry.js'; import { ITEM_TOOL_TAB_PARAM } from '../item-tools/ItemToolTabs.js'; import type { StudioBaseCustomization } from './StudioDesignSurface.js'; @@ -266,6 +267,19 @@ function AreaItemOpen({ /> ); } + // objectstack#37087 — a form opens Studio's form editor (its registered + // `EditPage`), handed what only the area's surface holds: a read-only base's + // customization, where a form the app ships is saved as a declared override. + if (type === 'form' && host?.packageId) { + return ( + + ); + } return ; } diff --git a/ui/packages/app-shell/src/views/studio-design/publicForm/PublicFormsDesigner.test.tsx b/ui/packages/app-shell/src/views/studio-design/publicForm/PublicFormsDesigner.test.tsx new file mode 100644 index 00000000000..67790ad802a --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/publicForm/PublicFormsDesigner.test.tsx @@ -0,0 +1,527 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36444, objectstack#37087 — Studio's `form` editor, over a + * metadata client double: the HotCRM acceptance walk on the CRM example's lead + * form, read and written as a `form` item (ADR-0159). + * + * - editing an installed app's form (make Phone required, remove Title, change + * the title) saves a draft in its customization package, declaring the + * override, then publishes it there; the app's own package is never written; + * - an old-shape form (served through the projection, with `data`) is saved + * as a `form` item without it; + * - removing a field the object requires is refused, with the reason; + * - a new form (four fields) is drafted where the editor is open; + * - an address another form uses is refused, and nothing can be saved; + * - the preview renders the form being edited; + * - a form the app ships cannot be deleted; a form of a writable package can; + * - a new form's name may be no other form's; + * - the editor has no switch: a save and a publish carry the form's sharing as + * stored at that time (a form Setup switched off stays off), and write + * nothing when it cannot be read; + * - the server's address refusal its own check missed (`409 + * FORM_ADDRESS_TAKEN`) is shown as the address clash, and any other `409` + * as a pending draft. + * + * The runtime form renderer is stubbed: it renders the sections it is given. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import React from 'react'; + +vi.mock('@object-ui/plugin-form', async (importOriginal) => ({ + ...(await importOriginal>()), + ObjectForm: ({ schema }: { schema: { sections: Array<{ label?: string; fields: Array<{ field: string; required?: boolean }> }> } }) => ( +
+ {schema.sections.map((s, i) => ( +
+ {s.label &&

{s.label}

} + {s.fields.map((f) => ( + + {f.field} + + ))} +
+ ))} +
+ ), +})); +vi.mock('../../../assistant/assistantBus.js', () => ({ emitMetadataRefresh: vi.fn() })); +vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); + +import { FormSchema } from '@objectstack/spec/ui'; +import { FormItemEditor } from './PublicFormsDesigner'; + +afterEach(cleanup); + +const BASE = 'com.example.crm'; +const PAIR = 'com.example.crm.custom'; + +const lead = { + name: 'crm_lead', + fields: { + name: { type: 'text', label: 'Lead Name', required: true }, + company: { type: 'text', label: 'Company' }, + email: { type: 'email', label: 'Email', required: true }, + phone: { type: 'phone', label: 'Phone' }, + title: { type: 'text', label: 'Title' }, + score: { type: 'formula', label: 'Score' }, + }, +}; + +/** The CRM's contact-us form, as its `form` item. */ +const contactUs = (): Record => ({ + name: 'crm_lead.web_to_lead', + object: 'crm_lead', + type: 'simple', + sections: [ + { + name: 'contact_us', + label: 'Contact us', + columns: 1, + fields: [{ field: 'name', required: true }, { field: 'company' }, { field: 'email', required: true }, { field: 'phone' }, { field: 'title' }], + }, + ], + sharing: { enabled: true, publicLink: '/forms/contact-us', allowAnonymous: true }, +}); + +const drafted = { + name: 'crm_lead.event_rsvp', + object: 'crm_lead', + label: 'Event RSVP', + sections: [{ name: 'main', fields: [{ field: 'name', required: true }, { field: 'email', required: true }] }], + sharing: { enabled: true, publicLink: '/forms/event-rsvp', allowAnonymous: true }, +}; + +function clientDouble(opts: { owner?: string; appDoc?: Record } = {}) { + const owner = opts.owner ?? BASE; + const appDoc = opts.appDoc ?? contactUs(); + // What is stored now: the served contact-us form (Setup may switch it meanwhile), and the drafts saved. + // The served form is read at the package that ships it (a read at a customization package finds no served item there). + const stored = { + served: { ...appDoc, _packageId: owner } as Record, + drafts: new Map>([['crm_lead.event_rsvp', drafted]]), + /** A layered read fails (the server is unreachable). */ + readsFail: false, + }; + const client = { + stored, + list: vi.fn(async () => [ + stored.served, + { name: 'crm_lead.quick_add', object: 'crm_lead', sections: [], _packageId: owner }, + { ...contactUs(), name: 'crm_account.signup', object: 'crm_account', sharing: { enabled: false, allowAnonymous: true, publicLink: '/forms/signup' }, _packageId: owner }, + ]), + listDrafts: vi.fn(async () => [{ type: 'form', name: 'crm_lead.event_rsvp', packageId: owner }]), + getDraft: vi.fn(async (_t: string, name: string) => stored.drafts.get(name) ?? null), + get: vi.fn(async (type: string, name: string) => (type === 'object' && name === 'crm_lead' ? lead : null)), + layered: vi.fn(async (_t: string, name: string, options?: { packageId?: string }) => { + if (stored.readsFail) throw new Error('503 Service Unavailable'); + const draft = stored.drafts.get(name) ?? null; + if (name !== 'crm_lead.web_to_lead') return { code: null, effective: null, draft }; + const atOwner = options?.packageId === undefined || options.packageId === owner; + return { code: atOwner ? appDoc : null, effective: atOwner ? stored.served : null, draft }; + }), + save: vi.fn(async (_t: string, name: string, body: Record) => { + stored.drafts.set(name, body); + return {}; + }), + publish: vi.fn(async () => ({})), + reset: vi.fn(async () => ({})), + }; + return client; +} + +/** Setup switches the served contact-us form on or off. */ +function switchServed(client: ReturnType, enabled: boolean) { + const served = client.stored.served; + client.stored.served = { ...served, sharing: { ...served.sharing, enabled } }; +} + +const customization = () => ({ + base: BASE, + baseLabel: 'CRM', + basedOn: '4.0.0', + walled: false, + pairId: null, + ensure: vi.fn(async () => PAIR), + ensurePackage: vi.fn(), + marks: { state: 'loaded' } as never, +}); + +function renderEditor(client: ReturnType, extra: Partial> = {}) { + const onDraftSaved = vi.fn(); + const onCreated = vi.fn(); + const onDeleted = vi.fn(); + render( + , + ); + return { onDraftSaved, onCreated, onDeleted }; +} + +const OWN = { readOnly: false, customization: null, packageId: 'com.acme.sales' } as const; + +/** A new form of the lead object, its title typed (the address follows it). */ +async function startNew(user: ReturnType, title: string) { + await user.selectOptions(await screen.findByTestId('public-form-create-object'), 'crm_lead'); + await user.type(screen.getByTestId('public-form-create-title'), title); +} + +describe('Studio form editor (objectstack#36444, objectstack#37087)', () => { + it('edits an installed app\'s form as a customization: Phone required, Title removed, a new title; then publishes it there', async () => { + const user = userEvent.setup(); + const client = clientDouble(); + const custom = customization(); + const { onDraftSaved } = renderEditor(client, { customization: custom as never }); + await screen.findByTestId('public-form-title'); + await screen.findByTestId('public-form-required-phone'); + + await user.click(screen.getByTestId('public-form-required-phone')); + await user.click(screen.getByTestId('public-form-remove-title')); + const title = screen.getByTestId('public-form-title'); + await user.clear(title); + await user.type(title, 'Talk to sales'); + + // The live preview follows the edit. + expect(screen.getByTestId('public-form-preview-title')).toHaveTextContent('Talk to sales'); + expect(screen.getByTestId('preview-field-phone')).toHaveAttribute('data-required', 'true'); + expect(screen.queryByTestId('preview-field-title')).toBeNull(); + + await user.click(screen.getByTestId('public-form-save')); + await waitFor(() => expect(client.save).toHaveBeenCalledTimes(1)); + expect(custom.ensure).toHaveBeenCalled(); + const [type, name, body, options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; + expect([type, name]).toEqual(['form', 'crm_lead.web_to_lead']); + expect(options).toMatchObject({ mode: 'draft', packageId: PAIR, surface: 'studio', ifNoneMatch: '*' }); + expect(body.overrides).toEqual({ package: BASE, basedOn: '4.0.0' }); + expect(body._packageId).toBeUndefined(); + expect(body.label).toBe('Talk to sales'); + expect(body.title).toBe('Talk to sales'); + expect(body.config).toBeUndefined(); + expect(body.sections[0].fields).toEqual([ + { field: 'name', required: true }, + { field: 'company' }, + { field: 'email', required: true }, + { field: 'phone', required: true }, + ]); + expect(body.sharing).toEqual({ enabled: true, publicLink: '/forms/contact-us', allowAnonymous: true }); + expect(FormSchema.safeParse(body).success).toBe(true); + expect(onDraftSaved).toHaveBeenCalledWith({ type: 'form', name: 'crm_lead.web_to_lead' }); + + await user.click(await screen.findByTestId('public-form-publish')); + await waitFor(() => expect(client.publish).toHaveBeenCalledWith('form', 'crm_lead.web_to_lead', { packageId: PAIR })); + // Nothing is ever written to the app's own package. + for (const call of [...client.save.mock.calls, ...client.publish.mock.calls] as unknown as unknown[][]) { + expect(JSON.stringify(call)).not.toContain(`"packageId":"${BASE}"`); + } + }); + + it('saves an old-shape form (served through the projection) as a `form` item, without its `data`', async () => { + const user = userEvent.setup(); + const projected = { ...contactUs(), data: { provider: 'object', object: 'crm_lead' }, _formDefinedIn: 'view' }; + const client = clientDouble({ appDoc: projected }); + renderEditor(client); + await user.type(await screen.findByTestId('public-form-title'), 'Contact us'); + await user.click(screen.getByTestId('public-form-save')); + await waitFor(() => expect(client.save).toHaveBeenCalledTimes(1)); + const [type, , body] = client.save.mock.calls[0] as unknown as [string, string, any]; + expect(type).toBe('form'); + expect(body.data).toBeUndefined(); + expect(body._formDefinedIn).toBeUndefined(); + expect(FormSchema.safeParse(body).success).toBe(true); + }); + + it('refuses to remove a field the object requires, and says why', async () => { + const user = userEvent.setup(); + renderEditor(clientDouble()); + await user.click(await screen.findByTestId('public-form-remove-email')); + expect(screen.getByTestId('public-form-notice')).toHaveTextContent('“Email” cannot be removed: the object requires it'); + expect(screen.getByTestId('public-form-field-email')).toBeInTheDocument(); + // And it stays required: its box is checked and cannot be cleared. + expect(screen.getByTestId('public-form-required-email')).toBeChecked(); + expect(screen.getByTestId('public-form-required-email')).toBeDisabled(); + }); + + it('creates a new form with four fields, drafted where the editor is open, then opens it at its own address', async () => { + const user = userEvent.setup(); + const client = clientDouble({ owner: 'com.acme.sales' }); + const { onCreated } = renderEditor(client, { ...OWN, name: null }); + await startNew(user, 'Demo signup'); + expect(screen.getByTestId('public-form-create-address')).toHaveValue('demo-signup'); + await waitFor(() => expect(screen.getByTestId('public-form-create-confirm')).toBeEnabled()); + await user.click(screen.getByTestId('public-form-create-confirm')); + + // Starts with the fields the object requires; two more are added. + expect(await screen.findByTestId('public-form-field-name')).toBeInTheDocument(); + expect(screen.getByTestId('public-form-field-email')).toBeInTheDocument(); + await user.selectOptions(screen.getByTestId('public-form-add-field-main'), 'company'); + await user.selectOptions(screen.getByTestId('public-form-add-field-main'), 'phone'); + // A formula is never offered. + expect(within(screen.getByTestId('public-form-add-field-main')).queryByText('Score')).toBeNull(); + + await user.click(screen.getByTestId('public-form-save')); + await waitFor(() => expect(client.save).toHaveBeenCalledTimes(1)); + const [type, name, body, options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; + expect([type, name]).toEqual(['form', 'crm_lead.demo_signup']); + expect(options).toMatchObject({ mode: 'draft', packageId: 'com.acme.sales', ifNoneMatch: '*' }); + expect(body).toMatchObject({ name: 'crm_lead.demo_signup', object: 'crm_lead', label: 'Demo signup' }); + expect(body.sections[0].fields.map((f: { field: string }) => f.field)).toEqual(['name', 'email', 'company', 'phone']); + expect(body.sharing).toEqual({ enabled: true, allowAnonymous: true, publicLink: '/forms/demo-signup' }); + expect(body.overrides).toBeUndefined(); + expect(FormSchema.safeParse(body).success).toBe(true); + expect(onCreated).toHaveBeenCalledWith('crm_lead.demo_signup', 'com.acme.sales'); + }); + + it('refuses an address another form uses, switched off or not, and saves nothing', async () => { + const user = userEvent.setup(); + const client = clientDouble(); + renderEditor(client, { name: null }); + await startNew(user, 'Contact us'); + await waitFor(() => + expect(screen.getByTestId('public-form-create-address-problem')).toHaveTextContent('Another form already uses this address'), + ); + expect(screen.getByTestId('public-form-create-confirm')).toBeDisabled(); + // The address of a switched-off form of another object is taken too. + await user.clear(screen.getByTestId('public-form-create-address')); + await user.type(screen.getByTestId('public-form-create-address'), 'signup'); + expect(screen.getByTestId('public-form-create-confirm')).toBeDisabled(); + cleanup(); + + // An existing form moved onto another's address cannot be saved. + renderEditor(client); + const address = await screen.findByTestId('public-form-address'); + await waitFor(() => expect(client.getDraft).toHaveBeenCalled()); + await user.clear(address); + await user.type(address, 'event-rsvp'); + expect(await screen.findByTestId('public-form-address-problem')).toHaveTextContent('crm_lead.event_rsvp'); + expect(screen.getByTestId('public-form-save')).toBeDisabled(); + expect(client.save).not.toHaveBeenCalled(); + }); + + it('groups fields into a named section', async () => { + const user = userEvent.setup(); + renderEditor(clientDouble()); + await user.click(await screen.findByTestId('public-form-add-section')); + const sections = within(screen.getByTestId('public-form-sections')).getAllByTestId(/^public-form-section-label-/); + expect(sections).toHaveLength(2); + await user.clear(sections[1]); + await user.type(sections[1], 'About you'); + expect(screen.getAllByTestId('preview-section')).toHaveLength(2); + expect(screen.getByText('About you', { selector: 'h4' })).toBeInTheDocument(); + }); + + it('does not delete a form the app ships; deletes one of a writable package', async () => { + const user = userEvent.setup(); + renderEditor(clientDouble()); + expect(await screen.findByTestId('public-form-delete-shipped')).toHaveTextContent('switch it off in Setup'); + cleanup(); + + const own = clientDouble({ owner: 'com.acme.sales' }); + const { onDeleted } = renderEditor(own, OWN); + await user.click(await screen.findByTestId('public-form-delete')); + await user.click(screen.getByTestId('public-form-delete-yes')); + await waitFor(() => expect(own.reset).toHaveBeenCalledWith('form', 'crm_lead.web_to_lead', { packageId: 'com.acme.sales' })); + expect(onDeleted).toHaveBeenCalled(); + }); + + it('refuses a new form whose name another form of the object already has', async () => { + const user = userEvent.setup(); + const client = clientDouble(); + renderEditor(client, { name: null }); + // `quick add` names the new form `crm_lead.quick_add`: the object's internal form. + await startNew(user, 'Quick add'); + expect(screen.getByTestId('public-form-create-address')).toHaveValue('quick-add'); + await waitFor(() => + expect(screen.getByTestId('public-form-create-address-problem')).toHaveTextContent('Another form already uses this address'), + ); + expect(screen.getByTestId('public-form-create-confirm')).toBeDisabled(); + // A form only drafted too. + await user.clear(screen.getByTestId('public-form-create-address')); + await user.type(screen.getByTestId('public-form-create-address'), 'event-rsvp'); + expect(screen.getByTestId('public-form-create-confirm')).toBeDisabled(); + // A free one is accepted. + await user.clear(screen.getByTestId('public-form-create-address')); + await user.type(screen.getByTestId('public-form-create-address'), 'all-leads'); + expect(screen.getByTestId('public-form-create-confirm')).toBeEnabled(); + expect(client.save).not.toHaveBeenCalled(); + }); + + it('has no switch: saves and publishes the form\'s sharing as it is stored at that time, not as it was when the form was opened', async () => { + const user = userEvent.setup(); + const client = clientDouble({ owner: 'com.acme.sales' }); + renderEditor(client, OWN); + const title = await screen.findByTestId('public-form-title'); + expect(screen.queryByRole('switch')).toBeNull(); + expect(screen.getByTestId('public-form-switch-in-setup')).toHaveTextContent('Setup'); + // Switched off in Setup after the form was opened here. + switchServed(client, false); + await user.type(title, '!'); + await user.click(screen.getByTestId('public-form-save')); + await waitFor(() => expect(client.save).toHaveBeenCalledTimes(1)); + const [, , body] = client.save.mock.calls[0] as unknown as [string, string, any]; + expect(body.sharing.enabled).toBe(false); + expect(body.title).toBe('!'); + + // Switched back on before the draft is published: the draft is brought in line first. + switchServed(client, true); + await user.click(screen.getByTestId('public-form-publish')); + await waitFor(() => expect(client.publish).toHaveBeenCalledTimes(1)); + expect(client.save).toHaveBeenCalledTimes(2); + const [, , again, options] = client.save.mock.calls[1] as unknown as [string, string, any, any]; + expect(again.sharing.enabled).toBe(true); + expect(again.title).toBe('!'); + expect(options).toMatchObject({ mode: 'draft', packageId: 'com.acme.sales' }); + expect(client.save.mock.invocationCallOrder[1]).toBeLessThan(client.publish.mock.invocationCallOrder[0]); + }); + + it('publishes a draft whose sharing is the stored one without saving it again', async () => { + const user = userEvent.setup(); + const client = clientDouble({ owner: 'com.acme.sales' }); + renderEditor(client, OWN); + await user.type(await screen.findByTestId('public-form-title'), '!'); + await user.click(screen.getByTestId('public-form-save')); + await waitFor(() => expect(client.save).toHaveBeenCalledTimes(1)); + await user.click(screen.getByTestId('public-form-publish')); + await waitFor(() => expect(client.publish).toHaveBeenCalledTimes(1)); + expect(client.save).toHaveBeenCalledTimes(1); + }); + + it('publishes an installed app\'s form with the switch as stored at the app, after it was switched off', async () => { + const user = userEvent.setup(); + const client = clientDouble(); + const custom = customization(); + renderEditor(client, { customization: custom as never }); + await user.type(await screen.findByTestId('public-form-title'), '!'); + await user.click(screen.getByTestId('public-form-save')); + await waitFor(() => expect(client.save).toHaveBeenCalledTimes(1)); + expect((client.save.mock.calls[0] as unknown as [string, string, any])[2].sharing.enabled).toBe(true); + + // Switched off in Setup while the draft waits: the draft (on) is saved again, off, before it goes live. + switchServed(client, false); + // The draft read for display comes back translated; the one written back is the stored draft, never that. + client.getDraft.mockImplementation(async (_t: string, name: string) => { + const d = client.stored.drafts.get(name); + return d ? { ...d, title: '¡Gracias!' } : null; + }); + client.layered.mockClear(); + await user.click(screen.getByTestId('public-form-publish')); + await waitFor(() => expect(client.publish).toHaveBeenCalledWith('form', 'crm_lead.web_to_lead', { packageId: PAIR })); + // The customization package serves nothing yet, so the switch is read where the app ships the form. + expect(client.layered.mock.calls.slice(0, 2).map((c) => (c as unknown[])[2])).toEqual([{ packageId: PAIR }, { packageId: BASE }]); + expect(client.save).toHaveBeenCalledTimes(2); + const [, , again, options] = client.save.mock.calls[1] as unknown as [string, string, any, any]; + expect(again.sharing.enabled).toBe(false); + expect(again.title).toBe('!'); + expect(again.overrides).toEqual({ package: BASE, basedOn: '4.0.0' }); + expect(options).toMatchObject({ mode: 'draft', packageId: PAIR }); + expect(client.save.mock.invocationCallOrder[1]).toBeLessThan(client.publish.mock.invocationCallOrder[0]); + }); + + it('saves nothing when the form\'s switch cannot be read', async () => { + const user = userEvent.setup(); + const client = clientDouble({ owner: 'com.acme.sales' }); + renderEditor(client, OWN); + await user.type(await screen.findByTestId('public-form-title'), '!'); + client.stored.readsFail = true; + await user.click(screen.getByTestId('public-form-save')); + expect(await screen.findByTestId('public-form-notice')).toBeInTheDocument(); + expect(client.save).not.toHaveBeenCalled(); + }); + + it('publishes nothing when the draft cannot be read', async () => { + const user = userEvent.setup(); + const client = clientDouble({ owner: 'com.acme.sales' }); + renderEditor(client, OWN); + await user.type(await screen.findByTestId('public-form-title'), '!'); + await user.click(screen.getByTestId('public-form-save')); + await waitFor(() => expect(client.save).toHaveBeenCalledTimes(1)); + + // The read fails outright. + client.stored.readsFail = true; + await user.click(screen.getByTestId('public-form-publish')); + expect(await screen.findByTestId('public-form-notice')).toBeInTheDocument(); + // The read answers, but with no draft in it. + await user.click(screen.getByRole('button', { name: 'Dismiss' })); + expect(screen.queryByTestId('public-form-notice')).toBeNull(); + client.stored.readsFail = false; + client.stored.drafts.delete('crm_lead.web_to_lead'); + await user.click(screen.getByTestId('public-form-publish')); + expect(await screen.findByTestId('public-form-notice')).toBeInTheDocument(); + expect(client.publish).not.toHaveBeenCalled(); + expect(client.save).toHaveBeenCalledTimes(1); + }); + + it('edits a form with no public address (one an action opens) without asking for one', async () => { + const user = userEvent.setup(); + const client = clientDouble({ owner: 'com.acme.sales' }); + const internal = { name: 'crm_lead.quick_add', object: 'crm_lead', sections: [{ name: 'main', fields: [{ field: 'name', required: true }, { field: 'email', required: true }] }], _packageId: 'com.acme.sales' }; + client.layered.mockImplementation(async (_t: string, name: string) => ({ + code: null, + effective: name === 'crm_lead.quick_add' ? internal : null, + draft: client.stored.drafts.get(name) ?? null, + })); + renderEditor(client, { ...OWN, name: 'crm_lead.quick_add' }); + await user.type(await screen.findByTestId('public-form-title'), 'Quick add'); + expect(screen.queryByTestId('public-form-address')).toBeNull(); + await user.click(screen.getByTestId('public-form-save')); + await waitFor(() => expect(client.save).toHaveBeenCalledTimes(1)); + const [, , body] = client.save.mock.calls[0] as unknown as [string, string, any]; + expect(body.sharing).toBeUndefined(); + expect(body.title).toBe('Quick add'); + }); + + /** A refusal as the metadata client throws it: the envelope's status and code on the error. */ + const refusal = (status: number, code: string, message: string) => Object.assign(new Error(message), { status, code }); + + it('shows the server\'s address refusal its own check missed (409 FORM_ADDRESS_TAKEN) as the address clash, at save and at publish', async () => { + const user = userEvent.setup(); + const client = clientDouble({ owner: 'com.acme.sales' }); + renderEditor(client, OWN); + await user.type(await screen.findByTestId('public-form-title'), '!'); + // Another form took the address after this one was read: the editor's own check saw it free. + client.save.mockRejectedValueOnce( + refusal(409, 'FORM_ADDRESS_TAKEN', "The form 'crm_lead.web_to_lead' cannot open the public address '/forms/contact-us': the form 'crm_lead.other' holds it."), + ); + await user.click(screen.getByTestId('public-form-save')); + const notice = await screen.findByTestId('public-form-notice'); + expect(notice).toHaveTextContent('Another form already uses this address. Choose a different one.'); + expect(notice).not.toHaveTextContent('draft of this form pending'); + + // The same refusal at publish (a draft whose address another form took after it was saved). + await user.click(screen.getByRole('button', { name: 'Dismiss' })); + await user.click(screen.getByTestId('public-form-save')); + await waitFor(() => expect(client.save).toHaveBeenCalledTimes(2)); + client.publish.mockRejectedValueOnce(refusal(409, 'FORM_ADDRESS_TAKEN', 'taken')); + await user.click(await screen.findByTestId('public-form-publish')); + expect(await screen.findByTestId('public-form-notice')).toHaveTextContent('Another form already uses this address. Choose a different one.'); + }); + + it('CONTROL: shows any other 409 as a pending draft', async () => { + const user = userEvent.setup(); + const client = clientDouble({ owner: 'com.acme.sales' }); + renderEditor(client, OWN); + await user.type(await screen.findByTestId('public-form-title'), '!'); + client.save.mockRejectedValueOnce(refusal(409, 'METADATA_CONFLICT', 'A draft exists.')); + await user.click(screen.getByTestId('public-form-save')); + const notice = await screen.findByTestId('public-form-notice'); + expect(notice).toHaveTextContent('Someone else has a draft of this form pending. Reopen the form to see it.'); + expect(notice).not.toHaveTextContent('already uses this address'); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/publicForm/PublicFormsDesigner.tsx b/ui/packages/app-shell/src/views/studio-design/publicForm/PublicFormsDesigner.tsx new file mode 100644 index 00000000000..f38d6e4f03e --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/publicForm/PublicFormsDesigner.tsx @@ -0,0 +1,1006 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Studio's `form` editor (objectstack#36444, objectstack#37087, ADR-0159 D9): + * the page a `form` item opens on, and the page its list's New opens. Pick a + * form's fields (fillable ones only), drag them into order, mark them required + * and group them into named sections; set its title, description, after-submit + * message and address; see it live as it is edited. A new form is made here + * too, and a form of a writable package deleted. + * + * The editor reads and writes the `form` item, whose body sits at the top + * level (ADR-0159 ruled question 5). Saves go through Studio's draft → publish + * path: Save draft writes the form's draft where it is edited (its package, or + * on an installed app its customization package, as a declared override of a + * form the app ships), and Publish puts it live. + * + * The editor has no switch: switching a form on or off is Setup's (Setup → + * Public forms). Its save is a whole-document override at the address Setup's + * switch-only override sits at (ADR-0159 D4), so every save and publish writes + * `sharing.enabled` and `sharing.allowAnonymous` as they are stored at that + * moment, read again then: a publish from here never opens a form Setup + * switched off. + * + * The rules (fillable fields, object-required fields, the address) are + * `publicFormDesign.ts`'s. + */ + +import * as React from 'react'; +import { useHref, useLocation, useNavigate, useSearchParams } from 'react-router-dom'; +import { toast } from 'sonner'; +import { ArrowDown, ArrowUp, GripVertical, Loader2, Plus, Trash2, X } from 'lucide-react'; +import type { MetadataClient } from '@object-ui/data-objectstack'; +import { ObjectForm } from '@object-ui/plugin-form'; +import { SchemaRendererProvider, useAdapter, useMetadata } from '@object-ui/react'; +import { emitMetadataRefresh } from '../../../assistant/assistantBus.js'; +import { t, tFormat, useMetadataLocale } from '../../metadata-admin/i18n.js'; +import { useMetadataClient } from '../../metadata-admin/useMetadata.js'; +import { useMetadataAreaHost } from '../../metadata-admin/metadataAreaHost.js'; +import { declaredOverrideOf, overrideDraftBody } from '../customizeOverride.js'; +import { formPreviewSource } from '../DataPillarHelpers.js'; +import { authorableForm } from '../../setup/publicForms.js'; +import type { StudioBaseCustomization, StudioSavedDraft } from '../StudioPillarKit.js'; +import { + addressProblem, + fieldsOnForm, + fillableFields, + missingRequiredFields, + newPublicFormModel, + newPublicFormName, + previewSectionsOf, + publicFormItemOf, + publicFormModelOf, + removeFieldRefusal, + slugFromTitle, + takenAddresses, + withField, + withFieldMoved, + withoutField, + withoutSection, + withRequired, + withSection, + withSectionLabel, + withSectionMoved, + type PublicFormModel, +} from './publicFormDesign.js'; + +type FormDoc = Record; + +const isDoc = (v: unknown): v is FormDoc => !!v && typeof v === 'object' && !Array.isArray(v); + +/** The `form` metadata type (ADR-0159). */ +const FORM_TYPE = 'form'; + +/** The open form: what was read, and the buffer being edited. */ +interface OpenForm { + name: string; + /** The stored document the buffer started from (`null`: a new form). */ + base: FormDoc | null; + /** The package whose row serves the form, or `null` for a new or draft-only one. */ + owner: string | null; + /** A draft of it is pending where it is saved. */ + hasDraft: boolean; + /** Where its draft is read and written: a package id, or `null` before the ensure door names the pair. */ + at: string | null; + model: PublicFormModel; + dirty: boolean; +} + +/** An object a new form can submit into. */ +export interface FormEditorObject { + name: string; + label: string; +} + +export interface FormItemEditorProps { + /** The form to open, or `null` to make a new one. */ + name: string | null; + client: MetadataClient; + /** The package the editor is open on, or `null` where none is (the cross-package leg). */ + packageId: string | null; + /** The open package is read-only (an installed app). */ + readOnly: boolean; + /** On a read-only base, its customization package. */ + customization: StudioBaseCustomization | null; + publishNonce?: number; + onDraftSaved?: (saved?: StudioSavedDraft) => void; + /** A new form's first draft was saved: the host opens it at its own address. */ + onCreated?: (name: string, packageId: string) => void; + /** The form was deleted: the host goes back to the list. */ + onDeleted?: () => void; + locale: string; + /** The data source the live preview renders with (it never writes). */ + previewDataSource: unknown; + /** The objects a new form may submit into. */ + objects?: readonly FormEditorObject[]; + /** The address of the anonymous form route (`useHref('/f')`), for the address preview. */ + formRoute?: string; +} + +/** The address prefix shown before the slug. */ +function addressPrefix(formRoute: string | undefined): string { + const origin = typeof window !== 'undefined' ? window.location.origin : ''; + return `${origin}${formRoute ?? '/f'}/`; +} + +/** The status of a refusal the client threw, if it carries one. */ +const statusOf = (err: unknown): unknown => (err as { status?: unknown })?.status; + +/** The code of a refusal the client threw, if it carries one. */ +const codeOf = (err: unknown): unknown => (err as { code?: unknown })?.code; + +/** + * The server's code for a form left open on an address another form holds + * (ADR-0159 ruled question 3, `409`). Its envelope names the holding form only + * in the message's prose, so the editor shows its own address sentence. + */ +const FORM_ADDRESS_TAKEN = 'FORM_ADDRESS_TAKEN'; + +export function FormItemEditor(props: FormItemEditorProps): React.ReactElement { + const { name, client, packageId, readOnly, customization, publishNonce = 0, onDraftSaved, locale } = props; + const [taken, setTaken] = React.useState>(new Map()); + /** Every form name of the environment, published or only drafted: a new form's name must be none of them. */ + const [formNames, setFormNames] = React.useState>(new Set()); + /** The package that serves each published form. */ + const [owners, setOwners] = React.useState | null>(null); + const [listError, setListError] = React.useState(null); + const [listNonce, setListNonce] = React.useState(0); + const [open, setOpen] = React.useState(null); + const [objectDef, setObjectDef] = React.useState(null); + const [busy, setBusy] = React.useState(null); + const [notice, setNotice] = React.useState(null); + const [creating, setCreating] = React.useState<{ object: string; title: string; slug: string; slugTouched: boolean } | null>( + name === null ? { object: '', title: '', slug: '', slugTouched: false } : null, + ); + const [confirmDelete, setConfirmDelete] = React.useState(false); + const [dragging, setDragging] = React.useState(null); + + const canWrite = !readOnly || (customization !== null && !customization.walled); + const objectName = open?.model.object ?? creating?.object ?? ''; + const fields = React.useMemo(() => fillableFields(objectDef), [objectDef]); + const fieldLabel = React.useMemo(() => new Map(fields.map((f) => [f.name, f.label])), [fields]); + const requiredByObject = React.useMemo( + () => new Set(fields.filter((f) => f.objectRequired).map((f) => f.name)), + [fields], + ); + + // The environment's forms: the addresses they hold and the names they use, + // published or only drafted, and the package that serves each. + React.useEffect(() => { + let live = true; + setListError(null); + (async () => { + try { + const [published, drafts] = await Promise.all([ + client.list(FORM_TYPE), + client.listDrafts({ type: FORM_TYPE }).catch(() => []), + ]); + const items = (published ?? []).filter(isDoc); + const seen = new Set(items.map((i) => i.name).filter((n): n is string => typeof n === 'string')); + const draftItems: FormDoc[] = []; + for (const d of drafts ?? []) { + if (!d?.name || seen.has(d.name)) continue; + const body = await client.getDraft(FORM_TYPE, d.name, d.packageId ? { packageId: d.packageId } : {}).catch(() => null); + const doc = isDoc(body) && isDoc((body as FormDoc).item) ? (body as FormDoc).item : body; + if (isDoc(doc)) draftItems.push({ ...doc, name: d.name }); + } + if (!live) return; + setTaken(takenAddresses([...items, ...draftItems])); + setFormNames(new Set([...seen, ...(drafts ?? []).map((d) => d?.name).filter((n): n is string => typeof n === 'string')])); + setOwners(new Map(items.map((i) => [String(i.name), typeof i._packageId === 'string' ? i._packageId : null]))); + } catch (err) { + if (live) setListError(err instanceof Error ? err.message : String(err)); + } + })(); + return () => { + live = false; + }; + }, [client, listNonce, publishNonce]); + + // The object the open (or new) form submits into: its fields. + React.useEffect(() => { + let live = true; + if (!objectName) { + setObjectDef(null); + return; + } + client + .get('object', objectName) + .then((def) => { + if (live) setObjectDef(isDoc(def) ? def : null); + }) + .catch(() => { + if (live) setObjectDef(null); + }); + return () => { + live = false; + }; + }, [client, objectName]); + + /** Where an existing form's draft is read and saved. */ + const addressOf = React.useCallback( + (owner: string | null): string | null => { + if (!readOnly) return packageId ?? owner; + // An installed app: the customization package, once it exists. + return customization?.pairId ?? null; + }, + [readOnly, packageId, customization], + ); + + const openForm = React.useCallback( + async (formName: string, owner: string | null) => { + setNotice(null); + setConfirmDelete(false); + setBusy('load'); + try { + const at = addressOf(owner); + // The form as it stands: read at its own address, else at the package that serves it. + let layers = await client.layered(FORM_TYPE, formName, at ? { packageId: at } : owner ? { packageId: owner } : {}); + if (!isDoc(layers.effective) && !isDoc(layers.code) && !isDoc((layers as FormDoc).draft) && owner) { + layers = await client.layered(FORM_TYPE, formName, { packageId: owner }); + } + const draft = isDoc((layers as FormDoc).draft) ? ((layers as FormDoc).draft as FormDoc) : null; + const stored = draft ?? (isDoc(layers.effective) ? layers.effective : isDoc(layers.code) ? layers.code : null); + if (!stored) throw new Error(tFormat('engine.studio.publicForms.unreadable', locale, { name: formName })); + setOpen({ + name: formName, + base: stored, + owner, + hasDraft: !!draft, + at, + model: publicFormModelOf({ ...stored, name: formName }), + dirty: false, + }); + } catch (err) { + setNotice(err instanceof Error ? err.message : String(err)); + } finally { + setBusy(null); + } + }, + [client, addressOf, locale], + ); + + // An existing form opens once the environment's forms say which package serves it. + const opened = React.useRef(null); + React.useEffect(() => { + if (name === null || owners === null || opened.current === name) return; + opened.current = name; + void openForm(name, owners.get(name) ?? null); + }, [name, owners, openForm]); + + const edit = (next: PublicFormModel) => setOpen((o) => (o ? { ...o, model: next, dirty: true } : o)); + + const problem = open?.model.public ? addressProblem(open.model.slug, open.model.name, taken) : null; + const missing = open ? missingRequiredFields(open.model, requiredByObject) : []; + const isNew = open !== null && open.base === null; + const shippedByApp = open !== null && readOnly && open.owner !== null && open.owner === customization?.base; + + /** + * The form's sharing as stored now (`sharing.enabled`, `sharing.allowAnonymous`), + * and its pending draft as stored (the layered read, untranslated). + * Switching is Setup's, never the editor's, so a save carries the sharing as + * it stands at save time, not as it stood when the form was opened: the + * served item when there is one, else the draft or the shipped document; a + * form never stored keeps what the editor made. Throws when it cannot be + * read, so nothing is written on a guess. + */ + const storedNow = async (form: OpenForm): Promise<{ enabled: boolean; allowAnonymous: boolean; draft: FormDoc | null }> => { + // A form never stored: nothing to read yet. + if (form.base === null && !form.hasDraft) { + return { enabled: form.model.enabled, allowAnonymous: form.model.allowAnonymous, draft: null }; + } + const sharingIn = (doc: unknown): FormDoc | undefined => (isDoc(doc) && isDoc(doc.sharing) ? doc.sharing : undefined); + const read = async (at: string | null) => client.layered(FORM_TYPE, form.name, at ? { packageId: at } : {}); + const where = form.at ?? form.owner; + const reads = [(await read(where)) as FormDoc]; + const draft = isDoc(reads[0].draft) ? (reads[0].draft as FormDoc) : null; + // Saved at a customization package: the served item may be read at the package that ships it. + if (!isDoc(reads[0].effective) && form.owner && form.owner !== where) reads.push((await read(form.owner)) as FormDoc); + const first = (layer: 'effective' | 'draft' | 'code') => reads.map((r) => sharingIn(r[layer])).find((v) => v !== undefined); + const sharing = first('effective') ?? first('draft') ?? first('code'); + if (sharing === undefined) { + // A form with no sharing at all (one an action opens) has no switch to keep. + const anyDoc = reads.some((r) => isDoc(r.effective) || isDoc(r.draft) || isDoc(r.code)); + if (anyDoc && !form.model.public) return { enabled: form.model.enabled, allowAnonymous: form.model.allowAnonymous, draft }; + throw new Error(tFormat('engine.studio.publicForms.unreadable', locale, { name: form.model.title || form.name })); + } + return { enabled: sharing.enabled === true, allowAnonymous: sharing.allowAnonymous === true, draft }; + }; + + /** Where a save lands, and the body it writes. */ + const writeTarget = async (model: PublicFormModel): Promise<{ packageId: string; body: FormDoc }> => { + const body = publicFormItemOf(model, open?.base ?? null); + if (!readOnly) { + const at = open?.at ?? packageId; + if (!at) throw new Error(t('engine.studio.publicForms.noPackage', locale)); + return { packageId: at, body }; + } + if (!customization || customization.walled) throw new Error(t('engine.studio.publicForms.readOnly', locale)); + const pair = await customization.ensure(); + if (!shippedByApp) return { packageId: pair, body }; + // A form the app ships is customized as a declared override, never edited in the app. + const declared = declaredOverrideOf(open?.base, customization.base) ? body : overrideDraftBody(body, customization.base, customization.basedOn); + if (!declared) throw new Error(t('engine.studio.publicForms.noVersion', locale)); + return { packageId: pair, body: declared }; + }; + + /** A refusal of the server, in the editor's words where it has some (a clash, a pending draft). */ + const refusalText = (err: unknown): string => { + // The address clash the editor's own check missed (another form took the address after it was read). + if (statusOf(err) === 409 && codeOf(err) === FORM_ADDRESS_TAKEN) return t('engine.studio.publicForms.addressTaken', locale); + if (statusOf(err) === 409) return t('engine.studio.publicForms.draftConflict', locale); + return err instanceof Error ? err.message : String(err); + }; + + const save = async () => { + if (!open || problem || missing.length > 0) return; + setBusy('save'); + setNotice(null); + try { + const now = await storedNow(open); + const target = await writeTarget({ ...open.model, enabled: now.enabled, allowAnonymous: now.allowAnonymous }); + await client.save(FORM_TYPE, open.model.name, target.body, { + mode: 'draft', + packageId: target.packageId, + surface: 'studio', + // A form nobody has drafted yet: a draft written meanwhile is never overwritten. + ...(open.hasDraft ? {} : { ifNoneMatch: '*' }), + } as never); + const saved = publicFormModelOf({ ...target.body, name: open.model.name }); + setOpen({ + ...open, + at: target.packageId, + hasDraft: true, + dirty: false, + base: target.body, + model: { ...open.model, enabled: saved.enabled, allowAnonymous: saved.allowAnonymous }, + }); + onDraftSaved?.({ type: FORM_TYPE, name: open.model.name }); + toast.success(tFormat('engine.studio.publicForms.saved', locale, { name: open.model.title || open.model.name })); + setListNonce((n) => n + 1); + if (open.base === null) props.onCreated?.(open.model.name, target.packageId); + } catch (err) { + setNotice(refusalText(err)); + } finally { + setBusy(null); + } + }; + + const publish = async () => { + if (!open?.hasDraft || open.dirty || !open.at) return; + setBusy('publish'); + setNotice(null); + try { + // The draft goes live with the sharing as it stands now: a draft that carries another is saved again first. + const { enabled, allowAnonymous, draft } = await storedNow(open); + if (!draft) throw new Error(tFormat('engine.studio.publicForms.unreadable', locale, { name: open.model.title || open.model.name })); + const draftSharing: FormDoc = isDoc(draft.sharing) ? draft.sharing : {}; + if (open.model.public && ((draftSharing.enabled === true) !== enabled || (draftSharing.allowAnonymous === true) !== allowAnonymous)) { + const body: FormDoc = { ...authorableForm(draft), sharing: { ...draftSharing, enabled, allowAnonymous } }; + await client.save(FORM_TYPE, open.model.name, body, { mode: 'draft', packageId: open.at, surface: 'studio' } as never); + } + await client.publish(FORM_TYPE, open.model.name, { packageId: open.at }); + toast.success(tFormat('engine.studio.publicForms.published', locale, { name: open.model.title || open.model.name })); + setOpen({ ...open, hasDraft: false, owner: open.owner ?? open.at }); + emitMetadataRefresh(); + setListNonce((n) => n + 1); + } catch (err) { + setNotice(refusalText(err)); + } finally { + setBusy(null); + } + }; + + const discard = async () => { + if (!open) return; + if (!open.hasDraft) { + // Nothing saved: the buffer goes back to what was read. + if (open.base) setOpen({ ...open, model: publicFormModelOf({ ...open.base, name: open.name }), dirty: false }); + return; + } + if (!open.at) return; + setBusy('discard'); + try { + await client.reset(FORM_TYPE, open.model.name, { state: 'draft', packageId: open.at }); + onDraftSaved?.(); + setListNonce((n) => n + 1); + const published = owners?.has(open.model.name) === true; + setOpen(null); + if (published) await openForm(open.model.name, open.owner); + else props.onDeleted?.(); + } catch (err) { + setNotice(refusalText(err)); + } finally { + setBusy(null); + } + }; + + const remove = async () => { + if (!open || shippedByApp) return; + setBusy('delete'); + setNotice(null); + try { + const at = open.at ?? open.owner; + if (open.hasDraft && at) await client.reset(FORM_TYPE, open.model.name, { state: 'draft', packageId: at }); + if (owners?.has(open.model.name)) { + const owner = owners.get(open.model.name) ?? at; + await client.reset(FORM_TYPE, open.model.name, { packageId: owner ?? undefined }); + } + toast.success(tFormat('engine.studio.publicForms.deleted', locale, { name: open.model.title || open.model.name })); + onDraftSaved?.(); + emitMetadataRefresh(); + setOpen(null); + setConfirmDelete(false); + setListNonce((n) => n + 1); + props.onDeleted?.(); + } catch (err) { + setNotice(refusalText(err)); + } finally { + setBusy(null); + } + }; + + const newName = creating && creating.object && creating.slug ? newPublicFormName(creating.object, creating.slug) : ''; + const createProblem = creating ? addressProblem(creating.slug, newName, taken) : null; + // The new form's name may be no other form's (published or only drafted). + const nameTaken = !!newName && formNames.has(newName); + + const create = () => { + if (!creating || !creating.object || !creating.title.trim() || createProblem || nameTaken) return; + const model = newPublicFormModel(creating.object, creating.title.trim(), creating.slug, objectDef); + setCreating(null); + setOpen({ name: model.name, base: null, owner: null, hasDraft: false, at: readOnly ? null : packageId, model, dirty: true }); + }; + + // A new form starts with the fields its object requires, once the object is read. + React.useEffect(() => { + setOpen((o) => { + if (!o || o.base !== null || o.hasDraft || !objectDef) return o; + const required = fillableFields(objectDef).filter((f) => f.objectRequired).map((f) => f.name); + let model = o.model; + for (const field of required) model = withField(model, field, null, new Set(required)); + return model === o.model ? o : { ...o, model }; + }); + }, [objectDef]); + + /** Ask to remove a field: refused, with the reason, for one the object requires. */ + const askRemoveField = (field: string) => { + if (!open) return; + if (removeFieldRefusal(field, requiredByObject)) { + setNotice(tFormat('engine.studio.publicForms.requiredByObject', locale, { field: fieldLabel.get(field) ?? field })); + return; + } + setNotice(null); + edit(withoutField(open.model, field, requiredByObject)); + }; + + const prefix = addressPrefix(props.formRoute); + const problemText = (p: string | null) => + p === 'empty' + ? t('engine.studio.publicForms.addressEmpty', locale) + : p === 'shape' + ? t('engine.studio.publicForms.addressShape', locale) + : p === 'taken' + ? t('engine.studio.publicForms.addressTaken', locale) + : null; + + const input = + 'h-8 w-full rounded-md border border-input bg-background px-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60'; + const smallBtn = + 'inline-flex h-7 items-center gap-1 rounded-md px-2 text-xs font-medium hover:bg-muted disabled:pointer-events-none disabled:opacity-50'; + const primaryBtn = + 'inline-flex h-7 items-center gap-1.5 rounded-md bg-primary px-2.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:pointer-events-none disabled:opacity-50'; + + const editable = canWrite && !!open; + + return ( +
+ {/* The editor's one toolbar row. */} +
+

+ {open ? open.model.title || open.model.name : t('engine.studio.publicForms.newTitle', locale)} +

+ {open && {open.model.name}} +
+ {open && ( + <> + {open.hasDraft && !open.dirty && ( + + {t('engine.studio.publicForms.draftChip', locale)} + + )} + {canWrite && ( + <> + + + + + )} + + )} +
+
+ +
+ {/* The editor. */} +
+ {creating ? ( +
+ {!canWrite &&

{t('engine.studio.publicForms.readOnly', locale)}

} + + + +

{t('engine.studio.publicForms.newHint', locale)}

+
+ + {props.onDeleted && ( + + )} +
+
+ ) : !open ? ( +
+ {notice || listError ? ( +

+ {notice ?? listError} +

+ ) : ( + + )} +
+ ) : ( +
+ {!canWrite &&

{t('engine.studio.publicForms.readOnly', locale)}

} + {notice && ( +
+ {notice} + +
+ )} + {missing.length > 0 && ( +

+ {tFormat('engine.studio.publicForms.missingRequired', locale, { + fields: missing.map((f) => fieldLabel.get(f) ?? f).join(', '), + })} +

+ )} + +
+ +