diff --git a/.changeset/36444-studio-public-form-designer.md b/.changeset/36444-studio-public-form-designer.md
new file mode 100644
index 00000000000..d7f206149c7
--- /dev/null
+++ b/.changeset/36444-studio-public-form-designer.md
@@ -0,0 +1,43 @@
+---
+'@object-ui/app-shell': patch
+'@object-ui/i18n': patch
+'@objectstack/spec': patch
+---
+
+feat(studio): design an object's public forms under the object, in Studio's Form tab
+
+Clause-②: yes (widening) — new Studio language-pack keys (`engine.studio.data.form.surface*` and the `engine.studio.publicForms.*` block) in en and zh
+Metadata-protocol: none
+
+Studio → Data → an object → Form now switches between the **Record form** (the New and Edit dialogs' layout, as before) and the object's **Public forms**, the forms anyone can fill in without signing in, each submission a record of the object. No new tab: the Data pillar keeps its seven.
+
+The designer lists the object's public forms (published ones, and ones only drafted) and:
+
+- creates one (a title and an address; it starts with the fields the object requires) and deletes one;
+- picks its fields from the object's fillable ones only: never a hidden, read-only, system, formula, roll-up or auto-number field;
+- reorders fields by dragging (or the move buttons), marks them required, and groups them into named sections;
+- sets the title, the description, the after-submit heading and message (`submitBehavior: { kind: 'thank-you' }`) and the address;
+- shows the form live as it is edited.
+
+Two refusals, each with its reason on screen:
+
+- **A field the object requires** cannot be removed and is always required on the form. "Requires" means required with no default value and no default choice: a field the write path fills in, such as a status with `defaultValue`, is not held.
+- **An address another form already uses** is refused, switched-off forms included, and nothing is saved.
+
+Saves follow Studio's draft → publish path: Save draft writes the form's draft, and Publish puts it live.
+
+- A form of a writable package is saved in that package.
+- On an installed app, a form the app ships is saved as a declared override in the app's customization package (ADR-0146), never in the app. A new form goes into the customization package.
+- A form the app ships cannot be deleted; the designer says to switch it off in Setup → Public forms instead.
+
+Switching a form on or off stays Setup's. The stored shape is the form view item it always was (`viewKind: 'form'`, `config.sharing`); no key is added. Access restrictions (password, expiry, domains) are not offered.
+
+Setup → Public forms names a form by the same rule: its label, else its title, else its first section's label, else its key.
+
+New locale keys: `engine.studio.data.form.surface*` and `engine.studio.publicForms.*` in the studio catalogue (en, zh).
+
+Alongside, from the review of the Setup page (#36697):
+
+- The designer's list reads an installed app's forms the way Setup → Public forms does: a form its app ships switched off (withdrawn by the app's own document, which no customization re-opens) is listed as "Off (its app ships it off)", never On, and a form whose app document cannot be read as "Unknown".
+- On Setup → Public forms, a row whose status is unknown offers no switch; Refresh reads it again.
+- `anonymousFormIntakeWithdrawnIn`'s docblock (`@objectstack/spec/ui`) names its callers as they are: the anonymous form doors, the v18 organization-ownership migration and the console's Setup → Public forms page. It no longer names an organization-scoped write door that does not call it. Prose only; the function is unchanged.
diff --git a/docs/qa/platform-checklist/areas/access-security.json b/docs/qa/platform-checklist/areas/access-security.json
index e897e686f43..ffe8820f5a0 100644
--- a/docs/qa/platform-checklist/areas/access-security.json
+++ b/docs/qa/platform-checklist/areas/access-security.json
@@ -1823,7 +1823,7 @@
{
"clause": "an administrator's save is environment-wide whatever organization the session has active, and its withdrawal closes the form: with ORG active, the save that sets allowAnonymous false with the link kept answers 200 and names the environment-wide scope (never org=ORG), the item read with no organization active serves that withdrawal, and both doors answer 404 with code FORM_NOT_FOUND and the probe leaves no row",
"oracle": "api",
- "verify": "step 2's baseline probe is recorded first (a form already closed is closed for an unrelated reason); then step 4's save status and message, the no-organization read, and the GET and POST status and body code with the admin's count for the marker, which is 0. Mechanism: the /meta doors hand the protocol no organization, and an organization-scoped write is refused by packages/metadata-protocol/src/protocol.ts#organizationScopedWriteRefusal (403 NOT_OVERRIDABLE, ADR-0131 D6); packages/rest/src/form-routes.ts#registerFormEndpoints reads the environment's view list alone and drops a candidate that packages/metadata-core/src/anonymous-form-intake.ts#anonymousFormIntakeWithdrawnIn finds withdrawn in that same list",
+ "verify": "step 2's baseline probe is recorded first (a form already closed is closed for an unrelated reason); then step 4's save status and message, the no-organization read, and the GET and POST status and body code with the admin's count for the marker, which is 0. Mechanism: the /meta doors hand the protocol no organization, and an organization-scoped write is refused by packages/metadata-protocol/src/protocol.ts#organizationScopedWriteRefusal (403 NOT_OVERRIDABLE, ADR-0131 D6); packages/rest/src/form-routes.ts#registerFormEndpoints reads the environment's view list alone and drops a candidate that packages/spec/src/ui/anonymous-form-intake.ts#anonymousFormIntakeWithdrawnIn finds withdrawn in that same list",
"evidence": "the baseline and step 4 probes (status, code, row count), the save response with the scope it names, and the no-organization read"
},
{
@@ -1835,7 +1835,7 @@
{
"clause": "only an explicit false withdraws (#21835 comment 5994082238, 「不算,写进文档」): another package's body of the view name that keeps the link with enabled true and allowAnonymous absent, or that names no public link, closes nothing, so the open form is still served (GET 200, POST 201)",
"oracle": "test",
- "verify": "pnpm --filter @objectstack/rest exec vitest run --maxWorkers=2 src/public-form-withdrawal.test.ts, the cases 'only an explicit false withdraws: a body with the link, enabled true and allowAnonymous absent closes nothing' and 'not a withdrawal: another package's body with the public link cleared leaves the form served'; and pnpm --filter @objectstack/metadata-core exec vitest run --maxWorkers=2 src/anonymous-form-intake.test.ts, the cases 'only an explicit false withdraws: an absent switch is not a withdrawal' and 'not a withdrawal: no body of the row, no sharing, the link cleared'. Mechanism: packages/metadata-core/src/anonymous-form-intake.ts#anonymousFormExplicitWithdrawals (a sharing withdraws only when it keeps a non-empty publicLink and sets enabled or allowAnonymous to false). No stock fixture (knownGaps)",
+ "verify": "pnpm --filter @objectstack/rest exec vitest run --maxWorkers=2 src/public-form-withdrawal.test.ts, the cases 'only an explicit false withdraws: a body with the link, enabled true and allowAnonymous absent closes nothing' and 'not a withdrawal: another package's body with the public link cleared leaves the form served'; and pnpm --filter @objectstack/metadata-core exec vitest run --maxWorkers=2 src/anonymous-form-intake.test.ts, the cases 'only an explicit false withdraws: an absent switch is not a withdrawal' and 'not a withdrawal: no body of the row, no sharing, the link cleared'. Mechanism: packages/spec/src/ui/anonymous-form-intake.ts#anonymousFormExplicitWithdrawals (a sharing withdraws only when it keeps a non-empty publicLink and sets enabled or allowAnonymous to false). No stock fixture (knownGaps)",
"evidence": "the two test runs, naming the cases above as passed"
},
{
@@ -1873,8 +1873,8 @@
"ref": "packages/qa/dogfood/test/showcase-public-form-withdrawal-layers.dogfood.test.ts ('showcase: a public form withdrawal at any metadata layer holds', 4 cases on a showcase boot with an organization active: the precondition, acceptance[0] and negative[1] through the save — 200, a message naming the env-wide scope and never the active organization's id, both doors 404 FORM_NOT_FOUND, 0 landed rows — then the no-organization read: set-active null, GET /meta/view/showcase_inquiry.contact serves config.sharing.allowAnonymous false with the link kept, set-active the organization again; and acceptance[1], both doors open with the row landing in the organization) + packages/rest/src/public-form-withdrawal.test.ts (the doors: '[#21331] public form withdrawal reaches every intake door', including '[ADR-0131 C7] no view read names an organization, whatever the tenancy answers: one environment read per door', and 'a public form withdrawal is a kill switch: one package's withdrawal of a view name closes its form') + packages/metadata-protocol/src/protocol.org-scoped-write-refused.test.ts ('[ADR-0131 D6] no organization-scoped metadata write is accepted', 'two packages shipping a view name' and 'each package's copy of a view container expands into its own package's slot', blocks (a) to (f)) + packages/metadata-core/src/anonymous-form-intake.test.ts (the anonymousFormIntakeWithdrawnIn cases). acceptance[0], acceptance[1], negative[0] and negative[1] score from the dogfood pin. acceptance[2] to acceptance[5] have no stock fixture (knownGaps); their pins are a unit (the rest file drives RestServer over a mocked protocol) and an in-process protocol over a stub registry (the metadata-protocol file), which is the layer their test oracle asks for. negative[2] is the dogfood pin's save at 200; negative[3] to negative[5] are procedural"
},
"source": [
- "packages/metadata-core/src/anonymous-form-intake.ts#anonymousFormIntakeWithdrawnIn (the one judgement the doors make over the environment's list: a body of the same view name withdraws a candidate matched by slot or by slug; the package is not compared)",
- "packages/metadata-core/src/anonymous-form-intake.ts#anonymousFormExplicitWithdrawals (explicit only: a sharing that keeps its publicLink and sets enabled or allowAnonymous to false; a schema-parsed artifact carries the default enabled false, which counts)",
+ "packages/spec/src/ui/anonymous-form-intake.ts#anonymousFormIntakeWithdrawnIn (the one judgement the doors make over the environment's list: a body of the same view name withdraws a candidate matched by slot or by slug; the package is not compared)",
+ "packages/spec/src/ui/anonymous-form-intake.ts#anonymousFormExplicitWithdrawals (explicit only: a sharing that keeps its publicLink and sets enabled or allowAnonymous to false; a schema-parsed artifact carries the default enabled false, which counts)",
"packages/rest/src/form-routes.ts#registerFormEndpoints (resolveFormBySlug: the environment's view list alone, judged against itself as the layer beneath each candidate; the Default Organization's legacy read was deleted with ADR-0131 C7, and the tenancy service is still read for the posture; a withdrawn form answers 404 FORM_NOT_FOUND on both doors)",
"packages/metadata-protocol/src/protocol.ts#getMetaItems (the environment's view list the doors read: one item per package that ships a view name, ADR-0048; a package-less copy stands in for every package with no copy of its own, packages/metadata-protocol/src/protocol.ts#servedViewExpansion)",
"packages/metadata-protocol/src/protocol.ts#organizationScopedWriteRefusal (every organization-scoped write refused 403 NOT_OVERRIDABLE, ADR-0131 D6; PR #22515 deleted the intake-specific organization refusals and the row anchor revision 1 cited, and since PR #22447 the /meta doors hand the protocol no organization, so an organization-active administrator's save is environment-wide)",
diff --git a/packages/spec/src/ui/anonymous-form-intake.ts b/packages/spec/src/ui/anonymous-form-intake.ts
index 64898008b49..2fdb985a582 100644
--- a/packages/spec/src/ui/anonymous-form-intake.ts
+++ b/packages/spec/src/ui/anonymous-form-intake.ts
@@ -178,18 +178,22 @@ function anonymousFormExplicitWithdrawals(view: unknown): Array<{ slot: string;
* Does one metadata layer withdraw an open form candidate? A WITHDRAWAL IS A
* KILL SWITCH: layering may only narrow anonymous intake, never re-open it, so
* the anonymous form doors serve a candidate only when no layer beneath it
- * withdraws it, and the organization-scoped write door refuses a save that
- * would leave one open.
+ * withdraws it.
+ *
+ * Three callers judge by it. The anonymous form doors (`registerFormEndpoints`
+ * in `@objectstack/rest`) pass the environment's view list as the layer. The
+ * v18 organization-ownership migration (`os migrate organization-ownership
+ * --apply`, `@objectstack/cli`) passes the organization rows it carries onto
+ * the environment. The console's Setup → Public forms page passes an installed
+ * app's own document, so it never shows on, or switches on, a form the app
+ * ships withdrawn (objectstack#36444).
*
* Identity is the `name`: the layer withdraws the candidate only through a
- * body of the same `name` as the candidate's `view`. What that name is depends
- * on the caller. The organization-scoped write door passes the env-wide body
- * of the stored row the overlay is keyed by, so a key rename, a `form.name`,
- * a slot move or an expansion rename is still judged against the form it was.
- * The anonymous doors pass the env-wide view list and the item they serve, so
- * they judge by the served item name (a known limit: an overlay stored before
- * the withdrawal, or restored by rollback or revert, that moves its form to
- * another key or slot is not matched there). The layer withdraws the
+ * body of the same `name` as the candidate's `view`. The anonymous doors pass
+ * the env-wide view list and the item they serve, so they judge by the served
+ * item name (a known limit: an overlay stored before the withdrawal, or
+ * restored by rollback or revert, that moves its form to another key or slot
+ * is not matched there). The layer withdraws the
* candidate when its body of that name EXPLICITLY
* withdraws a form ({@link anonymousFormExplicitWithdrawals}) that matches the
* candidate by slot (the same `form`, `formViews` key or `config`) OR by slug
@@ -205,8 +209,7 @@ function anonymousFormExplicitWithdrawals(view: unknown): Array<{ slot: string;
* limit that fails closed: it may over-close another package's form of the
* same name). It judges only the bodies the layer holds, so a caller closes a
* name in every package only when its layer holds every package's body of the
- * name. The organization-scoped write door anchors one body per package. The
- * env-wide view list the anonymous doors read holds one item per package of a
+ * name. The env-wide view list the anonymous doors read holds one item per package of a
* name: a package's saved env-wide copy of a view container serves that
* package's item of each form it expands, and a package-less copy stands in
* for every package with no copy of its own. A layer
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..8290cd3e355 100644
--- a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx
+++ b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx
@@ -170,6 +170,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 () => {
diff --git a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx
index 169a0eda27c..08dd38fd551 100644
--- a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx
+++ b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx
@@ -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.ts b/ui/packages/app-shell/src/views/setup/publicForms.ts
index a2052ff28f7..c8e1ea1e7be 100644
--- a/ui/packages/app-shell/src/views/setup/publicForms.ts
+++ b/ui/packages/app-shell/src/views/setup/publicForms.ts
@@ -77,6 +77,7 @@ import {
} from '../runtime-metadata-persistence.js';
import { declaredOverrideOf, overrideDraftBody } from '../studio-design/StudioCustomizeControls.js';
import { fetchListedPackageManifests } from '../studio-design/packages-io.js';
+import { publicFormShownName } from '../studio-design/publicForm/publicFormDesign.js';
type FormDoc = Record;
@@ -86,7 +87,7 @@ const isDoc = (v: unknown): v is FormDoc => !!v && typeof v === 'object' && !Arr
export interface PublicFormRow {
/** The form view item's name: the metadata address every write names. */
name: string;
- /** What the page shows as its name ({@link shownName}). */
+ /** What the page shows as its name (`publicFormShownName`, Studio's designer names it the same way). */
title: string;
/** The object a submission creates a record of. */
object?: string;
@@ -114,27 +115,6 @@ function withSwitch(form: FormDoc, on: boolean): FormDoc {
return { ...form, sharing: { ...(isDoc(form.sharing) ? form.sharing : {}), enabled: on } };
}
-const text = (v: unknown): string | undefined => (typeof v === 'string' && v.trim() ? v : undefined);
-
-/**
- * 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`).
- */
-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 dot = item.name.lastIndexOf('.');
- return (
- text(item.label) ??
- text(config.title) ??
- text(config.label) ??
- text(first?.label) ??
- (dot >= 0 && dot < item.name.length - 1 ? item.name.slice(dot + 1) : item.name)
- );
-}
-
/**
* 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.
@@ -149,7 +129,7 @@ export function publicFormRowOf(item: unknown): PublicFormRow | null {
const packageId = typeof item._packageId === 'string' && item._packageId ? item._packageId : null;
return {
name: item.name,
- title: shownName(item),
+ title: publicFormShownName(item),
object: anonymousFormObjectName(item, item.config),
slug: listed.slug,
on,
@@ -280,11 +260,11 @@ async function readFormLayers(name: string, target: ResolvedTarget, client: Pick
* app's form; a row whose layers cannot be read is marked `unknown` and is not
* shown as on.
*/
-export async function markShippedOff(
- rows: readonly PublicFormRow[],
+export async function markShippedOff>(
+ rows: readonly R[],
client: Pick,
doors?: Pick,
-): Promise {
+): Promise {
if (!rows.some((r) => r.packageId)) return [...rows];
const listPackages = doors?.listPackages ?? fetchListedPackageManifests;
let listing: ReturnType | undefined;
diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx
index 9a0c91440ce..66e8485d8cf 100644
--- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx
+++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx
@@ -16,7 +16,7 @@
import * as React from 'react';
import { createPortal } from 'react-dom';
-import { useParams, useNavigate, useSearchParams, useLocation, Link, Navigate } from 'react-router-dom';
+import { useParams, useNavigate, useSearchParams, useLocation, useHref, Link, Navigate } from 'react-router-dom';
import { useAdapter, SchemaRendererProvider, useMetadata } from '@object-ui/react';
import { leadWithNameField } from '@object-ui/core';
// The ONE draft-envelope reader (objectui#8181): unwrap AND strip the
@@ -453,6 +453,7 @@ import { StudioGridAddFieldButton, StudioGridAddFieldProvider, type StudioGridAd
import { useDraftAutoSave, type DraftSend } from './useDraftAutoSave.js';
import { FLOW_PRESETS, flowPresetTrigger, type FlowPreset } from './flowPresets.js';
import { FormToolbar, ObjectFormDesigner } from './ObjectFormDesigner.js';
+import { PublicFormsDesigner } from './publicForm/PublicFormsDesigner.js';
import { isStudioHiddenSystemField } from './studioHiddenSystemField.js';
import { ObjectGroupInspector } from './ObjectGroupInspector.js';
import { ObjectValidationsPanel } from './ObjectValidationsPanel.js';
@@ -5993,6 +5994,12 @@ export function DataPillar({
// Within the Form view: Layout (WYSIWYG drag/section designer) ⇄ Preview
// (live form).
const [formMode, setFormMode] = React.useState<'layout' | 'preview'>('layout');
+ // objectstack#36444 — which of the object's forms the Form tab designs: the
+ // record form (the New / Edit dialogs' layout) or its public forms (forms
+ // anyone fills in without signing in), designed under the object they
+ // submit into, with no tab of their own (objectui#12450's seven tabs).
+ const [formSurface, setFormSurface] = React.useState<'record' | 'public'>('record');
+ const publicFormRoute = useHref('/f');
// objectui#12515 — which definition Preview renders when the object has a
// published version AND a pending change: the draft (the default) or the
// published one. Without a published version only the draft exists.
@@ -7347,6 +7354,33 @@ export function DataPillar({
'h-6 rounded px-2.5 text-xs transition-colors',
active ? 'bg-background font-medium text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground',
);
+ const formSurfaceControl = (
+
+ setFormSurface('record')}
+ aria-pressed={formSurface === 'record'}
+ className={formModeItem(formSurface === 'record')}
+ data-testid="data-form-surface-record"
+ >
+ {t('engine.studio.data.form.surfaceRecord', locale)}
+
+ setFormSurface('public')}
+ aria-pressed={formSurface === 'public'}
+ className={formModeItem(formSurface === 'public')}
+ data-testid="data-form-surface-public"
+ >
+ {t('engine.studio.data.form.surfacePublic', locale)}
+
+
+ );
const formModeControl = (
+ {formSurfaceControl}
{formModeControl}
{formLayoutSource}
@@ -7418,6 +7453,7 @@ export function DataPillar({
) : (
+ {formSurfaceControl}
{formModeControl}
{formLayoutSource}
@@ -8025,7 +8061,23 @@ export function DataPillar({
left of the Form tab's one toolbar row (the designer's in
Layout, `FormToolbar` in Preview), and the caption that used
to trail it is each item's title. */}
- {formMode === 'layout' ? (
+ {formSurface === 'public' ? (
+
+ ) : formMode === 'layout' ? (
<>
({
+ ...(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() } }));
+// The package list the designer's list reads once (`markShippedOff`): the CRM app installed read-only, a writable own package.
+vi.mock('../packages-io.js', async (importOriginal) => ({
+ ...(await importOriginal>()),
+ fetchListedPackageManifests: async () =>
+ new Map([
+ ['com.example.crm', { writable: false, manifest: { id: 'com.example.crm', version: '4.0.0' } }],
+ ['com.acme.sales', { writable: true, manifest: { id: 'com.acme.sales', version: '1.0.0' } }],
+ ]),
+}));
+
+import { PublicFormsDesigner } 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' },
+ },
+};
+
+const contactUs = () => ({
+ name: 'crm_lead.web_to_lead',
+ object: 'crm_lead',
+ viewKind: 'form',
+ config: {
+ type: 'simple',
+ data: { provider: 'object', object: 'crm_lead' },
+ 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',
+ viewKind: 'form',
+ label: 'Event RSVP',
+ config: {
+ data: { provider: 'object', object: 'crm_lead' },
+ 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: { ...contactUs(), _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.form', object: 'crm_lead', viewKind: 'form', config: { sections: [] }, _packageId: owner },
+ { name: 'crm_lead.all', object: 'crm_lead', viewKind: 'list', config: {}, _packageId: owner },
+ { ...contactUs(), name: 'crm_account.signup', object: 'crm_account', config: { ...contactUs().config, data: { provider: 'object', object: 'crm_account' }, sharing: { enabled: false, allowAnonymous: true, publicLink: '/forms/signup' } }, _packageId: owner },
+ ]),
+ listDrafts: vi.fn(async () => [{ type: 'view', name: 'crm_lead.event_rsvp', packageId: owner }]),
+ getDraft: vi.fn(async (_t: string, name: string) => stored.drafts.get(name) ?? 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, config: { ...served.config, sharing: { ...served.config.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 renderDesigner(client: ReturnType, extra: Partial> = {}) {
+ const onDraftSaved = vi.fn();
+ render(
+ Form surface}
+ formRoute="/f"
+ {...extra}
+ />,
+ );
+ return { onDraftSaved };
+}
+
+describe('Studio public form designer (objectstack#36444)', () => {
+ it('lists the object\'s public forms: published ones and ones only drafted, not internal forms or another object\'s', async () => {
+ renderDesigner(clientDouble());
+ const list = await screen.findByTestId('public-forms-list');
+ await within(list).findByTestId('public-form-item-crm_lead.web_to_lead');
+ expect(within(list).getByTestId('public-form-item-crm_lead.event_rsvp')).toHaveTextContent('Draft');
+ expect(within(list).queryByTestId('public-form-item-crm_lead.form')).toBeNull();
+ expect(within(list).queryByTestId('public-form-item-crm_account.signup')).toBeNull();
+ });
+
+ it('lists a form its installed app ships switched off as off, even when this environment\'s customization switches it on', async () => {
+ const shippedOff = { ...contactUs(), config: { ...contactUs().config, sharing: { enabled: false, publicLink: '/forms/contact-us', allowAnonymous: true } } };
+ renderDesigner(clientDouble({ appDoc: shippedOff }));
+ const row = await screen.findByTestId('public-form-item-crm_lead.web_to_lead');
+ await waitFor(() => expect(row).toHaveTextContent('Off (its app ships it off)'));
+ expect(row).not.toHaveTextContent(/\bOn\b/);
+ });
+
+ 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 } = (() => {
+ const onDraftSaved = vi.fn();
+ render(
+ ,
+ );
+ return { onDraftSaved };
+ })();
+ await user.click(await screen.findByTestId('public-form-item-crm_lead.web_to_lead'));
+ await screen.findByTestId('public-form-title');
+
+ 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(['view', '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.config.title).toBe('Talk to sales');
+ expect(body.config.sections[0].fields).toEqual([
+ { field: 'name', required: true },
+ { field: 'company' },
+ { field: 'email', required: true },
+ { field: 'phone', required: true },
+ ]);
+ expect(body.config.sharing).toEqual({ enabled: true, publicLink: '/forms/contact-us', allowAnonymous: true });
+ expect(onDraftSaved).toHaveBeenCalledWith({ type: 'view', name: 'crm_lead.web_to_lead' });
+
+ await user.click(await screen.findByTestId('public-form-publish'));
+ await waitFor(() => expect(client.publish).toHaveBeenCalledWith('view', '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('refuses to remove a field the object requires, and says why', async () => {
+ const user = userEvent.setup();
+ renderDesigner(clientDouble());
+ await user.click(await screen.findByTestId('public-form-item-crm_lead.web_to_lead'));
+ 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 object is edited', async () => {
+ const user = userEvent.setup();
+ const client = clientDouble({ owner: 'com.acme.sales' });
+ renderDesigner(client, { readOnly: false, customization: null, packageId: 'com.acme.sales' });
+ await screen.findByTestId('public-form-item-crm_lead.web_to_lead');
+ await user.click(screen.getByTestId('public-form-new'));
+ await user.type(screen.getByTestId('public-form-create-title'), 'Demo signup');
+ expect(screen.getByTestId('public-form-create-address')).toHaveValue('demo-signup');
+ await user.click(screen.getByTestId('public-form-create-confirm'));
+
+ // Starts with the fields the object requires; two more are added.
+ expect(screen.getByTestId('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 [, name, body, options] = client.save.mock.calls[0] as unknown as [string, string, any, any];
+ expect(name).toBe('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', viewKind: 'form', label: 'Demo signup' });
+ expect(body.config.sections[0].fields.map((f: { field: string }) => f.field)).toEqual(['name', 'email', 'company', 'phone']);
+ expect(body.config.sharing).toEqual({ enabled: true, allowAnonymous: true, publicLink: '/forms/demo-signup' });
+ expect(body.overrides).toBeUndefined();
+ });
+
+ it('refuses an address another form uses, switched off or not, and saves nothing', async () => {
+ const user = userEvent.setup();
+ const client = clientDouble();
+ renderDesigner(client);
+ await screen.findByTestId('public-form-item-crm_lead.web_to_lead');
+ await user.click(screen.getByTestId('public-form-new'));
+ await user.type(screen.getByTestId('public-form-create-title'), 'Contact us');
+ 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();
+
+ // An existing form moved onto another's address cannot be saved.
+ await user.click(screen.getByTestId('public-form-item-crm_lead.web_to_lead'));
+ const address = await screen.findByTestId('public-form-address');
+ await user.clear(address);
+ await user.type(address, 'event-rsvp');
+ expect(screen.getByTestId('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();
+ renderDesigner(clientDouble());
+ await user.click(await screen.findByTestId('public-form-item-crm_lead.web_to_lead'));
+ 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();
+ renderDesigner(clientDouble());
+ await user.click(await screen.findByTestId('public-form-item-crm_lead.web_to_lead'));
+ expect(await screen.findByTestId('public-form-delete-shipped')).toHaveTextContent('switch it off in Setup');
+ cleanup();
+
+ const own = clientDouble({ owner: 'com.acme.sales' });
+ renderDesigner(own, { readOnly: false, customization: null, packageId: 'com.acme.sales' });
+ await user.click(await screen.findByTestId('public-form-item-crm_lead.web_to_lead'));
+ await user.click(await screen.findByTestId('public-form-delete'));
+ await user.click(screen.getByTestId('public-form-delete-yes'));
+ await waitFor(() => expect(own.reset).toHaveBeenCalledWith('view', 'crm_lead.web_to_lead', { packageId: 'com.acme.sales' }));
+ });
+ it('refuses a new form whose name another view item of the object already has', async () => {
+ const user = userEvent.setup();
+ const client = clientDouble();
+ renderDesigner(client);
+ await screen.findByTestId('public-form-item-crm_lead.web_to_lead');
+ await user.click(screen.getByTestId('public-form-new'));
+ // `all` names the new form `crm_lead.all`: the object's list view.
+ await user.type(screen.getByTestId('public-form-create-title'), 'All');
+ expect(screen.getByTestId('public-form-create-address')).toHaveValue('all');
+ expect(screen.getByTestId('public-form-create-address-problem')).toHaveTextContent('Another form already uses this address');
+ expect(screen.getByTestId('public-form-create-confirm')).toBeDisabled();
+ // An internal form's name too.
+ await user.clear(screen.getByTestId('public-form-create-address'));
+ await user.type(screen.getByTestId('public-form-create-address'), 'form');
+ 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('saves and publishes the form\'s on/off switch 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' });
+ renderDesigner(client, { readOnly: false, customization: null, packageId: 'com.acme.sales' });
+ await user.click(await screen.findByTestId('public-form-item-crm_lead.web_to_lead'));
+ const title = await screen.findByTestId('public-form-title');
+ // 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.config.sharing.enabled).toBe(false);
+ expect(body.config.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.config.sharing.enabled).toBe(true);
+ expect(again.config.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 switch is the stored one without saving it again', async () => {
+ const user = userEvent.setup();
+ const client = clientDouble({ owner: 'com.acme.sales' });
+ renderDesigner(client, { readOnly: false, customization: null, packageId: 'com.acme.sales' });
+ await user.click(await screen.findByTestId('public-form-item-crm_lead.web_to_lead'));
+ 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();
+ renderDesigner(client, { customization: custom as never });
+ await user.click(await screen.findByTestId('public-form-item-crm_lead.web_to_lead'));
+ 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].config.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, config: { ...d.config, title: '¡Gracias!' } } : null;
+ });
+ client.layered.mockClear();
+ await user.click(screen.getByTestId('public-form-publish'));
+ await waitFor(() => expect(client.publish).toHaveBeenCalledWith('view', 'crm_lead.web_to_lead', { packageId: PAIR }));
+ // The customization package serves nothing yet, so the switch is read where the app ships the form.
+ // (The list's own refresh reads afterwards.)
+ 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.config.sharing.enabled).toBe(false);
+ expect(again.config.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' });
+ renderDesigner(client, { readOnly: false, customization: null, packageId: 'com.acme.sales' });
+ await user.click(await screen.findByTestId('public-form-item-crm_lead.web_to_lead'));
+ 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' });
+ renderDesigner(client, { readOnly: false, customization: null, packageId: 'com.acme.sales' });
+ await user.click(await screen.findByTestId('public-form-item-crm_lead.web_to_lead'));
+ 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);
+ });
+});
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..4f33b410ff2
--- /dev/null
+++ b/ui/packages/app-shell/src/views/studio-design/publicForm/PublicFormsDesigner.tsx
@@ -0,0 +1,891 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+/**
+ * Studio → Data → an object → Form → Public forms (objectstack#36444): the
+ * designer of the object's public forms (forms anyone can fill in without
+ * signing in, each submission a record of the object). Create and delete a
+ * form; pick its 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.
+ *
+ * Saves go through Studio's draft → publish path: Save draft writes the
+ * form's draft where the open object 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. Switching a form on or off is
+ * Setup's (Setup → Public forms), not the designer's.
+ *
+ * The rules (fillable fields, object-required fields, the address) are
+ * `publicFormDesign.ts`'s.
+ */
+
+import * as React from 'react';
+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 } from '@object-ui/react';
+import { emitMetadataRefresh } from '../../../assistant/assistantBus.js';
+import { t, tFormat } from '../../metadata-admin/i18n.js';
+import { declaredOverrideOf, overrideDraftBody } from '../StudioCustomizeControls.js';
+import { markShippedOff } from '../../setup/publicForms.js';
+import type { StudioBaseCustomization, StudioSavedDraft } from '../StudioPillarKit.js';
+import {
+ addressProblem,
+ fieldsOnForm,
+ fillableFields,
+ isPublicFormItem,
+ missingRequiredFields,
+ newPublicFormModel,
+ newPublicFormName,
+ previewSectionsOf,
+ publicFormItemOf,
+ publicFormModelOf,
+ publicFormObjectOf,
+ publicFormShownName,
+ 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);
+
+/** One public form of the object, as the list shows it. */
+interface ListedForm {
+ name: string;
+ title: string;
+ slug: string;
+ /** Live (served) and taking submissions. */
+ on: boolean;
+ /** Published at all (a form only drafted is not). */
+ published: boolean;
+ /** The package that serves it, when published. */
+ packageId: string | null;
+ /** Its installed app ships it switched off, so it stays closed whatever is published here (`markShippedOff`). */
+ shippedOff?: boolean;
+ /** Its app's own document could not be read, so whether it is live is not known. */
+ unknown?: boolean;
+}
+
+/** 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;
+}
+
+export interface PublicFormsDesignerProps {
+ objectName: string;
+ /** The object's definition as Studio edits it (its fields). */
+ objectDef: Record;
+ client: MetadataClient;
+ /** The package the open object is read and saved at. */
+ packageId: string;
+ /** The open object's 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;
+ locale: string;
+ /** The data source the live preview renders with (it never writes). */
+ previewDataSource: unknown;
+ /** The Form tab's leading controls (the record form / public forms switch). */
+ leading: React.ReactNode;
+ /** 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'}/`;
+}
+
+export function PublicFormsDesigner(props: PublicFormsDesignerProps): React.ReactElement {
+ const { objectName, objectDef, client, packageId, readOnly, customization, publishNonce, onDraftSaved, locale } = props;
+ const [listed, setListed] = React.useState(null);
+ const [taken, setTaken] = React.useState>(new Map());
+ /** Every view item name of the environment, published or only drafted: a new form's name must be none of them. */
+ const [viewNames, setViewNames] = React.useState>(new Set());
+ const [listError, setListError] = React.useState(null);
+ const [listNonce, setListNonce] = React.useState(0);
+ const [open, setOpen] = React.useState(null);
+ const [busy, setBusy] = React.useState(null);
+ const [notice, setNotice] = React.useState(null);
+ const [creating, setCreating] = React.useState<{ title: string; slug: string; slugTouched: boolean } | null>(null);
+ const [confirmDelete, setConfirmDelete] = React.useState(false);
+ const [dragging, setDragging] = React.useState(null);
+
+ const canWrite = !readOnly || (customization !== null && !customization.walled);
+ 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 object's public forms: the published list, plus the forms only drafted.
+ React.useEffect(() => {
+ let live = true;
+ setListError(null);
+ (async () => {
+ try {
+ const [published, drafts] = await Promise.all([
+ client.list('view'),
+ client.listDrafts({ type: 'view' }).catch(() => []),
+ ]);
+ const items = (published ?? []).filter(isDoc);
+ const rows: ListedForm[] = [];
+ const seen = new Set();
+ for (const item of items) {
+ if (!isPublicFormItem(item) || publicFormObjectOf(item) !== objectName) continue;
+ const model = publicFormModelOf(item);
+ seen.add(model.name);
+ rows.push({
+ name: model.name,
+ title: publicFormShownName(item),
+ slug: model.slug,
+ on: model.enabled,
+ published: true,
+ packageId: typeof item._packageId === 'string' ? item._packageId : null,
+ });
+ }
+ const draftItems: FormDoc[] = [];
+ for (const d of drafts ?? []) {
+ if (!d?.name || seen.has(d.name) || !d.name.startsWith(`${objectName}.`)) continue;
+ const body = await client.getDraft('view', d.name, d.packageId ? { packageId: d.packageId } : {}).catch(() => null);
+ const doc = isDoc(body) && isDoc((body as FormDoc).item) ? (body as FormDoc).item : body;
+ if (!isPublicFormItem(doc)) continue;
+ draftItems.push(doc);
+ const model = publicFormModelOf(doc);
+ rows.push({ name: model.name, title: publicFormShownName(doc), slug: model.slug, on: false, published: false, packageId: null });
+ }
+ // A form its installed app ships switched off is never listed as on (Setup → Public forms reads it the same way).
+ const marked = await markShippedOff(rows, client as never);
+ if (!live) return;
+ marked.sort((a, b) => a.title.localeCompare(b.title));
+ setListed(marked);
+ setTaken(takenAddresses([...items, ...draftItems]));
+ setViewNames(
+ new Set([
+ ...items.map((i) => i.name).filter((n): n is string => typeof n === 'string'),
+ ...(drafts ?? []).map((d) => d?.name).filter((n): n is string => typeof n === 'string'),
+ ]),
+ );
+ } catch (err) {
+ if (live) setListError(err instanceof Error ? err.message : String(err));
+ }
+ })();
+ return () => {
+ live = false;
+ };
+ }, [client, objectName, listNonce, publishNonce]);
+
+ /** Where an existing form's draft is read and saved. */
+ const addressOf = React.useCallback(
+ (owner: string | null): string | null => {
+ if (!readOnly) return owner && owner !== packageId ? owner : packageId;
+ // An installed app: the customization package, once it exists.
+ return customization?.pairId ?? null;
+ },
+ [readOnly, packageId, customization],
+ );
+
+ const openForm = React.useCallback(
+ async (row: ListedForm) => {
+ setNotice(null);
+ setCreating(null);
+ setConfirmDelete(false);
+ setBusy('load');
+ try {
+ const at = addressOf(row.packageId);
+ let layers = await client.layered('view', row.name, at ? { packageId: at } : row.packageId ? { packageId: row.packageId } : {});
+ if (!isDoc(layers.effective) && !isDoc(layers.code) && !isDoc((layers as FormDoc).draft) && row.packageId) {
+ layers = await client.layered('view', row.name, { packageId: row.packageId });
+ }
+ 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: row.title }));
+ setOpen({
+ name: row.name,
+ base: stored,
+ owner: row.packageId,
+ hasDraft: !!draft,
+ at,
+ model: publicFormModelOf({ ...stored, name: row.name }),
+ dirty: false,
+ });
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : String(err));
+ } finally {
+ setBusy(null);
+ }
+ },
+ [client, addressOf, locale],
+ );
+
+ const edit = (next: PublicFormModel) => setOpen((o) => (o ? { ...o, model: next, dirty: true } : o));
+
+ const problem = open ? 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 on/off switch as stored now, and its pending draft as stored
+ * (the layered read, untranslated). Switching is Setup's, never the
+ * designer's, so a save carries the switch 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 is on. Throws when
+ * it cannot be read, so nothing is written on a guess.
+ */
+ const storedNow = async (form: OpenForm): Promise<{ enabled: boolean; draft: FormDoc | null }> => {
+ // A form never stored: nothing to read yet.
+ if (form.base === null && !form.hasDraft) return { enabled: form.model.enabled, draft: null };
+ const enabledIn = (doc: unknown): boolean | undefined =>
+ isDoc(doc) && isDoc(doc.config) && isDoc(doc.config.sharing) ? doc.config.sharing.enabled === true : undefined;
+ const read = async (at: string | null) => client.layered('view', 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) => enabledIn(r[layer])).find((v) => v !== undefined);
+ const enabled = first('effective') ?? first('draft') ?? first('code');
+ if (enabled === undefined) throw new Error(tFormat('engine.studio.publicForms.unreadable', locale, { name: form.model.title || form.name }));
+ return { enabled, 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) return { packageId: open?.at ?? packageId, 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 };
+ };
+
+ const save = async () => {
+ if (!open || problem || missing.length > 0) return;
+ setBusy('save');
+ setNotice(null);
+ try {
+ const target = await writeTarget({ ...open.model, enabled: (await storedNow(open)).enabled });
+ await client.save('view', 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 enabled = target.body.config?.sharing?.enabled === true;
+ setOpen({ ...open, at: target.packageId, hasDraft: true, dirty: false, base: { ...(open.base ?? {}), ...target.body }, model: { ...open.model, enabled } });
+ onDraftSaved?.({ type: 'view', name: open.model.name });
+ toast.success(tFormat('engine.studio.publicForms.saved', locale, { name: open.model.title || open.model.name }));
+ setListNonce((n) => n + 1);
+ } catch (err) {
+ const status = (err as { status?: unknown })?.status;
+ setNotice(status === 409 ? t('engine.studio.publicForms.draftConflict', locale) : err instanceof Error ? err.message : String(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 switch as it stands now: a draft that carries another is saved again first.
+ const { enabled, draft } = await storedNow(open);
+ if (!draft) throw new Error(tFormat('engine.studio.publicForms.unreadable', locale, { name: open.model.title || open.model.name }));
+ const draftSwitch = isDoc(draft.config) && isDoc(draft.config.sharing) ? draft.config.sharing.enabled === true : undefined;
+ if (draftSwitch !== enabled) {
+ const body: FormDoc = { ...draft, config: { ...(isDoc(draft.config) ? draft.config : {}), sharing: { ...(isDoc(draft.config?.sharing) ? draft.config.sharing : {}), enabled } } };
+ for (const key of Object.keys(body)) if (key.startsWith('_')) delete body[key];
+ await client.save('view', open.model.name, body, { mode: 'draft', packageId: open.at, surface: 'studio' } as never);
+ }
+ await client.publish('view', 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(err instanceof Error ? err.message : String(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 });
+ else setOpen(null);
+ return;
+ }
+ if (!open.at) return;
+ setBusy('discard');
+ try {
+ await client.reset('view', open.model.name, { state: 'draft', packageId: open.at });
+ onDraftSaved?.();
+ setListNonce((n) => n + 1);
+ const row = listed?.find((r) => r.name === open.model.name && r.published);
+ setOpen(null);
+ if (row) await openForm(row);
+ } catch (err) {
+ setNotice(err instanceof Error ? err.message : String(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('view', open.model.name, { state: 'draft', packageId: at });
+ const row = listed?.find((r) => r.name === open.model.name && r.published);
+ if (row) await client.reset('view', open.model.name, { packageId: row.packageId ?? at ?? 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);
+ } catch (err) {
+ setNotice(err instanceof Error ? err.message : String(err));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const startCreate = () => {
+ setOpen(null);
+ setNotice(null);
+ setConfirmDelete(false);
+ setCreating({ title: '', slug: '', slugTouched: false });
+ };
+
+ const createProblem = creating ? addressProblem(creating.slug, newPublicFormName(objectName, creating.slug), taken) : null;
+ // The new form's view item name may be no other view item's (a list view's, an internal form's, a draft's).
+ const nameTaken = creating !== null && !!creating.slug && viewNames.has(newPublicFormName(objectName, creating.slug));
+
+ const create = () => {
+ if (!creating || !creating.title.trim() || createProblem || nameTaken) return;
+ const model = newPublicFormModel(objectName, 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 });
+ };
+
+ /** 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 Form tab's one toolbar row. */}
+
+ {props.leading}
+
+ {open && (
+ <>
+ {open.hasDraft && !open.dirty && (
+
+ {t('engine.studio.publicForms.draftChip', locale)}
+
+ )}
+ {canWrite && (
+ <>
+ void discard()} disabled={busy !== null || (!open.dirty && !open.hasDraft)} data-testid="public-form-discard">
+ {t('engine.studio.publicForms.discard', locale)}
+
+ void save()}
+ disabled={busy !== null || !open.dirty || !!problem || missing.length > 0}
+ data-testid="public-form-save"
+ >
+ {busy === 'save' && }
+ {t('engine.studio.publicForms.saveDraft', locale)}
+
+ void publish()}
+ disabled={busy !== null || !open.hasDraft || open.dirty}
+ title={open.dirty ? t('engine.studio.publicForms.publishNeedsSave', locale) : undefined}
+ data-testid="public-form-publish"
+ >
+ {busy === 'publish' && }
+ {t('engine.studio.publicForms.publish', locale)}
+
+ >
+ )}
+ >
+ )}
+
+
+
+
+ {/* The object's public forms. */}
+
+
+
{t('engine.studio.publicForms.listTitle', locale)}
+ {canWrite && (
+
+ {t('engine.studio.publicForms.new', locale)}
+
+ )}
+
+
+ {listError ? (
+
{listError}
+ ) : listed === null ? (
+
{t('engine.studio.publicForms.loading', locale)}
+ ) : listed.length === 0 ? (
+
+ {t('engine.studio.publicForms.none', locale)}
+
+ ) : (
+ listed.map((row) => (
+
void openForm(row)}
+ aria-current={open?.name === row.name ? 'true' : undefined}
+ data-testid={`public-form-item-${row.name}`}
+ className={`mb-0.5 flex w-full flex-col items-start rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted ${open?.name === row.name ? 'bg-muted' : ''}`}
+ >
+ {row.title}
+
+ /f/{row.slug}
+
+ {!row.published
+ ? t('engine.studio.publicForms.stateDraft', locale)
+ : row.on
+ ? t('engine.studio.publicForms.stateOn', locale)
+ : row.shippedOff
+ ? t('engine.studio.publicForms.stateShippedOff', locale)
+ : row.unknown
+ ? t('engine.studio.publicForms.stateUnknown', locale)
+ : t('engine.studio.publicForms.stateOff', locale)}
+
+
+
+ ))
+ )}
+
+ {t('engine.studio.publicForms.switchInSetup', locale)}
+
+
+ {/* The editor. */}
+
+ {creating ? (
+
+
{t('engine.studio.publicForms.newTitle', locale)}
+
+ {t('engine.studio.publicForms.title', locale)}
+
+ setCreating((c) =>
+ c ? { ...c, title: e.target.value, slug: c.slugTouched ? c.slug : slugFromTitle(e.target.value) } : c,
+ )
+ }
+ data-testid="public-form-create-title"
+ />
+
+
+ {t('engine.studio.publicForms.address', locale)}
+
+ {prefix}
+ setCreating((c) => (c ? { ...c, slug: e.target.value.trim(), slugTouched: true } : c))}
+ data-testid="public-form-create-address"
+ />
+
+ {creating.slug && (createProblem || nameTaken) && (
+
+ {nameTaken ? t('engine.studio.publicForms.addressTaken', locale) : problemText(createProblem)}
+
+ )}
+
+
{t('engine.studio.publicForms.newHint', locale)}
+
+
+ {t('engine.studio.publicForms.create', locale)}
+
+ setCreating(null)}>
+ {t('engine.studio.publicForms.cancel', locale)}
+
+
+
+ ) : !open ? (
+
+ {busy === 'load' ? : t('engine.studio.publicForms.pick', locale)}
+
+ ) : (
+
+ {!canWrite &&
{t('engine.studio.publicForms.readOnly', locale)}
}
+ {notice && (
+
+ {notice}
+ setNotice(null)}>
+
+
+
+ )}
+ {missing.length > 0 && (
+
+ {tFormat('engine.studio.publicForms.missingRequired', locale, {
+ fields: missing.map((f) => fieldLabel.get(f) ?? f).join(', '),
+ })}
+
+ )}
+
+
+
+ {/* Sections and their fields. */}
+
+
+
{t('engine.studio.publicForms.fields', locale)}
+ {editable && (
+
edit(withSection(open.model, t('engine.studio.publicForms.newSection', locale)))}
+ data-testid="public-form-add-section"
+ >
+ {t('engine.studio.publicForms.addSection', locale)}
+
+ )}
+
+ {open.model.sections.map((section, si) => {
+ const offered = fields.filter((f) => !fieldsOnForm(open.model).includes(f.name));
+ return (
+
{
+ if (dragging) e.preventDefault();
+ }}
+ onDrop={(e) => {
+ e.preventDefault();
+ if (dragging) edit(withFieldMoved(open.model, dragging, section.key, section.fields.length));
+ setDragging(null);
+ }}
+ >
+
+
edit(withSectionLabel(open.model, section.key, e.target.value))}
+ data-testid={`public-form-section-label-${section.key}`}
+ />
+ {editable && (
+ <>
+
edit(withSectionMoved(open.model, section.key, -1))}>
+
+
+
edit(withSectionMoved(open.model, section.key, 1))}
+ >
+
+
+
edit(withoutSection(open.model, section.key))}
+ data-testid={`public-form-remove-section-${section.key}`}
+ >
+
+
+ >
+ )}
+
+
+ {section.fields.map((entry, fi) => {
+ const locked = requiredByObject.has(entry.field);
+ return (
+ setDragging(entry.field)}
+ onDragEnd={() => setDragging(null)}
+ onDragOver={(e) => {
+ if (dragging) e.preventDefault();
+ }}
+ onDrop={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (dragging && dragging !== entry.field) edit(withFieldMoved(open.model, dragging, section.key, fi));
+ setDragging(null);
+ }}
+ className={`flex items-center gap-2 px-2 py-1.5 text-sm ${dragging === entry.field ? 'opacity-50' : ''}`}
+ data-testid={`public-form-field-${entry.field}`}
+ >
+ {editable && }
+ {fieldLabel.get(entry.field) ?? entry.field}
+
+ edit(withRequired(open.model, entry.field, e.target.checked, requiredByObject))}
+ data-testid={`public-form-required-${entry.field}`}
+ />
+ {t('engine.studio.publicForms.required', locale)}
+
+ {editable && (
+ <>
+ edit(withFieldMoved(open.model, entry.field, section.key, fi - 1))}>
+
+
+ edit(withFieldMoved(open.model, entry.field, section.key, fi + 1))}
+ >
+
+
+ askRemoveField(entry.field)}
+ data-testid={`public-form-remove-${entry.field}`}
+ >
+
+
+ >
+ )}
+
+ );
+ })}
+ {section.fields.length === 0 && (
+ {t('engine.studio.publicForms.sectionEmpty', locale)}
+ )}
+
+ {editable && offered.length > 0 && (
+
+ {
+ if (e.target.value) edit(withField(open.model, e.target.value, section.key, requiredByObject));
+ }}
+ aria-label={t('engine.studio.publicForms.addField', locale)}
+ data-testid={`public-form-add-field-${section.key}`}
+ >
+ {t('engine.studio.publicForms.addField', locale)}
+ {offered.map((f) => (
+
+ {f.label}
+
+ ))}
+
+
+ )}
+
+ );
+ })}
+
+
+ {/* After submit. */}
+
+
{t('engine.studio.publicForms.afterSubmit', locale)}
+
+ {t('engine.studio.publicForms.thankYouTitle', locale)}
+ edit({ ...open.model, thankYouTitle: e.target.value })} data-testid="public-form-thank-you-title" />
+
+
+ {t('engine.studio.publicForms.thankYouMessage', locale)}
+
+
+
+ {canWrite && !isNew && (
+
+ {shippedByApp ? (
+
+ {t('engine.studio.publicForms.deleteShipped', locale)}
+
+ ) : confirmDelete ? (
+
+ {tFormat('engine.studio.publicForms.deleteConfirm', locale, { name: open.model.title || open.model.name })}
+ void remove()}
+ disabled={busy !== null}
+ data-testid="public-form-delete-yes"
+ >
+ {t('engine.studio.publicForms.delete', locale)}
+
+ setConfirmDelete(false)}>
+ {t('engine.studio.publicForms.cancel', locale)}
+
+
+ ) : (
+
setConfirmDelete(true)} data-testid="public-form-delete">
+ {t('engine.studio.publicForms.delete', locale)}
+
+ )}
+
+ )}
+
+ )}
+
+
+ {/* Live preview: the runtime form, as the person filling it in sees it. */}
+ {open && (
+
+ )}
+
+
+ );
+}
diff --git a/ui/packages/app-shell/src/views/studio-design/publicForm/publicFormDesign.test.ts b/ui/packages/app-shell/src/views/studio-design/publicForm/publicFormDesign.test.ts
new file mode 100644
index 00000000000..e943d979956
--- /dev/null
+++ b/ui/packages/app-shell/src/views/studio-design/publicForm/publicFormDesign.test.ts
@@ -0,0 +1,358 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+import { describe, it, expect } from 'vitest';
+import { anonymousFormIntakeCandidates } from '@objectstack/spec/ui';
+import {
+ addressProblem,
+ fieldsOnForm,
+ fillableFields,
+ isPublicFormItem,
+ missingRequiredFields,
+ newPublicFormModel,
+ objectRequiredFields,
+ previewSectionsOf,
+ publicFormItemOf,
+ publicFormModelOf,
+ slugFromTitle,
+ takenAddresses,
+ withField,
+ withFieldMoved,
+ withoutField,
+ withoutSection,
+ withRequired,
+ withSection,
+ withSectionLabel,
+ withSectionMoved,
+} from './publicFormDesign';
+
+/**
+ * objectstack#36444 — the rules of Studio's public form designer: which
+ * fields a form may hold and must keep, the address rule, and the view item a
+ * design is saved as.
+ */
+
+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' },
+ total: { type: 'summary', label: 'Total' },
+ code: { type: 'autonumber', label: 'Code' },
+ internal: { type: 'text', label: 'Internal', hidden: true },
+ locked: { type: 'text', label: 'Locked', readonly: true },
+ owning_business_unit_id: { type: 'lookup', system: true, hidden: true },
+ created_at: { type: 'datetime', label: 'Created' },
+ },
+};
+
+const stored = {
+ name: 'crm_lead.web_to_lead',
+ object: 'crm_lead',
+ viewKind: 'form',
+ label: 'Contact us',
+ _packageId: 'com.example.crm',
+ config: {
+ type: 'simple',
+ data: { provider: 'object', object: 'crm_lead' },
+ sections: [
+ {
+ name: 'contact_us',
+ label: 'Contact us',
+ collapsible: false,
+ columns: 1,
+ fields: [
+ { field: 'name', required: true, span: 'auto' },
+ { field: 'company' },
+ { field: 'email', required: true },
+ { field: 'phone' },
+ { field: 'title' },
+ ],
+ },
+ ],
+ sharing: { enabled: true, publicLink: '/forms/contact-us', allowAnonymous: true },
+ },
+};
+
+const required = new Set(objectRequiredFields(lead));
+
+describe('the fields a public form may hold', () => {
+ it('offers the fillable fields only: no hidden, read-only, system, formula, roll-up or auto-number field', () => {
+ expect(fillableFields(lead).map((f) => f.name)).toEqual(['name', 'company', 'email', 'phone', 'title']);
+ });
+ it('knows the fields the object requires', () => {
+ expect(objectRequiredFields(lead)).toEqual(['name', 'email']);
+ });
+ it('does not hold a form to a field the object fills in itself (a default value, or a default choice)', () => {
+ const withDefaults = {
+ fields: {
+ status: { type: 'select', required: true, defaultValue: 'new' },
+ stage: { type: 'select', required: true, options: [{ value: 'a' }, { value: 'b', default: true }] },
+ source: { type: 'select', required: true, options: [{ value: 'web' }] },
+ },
+ };
+ expect(objectRequiredFields(withDefaults)).toEqual(['source']);
+ });
+ it('reads `fields` as an array too', () => {
+ expect(fillableFields({ fields: [{ name: 'a', type: 'text' }, { name: 'b', type: 'formula' }] }).map((f) => f.name)).toEqual(['a']);
+ });
+});
+
+describe('the model of a stored public form', () => {
+ it('reads title, address, sections and required marks', () => {
+ const model = publicFormModelOf(stored);
+ expect(model).toMatchObject({ name: 'crm_lead.web_to_lead', object: 'crm_lead', title: 'Contact us', slug: 'contact-us', enabled: true });
+ expect(model.sections).toEqual([
+ {
+ key: 'contact_us',
+ label: 'Contact us',
+ fields: [
+ { field: 'name', required: true },
+ { field: 'company', required: false },
+ { field: 'email', required: true },
+ { field: 'phone', required: false },
+ { field: 'title', required: false },
+ ],
+ },
+ ]);
+ });
+
+ it('writes back only what was edited, keeping every other key and dropping the read\'s decorations', () => {
+ let model = publicFormModelOf(stored);
+ model = withRequired(model, 'phone', true, required);
+ model = withoutField(model, 'title', required);
+ model = { ...model, title: 'Get in touch' };
+ const item = publicFormItemOf(model, stored);
+ expect(item._packageId).toBeUndefined();
+ expect(item.label).toBe('Get in touch');
+ expect(item.config.title).toBe('Get in touch');
+ expect(item.config.sections[0]).toEqual({
+ name: 'contact_us',
+ label: 'Contact us',
+ collapsible: false,
+ columns: 1,
+ fields: [
+ { field: 'name', required: true, span: 'auto' },
+ { field: 'company' },
+ { field: 'email', required: true },
+ { field: 'phone', required: true },
+ ],
+ });
+ expect(item.config.sharing).toEqual(stored.config.sharing);
+ // The served rule still opens it, at the same address.
+ expect(anonymousFormIntakeCandidates(item).map((c) => c.slug)).toEqual(['contact-us']);
+ });
+
+ it('writes the after-submit message as a thank-you panel, and removes it when cleared', () => {
+ const model = { ...publicFormModelOf(stored), thankYouTitle: 'Thanks!', thankYouMessage: 'We will be in touch.' };
+ const item = publicFormItemOf(model, stored);
+ expect(item.config.submitBehavior).toEqual({ kind: 'thank-you', title: 'Thanks!', message: 'We will be in touch.' });
+ const back = publicFormModelOf(item);
+ expect([back.thankYouTitle, back.thankYouMessage]).toEqual(['Thanks!', 'We will be in touch.']);
+ const cleared = publicFormItemOf({ ...back, thankYouTitle: '', thankYouMessage: '' }, item);
+ expect(cleared.config.submitBehavior).toBeUndefined();
+ });
+
+ it('keeps a submit behaviour that is not a thank-you panel', () => {
+ const redirecting = { ...stored, config: { ...stored.config, submitBehavior: { kind: 'redirect', url: '/thanks' } } };
+ const item = publicFormItemOf(publicFormModelOf(redirecting), redirecting);
+ expect(item.config.submitBehavior).toEqual({ kind: 'redirect', url: '/thanks' });
+ });
+});
+
+describe('writing back a form stored in other shapes the spec allows', () => {
+ it('keeps every key of a section stored without a name, and of its field entries', () => {
+ const unnamed = {
+ ...stored,
+ config: {
+ ...stored.config,
+ sections: [
+ {
+ label: 'About you',
+ description: 'Tell us who you are',
+ columns: 2,
+ collapsible: true,
+ collapsed: false,
+ visibleOn: "record.source == 'web'",
+ fields: [{ field: 'name', required: true, span: 'full' }, { field: 'company', helpText: 'Where you work' }, 'email'],
+ },
+ { name: 'more', columns: 1, fields: [{ field: 'phone', placeholder: '+1' }] },
+ ],
+ },
+ };
+ let model = publicFormModelOf(unnamed);
+ expect(model.sections.map((s) => s.key)).toEqual(['section_1', 'more']);
+ model = withRequired(model, 'company', true, required);
+ model = withFieldMoved(model, 'phone', 'section_1', 0);
+ const item = publicFormItemOf(model, unnamed);
+ expect(item.config.sections[0]).toEqual({
+ name: 'section_1',
+ label: 'About you',
+ description: 'Tell us who you are',
+ columns: 2,
+ collapsible: true,
+ collapsed: false,
+ visibleOn: "record.source == 'web'",
+ fields: [
+ // A field moved from another section keeps its own keys.
+ { field: 'phone', placeholder: '+1' },
+ { field: 'name', required: true, span: 'full' },
+ { field: 'company', helpText: 'Where you work', required: true },
+ // A field stored as its bare name is written as an entry.
+ { field: 'email' },
+ ],
+ });
+ expect(item.config.sections[1]).toEqual({ name: 'more', columns: 1, fields: [] });
+ });
+
+ it('keys an unnamed section apart from a section named like its place', () => {
+ const clash = { ...stored, config: { ...stored.config, sections: [{ label: 'A', columns: 2, fields: ['name'] }, { name: 'section_1', label: 'B', fields: ['email'] }] } };
+ const model = publicFormModelOf(clash);
+ expect(model.sections.map((s) => s.key)).toEqual(['section_2', 'section_1']);
+ const item = publicFormItemOf(model, clash);
+ expect(item.config.sections.map((s: { label: string; columns?: number }) => [s.label, s.columns])).toEqual([['A', 2], ['B', undefined]]);
+ });
+
+ it('keeps titles and labels stored as maps of translations when they were not edited', () => {
+ const translated = {
+ ...stored,
+ label: undefined,
+ config: {
+ ...stored.config,
+ title: { en: 'Contact us', 'zh-CN': '联系我们' },
+ description: { en: 'We reply in a day', 'zh-CN': '一天内回复' },
+ sections: [{ ...stored.config.sections[0], label: { en: 'About you', 'zh-CN': '关于你' } }],
+ submitBehavior: { kind: 'thank-you', title: { en: 'Thanks', 'zh-CN': '谢谢' }, message: 'We will be in touch.' },
+ },
+ };
+ const model = withRequired(publicFormModelOf(translated), 'phone', true, required);
+ const item = publicFormItemOf({ ...model, thankYouMessage: 'Talk soon.' }, translated);
+ expect(item.config.title).toEqual(translated.config.title);
+ expect(item.config.description).toEqual(translated.config.description);
+ expect(item.config.sections[0].label).toEqual({ en: 'About you', 'zh-CN': '关于你' });
+ expect(item.config.submitBehavior).toEqual({ kind: 'thank-you', title: { en: 'Thanks', 'zh-CN': '谢谢' }, message: 'Talk soon.' });
+ expect(item.label).toBeUndefined();
+
+ // A text the person did edit replaces the map.
+ const renamed = withSectionLabel({ ...model, title: 'Get in touch' }, 'contact_us', 'Who you are');
+ const edited = publicFormItemOf(renamed, translated);
+ expect(edited.config.title).toBe('Get in touch');
+ expect(edited.label).toBe('Get in touch');
+ expect(edited.config.sections[0].label).toBe('Who you are');
+ });
+
+ it('keeps a thank-you title stored as translations when only the message is cleared', () => {
+ const translated = { ...stored, config: { ...stored.config, submitBehavior: { kind: 'thank-you', title: { en: 'Thanks', 'zh-CN': '谢谢' }, message: 'We will be in touch.' } } };
+ const item = publicFormItemOf({ ...publicFormModelOf(translated), thankYouMessage: '' }, translated);
+ expect(item.config.submitBehavior).toEqual({ kind: 'thank-you', title: { en: 'Thanks', 'zh-CN': '谢谢' } });
+ });
+
+ it('writes no column count onto a section that had none', () => {
+ const model = withSection(newPublicFormModel('crm_lead', 'Demo signup', 'demo-signup', lead), 'More');
+ const item = publicFormItemOf(model, null);
+ expect(item.config.sections.map((s: Record) => 'columns' in s)).toEqual([false, false]);
+ const kept = publicFormItemOf(publicFormModelOf(stored), stored);
+ expect(kept.config.sections[0].columns).toBe(1);
+ });
+});
+
+describe('a new public form', () => {
+ it('starts on with one section holding the fields the object requires, and saves as a form view of its object', () => {
+ const model = newPublicFormModel('crm_lead', 'Demo signup', 'demo-signup', lead);
+ expect(model.name).toBe('crm_lead.demo_signup');
+ expect(model.sections).toEqual([{ key: 'main', label: '', fields: [{ field: 'name', required: true }, { field: 'email', required: true }] }]);
+ const item = publicFormItemOf(withField(withField(model, 'company', null, required), 'phone', null, required), null);
+ expect(item).toMatchObject({ name: 'crm_lead.demo_signup', object: 'crm_lead', viewKind: 'form', label: 'Demo signup' });
+ expect(item.config.data).toEqual({ provider: 'object', object: 'crm_lead' });
+ expect(item.config.sections[0].fields.map((f: { field: string }) => f.field)).toEqual(['name', 'email', 'company', 'phone']);
+ expect(isPublicFormItem(item)).toBe(true);
+ expect(anonymousFormIntakeCandidates(item)).toEqual([expect.objectContaining({ key: 'crm_lead.demo_signup', slug: 'demo-signup' })]);
+ });
+
+ it('makes an address from a title', () => {
+ expect(slugFromTitle('Demo signup')).toBe('demo-signup');
+ expect(slugFromTitle(' Contact Us — 2026! ')).toBe('contact-us-2026');
+ expect(slugFromTitle('线索')).toBe('');
+ });
+});
+
+describe('the address', () => {
+ const taken = takenAddresses([stored, { name: 'x.form', viewKind: 'form', config: {} }, { name: 'other', config: { sharing: { publicLink: 'demo' } } }]);
+ it('is refused empty, malformed, or used by another form (switched off included)', () => {
+ expect(addressProblem('', 'crm_lead.new', taken)).toBe('empty');
+ expect(addressProblem('Contact Us', 'crm_lead.new', taken)).toBe('shape');
+ expect(addressProblem('a', 'crm_lead.new', taken)).toBe('shape');
+ expect(addressProblem('-x', 'crm_lead.new', taken)).toBe('shape');
+ expect(addressProblem('contact-us', 'crm_lead.new', taken)).toBe('taken');
+ expect(addressProblem('demo', 'crm_lead.new', taken)).toBe('taken');
+ });
+ it('is the form\'s own address, or a free one', () => {
+ expect(addressProblem('contact-us', 'crm_lead.web_to_lead', taken)).toBeNull();
+ expect(addressProblem('demo-signup', 'crm_lead.new', taken)).toBeNull();
+ });
+});
+
+describe('editing the fields', () => {
+ const model = publicFormModelOf(stored);
+
+ it('refuses to remove a field the object requires, and removes any other', () => {
+ expect(withoutField(model, 'email', required)).toBe(model);
+ expect(fieldsOnForm(withoutField(model, 'title', required))).not.toContain('title');
+ });
+
+ it('keeps a field the object requires required on the form', () => {
+ const after = withRequired(model, 'email', false, required);
+ expect(after.sections[0].fields.find((f) => f.field === 'email')?.required).toBe(true);
+ expect(withRequired(model, 'phone', true, required).sections[0].fields.find((f) => f.field === 'phone')?.required).toBe(true);
+ });
+
+ it('adds a field once, required when the object requires it', () => {
+ const without = withoutField(model, 'title', required);
+ expect(withField(without, 'title', 'contact_us', required).sections[0].fields.at(-1)).toEqual({ field: 'title', required: false });
+ expect(withField(model, 'title', 'contact_us', required)).toBe(model);
+ });
+
+ it('moves a field within a section and across sections', () => {
+ const reordered = withFieldMoved(model, 'title', 'contact_us', 0);
+ expect(fieldsOnForm(reordered)).toEqual(['title', 'name', 'company', 'email', 'phone']);
+ const two = withSection(model, 'About you');
+ const key = two.sections[1].key;
+ const moved = withFieldMoved(two, 'phone', key, 0);
+ expect(moved.sections[1].fields).toEqual([{ field: 'phone', required: false }]);
+ expect(fieldsOnForm(moved)).toHaveLength(5);
+ });
+
+ it('groups fields into named sections; removing a section keeps its fields', () => {
+ const two = withSection(model, 'About you');
+ const key = two.sections[1].key;
+ const moved = withFieldMoved(two, 'phone', key, 0);
+ const swapped = withSectionMoved(moved, key, -1);
+ expect(swapped.sections.map((s) => s.label)).toEqual(['About you', 'Contact us']);
+ const gone = withoutSection(swapped, key);
+ expect(gone.sections).toHaveLength(1);
+ expect(fieldsOnForm(gone).sort()).toEqual(['company', 'email', 'name', 'phone', 'title']);
+ expect(withoutSection(gone, gone.sections[0].key)).toBe(gone);
+ });
+
+ it('names the object-required fields a form lacks', () => {
+ const lacking = { ...model, sections: [{ ...model.sections[0], fields: [{ field: 'company', required: false }] }] };
+ expect(missingRequiredFields(lacking, required)).toEqual(['name', 'email']);
+ expect(missingRequiredFields(model, required)).toEqual([]);
+ });
+
+ it('previews an untitled section with no heading', () => {
+ const model = newPublicFormModel('crm_lead', 'Demo signup', 'demo-signup', lead);
+ expect(previewSectionsOf(model)).toEqual([{ fields: [{ field: 'name', required: true }, { field: 'email', required: true }] }]);
+ });
+
+ it('previews the sections as the runtime form takes them', () => {
+ expect(previewSectionsOf(model)[0]).toEqual({
+ name: 'contact_us',
+ label: 'Contact us',
+ fields: [{ field: 'name', required: true }, { field: 'company' }, { field: 'email', required: true }, { field: 'phone' }, { field: 'title' }],
+ });
+ });
+});
diff --git a/ui/packages/app-shell/src/views/studio-design/publicForm/publicFormDesign.ts b/ui/packages/app-shell/src/views/studio-design/publicForm/publicFormDesign.ts
new file mode 100644
index 00000000000..74b069d9a85
--- /dev/null
+++ b/ui/packages/app-shell/src/views/studio-design/publicForm/publicFormDesign.ts
@@ -0,0 +1,503 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+/**
+ * Studio → Data → an object → Form → Public forms (objectstack#36444): the
+ * design half of public forms, as data. A public form is a form view item of
+ * its object (`viewKind: 'form'`) whose `sharing` opens it to anonymous
+ * intake (`anonymousFormIntakeCandidates`, `@objectstack/spec/ui`). No new
+ * metadata shape: the designer reads and writes that item.
+ *
+ * This module is the designer's rules, free of React:
+ *
+ * - which of the object's fields a form may hold ({@link fillableFields}):
+ * none that is hidden, read-only, a system field, a formula, a roll-up or an
+ * auto-number, since nobody filling the form in could give it a value;
+ * - which fields the form must keep ({@link objectRequiredFields}): a field the
+ * object requires, and fills in for nobody, cannot be removed, or no
+ * submission could be saved;
+ * - the form as the designer edits it ({@link PublicFormModel}), read from the
+ * item ({@link publicFormModelOf}) and written back into it
+ * ({@link publicFormItemOf}), keeping every key the designer does not edit;
+ * - the address rule ({@link addressProblem}): a slug of lowercase letters,
+ * digits and hyphens that no other form of the environment uses.
+ */
+
+import { anonymousFormIntakeCandidates, anonymousFormObjectName, publicFormSlug } from '@objectstack/spec/ui';
+import { STUDIO_SYSTEM_FIELD_NAMES } from '../DataPillarHelpers.js';
+
+type FormDoc = Record;
+
+const isDoc = (v: unknown): v is FormDoc => !!v && typeof v === 'object' && !Array.isArray(v);
+const text = (v: unknown): string => (typeof v === 'string' ? v : '');
+
+/** A field type nobody filling a form in can give a value to. */
+const COMPUTED_FIELD_TYPES: ReadonlySet = new Set(['formula', 'summary', 'autonumber']);
+
+/** One field of the object, as the designer offers it. */
+export interface DesignerField {
+ name: string;
+ label: string;
+ type: string;
+ /**
+ * The object requires it and nothing fills it in for a submission that
+ * leaves it out: the form must keep it, and it is always required on the form.
+ */
+ objectRequired: boolean;
+}
+
+/**
+ * Whether a record written without the field would be refused: the object
+ * requires it and gives it no value of its own (a `defaultValue`, or a choice
+ * option marked `default: true`, which the write path falls back to).
+ */
+export function isRequiredWithoutDefault(def: Readonly): boolean {
+ if (def.required !== true) return false;
+ if (def.defaultValue !== undefined && def.defaultValue !== null && def.defaultValue !== '') return false;
+ const options = Array.isArray(def.options) ? def.options : [];
+ return !options.some((o: unknown) => isDoc(o) && o.default === true);
+}
+
+/** The object's fields as `[name, definition]` pairs, from `fields` as a map or an array. */
+function fieldEntries(objectDef: unknown): Array<[string, FormDoc]> {
+ const fields = isDoc(objectDef) ? objectDef.fields : undefined;
+ if (Array.isArray(fields)) {
+ return fields.filter(isDoc).filter((f) => typeof f.name === 'string').map((f) => [f.name as string, f]);
+ }
+ if (isDoc(fields)) return Object.entries(fields).filter((e): e is [string, FormDoc] => isDoc(e[1]));
+ return [];
+}
+
+/** Whether a field of the object can be filled in on a form. */
+export function isFillableField(name: string, def: Readonly): boolean {
+ if (STUDIO_SYSTEM_FIELD_NAMES.has(name)) return false;
+ if (def.system === true || def.hidden === true || def.readonly === true) return false;
+ return !COMPUTED_FIELD_TYPES.has(text(def.type));
+}
+
+/** The object's fields a public form may hold, in the object's order. */
+export function fillableFields(objectDef: unknown): DesignerField[] {
+ return fieldEntries(objectDef)
+ .filter(([name, def]) => isFillableField(name, def))
+ .map(([name, def]) => ({
+ name,
+ label: text(def.label) || name,
+ type: text(def.type) || 'text',
+ objectRequired: isRequiredWithoutDefault(def),
+ }));
+}
+
+/** The fillable fields the object requires: every public form of it must hold them. */
+export function objectRequiredFields(objectDef: unknown): string[] {
+ return fillableFields(objectDef).filter((f) => f.objectRequired).map((f) => f.name);
+}
+
+/** One field on the form. */
+export interface PublicFormFieldEntry {
+ field: string;
+ required: boolean;
+}
+
+/** One named section of the form. */
+export interface PublicFormSection {
+ /** The section's stable key (`name`). */
+ key: string;
+ label: string;
+ fields: PublicFormFieldEntry[];
+}
+
+/** The public form as the designer edits it. */
+export interface PublicFormModel {
+ /** The view item's name: `.`. */
+ name: string;
+ object: string;
+ title: string;
+ description: string;
+ /** The address slug (`/f/`). */
+ slug: string;
+ /** Whether the form takes submissions (`sharing.enabled`); switched in Setup, kept as it is here. */
+ enabled: boolean;
+ sections: PublicFormSection[];
+ /** What the person sees after submitting (`submitBehavior: { kind: 'thank-you' }`). */
+ thankYouTitle: string;
+ thankYouMessage: string;
+}
+
+/** The slug a `publicLink` names, or `''`. */
+function slugOf(sharing: unknown): string {
+ return isDoc(sharing) && typeof sharing.publicLink === 'string' ? publicFormSlug(sharing.publicLink) : '';
+}
+
+/**
+ * Whether a view item is a public form: a form item whose form opens to
+ * anonymous intake once switched on (the listing rule of Setup's page, so the
+ * two surfaces list the same forms).
+ */
+export function isPublicFormItem(item: unknown): item is FormDoc {
+ if (!isDoc(item) || item.viewKind !== 'form' || !isDoc(item.config) || typeof item.name !== 'string') return false;
+ const on = { ...item, config: { ...item.config, sharing: { ...(isDoc(item.config.sharing) ? item.config.sharing : {}), enabled: true } } };
+ return anonymousFormIntakeCandidates(on).some((c) => c.key === item.name);
+}
+
+/** The object a public form item submits into. */
+export function publicFormObjectOf(item: FormDoc): string | undefined {
+ return anonymousFormObjectName(item, item.config);
+}
+
+/**
+ * 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`). Setup's
+ * list names forms the same way.
+ */
+export function publicFormShownName(item: Readonly): string {
+ const config: FormDoc = isDoc(item.config) ? item.config : {};
+ const first = Array.isArray(config.sections) ? config.sections.find(isDoc) : undefined;
+ const name = text(item.name);
+ const dot = name.lastIndexOf('.');
+ const pick = (v: unknown) => (typeof v === 'string' && v.trim() ? v : undefined);
+ return (
+ pick(item.label) ??
+ pick(config.title) ??
+ pick(config.label) ??
+ pick(first?.label) ??
+ (dot >= 0 && dot < name.length - 1 ? name.slice(dot + 1) : name)
+ );
+}
+
+/** A form's stored sections, the objects among them, in order. */
+function storedSections(config: FormDoc): FormDoc[] {
+ return (Array.isArray(config.sections) ? config.sections : []).filter(isDoc);
+}
+
+/**
+ * The key of each stored section, in order: its `name`, or for a section
+ * stored without one `section_` by its place (never one another section
+ * uses). The model and the write-back key sections by the same rule, so an
+ * unnamed section is matched with what it stored.
+ */
+function sectionKeysOf(sections: readonly FormDoc[]): string[] {
+ const named = new Set(sections.map((s) => text(s.name)).filter(Boolean));
+ const used = new Set();
+ return sections.map((s, i) => {
+ let key = text(s.name);
+ if (!key || used.has(key)) {
+ let n = i + 1;
+ while (named.has(`section_${n}`) || used.has(`section_${n}`)) n += 1;
+ key = `section_${n}`;
+ }
+ used.add(key);
+ return key;
+ });
+}
+
+/** The designer's model of a public form item. */
+export function publicFormModelOf(item: FormDoc): PublicFormModel {
+ const config: FormDoc = isDoc(item.config) ? item.config : {};
+ const stored = storedSections(config);
+ const keys = sectionKeysOf(stored);
+ const sections = stored.map((s, i) => ({
+ key: keys[i],
+ label: text(s.label),
+ fields: (Array.isArray(s.fields) ? s.fields : [])
+ .map((f: unknown) =>
+ typeof f === 'string'
+ ? { field: f, required: false }
+ : isDoc(f) && typeof f.field === 'string'
+ ? { field: f.field, required: f.required === true }
+ : null,
+ )
+ .filter((f: PublicFormFieldEntry | null): f is PublicFormFieldEntry => f !== null),
+ }));
+ const thankYou = isDoc(config.submitBehavior) && config.submitBehavior.kind === 'thank-you' ? config.submitBehavior : {};
+ return {
+ name: String(item.name),
+ object: publicFormObjectOf(item) ?? text(item.object),
+ title: text(config.title) || text(item.label),
+ description: text(config.description),
+ slug: slugOf(config.sharing),
+ enabled: isDoc(config.sharing) && config.sharing.enabled === true,
+ sections,
+ thankYouTitle: text(thankYou.title),
+ thankYouMessage: text(thankYou.message),
+ };
+}
+
+/**
+ * A section's stored body, keeping the keys the designer does not edit.
+ * `was` is the section as stored (by the same key); `fieldsWas` every field
+ * entry the form stored, so a field moved to another section keeps its own
+ * keys. A label the designer shows as it was (including one stored as a map
+ * of translations, which it shows empty) is kept as stored.
+ */
+function sectionBody(section: PublicFormSection, was: FormDoc | undefined, fieldsWas: ReadonlyMap): FormDoc {
+ const body: FormDoc = { ...(was ?? {}), name: section.key, fields: section.fields.map((f) => {
+ const entry: FormDoc = { ...(fieldsWas.get(f.field) ?? {}), field: f.field };
+ if (f.required) entry.required = true;
+ else delete entry.required;
+ return entry;
+ }) };
+ if (was && section.label === text(was.label)) return body;
+ if (section.label) body.label = section.label;
+ else delete body.label;
+ return body;
+}
+
+/**
+ * The view item a model is saved as. `base` is the item as its author stored
+ * it (the layered read, untranslated), or `null` for a new form: every key the
+ * designer does not edit is kept as it is, and a text the designer did not
+ * change (its title, description, after-submit message, a section's label) is
+ * kept as stored, even one stored as a map of translations.
+ */
+export function publicFormItemOf(model: PublicFormModel, base: FormDoc | null): FormDoc {
+ const item: FormDoc = {};
+ for (const [key, value] of Object.entries(base ?? {})) if (!key.startsWith('_')) item[key] = value;
+ const config: FormDoc = isDoc(item.config) ? { ...item.config } : {};
+ // What the designer read from `base`: a text equal to it was not edited.
+ const read = base ? publicFormModelOf({ ...base, name: model.name }) : null;
+ const stored = storedSections(config);
+ const keys = sectionKeysOf(stored);
+ const sectionsWas = new Map(stored.map((s, i) => [keys[i], s]));
+ const fieldsWas = new Map();
+ for (const s of stored) {
+ for (const f of Array.isArray(s.fields) ? s.fields : []) {
+ if (isDoc(f) && typeof f.field === 'string' && !fieldsWas.has(f.field)) fieldsWas.set(f.field, f);
+ }
+ }
+ config.type = config.type ?? 'simple';
+ config.data = isDoc(config.data) ? { ...config.data, object: model.object } : { provider: 'object', object: model.object };
+ const titleEdited = !read || model.title !== read.title;
+ if (titleEdited) {
+ if (model.title) config.title = model.title;
+ else delete config.title;
+ }
+ if (!read || model.description !== read.description) {
+ if (model.description) config.description = model.description;
+ else delete config.description;
+ }
+ config.sections = model.sections.map((s) => sectionBody(s, sectionsWas.get(s.key), fieldsWas));
+ config.sharing = {
+ ...(isDoc(config.sharing) ? config.sharing : {}),
+ enabled: model.enabled,
+ allowAnonymous: true,
+ publicLink: `/forms/${model.slug}`,
+ };
+ if (!read || model.thankYouTitle !== read.thankYouTitle || model.thankYouMessage !== read.thankYouMessage) {
+ const was = isDoc(config.submitBehavior) && config.submitBehavior.kind === 'thank-you' ? config.submitBehavior : null;
+ const thankYou: FormDoc = { ...(was ?? {}), kind: 'thank-you' };
+ // Each of the two texts is kept as stored unless it was edited.
+ for (const [key, value, before] of [
+ ['title', model.thankYouTitle, read?.thankYouTitle],
+ ['message', model.thankYouMessage, read?.thankYouMessage],
+ ] as const) {
+ if (was && value === before) continue;
+ if (value) thankYou[key] = value;
+ else delete thankYou[key];
+ }
+ if (thankYou.title !== undefined || thankYou.message !== undefined) config.submitBehavior = thankYou;
+ else if (was) delete config.submitBehavior;
+ }
+ item.name = model.name;
+ item.object = model.object;
+ item.viewKind = 'form';
+ if (titleEdited && model.title) item.label = model.title;
+ item.config = config;
+ return item;
+}
+
+/** The fields a model holds, in form order. */
+export function fieldsOnForm(model: PublicFormModel): string[] {
+ return model.sections.flatMap((s) => s.fields.map((f) => f.field));
+}
+
+/** An address slug's shape: lowercase letters, digits and single hyphens, 2 to 64 characters. */
+const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
+
+/** What is wrong with an address, or `null`. */
+export type AddressProblem = 'empty' | 'shape' | 'taken';
+
+/**
+ * Whether `slug` can be this form's address: well formed, and used by no
+ * other form of the environment (`taken`: slug → the form that holds it).
+ */
+export function addressProblem(slug: string, formName: string, taken: ReadonlyMap): AddressProblem | null {
+ if (!slug) return 'empty';
+ if (slug.length < 2 || slug.length > 64 || !SLUG_RE.test(slug)) return 'shape';
+ const holder = taken.get(slug);
+ return holder !== undefined && holder !== formName ? 'taken' : null;
+}
+
+/** Every address the environment's view items use: slug → the form that holds it (switched off included). */
+export function takenAddresses(items: readonly unknown[]): Map {
+ const taken = new Map();
+ for (const item of items) {
+ if (!isDoc(item) || typeof item.name !== 'string' || !isDoc(item.config)) continue;
+ const slug = slugOf(item.config.sharing);
+ if (slug && !taken.has(slug)) taken.set(slug, item.name);
+ }
+ return taken;
+}
+
+/** A slug made from a title: `Demo signup` → `demo-signup`. */
+export function slugFromTitle(title: string): string {
+ return title
+ .normalize('NFKD')
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 64)
+ .replace(/-+$/, '');
+}
+
+/** The view item name of a new form of `object` at `slug`: `.`. */
+export function newPublicFormName(object: string, slug: string): string {
+ return `${object}.${slug.replace(/-/g, '_')}`;
+}
+
+/** A new public form of `object`: one section holding the fields the object requires. */
+export function newPublicFormModel(object: string, title: string, slug: string, objectDef: unknown): PublicFormModel {
+ return {
+ name: newPublicFormName(object, slug),
+ object,
+ title,
+ description: '',
+ slug,
+ enabled: true,
+ sections: [
+ {
+ key: 'main',
+ label: '',
+ fields: objectRequiredFields(objectDef).map((field) => ({ field, required: true })),
+ },
+ ],
+ thankYouTitle: '',
+ thankYouMessage: '',
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Edits. Each returns a new model, or the same model when the edit is refused.
+// ---------------------------------------------------------------------------
+
+/** Why a field cannot leave the form, or `null`. */
+export function removeFieldRefusal(field: string, requiredByObject: ReadonlySet): 'object-required' | null {
+ return requiredByObject.has(field) ? 'object-required' : null;
+}
+
+/** `model` without `field`: refused (the same model) for a field the object requires. */
+export function withoutField(model: PublicFormModel, field: string, requiredByObject: ReadonlySet): PublicFormModel {
+ if (removeFieldRefusal(field, requiredByObject)) return model;
+ return { ...model, sections: model.sections.map((s) => ({ ...s, fields: s.fields.filter((f) => f.field !== field) })) };
+}
+
+/** `model` with `field` added at the end of section `sectionKey` (first section when absent). */
+export function withField(model: PublicFormModel, field: string, sectionKey: string | null, requiredByObject: ReadonlySet): PublicFormModel {
+ if (fieldsOnForm(model).includes(field)) return model;
+ const sections = model.sections.length > 0 ? model.sections : [{ key: 'main', label: '', fields: [] }];
+ const target = sections.find((s) => s.key === sectionKey) ?? sections[0];
+ return {
+ ...model,
+ sections: sections.map((s) =>
+ s === target ? { ...s, fields: [...s.fields, { field, required: requiredByObject.has(field) }] } : s,
+ ),
+ };
+}
+
+/** `model` with `field` marked required or not; a field the object requires stays required. */
+export function withRequired(model: PublicFormModel, field: string, required: boolean, requiredByObject: ReadonlySet): PublicFormModel {
+ const value = requiredByObject.has(field) ? true : required;
+ return {
+ ...model,
+ sections: model.sections.map((s) => ({
+ ...s,
+ fields: s.fields.map((f) => (f.field === field ? { ...f, required: value } : f)),
+ })),
+ };
+}
+
+/**
+ * `model` with `field` moved to `index` of section `sectionKey` (drag and
+ * drop, or the move buttons). An index past the end appends.
+ */
+export function withFieldMoved(model: PublicFormModel, field: string, sectionKey: string, index: number): PublicFormModel {
+ let moving: PublicFormFieldEntry | undefined;
+ const lifted = model.sections.map((s) => {
+ const at = s.fields.findIndex((f) => f.field === field);
+ if (at < 0) return s;
+ moving = s.fields[at];
+ return { ...s, fields: s.fields.filter((_, i) => i !== at) };
+ });
+ if (!moving || !lifted.some((s) => s.key === sectionKey)) return model;
+ return {
+ ...model,
+ sections: lifted.map((s) => {
+ if (s.key !== sectionKey) return s;
+ const fields = [...s.fields];
+ fields.splice(Math.max(0, Math.min(index, fields.length)), 0, moving!);
+ return { ...s, fields };
+ }),
+ };
+}
+
+/** A section key not used by `model`. */
+function freshSectionKey(model: PublicFormModel): string {
+ const used = new Set(model.sections.map((s) => s.key));
+ let n = model.sections.length + 1;
+ while (used.has(`section_${n}`)) n += 1;
+ return `section_${n}`;
+}
+
+/** `model` with a new, empty section named `label` at the end. */
+export function withSection(model: PublicFormModel, label: string): PublicFormModel {
+ return { ...model, sections: [...model.sections, { key: freshSectionKey(model), label, fields: [] }] };
+}
+
+/** `model` with section `sectionKey` renamed. */
+export function withSectionLabel(model: PublicFormModel, sectionKey: string, label: string): PublicFormModel {
+ return { ...model, sections: model.sections.map((s) => (s.key === sectionKey ? { ...s, label } : s)) };
+}
+
+/** `model` with section `sectionKey` moved one place up (-1) or down (+1). */
+export function withSectionMoved(model: PublicFormModel, sectionKey: string, step: -1 | 1): PublicFormModel {
+ const at = model.sections.findIndex((s) => s.key === sectionKey);
+ const to = at + step;
+ if (at < 0 || to < 0 || to >= model.sections.length) return model;
+ const sections = [...model.sections];
+ [sections[at], sections[to]] = [sections[to], sections[at]];
+ return { ...model, sections };
+}
+
+/**
+ * `model` without section `sectionKey`; its fields move to the section before
+ * it (or after it, for the first), so removing a section never removes a
+ * field. The last section cannot be removed.
+ */
+export function withoutSection(model: PublicFormModel, sectionKey: string): PublicFormModel {
+ const at = model.sections.findIndex((s) => s.key === sectionKey);
+ if (at < 0 || model.sections.length < 2) return model;
+ const heir = at > 0 ? at - 1 : 1;
+ const moved = model.sections[at].fields;
+ return {
+ ...model,
+ sections: model.sections
+ .map((s, i) => (i === heir ? { ...s, fields: at > 0 ? [...s.fields, ...moved] : [...moved, ...s.fields] } : s))
+ .filter((_, i) => i !== at),
+ };
+}
+
+/** The object-required fields a model is missing (a form read from elsewhere may lack one). */
+export function missingRequiredFields(model: PublicFormModel, requiredByObject: ReadonlySet): string[] {
+ const on = new Set(fieldsOnForm(model));
+ return [...requiredByObject].filter((f) => !on.has(f));
+}
+
+/** What the live preview renders: the runtime form's sections, as `ObjectForm` takes them. */
+export function previewSectionsOf(model: PublicFormModel): Array<{ name?: string; label?: string; fields: Array<{ field: string; required?: boolean }> }> {
+ // An untitled section is drawn with no heading, as the form's own page draws
+ // it: the renderer would head it with its key.
+ return model.sections.map((s) => ({
+ ...(s.label ? { name: s.key, label: s.label } : {}),
+ fields: s.fields.map((f) => (f.required ? { field: f.field, required: true } : { field: f.field })),
+ }));
+}
diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts
index 2eb5d1d9148..dd1a28bcc56 100644
--- a/ui/packages/i18n/src/namespaces/studio/en.ts
+++ b/ui/packages/i18n/src/namespaces/studio/en.ts
@@ -2627,6 +2627,68 @@ const STUDIO_EN: Record = {
'engine.studio.data.tab.hooks': 'Hooks',
'engine.studio.data.tab.actions': 'Actions',
'engine.studio.data.tab.api': 'API',
+ // objectstack#36444 — the object's public forms (Form tab → Public forms).
+ 'engine.studio.data.form.surfaceLabel': 'Which form',
+ 'engine.studio.data.form.surfaceRecord': 'Record form',
+ 'engine.studio.data.form.surfacePublic': 'Public forms',
+ 'engine.studio.publicForms.listTitle': 'Public forms',
+ 'engine.studio.publicForms.new': 'New',
+ 'engine.studio.publicForms.loading': 'Loading…',
+ 'engine.studio.publicForms.none': 'No public forms yet. A public form is one anyone can fill in without signing in; each submission becomes a record.',
+ 'engine.studio.publicForms.stateDraft': 'Draft',
+ 'engine.studio.publicForms.stateOn': 'On',
+ 'engine.studio.publicForms.stateOff': 'Off',
+ 'engine.studio.publicForms.stateShippedOff': 'Off (its app ships it off)',
+ 'engine.studio.publicForms.stateUnknown': 'Unknown',
+ 'engine.studio.publicForms.switchInSetup': 'Switch a form on or off in Setup → Public forms.',
+ 'engine.studio.publicForms.newTitle': 'New public form',
+ 'engine.studio.publicForms.newHint': 'The form starts with the fields this object requires. Add more, group them and save a draft; it takes submissions once published.',
+ 'engine.studio.publicForms.create': 'Create',
+ 'engine.studio.publicForms.cancel': 'Cancel',
+ 'engine.studio.publicForms.pick': 'Pick a public form on the left, or create one.',
+ 'engine.studio.publicForms.unreadable': '“{name}” could not be read.',
+ 'engine.studio.publicForms.readOnly': 'This app is installed and cannot be changed here.',
+ 'engine.studio.publicForms.noVersion': 'The installed app states no version, so a change to its form cannot be saved.',
+ 'engine.studio.publicForms.dismiss': 'Dismiss',
+ 'engine.studio.publicForms.missingRequired': 'This form is missing fields the object requires: {fields}. Add them before saving.',
+ 'engine.studio.publicForms.title': 'Title',
+ 'engine.studio.publicForms.description': 'Description',
+ 'engine.studio.publicForms.address': 'Address',
+ 'engine.studio.publicForms.addressEmpty': 'Enter an address.',
+ 'engine.studio.publicForms.addressShape': 'Use 2 to 64 lowercase letters, digits and hyphens, such as contact-us.',
+ 'engine.studio.publicForms.addressTaken': 'Another form already uses this address. Choose a different one.',
+ 'engine.studio.publicForms.addressTakenBy': 'The form “{form}” already uses this address. Choose a different one.',
+ 'engine.studio.publicForms.fields': 'Fields',
+ 'engine.studio.publicForms.addSection': 'Add section',
+ 'engine.studio.publicForms.newSection': 'New section',
+ 'engine.studio.publicForms.sectionUnnamed': 'Untitled section',
+ 'engine.studio.publicForms.sectionName': 'Section name',
+ 'engine.studio.publicForms.moveUp': 'Move up',
+ 'engine.studio.publicForms.moveDown': 'Move down',
+ 'engine.studio.publicForms.removeSection': 'Remove section',
+ 'engine.studio.publicForms.removeSectionHint': 'Its fields move to the section next to it.',
+ 'engine.studio.publicForms.required': 'Required',
+ 'engine.studio.publicForms.requiredLockedHint': 'The object requires this field, so every form must keep it and it is always required.',
+ 'engine.studio.publicForms.removeField': 'Remove field',
+ 'engine.studio.publicForms.requiredByObject': '“{field}” cannot be removed: the object requires it, so a submission without it could not be saved.',
+ 'engine.studio.publicForms.sectionEmpty': 'No fields in this section yet. Drag one here, or add one below.',
+ 'engine.studio.publicForms.addField': 'Add field…',
+ 'engine.studio.publicForms.afterSubmit': 'After submitting',
+ 'engine.studio.publicForms.thankYouTitle': 'Heading',
+ 'engine.studio.publicForms.thankYouMessage': 'Message',
+ 'engine.studio.publicForms.deleteShipped': 'This form comes with the installed app and cannot be deleted. To stop it taking submissions, switch it off in Setup → Public forms.',
+ 'engine.studio.publicForms.deleteConfirm': 'Delete “{name}”? Its address will stop working. Records already submitted are kept.',
+ 'engine.studio.publicForms.delete': 'Delete form',
+ 'engine.studio.publicForms.deleted': 'Deleted “{name}”.',
+ 'engine.studio.publicForms.draftChip': 'Draft saved',
+ 'engine.studio.publicForms.discard': 'Discard',
+ 'engine.studio.publicForms.saveDraft': 'Save draft',
+ 'engine.studio.publicForms.publish': 'Publish',
+ 'engine.studio.publicForms.publishNeedsSave': 'Save the draft first.',
+ 'engine.studio.publicForms.saved': 'Draft saved: “{name}”.',
+ 'engine.studio.publicForms.published': 'Published “{name}”.',
+ 'engine.studio.publicForms.draftConflict': 'Someone else has a draft of this form pending. Reopen the form to see it.',
+ 'engine.studio.publicForms.preview': 'Preview',
'engine.studio.data.addField': 'Add field',
'engine.studio.data.addFieldCreate': 'Create',
'engine.studio.data.addFieldNeedsLabel': 'Type a label first.',
diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts
index 4a0d4c9e42e..d0e18f6a3c3 100644
--- a/ui/packages/i18n/src/namespaces/studio/zh.ts
+++ b/ui/packages/i18n/src/namespaces/studio/zh.ts
@@ -2363,6 +2363,68 @@ const STUDIO_ZH: Record = {
'engine.studio.data.tab.hooks': '钩子',
'engine.studio.data.tab.actions': '操作',
'engine.studio.data.tab.api': 'API',
+ // objectstack#36444 — the object's public forms (Form tab → Public forms).
+ 'engine.studio.data.form.surfaceLabel': '编辑哪个表单',
+ 'engine.studio.data.form.surfaceRecord': '记录表单',
+ 'engine.studio.data.form.surfacePublic': '对外表单',
+ 'engine.studio.publicForms.listTitle': '对外表单',
+ 'engine.studio.publicForms.new': '新建',
+ 'engine.studio.publicForms.loading': '加载中…',
+ 'engine.studio.publicForms.none': '还没有对外表单。对外表单无需登录即可填写,每次提交都会生成一条记录。',
+ 'engine.studio.publicForms.stateDraft': '草稿',
+ 'engine.studio.publicForms.stateOn': '已开启',
+ 'engine.studio.publicForms.stateOff': '已关闭',
+ 'engine.studio.publicForms.stateShippedOff': '已关闭(应用自带关闭)',
+ 'engine.studio.publicForms.stateUnknown': '未知',
+ 'engine.studio.publicForms.switchInSetup': '在 设置 › 对外表单 中开启或关闭表单。',
+ 'engine.studio.publicForms.newTitle': '新建对外表单',
+ 'engine.studio.publicForms.newHint': '新表单会先放入本对象的必填字段。可继续添加字段、分组并保存草稿;发布后即可接收提交。',
+ 'engine.studio.publicForms.create': '创建',
+ 'engine.studio.publicForms.cancel': '取消',
+ 'engine.studio.publicForms.pick': '请在左侧选择一个对外表单,或新建一个。',
+ 'engine.studio.publicForms.unreadable': '无法读取「{name}」。',
+ 'engine.studio.publicForms.readOnly': '此应用为已安装应用,无法在此修改。',
+ 'engine.studio.publicForms.noVersion': '已安装应用未声明版本,无法保存对其表单的修改。',
+ 'engine.studio.publicForms.dismiss': '关闭',
+ 'engine.studio.publicForms.missingRequired': '此表单缺少对象的必填字段:{fields}。请先添加再保存。',
+ 'engine.studio.publicForms.title': '标题',
+ 'engine.studio.publicForms.description': '说明',
+ 'engine.studio.publicForms.address': '地址',
+ 'engine.studio.publicForms.addressEmpty': '请填写地址。',
+ 'engine.studio.publicForms.addressShape': '请使用 2 到 64 个小写字母、数字或连字符,例如 contact-us。',
+ 'engine.studio.publicForms.addressTaken': '已有其他表单使用此地址,请换一个。',
+ 'engine.studio.publicForms.addressTakenBy': '表单「{form}」已使用此地址,请换一个。',
+ 'engine.studio.publicForms.fields': '字段',
+ 'engine.studio.publicForms.addSection': '添加分组',
+ 'engine.studio.publicForms.newSection': '新分组',
+ 'engine.studio.publicForms.sectionUnnamed': '未命名分组',
+ 'engine.studio.publicForms.sectionName': '分组名称',
+ 'engine.studio.publicForms.moveUp': '上移',
+ 'engine.studio.publicForms.moveDown': '下移',
+ 'engine.studio.publicForms.removeSection': '移除分组',
+ 'engine.studio.publicForms.removeSectionHint': '分组内的字段会移到相邻分组。',
+ 'engine.studio.publicForms.required': '必填',
+ 'engine.studio.publicForms.requiredLockedHint': '对象要求此字段必填,因此所有表单都必须保留它,并且始终必填。',
+ 'engine.studio.publicForms.removeField': '移除字段',
+ 'engine.studio.publicForms.requiredByObject': '无法移除「{field}」:对象要求此字段必填,缺少它的提交将无法保存。',
+ 'engine.studio.publicForms.sectionEmpty': '此分组还没有字段。可拖入字段,或在下方添加。',
+ 'engine.studio.publicForms.addField': '添加字段…',
+ 'engine.studio.publicForms.afterSubmit': '提交之后',
+ 'engine.studio.publicForms.thankYouTitle': '标题',
+ 'engine.studio.publicForms.thankYouMessage': '提示内容',
+ 'engine.studio.publicForms.deleteShipped': '此表单随已安装应用提供,无法删除。如需停止接收提交,请在 设置 › 对外表单 中关闭它。',
+ 'engine.studio.publicForms.deleteConfirm': '删除「{name}」?其地址将无法再打开,已提交的记录会保留。',
+ 'engine.studio.publicForms.delete': '删除表单',
+ 'engine.studio.publicForms.deleted': '已删除「{name}」。',
+ 'engine.studio.publicForms.draftChip': '草稿已保存',
+ 'engine.studio.publicForms.discard': '放弃修改',
+ 'engine.studio.publicForms.saveDraft': '保存草稿',
+ 'engine.studio.publicForms.publish': '发布',
+ 'engine.studio.publicForms.publishNeedsSave': '请先保存草稿。',
+ 'engine.studio.publicForms.saved': '已保存草稿:「{name}」。',
+ 'engine.studio.publicForms.published': '已发布「{name}」。',
+ 'engine.studio.publicForms.draftConflict': '此表单有他人尚未发布的草稿。请重新打开表单查看。',
+ 'engine.studio.publicForms.preview': '预览',
'engine.studio.data.addField': '添加字段',
'engine.studio.data.addFieldCreate': '创建',
'engine.studio.data.addFieldNeedsLabel': '请先填写显示名。',