Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

style(forms): unify builder and respondent layouts (#7751)

teo500858ab5a81
diff --git a/apps/web/src/components/DocumentOutline.tsx b/apps/web/src/components/DocumentOutline.tsx
new file mode 100644
index 0000000000..5d66fbda8d
--- /dev/null
+++ b/apps/web/src/components/DocumentOutline.tsx
@@ -0,0 +1,106 @@
+import { HoverCard } from '@core/component/HoverCard';
+import { Key } from '@solid-primitives/keyed';
+import { createSignal, Show } from 'solid-js';
+
+export type DocumentOutlineItem = {
+ key: string;
+ text: string;
+ preview: string;
+};
+
+/** The compact outline rail shared by documents and form builders. */
+export function DocumentOutline(props: {
+ label: string;
+ items: DocumentOutlineItem[];
+ activeKeys: ReadonlySet<string>;
+ viewportHeight: number;
+ portalMount: HTMLElement;
+ onSelect: (key: string) => void;
+}) {
+ const [hoveredIndex, setHoveredIndex] = createSignal<number>();
+ return (
+ <nav
+ aria-label={props.label}
+ class="pointer-events-auto sticky z-1 w-7 -translate-y-1/2"
+ style={{ top: `${props.viewportHeight / 2}px` }}
+ >
+ <div
+ class="flex w-7 flex-col items-start overflow-y-auto py-1"
+ style={{
+ 'max-height': `${Math.max(0, props.viewportHeight - 32)}px`,
+ }}
+ >
+ <Key each={props.items} by="key">
+ {(heading, index) => {
+ const active = () => props.activeKeys.has(heading().key);
+ const distance = () =>
+ Math.abs(index() - (hoveredIndex() ?? Number.POSITIVE_INFINITY));
+ const width = () => [26, 20, 14, 10][distance()] ?? 6;
+ const emphasized = () =>
+ hoveredIndex() === undefined ? active() : distance() === 0;
+
+ return (
+ <HoverCard
+ closeDelay={80}
+ closeOnScroll={false}
+ keepOpenOnTriggerPress
+ openDelay={0}
+ open={hoveredIndex() === index()}
+ onOpenChange={(open) => {
+ setHoveredIndex((current) =>
+ open ? index() : current === index() ? undefined : current
+ );
+ }}
+ content={
+ <div class="w-80 max-w-[calc(100vw-3rem)] rounded-xl border border-edge bg-surface px-3 py-2 shadow-menu">
+ <div class="truncate text-sm font-medium text-ink">
+ {heading().text}
+ </div>
+ <Show when={heading().preview}>
+ <p class="mt-1 line-clamp-3 text-sm leading-relaxed text-ink-muted">
+ {heading().preview}
+ </p>
+ </Show>
+ </div>
+ }
+ contentZIndexClass="z-item-options-menu"
+ gutter={10}
+ // Previews must not intercept clicks on controls beside the rail.
+ passThroughPointerEvents
+ placement="right"
+ portalMount={props.portalMount}
+ trigger={
+ <button
+ type="button"
+ aria-label={heading().text}
+ aria-current={active() ? 'location' : undefined}
+ class="flex h-2.5 w-7 items-center outline-none focus-visible:rounded-sm focus-visible:ring-1 focus-visible:ring-ink"
+ onFocus={() => setHoveredIndex(index())}
+ onBlur={() =>
+ setHoveredIndex((current) =>
+ current === index() ? undefined : current
+ )
+ }
+ onClick={() => props.onSelect(heading().key)}
+ >
+ <span
+ aria-hidden="true"
+ class="h-0.5 shrink-0 transition-[width,background-color] duration-150 ease-out motion-reduce:transition-none"
+ classList={{
+ 'bg-ink': emphasized(),
+ 'bg-ink/20': !emphasized(),
+ }}
+ style={{ width: `${width()}px` }}
+ />
+ </button>
+ }
+ triggerClass="block w-7"
+ triggerTabIndex={-1}
+ />
+ );
+ }}
+ </Key>
+ </div>
+ </nav>
+ );
+}
diff --git a/apps/web/src/features/block-form/components/builder/builder-chrome.test.tsx b/apps/web/src/features/block-form/components/builder/builder-chrome.test.tsx
index 757aa261f0..1f30dc6ded 100644
--- a/apps/web/src/features/block-form/components/builder/builder-chrome.test.tsx
+++ b/apps/web/src/features/block-form/components/builder/builder-chrome.test.tsx
@@ -34,7 +34,6 @@ function mount() {
<TitleCard
name={name()}
description={description()}
- meta={null}
databaseLink={null}
onName={names.save}
onDescription={descriptions.save}
@@ -64,7 +63,6 @@ describe('TitleCard', () => {
<TitleCard
name={name()}
description={description()}
- meta={null}
databaseLink={null}
onName={(value) => {
sentNames.push(value);
@@ -142,7 +140,6 @@ describe('TitleCard', () => {
<TitleCard
name="Workshop ideas"
description="Saved words"
- meta={null}
databaseLink={null}
onName={async () => true}
onDescription={() => failure}
diff --git a/apps/web/src/features/block-form/components/builder/builder-chrome.tsx b/apps/web/src/features/block-form/components/builder/builder-chrome.tsx
index 593f55c8b8..64ac5b440f 100644
--- a/apps/web/src/features/block-form/components/builder/builder-chrome.tsx
+++ b/apps/web/src/features/block-form/components/builder/builder-chrome.tsx
@@ -1,18 +1,9 @@
-import CalendarCheck from '@phosphor/calendar-check.svg';
import CaretDown from '@phosphor/caret-down.svg';
import Database from '@phosphor/database.svg';
import Plus from '@phosphor/plus.svg';
-import ShieldCheck from '@phosphor/shield-check.svg';
-import { Key } from '@solid-primitives/keyed';
import { Button, cn } from '@ui';
-import { createSignal, For, type JSX, Match, Show, Switch } from 'solid-js';
-import type { SectionKind } from '../../core/form-model';
-import {
- QUESTION_TYPE_CHOICES,
- QUESTION_TYPE_GROUPS,
- type QuestionTypeChoice,
- type QuestionTypeId,
-} from '../../core/question-types';
+import { createSignal, For, type JSX, Show } from 'solid-js';
+import type { QuestionTypeId } from '../../core/question-types';
import { QuestionTypeIcon } from '../question-type-icon';
import { DraftInput, DraftTextarea } from './draft-input';
@@ -27,46 +18,16 @@ export function BuilderSkeleton() {
>
<div
aria-hidden="true"
- class="mx-auto grid w-full max-w-[1320px] grid-cols-1 items-start justify-center gap-5 p-4 @3xl/builder:grid-cols-[minmax(0,680px)_272px] @5xl/builder:grid-cols-[272px_minmax(0,680px)_272px] @5xl/builder:py-6"
+ class="mx-auto flex w-full max-w-3xl flex-col gap-6 pt-12 px-6"
>
- <div class="mx-auto flex h-38 w-full max-w-[680px] flex-col gap-4 rounded-xl border border-edge-muted bg-surface p-6 @3xl/builder:col-span-full @3xl/builder:max-w-none">
- <div class="h-7 w-2/5 rounded bg-hover motion-safe:animate-pulse" />
- <div class="h-4 w-3/5 rounded bg-hover motion-safe:animate-pulse" />
- <div class="mt-auto h-3 w-1/4 rounded bg-hover motion-safe:animate-pulse" />
- </div>
- <div class="hidden flex-col gap-5 px-1 py-2 @5xl/builder:flex">
- <div class="h-3 w-16 rounded bg-hover motion-safe:animate-pulse" />
- <For each={[0, 1, 2]}>
- {() => (
- <div class="flex flex-col gap-3">
- <div class="h-4 w-3/5 rounded bg-hover motion-safe:animate-pulse" />
- <div class="ml-3 h-3 w-3/4 rounded bg-hover motion-safe:animate-pulse" />
- </div>
- )}
- </For>
- </div>
- <div class="mx-auto flex w-full max-w-[680px] flex-col gap-4">
- <For each={[0, 1]}>
- {() => (
- <div class="flex h-56 flex-col gap-5 rounded-xl border border-edge-muted bg-surface p-5">
- <div class="h-3 w-1/4 rounded bg-hover motion-safe:animate-pulse" />
- <div class="h-5 w-2/5 rounded bg-hover motion-safe:animate-pulse" />
- <div class="mt-4 h-4 w-1/2 rounded bg-hover motion-safe:animate-pulse" />
- <div class="h-9 w-full rounded bg-hover motion-safe:animate-pulse" />
- </div>
- )}
- </For>
- </div>
- <div class="hidden flex-col gap-3 rounded-xl border border-edge-muted bg-surface p-2 @3xl/builder:flex">
- <div class="h-4 w-24 rounded bg-hover motion-safe:animate-pulse" />
- <div class="grid grid-cols-2 gap-0.5">
- <For each={[0, 1, 2, 3, 4, 5, 6, 7]}>
- {() => (
- <div class="h-8 rounded-md bg-hover motion-safe:animate-pulse" />
- )}
- </For>
- </div>
- </div>
+ <div class="h-8 w-2/5 rounded bg-hover motion-safe:animate-pulse" />
+ <div class="h-5 w-1/4 rounded bg-hover motion-safe:animate-pulse" />
+ <div class="h-5 w-3/5 rounded bg-hover motion-safe:animate-pulse" />
+ <For each={[0, 1]}>
+ {() => (
+ <div class="h-56 rounded-xl border border-edge-muted bg-surface motion-safe:animate-pulse" />
+ )}
+ </For>
</div>
</div>
);
@@ -104,50 +65,39 @@ export function DropIndicator(props: { top: number; refusal?: string }) {
}
/**
- * The form's own card: its name, description and where its answers go. Both
+ * The form's document-style heading: its name, description and where its answers go. Both
* fields keep what is being typed while the form is read again underneath.
*/
export function TitleCard(props: {
name: string;
description: string;
- meta: JSX.Element;
databaseLink: JSX.Element;
/** Each resolves whether it saved; a refused one stays in its field. */
onName: (name: string) => PromiseLike<boolean>;
onDescription: (description: string) => PromiseLike<boolean>;
}) {
return (
- <section
- aria-label="Form details"
- class="flex flex-col gap-4 rounded-xl border border-edge bg-surface p-4 shadow-xs @2xl/builder:flex-row @2xl/builder:items-start"
- >
- <div class="flex min-w-0 flex-1 flex-col gap-1">
+ <section aria-label="Form details" class="flex min-w-0 flex-col">
+ <div class="flex min-w-0 flex-col">
<DraftInput
aria-label="Form name"
value={props.name}
maxlength={200}
- class="h-10 w-full rounded-md border border-transparent bg-transparent px-1.5 text-2xl font-semibold text-ink outline-none hover:border-edge-muted focus:border-edge-focus focus:bg-input aria-invalid:border-failure"
+ class="h-8 w-full border-0 bg-transparent p-0 text-2xl font-semibold text-ink outline-none aria-invalid:text-failure"
onCommit={props.onName}
/>
+ <div class="mt-3 mb-6 flex flex-wrap items-center gap-2 text-sm">
+ {props.databaseLink}
+ </div>
<DraftTextarea
aria-label="Form description"
- placeholder="Form description"
+ placeholder="Tell people what this form is for…"
value={props.description}
maxlength={4000}
- rows={2}
- class="w-full resize-none rounded-md border border-transparent bg-transparent px-1.5 py-1 text-sm text-ink-muted outline-none placeholder:text-ink-placeholder hover:border-edge-muted focus:border-edge-focus focus:bg-input aria-invalid:border-failure"
+ rows={1}
+ class="w-full resize-none border-0 bg-transparent p-0 text-base leading-relaxed text-ink outline-none placeholder:text-ink-placeholder field-sizing-content aria-invalid:text-failure"
onCommit={props.onDescription}
/>
- {/* Each item's separator sits in its left gutter; the list's negative
- margin clips the gutter of whichever item starts a line. */}
- <div class="overflow-hidden px-1.5 pt-1">
- <ul class="-ml-4 flex flex-wrap items-center gap-y-1 text-xs text-ink-muted [&>li]:relative [&>li]:pl-4 [&>li]:before:absolute [&>li]:before:left-1.5 [&>li]:before:content-['·']">
- {props.meta}
- </ul>
- </div>
- </div>
- <div class="min-w-0 shrink-0 @2xl/builder:max-w-64">
- {props.databaseLink}
</div>
</section>
);
@@ -215,146 +165,6 @@ export function HiddenColumns(props: {
);
}
-/** Section and question navigation to the left of the canvas. */
-export function BuilderSidebar(props: { outline: JSX.Element }) {
- return (
- <nav
- aria-label="Form outline"
- class="hidden min-w-0 flex-col gap-2 rounded-xl border border-edge-muted bg-surface p-2.5 text-sm @5xl/builder:sticky @5xl/builder:top-4 @5xl/builder:flex @5xl/builder:max-h-[calc(100dvh-8rem)] @5xl/builder:overflow-y-auto"
- >
- <h3 class="px-1.5 py-1 text-sm font-semibold text-ink">Outline</h3>
- {props.outline}
- </nav>
- );
-}
-
-/** Visible type choices are both buttons and drag sources, supplied by the view. */
-export function BuilderPalette(props: {
- question: (choice: QuestionTypeChoice) => JSX.Element;
- structure: JSX.Element;
- database: JSX.Element;
-}) {
- return (
- <aside
- aria-label="Add to form"
- class="mx-auto hidden w-full max-w-[680px] min-w-0 flex-col rounded-xl border border-edge-muted bg-surface @3xl/builder:sticky @3xl/builder:top-4 @3xl/builder:flex @3xl/builder:max-h-[calc(100dvh-8rem)] @3xl/builder:overflow-y-auto"
- >
- <div class="border-b border-edge-divider px-3.5 py-2.5">
- <h3 class="text-sm font-semibold text-ink">Add question</h3>
- </div>
- <div class="flex flex-col gap-2 p-2.5">
- <For each={QUESTION_TYPE_GROUPS}>
- {(group) => (
- <div
- role="group"
- aria-label={group.label}
- class="border-t border-edge-divider pt-2 first:border-t-0 first:pt-0"
- >
- <h4 class="mb-1 px-1 text-[11px] font-medium text-ink-muted">
- {group.label}
- </h4>
- <div class="grid grid-cols-2 gap-0.5">
- <For
- each={QUESTION_TYPE_CHOICES.filter(
- (choice) => choice.group === group.id
- )}
- >
- {props.question}
- </For>
- </div>
- </div>
- )}
- </For>
- {props.database}
- </div>
- <div class="border-t border-edge-divider p-2.5">
- <h3 class="mb-1 px-1 text-xs font-semibold text-ink">Form flow</h3>
- {props.structure}
- </div>
- </aside>
- );
-}
-
-/** One line of the outline: a section, gate or booking step with its questions. */
-export function OutlineSection(props: {
- name: string;
- kind: SectionKind;
- number: number;
- selected: boolean;
- questions: readonly { id: string; title: string; selected: boolean }[];
- onSelectSection: () => void;
- onSelectQuestion: (questionId: string) => void;
-}) {
- return (
- <li class="flex flex-col gap-0.5">
- <Button
- variant="ghost"
- size="md"
- fullWidth
- tooltip={props.name}
- aria-current={props.selected ? 'true' : undefined}
- class={cn(
- 'justify-start gap-2 rounded-md px-1.5 text-xs text-ink',
- props.selected && 'bg-active'
- )}
- onClick={props.onSelectSection}
- >
- <Switch>
- <Match when={props.kind === 'questions'}>
- <span
- aria-hidden="true"
- class="flex size-5 shrink-0 items-center justify-center rounded border border-edge-muted text-[11px] text-ink-muted"
- >
- {props.number}
- </span>
- </Match>
- <Match when={props.kind === 'gate'}>
- <ShieldCheck class="size-3.5 text-amber-ink" aria-hidden="true" />
- </Match>
- <Match when={props.kind === 'booking'}>
- <CalendarCheck class="size-3.5 text-ink-muted" aria-hidden="true" />
- </Match>
- </Switch>
- <span class="min-w-0 flex-1 truncate text-left">{props.name}</span>
- <Show when={props.questions.length > 0}>
- <span
- aria-hidden="true"
- class="text-[11px] font-normal text-ink-muted"
- >
- {props.questions.length}
- </span>
- </Show>
- </Button>
- <Show when={props.questions.length > 0}>
- <ul class="ml-4 flex flex-col border-l border-edge-divider pl-2">
- <Key each={props.questions} by="id">
- {(question) => (
- <li>
- <Button
- variant="ghost"
- size="sm"
- fullWidth
- tooltip={question().title}
- aria-current={question().selected ? 'true' : undefined}
- class={cn(
- 'h-7 justify-start rounded-md px-1.5 text-left text-xs font-normal',
- question().selected
- ? 'bg-active text-ink'
- : 'text-ink-muted hover:bg-hover hover:text-ink'
- )}
- onClick={() => props.onSelectQuestion(question().id)}
- >
- <span class="truncate">{question().title}</span>
- </Button>
- </li>
- )}
- </Key>
- </ul>
- </Show>
- </li>
- );
-}
-
/** A type change the column refused: what does not fit, and the conversion. */
export function ConversionNotice(props: {
message: string;
diff --git a/apps/web/src/features/block-form/components/builder/insertion-point.tsx b/apps/web/src/features/block-form/components/builder/insertion-point.tsx
new file mode 100644
index 0000000000..f27386d902
--- /dev/null
+++ b/apps/web/src/features/block-form/components/builder/insertion-point.tsx
@@ -0,0 +1,17 @@
+import type { JSX } from 'solid-js';
+
+/** An insertion affordance over a boundary, without moving the surrounding cards. */
+export function InsertionPoint(props: {
+ betweenSections?: boolean;
+ children: JSX.Element;
+}) {
+ return (
+ <div
+ class={`absolute inset-x-0 z-20 flex h-6 items-center justify-center gap-2 opacity-0 transition-opacity hover:opacity-100 focus-within:opacity-100 has-[[data-expanded]]:opacity-100 ${props.betweenSections ? '-top-8' : '-top-3'}`}
+ >
+ <span class="h-px flex-1 bg-accent" />
+ {props.children}
+ <span class="h-px flex-1 bg-accent" />
+ </div>
+ );
+}
diff --git a/apps/web/src/features/block-form/components/builder/question-row.tsx b/apps/web/src/features/block-form/components/builder/question-row.tsx
index 9b559c1a50..94fdec708a 100644
--- a/apps/web/src/features/block-form/components/builder/question-row.tsx
+++ b/apps/web/src/features/block-form/components/builder/question-row.tsx
@@ -38,7 +38,7 @@ export function QuestionRow(props: {
data-selected={props.selected ? '' : undefined}
class={cn(
'group/question relative flex gap-1 px-2 py-3 transition-[background-color,opacity] duration-100',
- props.selected ? 'bg-panel' : 'hover:bg-hover/50',
+ props.selected ? 'ring-1 ring-inset ring-accent!' : 'hover:bg-hover/50',
props.dragging && 'opacity-40'
)}
onFocusIn={(event) => {
@@ -55,12 +55,6 @@ export function QuestionRow(props: {
props.onSelect();
}}
>
- <Show when={props.selected}>
- <span
- aria-hidden="true"
- class="absolute inset-y-2 left-0 w-0.5 rounded-full bg-accent"
- />
- </Show>
<div
class={cn(
'pt-0.5 transition-opacity',
diff --git a/apps/web/src/features/block-form/components/builder/section-card.tsx b/apps/web/src/features/block-form/components/builder/section-card.tsx
index 30fd5478df..9450f73cc6 100644
--- a/apps/web/src/features/block-form/components/builder/section-card.tsx
+++ b/apps/web/src/features/block-form/components/builder/section-card.tsx
@@ -69,7 +69,7 @@ export function SectionCard(props: {
/** New questions go to this section's end. */
targeted: boolean;
onTarget: () => void;
- /** Adds a question into this section; shown while it is empty. */
+ /** Adds a question into this section; shown after its questions. */
addQuestion: JSX.Element;
handle: JSX.Element;
menu: JSX.Element;
@@ -134,19 +134,12 @@ export function SectionCard(props: {
</header>
<div
data-form-section-list={props.sectionId}
- class="flex min-h-16 flex-col divide-y divide-edge-divider"
+ class="flex flex-col divide-y divide-edge-divider"
>
- <Show
- when={!props.empty}
- fallback={
- <div class="flex min-h-16 flex-col items-center justify-center gap-2 px-4 py-3 text-xs text-ink-muted">
- <span>No questions yet. Add one, or drag a question here.</span>
- <div class="w-44">{props.addQuestion}</div>
- </div>
- }
- >
- {props.children}
- </Show>
+ <Show when={!props.empty}>{props.children}</Show>
+ </div>
+ <div classList={{ 'border-t border-edge-divider': !props.empty }}>
+ {props.addQuestion}
</div>
{props.routing}
</section>
@@ -183,7 +176,7 @@ export function GateCard(props: {
data-form-section={props.sectionId}
data-section-kind="gate"
class={cn(
- 'overflow-hidden rounded-xl border border-dashed border-edge bg-panel transition-opacity',
+ 'overflow-hidden rounded-xl border border-edge bg-surface shadow-xs transition-opacity',
props.dragging && 'opacity-40'
)}
>
diff --git a/apps/web/src/features/block-form/components/builder/type-menu.tsx b/apps/web/src/features/block-form/components/builder/type-menu.tsx
index 34d5e3c7f6..15cb17e786 100644
--- a/apps/web/src/features/block-form/components/builder/type-menu.tsx
+++ b/apps/web/src/features/block-form/components/builder/type-menu.tsx
@@ -119,6 +119,7 @@ export function TypeMenu(props: {
export function AddQuestionMenu(props: {
trigger: JSX.Element;
triggerRef?: (element: HTMLButtonElement) => void;
+ triggerClass?: string;
disabled?: boolean;
children?: JSX.Element;
tables: readonly RelationTable[];
@@ -133,12 +134,11 @@ export function AddQuestionMenu(props: {
<Dropdown.Trigger
variant="outline"
size="md"
- class="w-full justify-start gap-2"
+ class={`w-full justify-start gap-2 ${props.triggerClass ?? ''}`}
ref={props.triggerRef}
disabled={props.disabled}
>
{props.trigger}
- <CaretDown class="ml-auto size-3.5" aria-hidden="true" />
</Dropdown.Trigger>
<Dropdown.Content
class="max-h-[min(32rem,75vh)] w-64 overflow-y-auto"
diff --git a/apps/web/src/features/block-form/components/form-tabs.tsx b/apps/web/src/features/block-form/components/form-tabs.tsx
index 587f9ba7a8..57f83d3970 100644
--- a/apps/web/src/features/block-form/components/form-tabs.tsx
+++ b/apps/web/src/features/block-form/components/form-tabs.tsx
@@ -1,74 +1,52 @@
-import { cn } from '@ui';
-import { For, type JSX } from 'solid-js';
+import { Tabs } from '@kobalte/core/tabs';
+import { TabSelector } from '@ui';
+import { For } from 'solid-js';
export type FormTab = 'build' | 'responses' | 'share';
const TABS: { value: FormTab; label: string }[] = [
{ value: 'build', label: 'Build' },
{ value: 'responses', label: 'Responses' },
- { value: 'share', label: 'Share' },
+ { value: 'share', label: 'Settings' },
];
-/** Build, Responses, Share, with the form's status at the right. */
export function FormTabs(props: {
tab: FormTab;
/** Ties each tab to its panel; unique per mounted form page. */
idPrefix: string;
- status: JSX.Element;
responsesCount: number | undefined;
onChange: (tab: FormTab) => void;
}) {
- const select = (
- event: KeyboardEvent & { currentTarget: HTMLButtonElement },
- index: number
- ) => {
- const next =
- event.key === 'ArrowRight'
- ? (index + 1) % TABS.length
- : event.key === 'ArrowLeft'
- ? (index - 1 + TABS.length) % TABS.length
- : undefined;
- if (next === undefined) return;
- event.preventDefault();
- props.onChange(TABS[next].value);
- const list = event.currentTarget.parentElement;
- list?.querySelectorAll<HTMLElement>('[role="tab"]')[next]?.focus();
- };
return (
- <div class="flex items-center gap-3 border-b border-edge-divider bg-surface px-3">
- <div role="tablist" aria-label="Form" class="flex items-end gap-1">
- <For each={TABS}>
- {(tab, index) => (
- <button
- type="button"
- role="tab"
- id={`${props.idPrefix}-tab-${tab.value}`}
- aria-selected={props.tab === tab.value}
- aria-controls={`${props.idPrefix}-panel-${tab.value}`}
- tabIndex={props.tab === tab.value ? 0 : -1}
- class={cn(
- '-mb-px flex h-10 items-center gap-1.5 border-b-2 px-2.5 text-sm outline-none focus-visible:ring-2 focus-visible:ring-edge-focus focus-visible:ring-inset',
- props.tab === tab.value
- ? 'border-accent font-medium text-ink'
- : 'border-transparent text-ink-muted hover:text-ink'
- )}
- onClick={() => props.onChange(tab.value)}
- onKeyDown={(event) => select(event, index())}
- >
- {tab.label}
- {tab.value === 'responses' &&
- props.responsesCount !== undefined ? (
- <span class="rounded-full bg-active px-1.5 text-[11px] text-ink-muted tabular-nums">
- {props.responsesCount}
- </span>
- ) : null}
- </button>
- )}
- </For>
- </div>
- <div class="ml-auto min-w-0 truncate text-xs text-ink-muted">
- {props.status}
- </div>
- </div>
+ <TabSelector>
+ <Tabs
+ value={props.tab}
+ onChange={(value) => {
+ const tab = TABS.find((tab) => tab.value === value);
+ if (tab) props.onChange(tab.value);
+ }}
+ class="min-w-0"
+ >
+ <TabSelector.List aria-label="Form">
+ <For each={TABS}>
+ {(tab) => (
+ <TabSelector.Tab
+ value={tab.value}
+ id={`${props.idPrefix}-tab-${tab.value}`}
+ aria-controls={`${props.idPrefix}-panel-${tab.value}`}
+ >
+ {tab.label}
+ {tab.value === 'responses' &&
+ props.responsesCount !== undefined ? (
+ <span class="rounded-full bg-active px-1.5 text-[11px] text-ink-muted tabular-nums">
+ {props.responsesCount}
+ </span>
+ ) : null}
+ </TabSelector.Tab>
+ )}
+ </For>
+ </TabSelector.List>
+ </Tabs>
+ </TabSelector>
);
}
diff --git a/apps/web/src/features/block-form/components/respond/question-field.tsx b/apps/web/src/features/block-form/components/respond/question-field.tsx
index ad03ea293e..111a366ddb 100644
--- a/apps/web/src/features/block-form/components/respond/question-field.tsx
+++ b/apps/web/src/features/block-form/components/respond/question-field.tsx
@@ -286,9 +286,13 @@ export function QuestionField(props: {
return (
<div
class={cn(
- 'flex flex-col gap-2 rounded-xl border bg-surface',
- props.compact ? 'px-3 py-3' : 'px-4 py-4 sm:px-5',
- invalid() ? 'border-failure' : 'border-edge'
+ 'flex flex-col gap-2',
+ props.compact
+ ? 'rounded-xl border bg-surface px-3 py-3'
+ : 'py-3 pr-2 pl-4',
+ invalid()
+ ? 'border-failure ring-1 ring-inset ring-failure'
+ : 'border-edge'
)}
data-question-field={props.question.id}
>
@@ -296,7 +300,10 @@ export function QuestionField(props: {
<label
id={`${id()}-label`}
for={kind().type === 'boolean' ? `${id()}-input` : id()}
- class="text-sm font-medium text-ink wrap-anywhere"
+ class={cn(
+ 'text-sm font-medium text-ink wrap-anywhere',
+ !props.compact && 'pt-1'
+ )}
>
{props.column.name}
<Show when={props.question.required}>
diff --git a/apps/web/src/features/block-form/components/respond/respond-screens.tsx b/apps/web/src/features/block-form/components/respond/respond-screens.tsx
index 5e1c9f5663..763d30070f 100644
--- a/apps/web/src/features/block-form/components/respond/respond-screens.tsx
+++ b/apps/web/src/features/block-form/components/respond/respond-screens.tsx
@@ -47,8 +47,14 @@ export function RespondTitleCard(props: {
compact: boolean;
}) {
return (
- <div class="overflow-hidden rounded-xl border border-edge bg-surface">
- <div class={cn('flex flex-col gap-1.5', props.compact ? 'p-3' : 'p-5')}>
+ <div
+ class={
+ props.compact
+ ? 'overflow-hidden rounded-xl border border-edge bg-surface'
+ : undefined
+ }
+ >
+ <div class={cn('flex flex-col', props.compact ? 'gap-1.5 p-3' : 'gap-6')}>
<h1
class={cn(
'font-semibold text-ink wrap-anywhere',
@@ -58,7 +64,12 @@ export function RespondTitleCard(props: {
{props.name}
</h1>
<Show when={props.description}>
- <p class="text-sm whitespace-pre-wrap text-ink-muted wrap-anywhere">
+ <p
+ class={cn(
+ 'whitespace-pre-wrap text-ink-muted wrap-anywhere',
+ props.compact ? 'text-sm' : 'text-base leading-relaxed'
+ )}
+ >
{props.description}
</p>
</Show>
diff --git a/apps/web/src/features/block-form/form-block.tsx b/apps/web/src/features/block-form/form-block.tsx
index cd638ef518..4cdbb7ad82 100644
--- a/apps/web/src/features/block-form/form-block.tsx
+++ b/apps/web/src/features/block-form/form-block.tsx
@@ -7,6 +7,7 @@
*/
import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { HeaderActionButton } from '@components/app/HeaderActionButton';
import { ResponsivePermissionsBadge } from '@components/app/ResponsiveBlockToolbar';
import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';
import {
@@ -45,9 +46,17 @@ import { createFormShareInput } from './form-global-sharing';
import { reservePreviewTab } from './form-preview-tab';
import { createPreview } from './primitives/create-preview';
import { FormCardView } from './views/form-card-view';
-import { FormPageView } from './views/form-page-view';
+import { type FormHeaderProps, FormPageView } from './views/form-page-view';
import { RespondView } from './views/respond-view';
+function FormHeader(props: FormHeaderProps) {
+ return (
+ <SplitHeaderLeft>
+ <div class="ml-2 min-w-0 max-w-xl shrink">{props.tabs}</div>
+ </SplitHeaderLeft>
+ );
+}
+
function FormBlockContent(props: {
respondOnly: boolean;
initialTab: FormTab | undefined;
@@ -124,10 +133,11 @@ function FormBlockContent(props: {
<Show
when={published()}
fallback={
- <Button variant="cta" size="sm" onClick={openShare}>
- <PaperPlaneTilt class="size-3.5" />
- Publish
- </Button>
+ <HeaderActionButton
+ label="Publish"
+ icon={<PaperPlaneTilt />}
+ onClick={openShare}
+ />
}
>
<Button variant="outline" size="sm" onClick={openRespond}>
@@ -186,6 +196,7 @@ function FormBlockContent(props: {
when={props.respondOnly}
fallback={
<FormPageView
+ header={FormHeader}
source={source}
tab={tab()}
respondLink={link()}
diff --git a/apps/web/src/features/block-form/form-respond-page.tsx b/apps/web/src/features/block-form/form-respond-page.tsx
index 174fcfff1a..be28823a8b 100644
--- a/apps/web/src/features/block-form/form-respond-page.tsx
+++ b/apps/web/src/features/block-form/form-respond-page.tsx
@@ -1,72 +1,23 @@
/**
* The respond route (RFC 02 §4): `/app/form/:id/respond`. One page, two
* shells: signed-in visitors see it inside the app shell (sidebar, command
- * menu) with their own header and can edit their response; anonymous
+ * menu) and can edit their response; anonymous
* visitors get the focused shell, so a public form never meets the login
* redirect (`routes/focused-shell.ts`). The form itself is the shared
* `RespondView`.
*/
import { settingsTabToSlug } from '@core/constant/settingsTabsConfig';
-import { useEmail, useUserId } from '@core/context/user';
-import ArrowSquareOut from '@phosphor/arrow-square-out.svg';
-import ClipboardText from '@phosphor/clipboard-text.svg';
+import { useUserId } from '@core/context/user';
import Eye from '@phosphor/eye.svg';
-import { A, useNavigate, useSearchParams } from '@solidjs/router';
-import { Button } from '@ui';
-import { Match, Show, Switch } from 'solid-js';
+import { useNavigate, useSearchParams } from '@solidjs/router';
+import { Button, Layer } from '@ui';
+import { Show } from 'solid-js';
import { FormProvider } from './context/form-context';
import { createAppFormContext } from './form-context-production';
import { SignInToRespond } from './sign-in-to-respond';
import { FormLoadFailureView, FormSkeleton } from './views/form-page-view';
import { RespondView } from './views/respond-view';
-function RespondHeader(props: {
- name: string;
- formId: string;
- isPublic: boolean;
-}) {
- const userId = useUserId();
- const email = useEmail();
- return (
- <Switch>
- <Match when={userId()}>
- <header class="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-ink-muted">
- <span class="font-semibold text-ink">Macro</span>
- <span aria-hidden="true">/</span>
- <span>Forms</span>
- <span aria-hidden="true">/</span>
- <span class="max-w-60 truncate text-ink">{props.name}</span>
- <span class="ml-auto">Responding as {email() ?? 'you'}</span>
- <A
- href={`/form/${encodeURIComponent(props.formId)}`}
- class="inline-flex items-center gap-1 text-link hover:underline"
- >
- Open in Macro
- <ArrowSquareOut class="size-3" aria-hidden="true" />
- </A>
- </header>
- </Match>
- <Match when={!userId()}>
- <header class="flex flex-col gap-2">
- <p class="flex items-center gap-1.5 text-xs text-ink-muted">
- <ClipboardText class="size-3.5 text-violet" aria-hidden="true" />
- Macro Forms
- <Show when={props.isPublic}>
- {' · Public form · you’re responding anonymously'}
- </Show>
- </p>
- <Show when={props.isPublic}>
- <p class="rounded-lg border border-edge-muted bg-panel px-3 py-2 text-xs text-ink-muted">
- Have a Macro account? <SignInToRespond>Sign in</SignInToRespond>{' '}
- to edit your answer later.
- </p>
- </Show>
- </header>
- </Match>
- </Switch>
- );
-}
-
function RespondFooter() {
return (
<footer class="mx-auto flex w-full max-w-[680px] flex-col gap-1 px-4 pb-8 text-center text-[11px] text-ink-muted">
@@ -85,6 +36,7 @@ function RespondFooter() {
function FormRespondContent(props: { formId: string }) {
const navigate = useNavigate();
+ const userId = useUserId();
const [searchParams] = useSearchParams();
const preview = () => searchParams.preview === 'true';
const context = createAppFormContext({
@@ -97,88 +49,92 @@ function FormRespondContent(props: { formId: string }) {
const source = context.createFormSource(() => props.formId);
return (
<FormProvider value={context}>
- <main class="h-full min-h-0 overflow-y-auto bg-canvas-base text-ink">
- <Show
- when={source.detail()}
- fallback={
- <Show when={source.failure()} fallback={<FormSkeleton />}>
- {(failure) => (
- <div class="mx-auto flex max-w-[680px] flex-col px-4 py-16">
- <FormLoadFailureView
- failure={failure()}
- onRetry={() => void source.refetch()}
- />
- <Show when={failure().kind === 'sign-in'}>
- <SignInToRespond class="mx-auto text-sm text-link hover:underline">
- Sign in
- </SignInToRespond>
- </Show>
- </div>
- )}
- </Show>
- }
- >
- {(detail) => (
- <Show
- when={!preview() || detail().access !== 'view'}
- fallback={
- <div class="mx-auto max-w-[680px] px-4 py-16">
- <FormLoadFailureView
- failure={{ kind: 'forbidden' }}
- onRetry={() => void source.refetch()}
- />
- </div>
- }
- >
- {/* A preview answers nothing for real: switching to or from it
- in this mounted route starts the form again. */}
+ <Layer depth={1}>
+ <main class="h-full min-h-0 overflow-y-auto bg-canvas-base text-ink">
+ <Show
+ when={source.detail()}
+ fallback={
+ <Show when={source.failure()} fallback={<FormSkeleton />}>
+ {(failure) => (
+ <div class="mx-auto flex max-w-[680px] flex-col px-4 py-16">
+ <FormLoadFailureView
+ failure={failure()}
+ onRetry={() => void source.refetch()}
+ />
+ <Show when={failure().kind === 'sign-in'}>
+ <SignInToRespond class="mx-auto text-sm text-link hover:underline">
+ Sign in
+ </SignInToRespond>
+ </Show>
+ </div>
+ )}
+ </Show>
+ }
+ >
+ {(detail) => (
<Show
- when={preview()}
+ when={!preview() || detail().access !== 'view'}
fallback={
+ <div class="mx-auto max-w-[680px] px-4 py-16">
+ <FormLoadFailureView
+ failure={{ kind: 'forbidden' }}
+ onRetry={() => void source.refetch()}
+ />
+ </div>
+ }
+ >
+ {/* A preview answers nothing for real: switching to or from it
+ in this mounted route starts the form again. */}
+ <Show
+ when={preview()}
+ fallback={
+ <RespondView
+ detail={detail()}
+ refetch={source.refetch}
+ compact={false}
+ />
+ }
+ >
<RespondView
detail={detail()}
refetch={source.refetch}
compact={false}
+ preview
header={
- <RespondHeader
- name={detail().form.name}
- formId={props.formId}
- isPublic={detail().form.audience === 'public'}
- />
+ <header class="flex flex-wrap items-center justify-between gap-2 text-sm text-ink-muted">
+ <span class="flex items-center gap-2">
+ <Eye class="size-4" />
+ Preview · responses won’t be saved
+ </span>
+ <Button
+ variant="outline"
+ onClick={() =>
+ navigate(
+ `/form/${encodeURIComponent(props.formId)}`
+ )
+ }
+ >
+ Back to builder
+ </Button>
+ </header>
}
/>
- }
- >
- <RespondView
- detail={detail()}
- refetch={source.refetch}
- compact={false}
- preview
- header={
- <header class="flex flex-wrap items-center justify-between gap-2 text-sm text-ink-muted">
- <span class="flex items-center gap-2">
- <Eye class="size-4" />
- Preview · responses won’t be saved
- </span>
- <Button
- variant="outline"
- onClick={() =>
- navigate(`/form/${encodeURIComponent(props.formId)}`)
- }
- >
- Back to builder
- </Button>
- </header>
- }
- />
- </Show>
- <Show when={!preview() && detail().form.audience === 'public'}>
- <RespondFooter />
+ </Show>
+ <Show when={!preview() && detail().form.audience === 'public'}>
+ <Show when={!userId()}>
+ <p class="mx-auto mb-6 max-w-3xl px-6 text-center text-xs text-ink-muted">
+ You’re responding anonymously.{' '}
+ <SignInToRespond>Sign in</SignInToRespond> to edit your
+ answer later.
+ </p>
+ </Show>
+ <RespondFooter />
+ </Show>
</Show>
- </Show>
- )}
- </Show>
- </main>
+ )}
+ </Show>
+ </main>
+ </Layer>
</FormProvider>
);
}
diff --git a/apps/web/src/features/block-form/views/builder-view.test.tsx b/apps/web/src/features/block-form/views/builder-view.test.tsx
index b3d2fc57a6..af9f8a2cc1 100644
--- a/apps/web/src/features/block-form/views/builder-view.test.tsx
+++ b/apps/web/src/features/block-form/views/builder-view.test.tsx
@@ -36,6 +36,14 @@ beforeAll(() => {
});
let animationStyle: HTMLStyleElement;
beforeEach(() => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
vi.useFakeTimers();
// jsdom's empty animation name otherwise leaves native menus waiting forever
// for an animationend event, preventing their close-focus lifecycle.
@@ -158,6 +166,19 @@ function mount(
return { ...mock, unmount: rendered.unmount };
}
+async function addQuestion(type: string) {
+ const trigger = screen.getByRole('button', {
+ name: 'Add question',
+ });
+ trigger.focus();
+ fireEvent.keyDown(trigger, { key: 'ArrowDown' });
+ await vi.advanceTimersByTimeAsync(0);
+ const item = screen.getByRole('menuitem', { name: type });
+ item.focus();
+ fireEvent.keyDown(item, { key: 'Enter' });
+ await vi.advanceTimersByTimeAsync(100);
+}
+
describe('BuilderView', () => {
it('saves a focused title before a background click closes question editing', async () => {
const { context } = mount();
@@ -183,31 +204,73 @@ describe('BuilderView', () => {
const outline = screen.getByRole('navigation', { name: 'Form outline' });
const section = within(outline).getByRole('button', { name: 'About you' });
fireEvent.click(section);
- expect(section.getAttribute('aria-current')).toBe('true');
+ expect(section.getAttribute('aria-current')).toBe('location');
fireEvent.click(screen.getByRole('region', { name: 'Form canvas' }));
- expect(section.getAttribute('aria-current')).not.toBe('true');
+ expect(section.getAttribute('aria-current')).not.toBe('location');
});
- it('keeps focus on a new section after the compact add menu closes', async () => {
+ it('adds a section directly and focuses its handle', async () => {
mount();
const trigger = screen.getByRole('button', {
- name: 'Add question',
+ name: 'Add section',
});
trigger.focus();
- fireEvent.keyDown(trigger, { key: 'ArrowDown' });
- await vi.advanceTimersByTimeAsync(0);
- const section = screen.getByRole('menuitem', {
- name: 'Section',
- });
- section.focus();
- fireEvent.keyDown(section, { key: 'Enter' });
- await vi.advanceTimersByTimeAsync(400);
- expect(screen.queryByRole('menu')).toBeNull();
+ fireEvent.click(trigger);
+ await vi.advanceTimersByTimeAsync(100);
expect(document.activeElement).toBe(
screen.getByRole('button', { name: 'Move Section 2' })
);
});
+ it('inserts a question at its hovered boundary instead of appending it', async () => {
+ const { shared } = mount();
+ const trigger = screen.getByRole('button', {
+ name: 'Insert question before Team',
+ });
+ trigger.focus();
+ fireEvent.keyDown(trigger, { key: 'ArrowDown' });
+ await vi.advanceTimersByTimeAsync(0);
+ const item = screen.getByRole('menuitem', { name: 'Short answer' });
+ item.focus();
+ fireEvent.keyDown(item, { key: 'Enter' });
+ await vi.advanceTimersByTimeAsync(100);
+ const questions = shared.theirs().sections[0].questions;
+ expect(questions).toHaveLength(3);
+ expect(questions.map((question) => question.id)).toEqual([
+ 'q-name',
+ expect.any(String),
+ 'q-team',
+ ]);
+ expect(questions[1].widget).toBe('short');
+ });
+
+ it.each(['Section', 'Gate'])(
+ 'inserts a %s between sections without offering a meeting link',
+ async (kind) => {
+ const { shared } = mount();
+ fireEvent.click(screen.getByRole('button', { name: 'Add section' }));
+ await vi.advanceTimersByTimeAsync(100);
+ const lastId = shared.theirs().sections[1].id;
+ const trigger = screen.getByRole('button', {
+ name: 'Insert before Section 2',
+ });
+ trigger.focus();
+ fireEvent.keyDown(trigger, { key: 'ArrowDown' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(
+ screen.getAllByRole('menuitem').map((item) => item.textContent?.trim())
+ ).toEqual(['Section', 'Gate']);
+ const item = screen.getByRole('menuitem', { name: kind });
+ item.focus();
+ fireEvent.keyDown(item, { key: 'Enter' });
+ await vi.advanceTimersByTimeAsync(100);
+ const sections = shared.theirs().sections;
+ expect(sections).toHaveLength(3);
+ expect(sections[1].kind).toBe(kind === 'Gate' ? 'gate' : 'questions');
+ expect(sections[2].id).toBe(lastId);
+ }
+ );
+
it('keeps keyboard focus in the outline when another editor changes a section', () => {
const { shared } = mount();
const outline = screen.getByRole('navigation', { name: 'Form outline' });
@@ -259,7 +322,7 @@ describe('BuilderView', () => {
within(outline)
.getByRole('button', { name: 'Team' })
.getAttribute('aria-current')
- ).toBe('true');
+ ).toBe('location');
});
it('shows required state below a question and edits it from the footer', async () => {
@@ -282,8 +345,8 @@ describe('BuilderView', () => {
const outline = screen.getByRole('navigation', { name: 'Form outline' });
const section = within(outline).getByRole('button', { name: 'About you' });
fireEvent.click(section);
- expect(section.getAttribute('aria-current')).toBe('true');
- fireEvent.click(screen.getByRole('button', { name: 'Add Paragraph' }));
+ expect(section.getAttribute('aria-current')).toBe('location');
+ await addQuestion('Paragraph');
await vi.advanceTimersByTimeAsync(0);
expect(shared.theirs().sections[0].questions.at(-1)?.widget).toBe(
'paragraph'
@@ -292,10 +355,10 @@ describe('BuilderView', () => {
within(outline)
.getByRole('button', { name: 'About you' })
.getAttribute('aria-current')
- ).not.toBe('true');
+ ).not.toBe('location');
});
- it('shows the question palette beside a separate outline and adds the chosen type after the selected question', async () => {
+ it('appends a question to the section even when an earlier question is selected', async () => {
const { calls, shared } = mount();
const banner = screen.getByRole('region', { name: 'Form details' });
expect(within(banner).getByLabelText('Form name')).toBeTruthy();
@@ -306,41 +369,29 @@ describe('BuilderView', () => {
expect(
screen.getByRole('navigation', { name: 'Form outline' })
).toBeTruthy();
- const palette = screen.getByRole('complementary', { name: 'Add to form' });
- for (const name of [
- 'Short answer',
- 'Paragraph',
- 'Multiple choice',
- 'Checkboxes',
- 'Dropdown',
- 'Number',
- 'Date & time',
- 'Person',
- 'Document',
- 'Database row',
- ]) {
- expect(
- within(palette).getByRole('button', { name: `Add ${name}` })
- ).toBeTruthy();
- }
+ expect(
+ screen.queryByRole('complementary', { name: 'Add to form' })
+ ).toBeNull();
fireEvent.click(screen.getByRole('group', { name: 'Question 1: Name' }));
- fireEvent.click(
- within(palette).getByRole('button', { name: 'Add Paragraph' })
- );
+ await addQuestion('Paragraph');
await vi.advanceTimersByTimeAsync(0);
const questions = shared.theirs().sections[0].questions;
expect(questions).toHaveLength(3);
expect(questions[0].id).toBe('q-name');
- expect(questions[1].widget).toBe('paragraph');
- expect(questions[2].id).toBe('q-team');
+ expect(questions[1].id).toBe('q-team');
+ expect(questions[2].widget).toBe('paragraph');
expect(calls.notices).toEqual([]);
});
- it('adds the first question to an empty form from the palette', async () => {
+ it('adds the first question to an empty form from the add menu', async () => {
const detail = rsvp();
detail.layout = { sections: [] };
const { shared, calls } = mount({ detail });
- fireEvent.click(screen.getByRole('button', { name: 'Add Short answer' }));
+ expect(screen.queryByRole('button', { name: 'Add question' })).toBeNull();
+ const trigger = screen.getByRole('button', { name: 'Add section' });
+ fireEvent.click(trigger);
+ await vi.advanceTimersByTimeAsync(100);
+ await addQuestion('Short answer');
await vi.advanceTimersByTimeAsync(0);
expect(shared.theirs().sections).toHaveLength(1);
expect(shared.theirs().sections[0].questions).toHaveLength(1);
@@ -441,21 +492,22 @@ describe('BuilderView', () => {
it('waits for the native table picker before creating a relation question, and cancel creates nothing', async () => {
const { shared, calls } = mount();
- fireEvent.click(screen.getByRole('button', { name: 'Add Database row' }));
+ await addQuestion('Database row');
expect(screen.getByRole('dialog', { name: 'Choose a table' })).toBeTruthy();
expect(shared.theirs().sections[0].questions).toHaveLength(2);
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ await vi.advanceTimersByTimeAsync(100);
expect(screen.queryByRole('dialog')).toBeNull();
expect(calls.layouts).toEqual([]);
fireEvent.click(screen.getByRole('group', { name: 'Question 1: Name' }));
- fireEvent.click(screen.getByRole('button', { name: 'Add Database row' }));
+ await addQuestion('Database row');
fireEvent.click(screen.getByRole('button', { name: 'Responses' }));
await vi.advanceTimersByTimeAsync(0);
expect(screen.queryByRole('dialog')).toBeNull();
const questions = shared.theirs().sections[0].questions;
expect(questions).toHaveLength(3);
expect(questions[0].id).toBe('q-name');
- expect(questions[2].id).toBe('q-team');
+ expect(questions[1].id).toBe('q-team');
expect(calls.notices).toEqual([]);
});
@@ -514,16 +566,6 @@ describe('BuilderView', () => {
it('builds a gate rule in the grid’s filter editor: the new condition stays while it is filled in, and saves once complete', async () => {
const detail = rsvp();
- detail.layout.sections.push({
- id: 'gate',
- title: 'Eligibility',
- description: '',
- kind: 'gate',
- gateRules: { conjunction: 'and', conditions: [] },
- gateMessage: 'Not this time.',
- bookingTarget: null,
- questions: [],
- });
const mock = createMockFormContext({ detail, tableColumns: columns });
const context = {
...mock.context,
@@ -543,11 +585,14 @@ describe('BuilderView', () => {
/>
</FormProvider>
));
- fireEvent.click(screen.getByRole('button', { name: 'Add rule' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Add gate' }));
+ await vi.advanceTimersByTimeAsync(100);
+ expect(mock.shared.theirs().sections.at(-1)?.kind).toBe('gate');
+ const savedCount = mock.calls.layouts.length;
fireEvent.click(screen.getByRole('button', { name: /Add condition/ }));
await vi.advanceTimersByTimeAsync(1000);
// Incomplete, so nothing is saved, and the row is still there to fill in.
- expect(mock.calls.layouts).toHaveLength(0);
+ expect(mock.calls.layouts).toHaveLength(savedCount);
const value = screen.getByRole('textbox', { name: 'Filter value' });
fireEvent.input(value, { target: { value: 'Ada' } });
await vi.advanceTimersByTimeAsync(400);
@@ -868,8 +913,10 @@ describe('BuilderView', () => {
it('adds one of the editor’s booking links as the last step and saves it', async () => {
const { calls } = mountBooking(rsvp());
- await openMenu('Booking');
- await choose(/Intro call/);
+ fireEvent.click(screen.getByRole('button', { name: 'Add meeting link' }));
+ await vi.advanceTimersByTimeAsync(100);
+ fireEvent.click(screen.getByRole('button', { name: /Intro call/ }));
+ await vi.advanceTimersByTimeAsync(100);
expect(calls.layouts.at(-1)?.sections.at(-1)).toEqual({
id: expect.any(String),
title: 'Book a time',
@@ -885,13 +932,13 @@ describe('BuilderView', () => {
expect(within(card).getByText('30 min · Ada Lovelace')).toBeTruthy();
});
- it('returns focus to the compact add trigger when booking selection is canceled', async () => {
+ it('returns focus to Add meeting link when selection is canceled', async () => {
mountBooking(rsvp());
const trigger = screen.getByRole('button', {
- name: 'Add question',
+ name: 'Add meeting link',
});
- await openMenu('Add question');
- await choose(/^Booking$/);
+ fireEvent.click(screen.getByRole('button', { name: 'Add meeting link' }));
+ await vi.advanceTimersByTimeAsync(100);
const dialog = screen.getByRole('dialog', {
name: 'Choose a booking link',
});
@@ -901,10 +948,10 @@ describe('BuilderView', () => {
expect(document.activeElement).toBe(trigger);
});
- it('chooses a booking link in a dialog from the compact menu and focuses its new step', async () => {
+ it('chooses a booking link from the visible action and focuses its new step', async () => {
const { shared } = mountBooking(rsvp());
- await openMenu('Add question');
- await choose(/^Booking$/);
+ fireEvent.click(screen.getByRole('button', { name: 'Add meeting link' }));
+ await vi.advanceTimersByTimeAsync(100);
const dialog = screen.getByRole('dialog', {
name: 'Choose a booking link',
});
@@ -922,6 +969,26 @@ describe('BuilderView', () => {
);
});
+ it('keeps the meeting link last when another section is added', async () => {
+ const { shared } = mountBooking(rsvp());
+ fireEvent.click(screen.getByRole('button', { name: 'Add meeting link' }));
+ fireEvent.click(screen.getByRole('button', { name: /Intro call/ }));
+ await vi.advanceTimersByTimeAsync(100);
+ fireEvent.click(screen.getByRole('button', { name: 'Add section' }));
+ await vi.advanceTimersByTimeAsync(100);
+ expect(shared.theirs().sections.map((section) => section.kind)).toEqual([
+ 'questions',
+ 'questions',
+ 'booking',
+ ]);
+ expect(
+ screen.queryByRole('button', { name: 'Add meeting link' })
+ ).toBeNull();
+ expect(
+ screen.getByRole('button', { name: 'View meeting link' })
+ ).toBeTruthy();
+ });
+
it('shows each of two concurrently added booking steps with its own link, for an editor to remove one', async () => {
const detail = rsvp();
detail.layout.sections.push(
@@ -979,9 +1046,12 @@ describe('BuilderView', () => {
it('explains how to make a booking link when the editor has none', async () => {
const { calls } = mountBooking(rsvp(), []);
- await openMenu('Booking');
+ fireEvent.click(screen.getByRole('button', { name: 'Add meeting link' }));
+ await vi.advanceTimersByTimeAsync(100);
expect(screen.getByText(/You have no booking links yet/)).toBeTruthy();
- await choose(/Create a booking link/);
+ fireEvent.click(
+ screen.getByRole('button', { name: /Create a booking link/ })
+ );
expect(calls.settingsOpened).toBe(1);
expect(calls.layouts).toHaveLength(0);
});
@@ -999,7 +1069,10 @@ describe('BuilderView', () => {
questions: [],
});
const { calls } = mountBooking(detail);
- fireEvent.click(screen.getByRole('button', { name: 'Booking' }));
+ fireEvent.click(
+ screen.getByRole('button', { name: 'View meeting link' })
+ );
+ await vi.advanceTimersByTimeAsync(100);
await vi.advanceTimersByTimeAsync(0);
expect(document.activeElement).toBe(
screen.getByRole('region', { name: 'Book a call' })
diff --git a/apps/web/src/features/block-form/views/builder-view.tsx b/apps/web/src/features/block-form/views/builder-view.tsx
index b913acc63b..dc67afeaac 100644
--- a/apps/web/src/features/block-form/views/builder-view.tsx
+++ b/apps/web/src/features/block-form/views/builder-view.tsx
@@ -1,13 +1,20 @@
+import { DocumentOutline } from '@app/components/DocumentOutline';
import ArrowSquareOut from '@phosphor/arrow-square-out.svg';
import CalendarCheck from '@phosphor/calendar-check.svg';
import Database from '@phosphor/database.svg';
import Plus from '@phosphor/plus.svg';
-import Rows from '@phosphor/rows.svg';
import ShieldCheck from '@phosphor/shield-check.svg';
import Warning from '@phosphor/warning.svg';
import { makeEventListener } from '@solid-primitives/event-listener';
-import { Key } from '@solid-primitives/keyed';
-import { Button, Dialog, Dropdown, Panel } from '@ui';
+import { createResizeObserver } from '@solid-primitives/resize-observer';
+import {
+ Badge,
+ Button,
+ badgeTriggerClasses,
+ Dialog,
+ Dropdown,
+ Panel,
+} from '@ui';
import { errAsync, okAsync, ResultAsync } from 'neverthrow';
import {
type Accessor,
@@ -30,19 +37,17 @@ import {
} from '../components/builder/booking-card';
import { BookingLinkDialog } from '../components/builder/booking-link-dialog';
import {
- BuilderPalette,
- BuilderSidebar,
BuilderSkeleton,
ConversionNotice,
DropIndicator,
HiddenColumns,
- OutlineSection,
TitleCard,
} from '../components/builder/builder-chrome';
import {
DragHandle,
DragInstructions,
} from '../components/builder/drag-handle';
+import { InsertionPoint } from '../components/builder/insertion-point';
import { OptionListEditor } from '../components/builder/option-list-editor';
import { QuestionPreview } from '../components/builder/question-body';
import { QuestionFooter } from '../components/builder/question-footer';
@@ -83,6 +88,7 @@ import type {
FormSection,
SectionKind,
} from '../core/form-model';
+import { availabilityLine, formAvailability } from '../core/form-status';
import {
placementDescription,
routingLine,
@@ -271,7 +277,7 @@ function BuilderCanvas(
const [editingRules, setEditingRules] = createSignal<string>();
const [choosingBooking, setChoosingBooking] = createSignal(false);
let afterMenuClose: (() => void) | undefined;
- let compactAddTrigger: HTMLButtonElement | undefined;
+ const sectionAddTriggers = new Map<string, HTMLButtonElement>();
let dialogReturnFocus: HTMLButtonElement | undefined;
const [pendingRelation, setPendingRelation] = createSignal<{
choice: QuestionTypeChoice;
@@ -280,6 +286,11 @@ function BuilderCanvas(
// One per mount: the same form can be built in two splits.
const instructionsId = createUniqueId();
let viewport: HTMLDivElement | undefined;
+ const [outlineViewport, setOutlineViewport] = createSignal<HTMLDivElement>();
+ const [viewportHeight, setViewportHeight] = createSignal(0);
+ createResizeObserver(outlineViewport, (entries) => {
+ setViewportHeight(entries.height);
+ });
let column: HTMLDivElement | undefined;
const layout = props.layout;
@@ -458,9 +469,6 @@ function BuilderCanvas(
builder.removeSection(section.id);
}
- const gateCount = () =>
- layout().sections.filter((section) => section.kind === 'gate').length;
-
const booking = () => bookingStep(layout());
const bookingLinks = context.booking.createLinks(
() => !props.detail.tableGone
@@ -494,11 +502,6 @@ function BuilderCanvas(
card?.focus({ preventScroll: true });
});
- const addBooking = (target: FormBookingTarget) => {
- const result = builder.addBooking(target);
- if (result) revealBooking(result.sectionId);
- };
-
const bookingMenu = (menuProps: {
trigger: JSX.Element;
triggerLabel?: string;
@@ -529,14 +532,13 @@ function BuilderCanvas(
label: questionTypeLabel(hidden.kind, null),
}));
- const addAllHidden = () => {
- for (const hidden of builder.hiddenColumns())
- builder.addExistingColumn(hidden.id);
- };
-
return (
<div
- ref={viewport}
+ ref={(element) => {
+ viewport = element;
+ setOutlineViewport(element);
+ setViewportHeight(element.clientHeight);
+ }}
data-form-builder-background
class="@container/builder relative h-full min-h-0 overflow-y-auto bg-canvas-base touch:pb-(--mobile-content-inset-bottom)"
onClick={(event) => {
@@ -557,26 +559,40 @@ function BuilderCanvas(
<div aria-live="assertive" aria-atomic="true" class="sr-only">
{drag.announcement()}
</div>
- <div
- data-form-builder-background
- class="mx-auto grid w-full max-w-[1320px] grid-cols-1 items-start justify-center gap-5 p-4 @3xl/builder:grid-cols-[minmax(0,680px)_272px] @5xl/builder:grid-cols-[272px_minmax(0,680px)_272px] @5xl/builder:py-6"
- >
- <div class="mx-auto w-full max-w-[680px] @3xl/builder:col-span-full @3xl/builder:max-w-none">
+ <div data-form-builder-background class="relative min-h-full px-6">
+ <div class="mx-auto flex w-full max-w-3xl min-w-0 flex-col gap-6 pt-12 pb-24">
<TitleCard
databaseLink={
- <Button
- variant="outline"
- class="max-w-full gap-2"
- aria-label={`Open database ${table.databaseName() ?? 'Database'}`}
- tooltip={table.databaseName() ?? 'Database'}
- onClick={() => props.onOpenDatabase(form().databaseId)}
- >
- <Database class="size-4 text-code" aria-hidden="true" />
- <span class="truncate">
- {table.databaseName() ?? 'Database'}
- </span>
- <ArrowSquareOut class="size-3.5" aria-hidden="true" />
- </Button>
+ <>
+ <Button
+ variant="outline"
+ size="sm"
+ class={badgeTriggerClasses({
+ variant: 'outline',
+ size: 'sm',
+ class: 'max-w-full text-ink-muted',
+ })}
+ aria-label={`Open database ${table.databaseName() ?? 'Database'}`}
+ tooltip={table.databaseName() ?? 'Database'}
+ onClick={() => props.onOpenDatabase(form().databaseId)}
+ >
+ <Database class="size-3 text-code" aria-hidden="true" />
+ <span class="truncate">
+ {table.databaseName() ?? 'Database'}
+ </span>
+ <ArrowSquareOut class="size-3" aria-hidden="true" />
+ </Button>
+ <Badge variant="outline" size="sm">
+ {availabilityLine(
+ formAvailability(
+ form(),
+ props.detail.tableGone,
+ new Date()
+ ),
+ new Date()
+ )}
+ </Badge>
+ </>
}
name={form().name}
description={form().description}
@@ -606,280 +622,331 @@ function BuilderCanvas(
)
)
}
- meta={
- <>
- <li>
- {form().audience === 'public'
- ? 'Anyone with the link'
- : 'Invited people'}
- </li>
- <li>
- {questionSections().length === 1
- ? '1 section'
- : `${questionSections().length} sections`}
- </li>
- <Show when={gateCount() > 0}>
- <li>
- {gateCount() === 1
- ? '1 screener'
- : `${gateCount()} screeners`}
- </li>
- </Show>
- <Show when={booking()}>
- <li>Ends with booking</li>
- </Show>
- </>
- }
/>
- </div>
- <BuilderSidebar
- outline={
- <ul class="flex flex-col gap-2">
- <Key each={layout().sections} by="id">
- {(section) => (
- <OutlineSection
- name={sectionName(layout(), section().id)}
- kind={section().kind}
- number={sectionPosition(layout(), section().id)}
- selected={builder.targetSectionId() === section().id}
- onSelectSection={() => {
- builder.focusSection(section().id);
- viewport
- ?.querySelector(`[data-form-section="${section().id}"]`)
- ?.scrollIntoView({
- block: 'start',
- behavior: 'smooth',
- });
- }}
- questions={section().questions.map((question) => ({
- id: question.id,
- title: columnTitle(question.columnId),
- selected: builder.selectedId() === question.id,
- }))}
- onSelectQuestion={(questionId) => {
- builder.select(questionId);
- viewport
- ?.querySelector(`[data-form-question="${questionId}"]`)
- ?.scrollIntoView({
- block: 'center',
- behavior: 'smooth',
- });
- }}
- />
- )}
- </Key>
- </ul>
- }
- />
- <div
- role="region"
- aria-label="Form canvas"
- data-form-builder-background
- class="mx-auto flex w-full max-w-[680px] min-w-0 flex-col gap-4"
- >
- <Show when={props.detail.tableGone}>
- <div
- role="alert"
- class="flex items-start gap-2 rounded-lg border border-failure bg-failure-bg px-3 py-2.5 text-sm text-failure-ink"
- >
- <Warning class="mt-0.5 size-4 shrink-0" aria-hidden="true" />
- This form’s table was deleted or its database is in the trash. It
- can’t take responses until the database is restored.
- </div>
- </Show>
- <Show when={props.failure}>
- {(message) => <LayoutFailure message={message()} />}
- </Show>
- <Show when={props.collaboration.publicationError()}>
- {(problem) => (
- <LayoutFailure
- message={`Respondents still see the last valid version of this form. ${problem()}`}
- />
- )}
- </Show>
- <Show when={saveNotice(props.collaboration)}>
- {(notice) => (
- <p
- role="status"
- class="rounded-lg border border-edge-muted bg-panel px-3 py-2 text-sm text-ink-muted"
+ <div
+ role="region"
+ aria-label="Form canvas"
+ data-form-builder-background
+ class="flex w-full min-w-0 flex-col gap-4"
+ >
+ <Show when={props.detail.tableGone}>
+ <div
+ role="alert"
+ class="flex items-start gap-2 rounded-lg border border-failure bg-failure-bg px-3 py-2.5 text-sm text-failure-ink"
>
- {notice()}
- </p>
- )}
- </Show>
- <Show when={builder.conversion()}>
- {(pending) => (
- <ConversionNotice
- message={pending().message}
- label={pending().label}
- onConvert={() => void builder.convertQuestion()}
- onDismiss={builder.dismissConversion}
- />
- )}
- </Show>
- <div ref={column} class="relative flex min-h-60 flex-col gap-6">
- <Show when={layout().sections.length === 0}>
- <div class="flex min-h-72 items-center justify-center rounded-xl border border-dashed border-edge bg-surface p-6 text-sm text-ink-muted">
- Click a question type or drag it here.
+ <Warning class="mt-0.5 size-4 shrink-0" aria-hidden="true" />
+ This form’s table was deleted or its database is in the trash.
+ It can’t take responses until the database is restored.
</div>
</Show>
- <For each={sectionIds()}>
- {(sectionId) => {
- const section = () => sectionById(sectionId);
- const index = () =>
- layout().sections.findIndex((item) => item.id === sectionId);
- const sectionTarget: DragTarget = {
- kind: 'section',
- id: sectionId,
- };
- const handle = () => (
- <DragHandle
- instructionsId={instructionsId}
- data-drag-handle={`section:${sectionId}`}
- label={`Move ${sectionName(layout(), sectionId)}`}
- dragging={drag.isDragging(sectionTarget)}
- disabled={props.detail.tableGone}
- handle={drag.handleProps(() => sectionTarget)}
- />
- );
- const menu = () => (
- <SectionMenu
- label={`${sectionName(layout(), sectionId)} actions`}
- canMoveUp={
- index() > 0 &&
- !builder.sectionMoveRefusal(sectionId, index() - 1)
- }
- canMoveDown={
- index() < layout().sections.length - 1 &&
- !builder.sectionMoveRefusal(sectionId, index() + 1)
- }
- deleteLabel={
- section()?.kind === 'gate'
- ? 'Delete screener'
- : 'Delete section'
- }
- onMoveUp={() => builder.moveSection(sectionId, index() - 1)}
- onMoveDown={() =>
- builder.moveSection(sectionId, index() + 1)
- }
- onDelete={() => {
- const current = section();
- if (current) void confirmRemoveSection(current);
- }}
- />
- );
- return (
- <Show when={section()}>
- {(current) => (
- <Switch>
- <Match when={current().kind === 'gate'}>
- <GateCard
- sectionId={sectionId}
- eyebrow={`Screener ${sectionPosition(layout(), sectionId)}`}
- title={current().title}
- sentence={rulesSentence(
- current().gateRules,
- builder.columns()
- )}
- message={current().gateMessage}
- dragging={drag.isDragging(sectionTarget)}
- editingRules={editingRules() === sectionId}
- brokenRules={
- brokenGateColumns(layout(), sectionId).length
- }
- onRepair={() => builder.repairGate(sectionId)}
- handle={handle()}
- menu={menu()}
- noQuestionsBefore={
- gateColumns(layout(), sectionId).length === 0
- }
- onEditRules={() => setEditingRules(sectionId)}
- onTitle={(title) =>
- builder.updateSection(sectionId, { title })
- }
- onMessage={(gateMessage) =>
- builder.updateSection(sectionId, { gateMessage })
- }
- ruleEditor={
- <div class="flex flex-col gap-2 rounded-lg border border-edge-muted bg-surface p-3">
- {
- // Rendered once per opening, its props read
- // live: a save must not remount the editor
- // and drop a condition still being filled.
- untrack(() =>
- context.ui.renderConditionEditor({
- get columns() {
- return gateColumns(
- layout(),
- sectionId
- ).flatMap((columnId): FormColumn[] => {
- const found =
- builder.column(columnId);
- return found ? [found] : [];
- });
- },
- get rules() {
- return current().gateRules;
- },
- onChange: (gateRules) =>
- builder.updateSection(sectionId, {
- gateRules: gateRules ?? {
- conjunction: 'and',
- conditions: [],
+ <Show when={props.failure}>
+ {(message) => <LayoutFailure message={message()} />}
+ </Show>
+ <Show when={props.collaboration.publicationError()}>
+ {(problem) => (
+ <LayoutFailure
+ message={`Respondents still see the last valid version of this form. ${problem()}`}
+ />
+ )}
+ </Show>
+ <Show when={saveNotice(props.collaboration)}>
+ {(notice) => (
+ <p
+ role="status"
+ class="rounded-lg border border-edge-muted bg-panel px-3 py-2 text-sm text-ink-muted"
+ >
+ {notice()}
+ </p>
+ )}
+ </Show>
+ <Show when={builder.conversion()}>
+ {(pending) => (
+ <ConversionNotice
+ message={pending().message}
+ label={pending().label}
+ onConvert={() => void builder.convertQuestion()}
+ onDismiss={builder.dismissConversion}
+ />
+ )}
+ </Show>
+ <div ref={column} class="relative flex flex-col gap-10">
+ <Show when={layout().sections.length === 0}>
+ <div class="flex min-h-72 items-center justify-center rounded-xl border border-dashed border-edge bg-surface p-6 text-sm text-ink-muted">
+ Click a question type or drag it here.
+ </div>
+ </Show>
+ <For each={sectionIds()}>
+ {(sectionId) => {
+ const section = () => sectionById(sectionId);
+ const index = () =>
+ layout().sections.findIndex(
+ (item) => item.id === sectionId
+ );
+ const sectionTarget: DragTarget = {
+ kind: 'section',
+ id: sectionId,
+ };
+ const handle = () => (
+ <DragHandle
+ instructionsId={instructionsId}
+ data-drag-handle={`section:${sectionId}`}
+ label={`Move ${sectionName(layout(), sectionId)}`}
+ dragging={drag.isDragging(sectionTarget)}
+ disabled={props.detail.tableGone}
+ handle={drag.handleProps(() => sectionTarget)}
+ />
+ );
+ const menu = () => (
+ <SectionMenu
+ label={`${sectionName(layout(), sectionId)} actions`}
+ canMoveUp={
+ index() > 0 &&
+ !builder.sectionMoveRefusal(sectionId, index() - 1)
+ }
+ canMoveDown={
+ index() < layout().sections.length - 1 &&
+ !builder.sectionMoveRefusal(sectionId, index() + 1)
+ }
+ deleteLabel={
+ section()?.kind === 'gate'
+ ? 'Delete screener'
+ : 'Delete section'
+ }
+ onMoveUp={() =>
+ builder.moveSection(sectionId, index() - 1)
+ }
+ onMoveDown={() =>
+ builder.moveSection(sectionId, index() + 1)
+ }
+ onDelete={() => {
+ const current = section();
+ if (current) void confirmRemoveSection(current);
+ }}
+ />
+ );
+ return (
+ <div class="relative min-w-0">
+ <Show when={index() > 0 && !props.detail.tableGone}>
+ <InsertionPoint betweenSections>
+ <Dropdown>
+ <Dropdown.Trigger
+ variant="outline"
+ size="sm"
+ class="h-6 shrink-0 bg-surface px-2"
+ aria-label={`Insert before ${sectionName(layout(), sectionId)}`}
+ >
+ <Plus class="size-3.5" />
+ Add
+ </Dropdown.Trigger>
+ <Dropdown.Content onCloseAutoFocus={runAfterClose}>
+ <Dropdown.Item
+ onSelect={() =>
+ insertSectionBefore('questions', sectionId)
+ }
+ >
+ <Plus class="size-4" />
+ Section
+ </Dropdown.Item>
+ <Dropdown.Item
+ onSelect={() =>
+ insertSectionBefore('gate', sectionId)
+ }
+ >
+ <ShieldCheck class="size-4" />
+ Gate
+ </Dropdown.Item>
+ </Dropdown.Content>
+ </Dropdown>
+ </InsertionPoint>
+ </Show>
+ <Show when={section()}>
+ {(current) => (
+ <Switch>
+ <Match when={current().kind === 'gate'}>
+ <GateCard
+ sectionId={sectionId}
+ eyebrow={`Screener ${sectionPosition(layout(), sectionId)}`}
+ title={current().title}
+ sentence={rulesSentence(
+ current().gateRules,
+ builder.columns()
+ )}
+ message={current().gateMessage}
+ dragging={drag.isDragging(sectionTarget)}
+ editingRules={editingRules() === sectionId}
+ brokenRules={
+ brokenGateColumns(layout(), sectionId).length
+ }
+ onRepair={() => builder.repairGate(sectionId)}
+ handle={handle()}
+ menu={menu()}
+ noQuestionsBefore={
+ gateColumns(layout(), sectionId).length === 0
+ }
+ onEditRules={() => setEditingRules(sectionId)}
+ onTitle={(title) =>
+ builder.updateSection(sectionId, { title })
+ }
+ onMessage={(gateMessage) =>
+ builder.updateSection(sectionId, {
+ gateMessage,
+ })
+ }
+ ruleEditor={
+ <div class="flex flex-col gap-2 rounded-lg border border-edge-muted bg-surface p-3">
+ {
+ // Rendered once per opening, its props read
+ // live: a save must not remount the editor
+ // and drop a condition still being filled.
+ untrack(() =>
+ context.ui.renderConditionEditor({
+ get columns() {
+ return gateColumns(
+ layout(),
+ sectionId
+ ).flatMap(
+ (columnId): FormColumn[] => {
+ const found =
+ builder.column(columnId);
+ return found ? [found] : [];
+ }
+ );
},
- }),
- })
- )
+ get rules() {
+ return current().gateRules;
+ },
+ onChange: (gateRules) =>
+ builder.updateSection(sectionId, {
+ gateRules: gateRules ?? {
+ conjunction: 'and',
+ conditions: [],
+ },
+ }),
+ })
+ )
+ }
+ <Button
+ size="sm"
+ variant="ghost"
+ class="self-end"
+ onClick={() => setEditingRules(undefined)}
+ >
+ Done
+ </Button>
+ </div>
}
- <Button
- size="sm"
- variant="ghost"
- class="self-end"
- onClick={() => setEditingRules(undefined)}
- >
- Done
- </Button>
- </div>
- }
- />
- </Match>
- <Match when={current().kind === 'booking' && current()}>
- {(booking) => {
- const link = bookingLinkState(
- () => booking().bookingTarget ?? undefined
- );
- return (
- <BookingCard
+ />
+ </Match>
+ <Match
+ when={current().kind === 'booking' && current()}
+ >
+ {(booking) => {
+ const link = bookingLinkState(
+ () => booking().bookingTarget ?? undefined
+ );
+ return (
+ <BookingCard
+ sectionId={sectionId}
+ title={current().title}
+ description={current().description}
+ link={link()}
+ menu={
+ <SectionMenu
+ label={`${sectionName(layout(), sectionId)} actions`}
+ canMoveUp={false}
+ canMoveDown={false}
+ deleteLabel="Remove booking step"
+ onMoveUp={() => {}}
+ onMoveDown={() => {}}
+ onDelete={() =>
+ builder.removeSection(sectionId)
+ }
+ />
+ }
+ change={bookingMenu({
+ trigger: 'Change',
+ triggerLabel: 'Change booking link',
+ triggerClass: 'shrink-0',
+ triggerVariant: 'outline',
+ selected:
+ current().bookingTarget ?? undefined,
+ onChoose: (target) =>
+ builder.changeBookingTarget(
+ sectionId,
+ target
+ ),
+ })}
+ onTitle={(title) =>
+ builder.updateSection(sectionId, {
+ title,
+ })
+ }
+ onDescription={(description) =>
+ builder.updateSection(sectionId, {
+ description,
+ })
+ }
+ />
+ );
+ }}
+ </Match>
+ <Match when={current().kind === 'questions'}>
+ <SectionCard
sectionId={sectionId}
+ eyebrow={`Section ${sectionPosition(layout(), sectionId)} of ${questionSections().length}`}
title={current().title}
description={current().description}
- link={link()}
- menu={
- <SectionMenu
- label={`${sectionName(layout(), sectionId)} actions`}
- canMoveUp={false}
- canMoveDown={false}
- deleteLabel="Remove booking step"
- onMoveUp={() => {}}
- onMoveDown={() => {}}
- onDelete={() =>
- builder.removeSection(sectionId)
+ questionCount={current().questions.length}
+ empty={current().questions.length === 0}
+ dragging={drag.isDragging(sectionTarget)}
+ targeted={
+ builder.targetSectionId() === sectionId
+ }
+ onTarget={() => builder.focusSection(sectionId)}
+ addQuestion={
+ <AddQuestionMenu
+ triggerClass="h-14 rounded-none border-0 bg-transparent px-5 text-sm"
+ triggerRef={(element) => {
+ sectionAddTriggers.set(
+ sectionId,
+ element
+ );
+ }}
+ trigger={
+ <>
+ <Plus class="size-3.5" />
+ Add question
+ </>
+ }
+ tables={relationTables()}
+ hiddenColumns={hiddenColumnRows()}
+ disabled={props.detail.tableGone}
+ onChoose={(choice, relation) => {
+ afterMenuClose = () => {
+ dialogReturnFocus =
+ sectionAddTriggers.get(sectionId);
+ void insertQuestion(
+ choice,
+ {
+ sectionId,
+ index: current().questions.length,
+ },
+ relation
+ );
+ };
+ }}
+ onCloseAutoFocus={runAfterClose}
+ onAddColumn={(columnId) =>
+ builder.addExistingColumn(columnId, {
+ sectionId,
+ index: current().questions.length,
+ })
}
/>
}
- change={bookingMenu({
- trigger: 'Change',
- triggerLabel: 'Change booking link',
- triggerClass: 'shrink-0',
- triggerVariant: 'outline',
- selected:
- current().bookingTarget ?? undefined,
- onChoose: (target) =>
- builder.changeBookingTarget(
- sectionId,
- target
- ),
- })}
+ handle={handle()}
+ menu={menu()}
+ editors={editors(sectionId, null)}
onTitle={(title) =>
builder.updateSection(sectionId, { title })
}
@@ -888,245 +955,155 @@ function BuilderCanvas(
description,
})
}
- />
- );
- }}
- </Match>
- <Match when={current().kind === 'questions'}>
- <SectionCard
- sectionId={sectionId}
- eyebrow={`Section ${sectionPosition(layout(), sectionId)} of ${questionSections().length}`}
- title={current().title}
- description={current().description}
- questionCount={current().questions.length}
- empty={current().questions.length === 0}
- dragging={drag.isDragging(sectionTarget)}
- targeted={builder.targetSectionId() === sectionId}
- onTarget={() => builder.focusSection(sectionId)}
- addQuestion={
- <AddQuestionMenu
- trigger={
- <>
- <Plus class="size-3.5" />
- Add question
- </>
- }
- tables={relationTables()}
- hiddenColumns={hiddenColumnRows()}
- disabled={props.detail.tableGone}
- onChoose={(choice, relation) => {
- afterMenuClose = () =>
- void insertQuestion(
- choice,
- { sectionId, index: 0 },
- relation
- );
- }}
- onCloseAutoFocus={runAfterClose}
- onAddColumn={(columnId) =>
- builder.addExistingColumn(columnId, {
- sectionId,
- index: 0,
- })
+ routing={
+ <RoutingFooter
+ next={routingLine(layout(), sectionId)}
+ />
}
- />
- }
- handle={handle()}
- menu={menu()}
- editors={editors(sectionId, null)}
- onTitle={(title) =>
- builder.updateSection(sectionId, { title })
- }
- onDescription={(description) =>
- builder.updateSection(sectionId, { description })
- }
- routing={
- <RoutingFooter
- next={routingLine(layout(), sectionId)}
- />
- }
- >
- <For
- each={current().questions.map(
- (question) => question.id
- )}
- >
- {(questionId) => (
- <QuestionItem
- questionId={questionId}
- sectionId={sectionId}
- />
- )}
- </For>
- </SectionCard>
- </Match>
- </Switch>
- )}
- </Show>
- );
- }}
- </For>
- <Show when={indicatorTop() !== undefined}>
- <DropIndicator
- top={indicatorTop() ?? 0}
- refusal={drag.session()?.refusal}
- />
- </Show>
- </div>
- <HiddenColumns
- columns={hiddenColumnRows()}
- onAdd={(columnId) => builder.addExistingColumn(columnId)}
- />
- <div class="@3xl/builder:hidden">
- <AddQuestionMenu
- triggerRef={(element) => {
- compactAddTrigger = element;
- }}
- trigger={
- <>
- <Plus class="size-4" />
- Add question
- </>
- }
- disabled={props.detail.tableGone}
- tables={relationTables()}
- hiddenColumns={hiddenColumnRows()}
- onChoose={(choice, table) => {
- afterMenuClose = () => {
- if (choice.kind === 'pick-table' && !table) {
- dialogReturnFocus = compactAddTrigger;
- }
- void insertQuestion(choice, undefined, table);
- };
- }}
- onAddColumn={(columnId) => builder.addExistingColumn(columnId)}
- onAddAllColumns={addAllHidden}
- onCloseAutoFocus={runAfterClose}
+ >
+ <For
+ each={current().questions.map(
+ (question) => question.id
+ )}
+ >
+ {(questionId, questionIndex) => (
+ <div class="relative min-w-0">
+ <Show
+ when={
+ questionIndex() > 0 &&
+ !props.detail.tableGone
+ }
+ >
+ <QuestionInsertion
+ sectionId={sectionId}
+ beforeId={questionId}
+ />
+ </Show>
+ <QuestionItem
+ questionId={questionId}
+ sectionId={sectionId}
+ />
+ </div>
+ )}
+ </For>
+ </SectionCard>
+ </Match>
+ </Switch>
+ )}
+ </Show>
+ </div>
+ );
+ }}
+ </For>
+ <Show when={indicatorTop() !== undefined}>
+ <DropIndicator
+ top={indicatorTop() ?? 0}
+ refusal={drag.session()?.refusal}
+ />
+ </Show>
+ </div>
+ <HiddenColumns
+ columns={hiddenColumnRows()}
+ onAdd={(columnId) => builder.addExistingColumn(columnId)}
+ />
+ <div
+ class="mt-6 flex flex-wrap gap-3"
+ role="group"
+ aria-label="Add to form"
>
- <Dropdown.Separator class="my-1 h-px bg-edge-divider" />
- <Dropdown.Group>
- <Dropdown.GroupLabel>Form flow</Dropdown.GroupLabel>
- <Dropdown.Item onSelect={() => addSectionFromMenu('questions')}>
- <Rows class="size-4" />
- Section
- </Dropdown.Item>
- <Dropdown.Item onSelect={() => addSectionFromMenu('gate')}>
- <ShieldCheck class="size-4" />
- Screener
- </Dropdown.Item>
- <Show
- when={booking()}
- fallback={
- <Show when={context.booking.available()}>
- <Dropdown.Item
- onSelect={() => {
- afterMenuClose = () => {
- dialogReturnFocus = compactAddTrigger;
- setChoosingBooking(true);
- };
- }}
- >
- <CalendarCheck class="size-4" />
- Booking
- </Dropdown.Item>
- </Show>
- }
+ <Button
+ variant="outline"
+ size="md"
+ class="h-14 flex-1 justify-start gap-2 rounded-xl px-5"
+ disabled={props.detail.tableGone}
+ onClick={() => addSectionAndFocus('questions')}
+ >
+ <Plus class="size-4" />
+ Add section
+ </Button>
+ <Button
+ variant="outline"
+ size="md"
+ class="h-14 flex-1 justify-start gap-2 rounded-xl px-5"
+ disabled={props.detail.tableGone}
+ onClick={() => addSectionAndFocus('gate')}
+ >
+ <ShieldCheck class="size-4" />
+ Add gate
+ </Button>
+ <Show when={booking() || context.booking.available()}>
+ <Button
+ variant="outline"
+ size="md"
+ class="h-14 flex-1 justify-start gap-2 rounded-xl px-5"
+ disabled={props.detail.tableGone}
+ onClick={(event) => {
+ const existing = booking();
+ if (existing) {
+ revealBooking(existing.id);
+ } else {
+ dialogReturnFocus = event.currentTarget;
+ setChoosingBooking(true);
+ }
+ }}
>
- {(existing) => (
- <Dropdown.Item
- onSelect={() => {
- afterMenuClose = () => revealBooking(existing().id);
- }}
- >
- <CalendarCheck class="size-4" />
- Booking
- </Dropdown.Item>
- )}
- </Show>
- </Dropdown.Group>
- </AddQuestionMenu>
+ <CalendarCheck class="size-4" />
+ {booking() ? 'View meeting link' : 'Add meeting link'}
+ </Button>
+ </Show>
+ </div>
</div>
</div>
- <BuilderPalette
- question={(choice) => <AddQuestionButton choice={choice} />}
- structure={
- <div class="flex flex-col gap-0.5">
- <div class="grid grid-cols-2 gap-0.5">
- <AddSectionButton kind="questions">
- <Rows class="size-3.5" />
- Section
- </AddSectionButton>
- <AddSectionButton kind="gate">
- <ShieldCheck class="size-3.5" />
- Screener
- </AddSectionButton>
- </div>
- <Show
- when={booking()}
- fallback={
- <Show when={context.booking.available()}>
- {bookingMenu({
- trigger: (
- <>
- <CalendarCheck class="size-3.5" />
- Booking
- </>
- ),
- triggerClass:
- 'w-full justify-start gap-1 rounded-md px-1 text-xs',
- triggerVariant: 'ghost',
- onChoose: addBooking,
- })}
- </Show>
+ <div class="pointer-events-none absolute inset-y-0 left-4 z-1 hidden w-10 @min-[880px]/builder:block">
+ <Show when={outlineViewport()}>
+ {(mount) => (
+ <DocumentOutline
+ label="Form outline"
+ items={layout().sections.flatMap((section) => [
+ {
+ key: section.id,
+ text: sectionName(layout(), section.id),
+ preview: section.questions
+ .map((q) => columnTitle(q.columnId))
+ .join(' · '),
+ },
+ ...section.questions.map((question) => ({
+ key: question.id,
+ text: columnTitle(question.columnId),
+ preview: questionTypeLabel(
+ builder.column(question.columnId)?.kind ?? {
+ type: 'text',
+ },
+ question.widget
+ ),
+ })),
+ ])}
+ activeKeys={
+ new Set(
+ [builder.selectedId() ?? builder.targetSectionId()].filter(
+ (id): id is string => !!id
+ )
+ )
}
- >
- {(existing) => (
- <Button
- variant="ghost"
- size="md"
- class="w-full justify-start gap-1 rounded-md px-1 text-xs"
- onClick={() => revealBooking(existing().id)}
- >
- <CalendarCheck class="size-3.5" />
- Booking
- </Button>
- )}
- </Show>
- </div>
- }
- database={
- <Dropdown>
- <Dropdown.Trigger
- variant="ghost"
- size="md"
- class="w-full justify-start gap-1 rounded-md px-1 text-xs"
- disabled={hiddenColumnRows().length === 0}
- >
- <Database class="size-3.5" />
- From database
- </Dropdown.Trigger>
- <Dropdown.Content class="w-60">
- <Dropdown.Item onSelect={addAllHidden}>
- <Plus class="size-4" />
- <span class="flex-1">
- Add all {hiddenColumnRows().length} columns
- </span>
- </Dropdown.Item>
- <Dropdown.Separator class="my-1 h-px bg-edge-divider" />
- <For each={hiddenColumnRows()}>
- {(hidden) => (
- <Dropdown.Item
- onSelect={() => builder.addExistingColumn(hidden.id)}
- >
- <QuestionTypeIcon type={hidden.type} />
- <span class="flex-1 truncate">{hidden.name}</span>
- </Dropdown.Item>
- )}
- </For>
- </Dropdown.Content>
- </Dropdown>
- }
- />
+ viewportHeight={viewportHeight()}
+ portalMount={mount()}
+ onSelect={(key) => {
+ const section = sectionById(key);
+ if (section) builder.focusSection(key);
+ else builder.select(key);
+ viewport
+ ?.querySelector(
+ `[data-form-${section ? 'section' : 'question'}="${key}"]`
+ )
+ ?.scrollIntoView({
+ block: section ? 'start' : 'center',
+ behavior: 'instant',
+ });
+ }}
+ />
+ )}
+ </Show>
+ </div>
</div>
<Show when={choosingBooking()}>
<BookingLinkDialog
@@ -1200,44 +1177,8 @@ function BuilderCanvas(
</div>
);
- function AddQuestionButton(buttonProps: { choice: QuestionTypeChoice }) {
- const target = (): DragTarget => ({
- kind: 'new-question',
- id: buttonProps.choice.id,
- });
- const handle = drag.handleProps(target);
- return (
- <Button
- variant="ghost"
- size="md"
- class="w-full touch-none justify-start gap-1 rounded-md px-1 text-xs"
- aria-label={`Add ${buttonProps.choice.label}`}
- data-drag-source
- data-drag-handle={`new-question:${buttonProps.choice.id}`}
- disabled={
- props.detail.tableGone ||
- (buttonProps.choice.kind === 'pick-table' &&
- relationTables().length === 0)
- }
- onPointerDown={handle.onPointerDown}
- onKeyDown={handle.onKeyDown}
- onBlur={handle.onBlur}
- onClick={(event) => {
- handle.onClick(event);
- if (!event.defaultPrevented) void insertQuestion(buttonProps.choice);
- }}
- >
- <QuestionTypeIcon
- type={buttonProps.choice.id}
- class="size-3.5 text-ink-muted"
- />
- <span>{buttonProps.choice.label}</span>
- </Button>
- );
- }
-
function addSection(kind: NewSectionKind) {
- const id = builder.addSection(kind);
+ const id = builder.addSection(kind, layout().sections.length);
if (!id) return;
if (kind === 'gate') setEditingRules(id);
return id;
@@ -1264,40 +1205,69 @@ function BuilderCanvas(
}
}
- function addSectionFromMenu(kind: NewSectionKind) {
+ function addSectionAndFocus(kind: NewSectionKind) {
const id = addSection(kind);
- if (id) afterMenuClose = () => focusHandle({ kind: 'section', id });
+ if (id) queueMicrotask(() => focusHandle({ kind: 'section', id }));
+ }
+
+ function insertSectionBefore(kind: NewSectionKind, beforeId: string) {
+ const index = layout().sections.findIndex(
+ (section) => section.id === beforeId
+ );
+ if (index < 0) return;
+ const id = builder.addSection(kind, index);
+ if (!id) return;
+ if (kind === 'gate') setEditingRules(id);
+ afterMenuClose = () => focusHandle({ kind: 'section', id });
}
- function AddSectionButton(buttonProps: {
- kind: NewSectionKind;
- children: JSX.Element;
+ function QuestionInsertion(insertion: {
+ sectionId: string;
+ beforeId: string;
}) {
- const target = (): DragTarget => ({
- kind: 'new-section',
- id: buttonProps.kind,
- });
- const handle = drag.handleProps(target);
+ let trigger: HTMLButtonElement | undefined;
+ const placement = (): QuestionPlacement | undefined => {
+ const index = sectionById(insertion.sectionId)?.questions.findIndex(
+ (question) => question.id === insertion.beforeId
+ );
+ return index !== undefined && index >= 0
+ ? { sectionId: insertion.sectionId, index }
+ : undefined;
+ };
return (
- <Button
- variant="ghost"
- size="md"
- class="w-full touch-none justify-start gap-1 rounded-md px-1 text-xs"
- data-drag-source
- data-drag-handle={`new-section:${buttonProps.kind}`}
- disabled={props.detail.tableGone}
- onPointerDown={handle.onPointerDown}
- onKeyDown={handle.onKeyDown}
- onBlur={handle.onBlur}
- onClick={(event) => {
- handle.onClick(event);
- if (event.defaultPrevented) return;
- const id = addSection(buttonProps.kind);
- if (id) drag.refocus({ kind: 'section', id });
- }}
- >
- {buttonProps.children}
- </Button>
+ <InsertionPoint>
+ <AddQuestionMenu
+ triggerClass="h-6 w-auto! shrink-0 bg-surface px-2 text-xs"
+ triggerRef={(element) => {
+ trigger = element;
+ }}
+ trigger={
+ <>
+ <Plus class="size-3.5" />
+ <span class="sr-only">
+ Insert question before {questionTitle(insertion.beforeId)}
+ </span>
+ </>
+ }
+ tables={relationTables()}
+ hiddenColumns={hiddenColumnRows()}
+ onChoose={(choice, relation) => {
+ afterMenuClose = () => {
+ const at = placement();
+ if (!at) return;
+ dialogReturnFocus = trigger;
+ void insertQuestion(choice, at, relation);
+ };
+ }}
+ onAddColumn={(columnId) => {
+ afterMenuClose = () => {
+ const at = placement();
+ if (at) void builder.addExistingColumn(columnId, at);
+ };
+ }}
+ onCloseAutoFocus={runAfterClose}
+ />
+ </InsertionPoint>
);
}
diff --git a/apps/web/src/features/block-form/views/form-page-view.test.tsx b/apps/web/src/features/block-form/views/form-page-view.test.tsx
index 633f414184..e83ec4d9bc 100644
--- a/apps/web/src/features/block-form/views/form-page-view.test.tsx
+++ b/apps/web/src/features/block-form/views/form-page-view.test.tsx
@@ -2,7 +2,15 @@ import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
import userEvent from '@testing-library/user-event';
import { ok, okAsync, type Result, ResultAsync } from 'neverthrow';
import { createSignal } from 'solid-js';
-import { afterEach, beforeAll, describe, expect, it } from 'vitest';
+import {
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
import type { FormTab } from '../components/form-tabs';
import { FormProvider, type FormWriteFailure } from '../context/form-context';
import type { FormDetail } from '../core/form-model';
@@ -11,10 +19,27 @@ import { createMockFormContext } from '../tests/mock-context';
import { FormPageView } from './form-page-view';
beforeAll(() => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
Element.prototype.scrollIntoView = () => {};
window.scrollTo = () => {};
});
-afterEach(cleanup);
+let animationStyle: HTMLStyleElement;
+beforeEach(() => {
+ animationStyle = document.createElement('style');
+ animationStyle.textContent = '* { animation-name: none !important; }';
+ document.head.append(animationStyle);
+});
+afterEach(() => {
+ cleanup();
+ animationStyle.remove();
+});
const detail: FormDetail = {
form: {
@@ -52,7 +77,7 @@ const detail: FormDetail = {
};
describe('form editor preview', () => {
- it('waits for a confirmation message saved on blur before opening Preview from Share', async () => {
+ it('waits for a confirmation message saved on blur before opening Preview from Settings', async () => {
const user = userEvent.setup();
let finishSave!: (result: Result<void, FormWriteFailure>) => void;
const saving = new ResultAsync(
@@ -177,8 +202,11 @@ describe('form editor preview', () => {
</FormProvider>
);
});
- fireEvent.click(screen.getByRole('button', { name: 'Add Short answer' }));
- await user.click(screen.getByRole('tab', { name: 'Share' }));
+ await user.click(
+ screen.getAllByRole('button', { name: 'Add question' }).at(-1)!
+ );
+ await user.click(screen.getByRole('menuitem', { name: 'Short answer' }));
+ await user.click(screen.getByRole('tab', { name: 'Settings' }));
expect(mock.shared.selections.at(-1)).toBeUndefined();
await user.click(screen.getByRole('button', { name: 'Preview' }));
expect(preview.opening()).toBe(true);
diff --git a/apps/web/src/features/block-form/views/form-page-view.tsx b/apps/web/src/features/block-form/views/form-page-view.tsx
index 6a4f353f3b..927528c820 100644
--- a/apps/web/src/features/block-form/views/form-page-view.tsx
+++ b/apps/web/src/features/block-form/views/form-page-view.tsx
@@ -1,5 +1,13 @@
import { Button } from '@ui';
-import { createUniqueId, Match, Show, Switch } from 'solid-js';
+import {
+ type Component,
+ createUniqueId,
+ type JSX,
+ Match,
+ Show,
+ Switch,
+} from 'solid-js';
+import { Dynamic } from 'solid-js/web';
import { type FormTab, FormTabs } from '../components/form-tabs';
import {
type FormDetailSource,
@@ -7,7 +15,6 @@ import {
useFormContext,
} from '../context/form-context';
import type { FormDetail } from '../core/form-model';
-import { availabilityLine, formAvailability } from '../core/form-status';
import type { Preview } from '../primitives/create-preview';
import { BuilderView } from './builder-view';
import { RespondView } from './respond-view';
@@ -67,11 +74,22 @@ export function FormSkeleton() {
);
}
+export type FormHeaderProps = { tabs: JSX.Element };
+
+function InlineFormHeader(props: FormHeaderProps) {
+ return (
+ <div class="flex items-center justify-between gap-3 px-4 py-2">
+ {props.tabs}
+ </div>
+ );
+}
+
/** The tab strip, with the response count only editors can read. */
function EditorTabs(props: {
detail: FormDetail;
tab: FormTab;
idPrefix: string;
+ header?: Component<FormHeaderProps>;
onTabChange: (tab: FormTab) => void;
}) {
const context = useFormContext();
@@ -80,25 +98,27 @@ function EditorTabs(props: {
() => props.detail.access !== 'view'
);
return (
- <FormTabs
- tab={props.tab}
- idPrefix={props.idPrefix}
- responsesCount={summary.value()?.submitted}
- onChange={props.onTabChange}
- status={availabilityLine(
- formAvailability(props.detail.form, props.detail.tableGone, new Date()),
- new Date()
- )}
+ <Dynamic
+ component={props.header ?? InlineFormHeader}
+ tabs={
+ <FormTabs
+ tab={props.tab}
+ idPrefix={props.idPrefix}
+ responsesCount={summary.value()?.submitted}
+ onChange={props.onTabChange}
+ />
+ }
/>
);
}
/**
- * The form page (RFC 02 §2): editors get Build, Responses and Share with the
- * status at the right; viewers land on the respond page.
+ * The form page: editors get Build, Responses and Share; viewers land on the respond page.
*/
type FormPageProps = {
source: FormDetailSource;
+ /** Host placement for navigation. */
+ header?: Component<FormHeaderProps>;
tab: FormTab;
respondLink: string;
/** What a preview waits for before it reads the form. */
@@ -142,6 +162,7 @@ function EditorPanels(
return (
<>
<EditorTabs
+ header={props.header}
detail={props.detail}
idPrefix={props.tabsId}
tab={props.tab}
@@ -156,10 +177,7 @@ function EditorPanels(
<Switch>
<Match when={props.tab === 'build'}>{builder}</Match>
<Match when={props.tab === 'responses'}>
- <ResponsesView
- detail={props.detail}
- onOpenDatabase={props.onOpenDatabase}
- />
+ <ResponsesView detail={props.detail} />
</Match>
<Match when={props.tab === 'share'}>{sharing}</Match>
</Switch>
diff --git a/apps/web/src/features/block-form/views/respond-view.tsx b/apps/web/src/features/block-form/views/respond-view.tsx
index 9cc9cfbe8b..d616f154f3 100644
--- a/apps/web/src/features/block-form/views/respond-view.tsx
+++ b/apps/web/src/features/block-form/views/respond-view.tsx
@@ -168,444 +168,482 @@ export function RespondView(props: {
);
return (
- <div
- ref={root}
- class={cn(
- 'mx-auto flex w-full flex-col',
- props.compact ? 'gap-3' : 'max-w-[680px] gap-4 px-4 pt-6 pb-28 sm:pb-10'
- )}
- data-form-respond={form().id}
- >
- <Show when={props.header}>{props.header}</Show>
- <Show when={!props.compact}>
- <RespondTitleCard
- name={form().name}
- description={form().description}
- compact={false}
- />
- </Show>
- <Switch>
- <Match
- when={(() => {
- const view = respond.view();
- return view.kind === 'preview-complete' ? view : undefined;
- })()}
- >
- {(completed) => (
- <Confirmation
- message={form().confirmationMessage || 'Preview complete.'}
- fresh
- submittedAt={undefined}
- receipt={receipt(completed().answers)}
- canEdit={false}
- compact={props.compact}
- renderEntityLabel={context.ui.renderEntityLabel}
- onEdit={respond.restartPreview}
- notice={
- <p class="text-sm text-ink-muted">No response was saved.</p>
- }
- footer={
- <Button
- variant="outline"
- class="self-start"
- onClick={() => {
- respond.restartPreview();
- revealTop();
- }}
- >
- Try again
- </Button>
- }
- />
- )}
- </Match>
- <Match
- when={(() => {
- const view = respond.view();
- return view.kind === 'booking' ? view : undefined;
- })()}
- >
- {(step) => (
- <>
- <BookingStepView
- booking={step().booking}
- preview={step().preview}
+ <div class={props.compact ? undefined : 'px-6'}>
+ <div
+ ref={root}
+ class={cn(
+ 'mx-auto flex w-full flex-col',
+ props.compact ? 'gap-3' : 'max-w-3xl gap-6 pt-12 pb-24'
+ )}
+ data-form-respond={form().id}
+ >
+ <Show when={props.header}>{props.header}</Show>
+ <Show when={!props.compact}>
+ <RespondTitleCard
+ name={form().name}
+ description={form().description}
+ compact={false}
+ />
+ </Show>
+ <Switch>
+ <Match
+ when={(() => {
+ const view = respond.view();
+ return view.kind === 'preview-complete' ? view : undefined;
+ })()}
+ >
+ {(completed) => (
+ <Confirmation
+ message={form().confirmationMessage || 'Preview complete.'}
+ fresh
+ submittedAt={undefined}
+ receipt={receipt(completed().answers)}
+ canEdit={false}
+ compact={props.compact}
+ renderEntityLabel={context.ui.renderEntityLabel}
+ onEdit={respond.restartPreview}
+ notice={
+ <p class="text-sm text-ink-muted">No response was saved.</p>
+ }
+ footer={
+ <Button
+ variant="outline"
+ class="self-start"
+ onClick={() => {
+ respond.restartPreview();
+ revealTop();
+ }}
+ >
+ Try again
+ </Button>
+ }
/>
- <Show when={step().preview}>
+ )}
+ </Match>
+ <Match
+ when={(() => {
+ const view = respond.view();
+ return view.kind === 'booking' ? view : undefined;
+ })()}
+ >
+ {(step) => (
+ <>
+ <BookingStepView
+ booking={step().booking}
+ preview={step().preview}
+ />
+ <Show when={step().preview}>
+ <Button
+ variant="outline"
+ class="self-start"
+ onClick={() => {
+ respond.restartPreview();
+ revealTop();
+ }}
+ >
+ Try again
+ </Button>
+ </Show>
+ </>
+ )}
+ </Match>
+ <Match when={respond.view().kind === 'loading'}>
+ <div
+ class="flex flex-col gap-3"
+ aria-busy="true"
+ aria-label="Loading"
+ >
+ <div class="h-24 animate-pulse rounded-xl bg-hover" />
+ <div class="h-24 animate-pulse rounded-xl bg-hover" />
+ </div>
+ </Match>
+ <Match
+ when={(() => {
+ const view = respond.view();
+ return view.kind === 'closed' ? view : undefined;
+ })()}
+ >
+ {(closed) => <ClosedNotice reason={closed().reason} />}
+ </Match>
+ <Match
+ when={(() => {
+ const view = respond.view();
+ return view.kind === 'response-unavailable' ? view : undefined;
+ })()}
+ >
+ {(unavailable) => (
+ <div
+ role="alert"
+ class="flex flex-col gap-3 rounded-xl border border-edge bg-surface p-5"
+ >
+ <p class="font-medium text-ink">You’ve already responded</p>
+ <p class="text-sm text-ink-muted">
+ Your saved response couldn’t be loaded.
+ </p>
<Button
variant="outline"
class="self-start"
- onClick={() => {
- respond.restartPreview();
- revealTop();
- }}
+ disabled={unavailable().retrying}
+ aria-busy={unavailable().retrying}
+ onClick={() => void respond.retryResponse()}
>
Try again
</Button>
- </Show>
- </>
- )}
- </Match>
- <Match when={respond.view().kind === 'loading'}>
- <div
- class="flex flex-col gap-3"
- aria-busy="true"
- aria-label="Loading"
- >
- <div class="h-24 animate-pulse rounded-xl bg-hover" />
- <div class="h-24 animate-pulse rounded-xl bg-hover" />
- </div>
- </Match>
- <Match
- when={(() => {
- const view = respond.view();
- return view.kind === 'closed' ? view : undefined;
- })()}
- >
- {(closed) => <ClosedNotice reason={closed().reason} />}
- </Match>
- <Match
- when={(() => {
- const view = respond.view();
- return view.kind === 'response-unavailable' ? view : undefined;
- })()}
- >
- {(unavailable) => (
+ </div>
+ )}
+ </Match>
+ <Match when={respond.view().kind === 'updating'}>
<div
- role="alert"
- class="flex flex-col gap-3 rounded-xl border border-edge bg-surface p-5"
+ role="status"
+ class="flex flex-col gap-1 rounded-xl border border-edge bg-surface p-5"
>
- <p class="font-medium text-ink">You’ve already responded</p>
+ <p class="text-sm font-medium text-ink">
+ This form is being updated
+ </p>
<p class="text-sm text-ink-muted">
- Your saved response couldn’t be loaded.
+ Nothing you entered was submitted. Try again in a moment.
</p>
<Button
variant="outline"
- class="self-start"
- disabled={unavailable().retrying}
- aria-busy={unavailable().retrying}
- onClick={() => void respond.retryResponse()}
+ size="sm"
+ class="mt-2 self-start"
+ onClick={() => void retry()}
>
Try again
</Button>
</div>
- )}
- </Match>
- <Match when={respond.view().kind === 'updating'}>
- <div
- role="status"
- class="flex flex-col gap-1 rounded-xl border border-edge bg-surface p-5"
+ </Match>
+ <Match
+ when={(() => {
+ const view = respond.view();
+ return view.kind === 'stopped' ? view : undefined;
+ })()}
>
- <p class="text-sm font-medium text-ink">
- This form is being updated
- </p>
- <p class="text-sm text-ink-muted">
- Nothing you entered was submitted. Try again in a moment.
- </p>
- <Button
- variant="outline"
- size="sm"
- class="mt-2 self-start"
- onClick={() => void retry()}
- >
- Try again
- </Button>
- </div>
- </Match>
- <Match
- when={(() => {
- const view = respond.view();
- return view.kind === 'stopped' ? view : undefined;
- })()}
- >
- {(stopped) => (
- <StopScreen
- message={stopped().message}
- editing={respond.editing()}
- onCheckAnswers={() => {
- respond.checkAnswers();
- revealTop();
- }}
- onMessageOwner={
- signedIn() && context.viewer.userId() !== form().ownerId
- ? () =>
- void context
- .messageOwner(form().ownerId)
- .mapErr((failure) =>
- context.notify.failure(
- `The conversation couldn’t be opened: ${failure.message}`
+ {(stopped) => (
+ <StopScreen
+ message={stopped().message}
+ editing={respond.editing()}
+ onCheckAnswers={() => {
+ respond.checkAnswers();
+ revealTop();
+ }}
+ onMessageOwner={
+ signedIn() && context.viewer.userId() !== form().ownerId
+ ? () =>
+ void context
+ .messageOwner(form().ownerId)
+ .mapErr((failure) =>
+ context.notify.failure(
+ `The conversation couldn’t be opened: ${failure.message}`
+ )
)
- )
- : undefined
- }
- />
- )}
- </Match>
- <Match
- when={(() => {
- const view = respond.view();
- return view.kind === 'confirmation' ? view : undefined;
- })()}
- >
- {(confirmation) => (
- <Confirmation
- message={form().confirmationMessage}
- fresh={confirmation().fresh}
- submittedAt={confirmation().submittedAt}
- receipt={receipt(confirmation().answers)}
- canEdit={confirmation().canEdit}
- compact={props.compact}
- renderEntityLabel={context.ui.renderEntityLabel}
- onEdit={() => {
- respond.editResponse();
- revealTop();
- }}
- notice={
- <>
- <Show when={!confirmation().fresh && !open()}>
- <p class="text-xs text-ink">
- This form is closed, so your response can’t be changed.
- </p>
- </Show>
- <Show when={confirmation().alreadyResponded}>
- <p class="text-xs text-ink">
- You had already responded, so the answers you just gave
- weren’t sent. This is your saved response.
- </p>
- </Show>
- </>
- }
- footer={
- <>
- <Show when={confirmation().booking}>
- <Button
- variant="cta"
- class="self-start"
- onClick={() => {
- respond.openBooking();
- revealTop();
- }}
- >
- <CalendarCheck class="size-3.5" />
- Book a time
- </Button>
- </Show>
- <p class="px-1 text-xs text-ink-muted">
- Stored as a row in a database the form owner controls. Your
- answers are visible to the form’s editors.
- </p>
- </>
- }
- />
- )}
- </Match>
- <Match
- when={(() => {
- const view = respond.view();
- return view.kind === 'answering' ? view : undefined;
- })()}
- >
- {(answering) => (
- <form
- class="flex flex-col gap-3"
- noValidate
- aria-label={answering().section?.title || form().name}
- onSubmit={(event) => {
- event.preventDefault();
- if (answering().isLast) {
- void submitAndReveal();
- return;
+ : undefined
}
- if (respond.next()) revealTop();
- else revealProblem();
- }}
- >
- <Show when={answering().total > 1}>
- <ProgressStrip
- position={answering().position}
- total={answering().total}
- />
- </Show>
- <SectionHeading
- title={answering().section?.title ?? ''}
- description={answering().section?.description ?? ''}
/>
- <For each={answering().section?.questions}>
- {(question) => {
- const column = () => respond.columns().get(question.columnId);
- return (
- <Show when={column()}>
- {(columnFacts) => {
- const widget = () =>
- resolvedWidget(columnFacts().kind, question.widget);
- // Files and Macro pickers need an account; an
- // anonymous visitor is told so, not shown a dead end.
- const needsSignIn = () => {
- if (signedIn()) return undefined;
- if (widget() === 'file' && isPublic())
- return 'asks for a file';
- const kind = columnFacts().kind.type;
- return kind === 'entity' || kind === 'relation'
- ? 'picks from Macro'
- : undefined;
- };
- return (
- <Show
- when={!needsSignIn()}
- fallback={
- <div class="rounded-xl border border-edge bg-surface px-4 py-3 text-sm text-ink-muted">
- <p>
- “{columnFacts().name}” {needsSignIn()}, which
- needs you to sign in.
- </p>
- <Show when={respond.problems()[question.id]}>
- {(problem) => (
- <p
- id={`${fieldId(scope, question.id)}-error`}
- class="mt-1 text-xs text-failure-ink"
- >
- {problem()}
- </p>
- )}
- </Show>
- </div>
- }
- >
- <QuestionField
- scope={scope}
- question={question}
- column={columnFacts()}
- widget={widget()}
- number={numbers().get(question.id) ?? 0}
- value={respond.answers()[question.id]}
- problem={respond.problems()[question.id]}
- disabled={answering().submitting}
- compact={props.compact}
- upload={upload}
- onChange={(value) =>
- respond.setAnswer(question.id, value)
- }
- renderEntityPicker={(picker) =>
- context.ui.renderEntityPicker({
- ...picker,
- label: columnFacts().name,
- value: respond.answers()[question.id],
- onChange: (value) =>
- respond.setAnswer(question.id, value),
- })
- }
- renderRelationPicker={(picker) =>
- context.ui.renderRelationPicker({
- ...picker,
- label: columnFacts().name,
- value: respond.answers()[question.id],
- onChange: (value) =>
- respond.setAnswer(question.id, value),
- })
- }
- />
- </Show>
- );
- }}
- </Show>
- );
+ )}
+ </Match>
+ <Match
+ when={(() => {
+ const view = respond.view();
+ return view.kind === 'confirmation' ? view : undefined;
+ })()}
+ >
+ {(confirmation) => (
+ <Confirmation
+ message={form().confirmationMessage}
+ fresh={confirmation().fresh}
+ submittedAt={confirmation().submittedAt}
+ receipt={receipt(confirmation().answers)}
+ canEdit={confirmation().canEdit}
+ compact={props.compact}
+ renderEntityLabel={context.ui.renderEntityLabel}
+ onEdit={() => {
+ respond.editResponse();
+ revealTop();
}}
- </For>
- <Show
- when={
- answering().section?.questions.some(
- (question) => question.required
- ) || editNote()
+ notice={
+ <>
+ <Show when={!confirmation().fresh && !open()}>
+ <p class="text-xs text-ink">
+ This form is closed, so your response can’t be changed.
+ </p>
+ </Show>
+ <Show when={confirmation().alreadyResponded}>
+ <p class="text-xs text-ink">
+ You had already responded, so the answers you just gave
+ weren’t sent. This is your saved response.
+ </p>
+ </Show>
+ </>
+ }
+ footer={
+ <>
+ <Show when={confirmation().booking}>
+ <Button
+ variant="cta"
+ class="self-start"
+ onClick={() => {
+ respond.openBooking();
+ revealTop();
+ }}
+ >
+ <CalendarCheck class="size-3.5" />
+ Book a time
+ </Button>
+ </Show>
+ <p class="px-1 text-xs text-ink-muted">
+ Stored as a row in a database the form owner controls.
+ Your answers are visible to the form’s editors.
+ </p>
+ </>
}
+ />
+ )}
+ </Match>
+ <Match
+ when={(() => {
+ const view = respond.view();
+ return view.kind === 'answering' ? view : undefined;
+ })()}
+ >
+ {(answering) => (
+ <form
+ class="flex flex-col gap-3"
+ noValidate
+ aria-label={answering().section?.title || form().name}
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (answering().isLast) {
+ void submitAndReveal();
+ return;
+ }
+ if (respond.next()) revealTop();
+ else revealProblem();
+ }}
>
<div
- role="note"
- aria-label="Form guidance"
- class="flex flex-wrap items-center gap-x-3 gap-y-1 px-1 pt-1 text-xs text-ink-muted"
+ class={
+ props.compact
+ ? 'flex flex-col gap-3'
+ : 'overflow-hidden rounded-xl border border-edge bg-surface shadow-xs divide-y divide-edge-divider'
+ }
>
<Show
- when={answering().section?.questions.some(
- (question) => question.required
- )}
+ when={
+ answering().total > 1 ||
+ answering().section?.title ||
+ answering().section?.description
+ }
>
- <p class="inline-flex items-center gap-1.5">
- <span class="text-failure-ink" aria-hidden="true">
- *
- </span>
- <span>Required fields</span>
- </p>
+ <div
+ class={
+ props.compact
+ ? 'flex flex-col gap-3'
+ : 'flex flex-col gap-3 pt-3 pr-2 pb-2 pl-4'
+ }
+ >
+ <Show when={answering().total > 1}>
+ <ProgressStrip
+ position={answering().position}
+ total={answering().total}
+ />
+ </Show>
+ <SectionHeading
+ title={answering().section?.title ?? ''}
+ description={answering().section?.description ?? ''}
+ />
+ </div>
</Show>
- <Show when={editNote()}>{(note) => <p>{note()}</p>}</Show>
- </div>
- </Show>
- <Show when={respond.failure()}>
- {(message) => (
- <p role="alert" class="px-1 text-sm text-failure-ink">
- {message()}
- </p>
- )}
- </Show>
- <div
- class={cn(
- 'flex items-center justify-between gap-2',
- !props.compact &&
- 'max-sm:fixed max-sm:inset-x-0 max-sm:bottom-0 touch:max-sm:bottom-[var(--mobile-content-inset-bottom,0px)] max-sm:z-10 max-sm:border-t max-sm:border-edge max-sm:bg-surface max-sm:px-4 max-sm:py-3 max-sm:pb-[max(0.75rem,env(safe-area-inset-bottom))]'
- )}
- >
- <Show when={!answering().isFirst} fallback={<span />}>
- <Button
- type="button"
- variant="ghost"
- size="md"
- disabled={answering().submitting}
- onClick={() => {
- respond.back();
- revealTop();
+ <For each={answering().section?.questions}>
+ {(question) => {
+ const column = () =>
+ respond.columns().get(question.columnId);
+ return (
+ <Show when={column()}>
+ {(columnFacts) => {
+ const widget = () =>
+ resolvedWidget(
+ columnFacts().kind,
+ question.widget
+ );
+ // Files and Macro pickers need an account; an
+ // anonymous visitor is told so, not shown a dead end.
+ const needsSignIn = () => {
+ if (signedIn()) return undefined;
+ if (widget() === 'file' && isPublic())
+ return 'asks for a file';
+ const kind = columnFacts().kind.type;
+ return kind === 'entity' || kind === 'relation'
+ ? 'picks from Macro'
+ : undefined;
+ };
+ return (
+ <Show
+ when={!needsSignIn()}
+ fallback={
+ <div
+ class={
+ props.compact
+ ? 'rounded-xl border border-edge bg-surface px-4 py-3 text-sm text-ink-muted'
+ : 'py-3 pr-2 pl-4 text-sm text-ink-muted'
+ }
+ >
+ <p>
+ “{columnFacts().name}” {needsSignIn()},
+ which needs you to sign in.
+ </p>
+ <Show
+ when={respond.problems()[question.id]}
+ >
+ {(problem) => (
+ <p
+ id={`${fieldId(scope, question.id)}-error`}
+ class="mt-1 text-xs text-failure-ink"
+ >
+ {problem()}
+ </p>
+ )}
+ </Show>
+ </div>
+ }
+ >
+ <QuestionField
+ scope={scope}
+ question={question}
+ column={columnFacts()}
+ widget={widget()}
+ number={numbers().get(question.id) ?? 0}
+ value={respond.answers()[question.id]}
+ problem={respond.problems()[question.id]}
+ disabled={answering().submitting}
+ compact={props.compact}
+ upload={upload}
+ onChange={(value) =>
+ respond.setAnswer(question.id, value)
+ }
+ renderEntityPicker={(picker) =>
+ context.ui.renderEntityPicker({
+ ...picker,
+ label: columnFacts().name,
+ value: respond.answers()[question.id],
+ onChange: (value) =>
+ respond.setAnswer(question.id, value),
+ })
+ }
+ renderRelationPicker={(picker) =>
+ context.ui.renderRelationPicker({
+ ...picker,
+ label: columnFacts().name,
+ value: respond.answers()[question.id],
+ onChange: (value) =>
+ respond.setAnswer(question.id, value),
+ })
+ }
+ />
+ </Show>
+ );
+ }}
+ </Show>
+ );
}}
+ </For>
+ </div>
+ <Show
+ when={
+ answering().section?.questions.some(
+ (question) => question.required
+ ) || editNote()
+ }
+ >
+ <div
+ role="note"
+ aria-label="Form guidance"
+ class="flex flex-wrap items-center gap-x-3 gap-y-1 px-1 pt-1 text-xs text-ink-muted"
>
- <ArrowLeft class="size-3.5" />
- Back
- </Button>
+ <Show
+ when={answering().section?.questions.some(
+ (question) => question.required
+ )}
+ >
+ <p class="inline-flex items-center gap-1.5">
+ <span class="text-failure-ink" aria-hidden="true">
+ *
+ </span>
+ <span>Required fields</span>
+ </p>
+ </Show>
+ <Show when={editNote()}>{(note) => <p>{note()}</p>}</Show>
+ </div>
</Show>
- <Button
- type="submit"
- variant="cta"
- size="md"
- disabled={answering().submitting || answering().uploading}
- aria-busy={answering().submitting}
+ <Show when={respond.failure()}>
+ {(message) => (
+ <p role="alert" class="px-1 text-sm text-failure-ink">
+ {message()}
+ </p>
+ )}
+ </Show>
+ <div
+ class={cn(
+ 'flex items-center justify-between gap-2',
+ !props.compact &&
+ 'max-sm:fixed max-sm:inset-x-0 max-sm:bottom-0 touch:max-sm:bottom-[var(--mobile-content-inset-bottom,0px)] max-sm:z-10 max-sm:border-t max-sm:border-edge max-sm:bg-surface max-sm:px-4 max-sm:py-3 max-sm:pb-[max(0.75rem,env(safe-area-inset-bottom))]'
+ )}
>
- <Show
- when={!answering().uploading}
- fallback={<>Waiting for upload…</>}
+ <Show when={!answering().isFirst} fallback={<span />}>
+ <Button
+ type="button"
+ variant="ghost"
+ size="md"
+ disabled={answering().submitting}
+ onClick={() => {
+ respond.back();
+ revealTop();
+ }}
+ >
+ <ArrowLeft class="size-3.5" />
+ Back
+ </Button>
+ </Show>
+ <Button
+ type="submit"
+ variant="cta"
+ size="md"
+ disabled={answering().submitting || answering().uploading}
+ aria-busy={answering().submitting}
>
<Show
- when={answering().isLast}
- fallback={
- <>
- Next
- <ArrowRight class="size-3.5" />
- </>
- }
+ when={!answering().uploading}
+ fallback={<>Waiting for upload…</>}
>
<Show
- when={answering().submitting}
- fallback={<PaperPlaneTilt class="size-3.5" />}
+ when={answering().isLast}
+ fallback={
+ <>
+ Next
+ <ArrowRight class="size-3.5" />
+ </>
+ }
>
- <Spinner class="size-3.5 animate-spin" />
+ <Show
+ when={answering().submitting}
+ fallback={<PaperPlaneTilt class="size-3.5" />}
+ >
+ <Spinner class="size-3.5 animate-spin" />
+ </Show>
+ {respond.editing()
+ ? 'Update response'
+ : answering().continuesToBooking
+ ? 'Continue to booking'
+ : 'Submit'}
</Show>
- {respond.editing()
- ? 'Update response'
- : answering().continuesToBooking
- ? 'Continue to booking'
- : 'Submit'}
</Show>
- </Show>
- </Button>
- </div>
- </form>
- )}
- </Match>
- </Switch>
+ </Button>
+ </div>
+ </form>
+ )}
+ </Match>
+ </Switch>
+ </div>
</div>
);
}
diff --git a/apps/web/src/features/block-form/views/responses-view.tsx b/apps/web/src/features/block-form/views/responses-view.tsx
index 560221821e..9551aa5989 100644
--- a/apps/web/src/features/block-form/views/responses-view.tsx
+++ b/apps/web/src/features/block-form/views/responses-view.tsx
@@ -1,8 +1,4 @@
-import ArrowSquareOut from '@phosphor/arrow-square-out.svg';
-import ClipboardText from '@phosphor/clipboard-text.svg';
-import DownloadSimple from '@phosphor/download-simple.svg';
-import { Button } from '@ui';
-import { createSignal, Show } from 'solid-js';
+import { Show } from 'solid-js';
import { StatTiles } from '../components/responses/stat-tiles';
import { useFormContext } from '../context/form-context';
import type { FormDetail } from '../core/form-model';
@@ -14,16 +10,9 @@ import { type ChannelReach, responseTiles } from '../core/response-stats';
* the ledger's counts above it. Every row of the table shows, not only this
* form's: filtering would hide data from the people who own it.
*/
-export function ResponsesView(props: {
- detail: FormDetail;
- onOpenDatabase: (databaseId: string) => void;
-}) {
+export function ResponsesView(props: { detail: FormDetail }) {
const context = useFormContext();
const form = () => props.detail.form;
- const table = context.createTableSource(
- () => props.detail.form.databaseId,
- () => props.detail.form.tableId
- );
const summary = context.responses.createSummary(
() => props.detail.form.id,
() => props.detail.access !== 'view'
@@ -41,54 +30,9 @@ export function ResponsesView(props: {
if (people === null) return 'none';
return people === undefined ? 'unknown' : people;
};
- const [exporting, setExporting] = createSignal(false);
-
- async function exportCsv() {
- if (exporting()) return;
- setExporting(true);
- const exported = await context.responses.exportCsv(
- form().databaseId,
- form().tableId
- );
- setExporting(false);
- if (exported.isErr())
- context.notify.failure(
- `The CSV couldn’t be exported: ${exported.error.message}`
- );
- }
-
return (
<div class="@container/responses flex size-full min-h-0 flex-col bg-canvas-base">
- <div class="flex flex-col gap-3 border-b border-edge-divider px-4 pt-4 pb-3 @2xl/responses:px-6">
- <div class="flex flex-wrap items-center gap-2">
- <h2 class="text-base font-semibold text-ink">
- {table.tableName() ?? 'Responses'}
- </h2>
- <span class="inline-flex items-center gap-1 rounded-full border border-edge-muted bg-surface px-2 py-0.5 text-xs text-ink-muted">
- <ClipboardText class="size-3.5 text-violet" aria-hidden="true" />
- Linked to {form().name}
- </span>
- <div class="ml-auto flex items-center gap-1.5">
- <Button
- variant="outline"
- size="sm"
- onClick={() => props.onOpenDatabase(form().databaseId)}
- >
- <ArrowSquareOut class="size-3.5" />
- Open database
- </Button>
- <Button
- variant="outline"
- size="sm"
- disabled={exporting()}
- aria-busy={exporting()}
- onClick={() => void exportCsv()}
- >
- <DownloadSimple class="size-3.5" />
- Export CSV
- </Button>
- </div>
- </div>
+ <div class="flex flex-col gap-3 px-4 pt-4 pb-3 @2xl/responses:px-6">
<Show
when={!summary.failure()}
fallback={
diff --git a/apps/web/src/features/block-md/component/MarkdownOutline.tsx b/apps/web/src/features/block-md/component/MarkdownOutline.tsx
index 2c060734b6..77ad8b62de 100644
--- a/apps/web/src/features/block-md/component/MarkdownOutline.tsx
+++ b/apps/web/src/features/block-md/component/MarkdownOutline.tsx
@@ -1,14 +1,7 @@
-import { HoverCard } from '@core/component/HoverCard';
+import { DocumentOutline } from '@app/components/DocumentOutline';
import { $isHeadingNode } from '@lexical/rich-text';
import { $getRoot, type LexicalEditor } from 'lexical';
-import {
- type Accessor,
- createEffect,
- createSignal,
- For,
- onCleanup,
- Show,
-} from 'solid-js';
+import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js';
type OutlineHeading = {
key: string;
@@ -138,7 +131,6 @@ export function MarkdownOutline(props: {
const [visibleHeadingKeys, setVisibleHeadingKeys] = createSignal<Set<string>>(
new Set()
);
- const [hoveredIndex, setHoveredIndex] = createSignal<number>();
const [viewportCenter, setViewportCenter] = createSignal(0);
createEffect(() => {
@@ -249,88 +241,18 @@ export function MarkdownOutline(props: {
};
return (
- <nav
- aria-label="Document outline"
- class="pointer-events-auto sticky z-1 w-7 -translate-y-1/2"
- style={{ top: `${viewportCenter()}px` }}
- >
- <div
- class="flex w-7 flex-col items-start overflow-y-auto py-1"
- style={{ 'max-height': `${Math.max(0, viewportCenter() * 2 - 32)}px` }}
- >
- <For each={props.outline.headings()}>
- {(heading, index) => {
- const active = () => visibleHeadingKeys().has(heading.key);
- const distance = () =>
- Math.abs(index() - (hoveredIndex() ?? Number.POSITIVE_INFINITY));
- const width = () => [26, 20, 14, 10][distance()] ?? 6;
- const emphasized = () =>
- hoveredIndex() === undefined ? active() : distance() === 0;
-
- return (
- <HoverCard
- closeDelay={80}
- closeOnScroll={false}
- keepOpenOnTriggerPress
- openDelay={0}
- open={hoveredIndex() === index()}
- onOpenChange={(open) => {
- setHoveredIndex((current) =>
- open ? index() : current === index() ? undefined : current
- );
- }}
- content={
- <div class="w-80 max-w-[calc(100vw-3rem)] rounded-xl border border-edge bg-surface px-3 py-2 shadow-menu">
- <div class="truncate text-sm font-medium text-ink">
- {heading.text}
- </div>
- <Show when={heading.preview}>
- <p class="mt-1 line-clamp-3 text-sm leading-relaxed text-ink-muted">
- {heading.preview}
- </p>
- </Show>
- </div>
- }
- contentZIndexClass="z-item-options-menu"
- gutter={10}
- // The preview covers the text column's left edge, including the
- // checkbox markers, so it must not take the pointer that is on
- // its way to one.
- passThroughPointerEvents
- placement="right"
- portalMount={props.portalMount()}
- trigger={
- <button
- type="button"
- aria-label={heading.text}
- aria-current={active() ? 'location' : undefined}
- class="flex h-2.5 w-7 items-center outline-none focus-visible:rounded-sm focus-visible:ring-1 focus-visible:ring-ink"
- onFocus={() => setHoveredIndex(index())}
- onBlur={() =>
- setHoveredIndex((current) =>
- current === index() ? undefined : current
- )
- }
- onClick={() => scrollToHeading(heading)}
- >
- <span
- aria-hidden="true"
- class="h-0.5 shrink-0 transition-[width,background-color] duration-150 ease-out motion-reduce:transition-none"
- classList={{
- 'bg-ink': emphasized(),
- 'bg-ink/20': !emphasized(),
- }}
- style={{ width: `${width()}px` }}
- />
- </button>
- }
- triggerClass="block w-7"
- triggerTabIndex={-1}
- />
- );
- }}
- </For>
- </div>
- </nav>
+ <DocumentOutline
+ label="Document outline"
+ items={props.outline.headings()}
+ activeKeys={visibleHeadingKeys()}
+ viewportHeight={viewportCenter() * 2}
+ portalMount={props.portalMount()}
+ onSelect={(key) => {
+ const heading = props.outline
+ .headings()
+ .find((heading) => heading.key === key);
+ if (heading) scrollToHeading(heading);
+ }}
+ />
);
}
diff --git a/docs/AGENT_GUIDE/forms.md b/docs/AGENT_GUIDE/forms.md
index d2781eab88..bd18f17304 100644
--- a/docs/AGENT_GUIDE/forms.md
+++ b/docs/AGENT_GUIDE/forms.md
@@ -32,9 +32,9 @@ decides who may respond.
## The form page
-Editors see three tabs, kept per split (a split opened with
-`params.view` `responses` or `share` starts there), with the status at the right ("Accepting responses · closes Oct 3",
-"Closed", "Table deleted"). Viewers (respondents) land on the respond page
+Editors see **Build**, **Responses** (with its count), and **Settings** in the
+shared pill tab selector beside the form title in the top bar, kept per split (a split opened with
+`params.view` `responses` or `share` starts there). Viewers (respondents) land on the respond page
instead. The header's primary button, for owners, is **Publish** (opens sharing)
until someone responds or the form is shared (public, a channel, the team),
then **Open form** (respond view in a new split); other editors always see
@@ -42,23 +42,25 @@ then **Open form** (respond view in a new split); other editors always see
### Build
-A banner at the top contains the editable form name, description, and a link
-to its database. Below, a centered column of sections holds the question rows,
-with a numbered **Outline** panel on the left and an **Add question** panel on
-the right. The outline marks the selected section or question. Question types
-use two columns of buttons, grouped as **Text & files**, **Choices**,
-**Numbers & dates**, and **Linked items**. **From database** reuses existing
-fields; **Form flow** separately holds Section, Screener, and Booking. Medium
-splits keep the palette beside the canvas. On mobile and narrow splits, a compact
-**Add question** dropdown below the canvas includes question types, existing
-database fields, and the Section, Screener, and Booking actions. Database row
-and Booking choices open dialogs that fit within the screen.
-
-- Click a question type in the right panel to add it after the selected
- question, or drag the button to an insertion line in the canvas. A drop creates
- exactly one question; Escape or dropping outside the canvas creates nothing.
- **Database row** asks which table to use before adding the question. An empty
- form accepts a question directly and creates its first section.
+Build uses the same centered 768px content column as a Markdown document.
+The editable title sits above a linked-database property pill and a read-only
+status pill ("Accepting responses", "Closed", or "Table deleted"), then the
+description.
+A compact document-style outline rail on the left previews sections and questions
+on hover and navigates to them on click. It marks the selected section or question.
+Each question section ends with a large **Add question** menu. It appends a new
+question or existing database field to that section, regardless of the current
+selection. Three visible actions sit below the canvas: **Add section** adds a
+question section directly, **Add gate** adds a screener with its inline rule editor
+open, and **Add meeting link** opens the booking-link picker (when scheduling is
+available). Hover a question boundary to reveal a plus that inserts a question
+at that position. Hover between sections to insert a **Section** or **Gate**.
+These controls also appear on keyboard focus and stay visible while their menus
+are open. Meeting links can only be added at the end; adding other sections later
+keeps the meeting link last. Start an empty form by adding a section, then its questions.
+
+- **Database row** asks which table to use before adding the question.
+ Existing questions and sections can still be reordered with their drag handles.
- After **Section** (or
focusing a section's title, which outlines it) it goes to the end of that
section. An empty section has its own **Add question** menu.
@@ -86,9 +88,6 @@ and Booking choices open dialogs that fit within the screen.
Rules are sent to respondents' browsers, so keep confidential criteria out.
A gate whose rule tests a question that is gone shows **Remove broken
rules**.
-- The right panel's **Section** and **Screener** controls can also be dragged directly
- into the canvas. The insertion line shows where the new section will go;
- dropping outside the canvas or pressing Escape leaves the form unchanged.
- "N columns not on this form" at the bottom lists table columns that are not
questions; **Add** puts one on the form.
- Layout edits collaborate live through Loro. Other editors' selections appear
@@ -99,13 +98,15 @@ and Booking choices open dialogs that fit within the screen.
question**: a new column gets the answers that convert and the question
moves to it; the old column stays (listed under columns not on the form).
- **Preview** opens a new tab with the respondent experience after pending
- question and Share settings edits are saved, including edits started before
+ question and form settings edits are saved, including edits started before
switching tabs. Fill it, try the screeners, and return to the builder. Preview
creates no response rows, file uploads or bookings.
On touch devices, Preview, Publish (or Open form), and Share are in the
floating header above the editor.
-- **Booking** in the right panel selects an existing booking link from **Booking links**
- settings. It is always the last step. **Change** selects another link;
+- **Add meeting link** selects an existing booking link from **Booking links**
+ settings, or opens settings to create one. It is always the last step. Once added,
+ the action becomes **View meeting link** and focuses the existing step rather than
+ adding a duplicate. **Change** selects another link;
**Remove booking step** leaves the link itself intact. A form's screeners
control when its respondents see the link; the native link still works directly.
- New standalone forms share their name with the database they create. Rename
@@ -113,8 +114,7 @@ and Booking choices open dialogs that fit within the screen.
### Responses
-The linked table's grid, embedded and live, with **Open database**, **Export
-CSV** and tiles: Responses, Stopped submissions (per screener in its hint), Rows in
+The linked table's grid, embedded and live, with summary tiles: Responses, Stopped submissions (per screener in its hint), Rows in
the table, and (owners, when posted in channels) People in its channels (the
owner excluded; a dash for public forms). Every row of the table shows,
including rows added in the grid. Stopped submissions counts signed-in respondents
@@ -122,7 +122,7 @@ whose latest recorded result is stopped. Retrying does not add another count;
a successful submission clears that stop. Anonymous attempts and stops before
submitting are not recorded; answers stay in the browser until Submit.
-### Share
+### Settings
**Who can respond**: Invited people (sign in, one response each, editable
while open) or Anyone with the link (anonymous; no file questions). The
@@ -152,7 +152,10 @@ while still checking, or when the check failed, instead of saying nothing).
it inside the app shell (sidebar, command menu); anonymous visitors get a
focused page, so a public form never hits login. Signed in, a respondent
keeps their identity on either audience and can edit their response while the
-form is open; anonymous visitors cannot. One section per screen with
+form is open; anonymous visitors cannot. The response page has no top bar:
+it uses the builder’s centered 768px content column, plain title and description,
+and questions grouped within a single section card. Public sign-in guidance
+sits below the form. One section per screen with
**Back / Next**, **Submit** on the last. Required fields keep their asterisks;
the legend and response-editing guidance sit below the questions. Next checks required answers and any
gate locally; a failing gate shows "This form can't take your response" with