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(database): streamline navigation and grid layout (#7750)

teo073371cda04d
diff --git a/apps/web/src/components/ui/components/TabSelector.docs.tsx b/apps/web/src/components/ui/components/TabSelector.docs.tsx
new file mode 100644
index 0000000000..249af624d8
--- /dev/null
+++ b/apps/web/src/components/ui/components/TabSelector.docs.tsx
@@ -0,0 +1,56 @@
+import { defineDoc } from '@app/features/ui-gallery/types';
+import { Tabs } from '@kobalte/core/tabs';
+import { createSignal, For } from 'solid-js';
+import { Dropdown } from './Dropdown';
+import { TabSelector } from './TabSelector';
+import { Tooltip } from './Tooltip';
+
+// #region demo:overflow
+function OverflowDemo() {
+ const [selected, setSelected] = createSignal('Authors');
+ return (
+ <TabSelector class="w-72 max-w-full">
+ <Tabs
+ value={selected()}
+ onChange={setSelected}
+ activationMode="manual"
+ class="min-w-0"
+ >
+ <TabSelector.List aria-label="Example tables">
+ <For each={['Authors', 'Books', 'Reading log', 'Recommendations']}>
+ {(name) => (
+ <Tooltip label={name}>
+ <TabSelector.Tab value={name}>
+ <span class="truncate">{name}</span>
+ </TabSelector.Tab>
+ </Tooltip>
+ )}
+ </For>
+ </TabSelector.List>
+ </Tabs>
+ <TabSelector.AddMenu label="Add table or form">
+ <Dropdown.Item>New table</Dropdown.Item>
+ <Dropdown.Item>New form</Dropdown.Item>
+ </TabSelector.AddMenu>
+ </TabSelector>
+ );
+}
+// #endregion
+
+export default defineDoc({
+ name: 'TabSelector',
+ category: 'Navigation',
+ description:
+ 'Inset tabs with horizontal scrolling and a fixed add menu. Compose the track with Kobalte Tabs; keep AddMenu outside the tab collection.',
+ exports: ['TabSelector'],
+ import: "import { TabSelector } from '@ui';",
+ demos: [
+ {
+ id: 'overflow',
+ title: 'Overflow and add menu',
+ description:
+ 'Use a trackpad, mouse wheel, or the arrow buttons to scroll. Keyboard focus reveals offscreen tabs, and the add menu stays at the right edge.',
+ render: OverflowDemo,
+ },
+ ],
+});
diff --git a/apps/web/src/components/ui/components/TabSelector.test.tsx b/apps/web/src/components/ui/components/TabSelector.test.tsx
new file mode 100644
index 0000000000..de75cdd819
--- /dev/null
+++ b/apps/web/src/components/ui/components/TabSelector.test.tsx
@@ -0,0 +1,96 @@
+import { Tabs } from '@kobalte/core/tabs';
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { Dropdown } from './Dropdown';
+import { TabSelector } from './TabSelector';
+
+beforeEach(() => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+ vi.stubGlobal('scrollTo', vi.fn());
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+it('keeps add actions separate from the tab selection', async () => {
+ const select = vi.fn();
+ const create = vi.fn();
+ render(() => (
+ <TabSelector>
+ <Tabs value="books" onChange={select}>
+ <TabSelector.List aria-label="Tables">
+ <TabSelector.Tab value="books">Books</TabSelector.Tab>
+ </TabSelector.List>
+ </Tabs>
+ <TabSelector.AddMenu label="Add">
+ <Dropdown.Item onSelect={create}>New table</Dropdown.Item>
+ </TabSelector.AddMenu>
+ </TabSelector>
+ ));
+ fireEvent.keyDown(screen.getByRole('button', { name: 'Add' }), {
+ key: 'Enter',
+ });
+ fireEvent.keyDown(
+ await screen.findByRole('menuitem', { name: 'New table' }),
+ { key: 'Enter' }
+ );
+ expect(create).toHaveBeenCalledOnce();
+ expect(select).not.toHaveBeenCalled();
+});
+
+it('scrolls with the wheel and arrows without moving the add menu', async () => {
+ render(() => (
+ <TabSelector>
+ <Tabs value="books">
+ <TabSelector.List aria-label="Tables">
+ <TabSelector.Tab value="books">Books</TabSelector.Tab>
+ </TabSelector.List>
+ </Tabs>
+ <TabSelector.AddMenu label="Add">
+ <Dropdown.Item>New table</Dropdown.Item>
+ </TabSelector.AddMenu>
+ </TabSelector>
+ ));
+ const rail = screen.getByRole('tablist');
+ Object.defineProperties(rail, {
+ clientWidth: { value: 100 },
+ scrollWidth: { value: 400 },
+ });
+ fireEvent.scroll(rail);
+ await screen.findByRole('button', { name: 'Scroll tabs right' });
+ expect(
+ screen
+ .getByRole('button', { name: 'Scroll tabs left' })
+ .hasAttribute('disabled')
+ ).toBe(true);
+ fireEvent.click(screen.getByRole('button', { name: 'Scroll tabs right' }));
+ expect(rail.scrollLeft).toBe(75);
+ fireEvent.wheel(rail, { deltaY: 50 });
+ expect(rail.scrollLeft).toBe(125);
+ rail.scrollLeft = 300;
+ fireEvent.scroll(rail);
+ await waitFor(() =>
+ expect(
+ screen
+ .getByRole('button', { name: 'Scroll tabs right' })
+ .hasAttribute('disabled')
+ ).toBe(true)
+ );
+ expect(rail.contains(screen.getByRole('button', { name: 'Add' }))).toBe(
+ false
+ );
+});
diff --git a/apps/web/src/components/ui/components/TabSelector.tsx b/apps/web/src/components/ui/components/TabSelector.tsx
new file mode 100644
index 0000000000..989a11d319
--- /dev/null
+++ b/apps/web/src/components/ui/components/TabSelector.tsx
@@ -0,0 +1,184 @@
+import { Tabs } from '@kobalte/core/tabs';
+import CaretLeft from '@phosphor/caret-left.svg';
+import CaretRight from '@phosphor/caret-right.svg';
+import Plus from '@phosphor/plus.svg';
+import { createResizeObserver } from '@solid-primitives/resize-observer';
+import {
+ type ComponentProps,
+ createSignal,
+ onCleanup,
+ onMount,
+ type ParentProps,
+ Show,
+ splitProps,
+} from 'solid-js';
+import { cn } from '../utils/classname';
+import { Button } from './Button';
+import { Dropdown } from './Dropdown';
+import { Layer } from './Layer';
+
+export type TabSelectorProps = ParentProps<{ class?: string }>;
+
+/**
+ * Inset navigation with a scrollable track and a fixed, independently focused add menu.
+ * @do Compose List and Tab inside Kobalte Tabs to retain keyboard navigation and selection semantics.
+ * @do Give List an accessible label and provide tooltips for truncated tab names.
+ * @dont Put AddMenu inside the tab collection; keep it beside Tabs so it remains independently focusable.
+ */
+export function TabSelector(props: TabSelectorProps) {
+ return (
+ <Layer depth={0}>
+ <div
+ class={cn(
+ 'flex min-w-0 items-center rounded-full border border-edge-muted bg-surface p-0.5',
+ props.class
+ )}
+ >
+ {props.children}
+ </div>
+ </Layer>
+ );
+}
+
+function List(props: ComponentProps<typeof Tabs.List>) {
+ const [local, rest] = splitProps(props, ['ref', 'class', 'children']);
+ const [rail, setRail] = createSignal<HTMLDivElement>();
+ const [left, setLeft] = createSignal(false);
+ const [right, setRight] = createSignal(false);
+ const measure = () => {
+ const element = rail();
+ if (!element) return;
+ setLeft(element.scrollLeft > 1);
+ setRight(
+ element.scrollLeft + element.clientWidth < element.scrollWidth - 1
+ );
+ };
+ const scroll = (direction: number) => {
+ const element = rail();
+ if (element) element.scrollLeft += direction * element.clientWidth * 0.75;
+ };
+ createResizeObserver(rail, measure);
+ onMount(() => {
+ const element = rail();
+ if (!element) return;
+ const observer = new MutationObserver(measure);
+ observer.observe(element, {
+ childList: true,
+ subtree: true,
+ characterData: true,
+ });
+ onCleanup(() => observer.disconnect());
+ measure();
+ });
+ return (
+ <div class="flex min-w-0 items-center">
+ <Show when={left() || right()}>
+ <Button
+ size="icon-sm"
+ label="Scroll tabs left"
+ class="shrink-0 rounded-full"
+ disabled={!left()}
+ onClick={() => scroll(-1)}
+ >
+ <CaretLeft class="size-3" />
+ </Button>
+ </Show>
+ <Tabs.List
+ {...rest}
+ ref={(element) => {
+ setRail(element);
+ if (typeof local.ref === 'function') local.ref(element);
+ }}
+ class={cn(
+ 'relative flex min-w-0 items-center gap-0.5 overflow-x-auto overscroll-x-contain [scrollbar-width:none] [&::-webkit-scrollbar]:hidden',
+ local.class
+ )}
+ onScroll={measure}
+ onWheel={(event: WheelEvent & { currentTarget: HTMLDivElement }) => {
+ const element = event.currentTarget;
+ if (
+ event.ctrlKey ||
+ event.metaKey ||
+ event.deltaX ||
+ !event.deltaY ||
+ element.scrollWidth <= element.clientWidth
+ )
+ return;
+ const before = element.scrollLeft;
+ element.scrollLeft += event.deltaY;
+ if (element.scrollLeft !== before) event.preventDefault();
+ }}
+ onFocusIn={(event) => {
+ const element = event.target.closest<HTMLElement>(
+ '[role="tab"], input'
+ );
+ if (!element) return;
+ const viewport = event.currentTarget.getBoundingClientRect();
+ const item = element.getBoundingClientRect();
+ if (item.left < viewport.left)
+ event.currentTarget.scrollLeft += item.left - viewport.left;
+ else if (item.right > viewport.right)
+ event.currentTarget.scrollLeft += item.right - viewport.right;
+ }}
+ >
+ {local.children}
+ </Tabs.List>
+ <Show when={left() || right()}>
+ <Button
+ size="icon-sm"
+ label="Scroll tabs right"
+ class="shrink-0 rounded-full"
+ disabled={!right()}
+ onClick={() => scroll(1)}
+ >
+ <CaretRight class="size-3" />
+ </Button>
+ </Show>
+ </div>
+ );
+}
+
+function Tab(props: ComponentProps<typeof Tabs.Trigger>) {
+ const [local, rest] = splitProps(props, ['class']);
+ return (
+ <Layer depth={2}>
+ <Tabs.Trigger
+ {...rest}
+ class={cn(
+ 'relative flex max-w-40 shrink-0 items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium text-ink-extra-muted outline-none hover:text-ink focus-visible:ring-2 focus-visible:ring-accent/50 data-selected:bg-surface data-selected:text-ink data-selected:ring data-selected:ring-inset data-selected:ring-edge-muted data-selected:shadow-sm',
+ local.class
+ )}
+ />
+ </Layer>
+ );
+}
+
+function AddMenu(
+ props: ParentProps<{
+ label: string;
+ ref?: (element: HTMLButtonElement) => void;
+ onCloseAutoFocus?: (event: Event) => void;
+ }>
+) {
+ return (
+ <div class="ml-0.5 shrink-0 pl-0.5">
+ <Dropdown>
+ <Dropdown.Trigger
+ ref={props.ref}
+ size="icon-sm"
+ class="rounded-full"
+ aria-label={props.label}
+ >
+ <Plus class="size-3.5" />
+ </Dropdown.Trigger>
+ <Dropdown.Content onCloseAutoFocus={props.onCloseAutoFocus}>
+ {props.children}
+ </Dropdown.Content>
+ </Dropdown>
+ </div>
+ );
+}
+
+TabSelector.List = List;
+TabSelector.Tab = Tab;
+TabSelector.AddMenu = AddMenu;
diff --git a/apps/web/src/components/ui/index.ts b/apps/web/src/components/ui/index.ts
index 2d7acddcf3..af16f65b68 100644
--- a/apps/web/src/components/ui/index.ts
+++ b/apps/web/src/components/ui/index.ts
@@ -156,6 +156,7 @@ export { SendButton } from './components/SendButton';
export { SideNav } from './components/SideNav';
export { Surface } from './components/Surface';
export { TabbedControl } from './components/TabbedControl';
+export { TabSelector } from './components/TabSelector';
export type { TabItem, TabsProps } from './components/Tabs';
export { Tabs } from './components/Tabs';
export { TagDot, type TagDotProps, type TagDotSize } from './components/TagDot';
diff --git a/apps/web/src/features/block-database/component/Block.tsx b/apps/web/src/features/block-database/component/Block.tsx
index 925043fc8f..7b4a491ac3 100644
--- a/apps/web/src/features/block-database/component/Block.tsx
+++ b/apps/web/src/features/block-database/component/Block.tsx
@@ -14,7 +14,7 @@ import { useBlockId } from '@core/block';
import { DATABASE_MODEL, modelsForPlan } from '@core/component/AI/constant';
import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
import { toast } from '@core/component/Toast/Toast';
-import { enableDatabases, enableForms } from '@core/constant/featureFlags';
+import { enableDatabases } from '@core/constant/featureFlags';
import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';
import { useUserId } from '@core/context/user';
import { registerHotkey } from '@core/hotkey/hotkeys';
@@ -38,20 +38,15 @@ import {
createSignal,
ErrorBoundary,
For,
- lazy,
onCleanup,
Show,
- Suspense,
} from 'solid-js';
import { match } from 'ts-pattern';
import { DatabaseSearch } from '../../database/components/database-search';
import type { ShownLayout } from '../../database/components/database-toolbar';
import { DatabaseToolbar } from '../../database/components/database-toolbar';
-import type {
- NewFormChoice,
- NewView,
-} from '../../database/components/new-view-dialog';
import type { DatabaseRelatedDestination } from '../../database/core/database-relations';
+import type { NewView } from '../../database/core/view-creation';
import type { ViewChange } from '../../database/core/view-state';
import { allRecordsView, boardLayout } from '../../database/core/views';
import { databaseOpMessage } from '../../database/core/write-failure';
@@ -75,12 +70,6 @@ import { DatabasePageShell } from './DatabasePageShell';
import { DatabaseSidePanelSections } from './sidepanel/DatabaseSidePanelSections';
import { TopBar } from './TopBar';
-// Forms load only when the flag is on, and only through this boundary.
-const DatabaseFormCreation = lazy(async () => ({
- default: (await import('@app/features/block-form/database-forms-entry'))
- .DatabaseFormCreation,
-}));
-
const Block: Component = () => {
const databaseId = useBlockId();
const panel = useSplitPanelOrThrow();
@@ -199,8 +188,6 @@ const Block: Component = () => {
() => detail()?.grant === 'edit' || detail()?.grant === 'owner'
);
const columns = () => activeTable()?.columns.map(toViewColumn) ?? [];
- const formsFlag = useFeatureFlag(enableForms);
- const [newForm, setNewForm] = createSignal<NewFormChoice>();
const creations = createViewCreation();
const storedViews = () => {
const drafts = creations
@@ -340,17 +327,6 @@ const Block: Component = () => {
databaseId={databaseId}
database={detail()?.database}
/>
- <Show when={formsFlag().enabled}>
- <Suspense>
- <DatabaseFormCreation
- databaseId={databaseId}
- tableId={activeTableId()}
- tableName={activeTable()?.table.name}
- isOwner={detail()?.grant === 'owner'}
- onChoice={setNewForm}
- />
- </Suspense>
- </Show>
<TopBar
databaseId={databaseId}
detail={detail()}
@@ -503,7 +479,6 @@ const Block: Component = () => {
view={shown().view}
selectedViewId={selectedView()?.id}
canEdit={canEdit() && !activeCreation()}
- newForm={newForm()}
search={
<DatabaseSearch
term={search.term()}
diff --git a/apps/web/src/features/block-database/component/DatabaseGrid.tsx b/apps/web/src/features/block-database/component/DatabaseGrid.tsx
index c01b83b242..eb6d7061b5 100644
--- a/apps/web/src/features/block-database/component/DatabaseGrid.tsx
+++ b/apps/web/src/features/block-database/component/DatabaseGrid.tsx
@@ -314,6 +314,7 @@ function TableAdapter(props: DatabaseGridProps & { tableId: string }) {
inferNewColumns
>
<DatabaseRecords
+ contentClass="mx-4 mb-4 mt-1 rounded-xl border border-edge-muted"
view={props.view}
stored={props.stored}
preparingView={props.preparingView}
diff --git a/apps/web/src/features/block-database/component/DatabasePageShell.tsx b/apps/web/src/features/block-database/component/DatabasePageShell.tsx
index c8bb312567..2274f42e85 100644
--- a/apps/web/src/features/block-database/component/DatabasePageShell.tsx
+++ b/apps/web/src/features/block-database/component/DatabasePageShell.tsx
@@ -2,14 +2,16 @@ import { SidePanel } from '@components/app/side-panel';
import type { ParentProps } from 'solid-js';
/**
- * The database page inside its block container, beside its side panel. One
+ * The database page inside its block container, with a floating details panel. One
* element: the side panel layout renders several roots, and the container
* marks only a single element as the block.
*/
export function DatabasePageShell(props: ParentProps) {
return (
<div class="relative flex size-full min-h-0 flex-col overflow-hidden">
- <SidePanel.Layout defaultOpen={false}>{props.children}</SidePanel.Layout>
+ <SidePanel.Layout defaultOpen={false} floating>
+ {props.children}
+ </SidePanel.Layout>
</div>
);
}
diff --git a/apps/web/src/features/block-database/component/TableTabs.tsx b/apps/web/src/features/block-database/component/TableTabs.tsx
index 43574f99e8..d76483454e 100644
--- a/apps/web/src/features/block-database/component/TableTabs.tsx
+++ b/apps/web/src/features/block-database/component/TableTabs.tsx
@@ -2,6 +2,7 @@ import { toast } from '@core/component/Toast/Toast';
import { applyDatabaseOps } from '@queries/storage/databases';
import type { TableDetail } from '@service-storage/generated/schemas/tableDetail';
import { ResultAsync } from 'neverthrow';
+import type { JSX } from 'solid-js';
import { TableNavigation } from '../../database/components/table-navigation';
import {
tableDeleteMessage,
@@ -18,6 +19,7 @@ export function TableTabs(props: {
tables: TableDetail[];
activeTableId: string | undefined;
canEdit: boolean;
+ menuItems?: () => JSX.Element;
onSelect: (tableId: string) => void;
}) {
const formsOver = useFormsOverTables(() => props.databaseId);
@@ -32,6 +34,7 @@ export function TableTabs(props: {
}))}
activeTableId={props.activeTableId}
canCreate={props.canEdit}
+ menuItems={props.menuItems}
onSelect={props.onSelect}
onRename={(tableId, name, previousName) =>
ResultAsync.fromSafePromise(
diff --git a/apps/web/src/features/block-database/component/TopBar.tsx b/apps/web/src/features/block-database/component/TopBar.tsx
index 23cb2b3004..7132c11961 100644
--- a/apps/web/src/features/block-database/component/TopBar.tsx
+++ b/apps/web/src/features/block-database/component/TopBar.tsx
@@ -5,10 +5,6 @@ import {
SplitHeaderRight,
} from '@components/app/split-layout/components/SplitHeader';
import { BlockItemSplitLabel } from '@components/app/split-layout/components/SplitLabel';
-import {
- SplitToolbarLeft,
- SplitToolbarRight,
-} from '@components/app/split-layout/components/SplitToolbar';
import { BlockLiveIndicators } from '@core/component/LiveIndicators';
import { toast } from '@core/component/Toast/Toast';
import { ShareTrigger } from '@core/component/TopBar/ShareButton';
@@ -102,6 +98,43 @@ export function TopBar(props: {
</Show>
}
/>
+ <Show when={props.detail}>
+ {(detail) => (
+ <>
+ <DatabasePageActions
+ detail={detail()}
+ table={props.activeTable}
+ onRename={() => editTitle?.()}
+ onDelete={props.onDelete}
+ onImported={props.onSelectTable}
+ />
+ <div class="ml-2 min-w-0 max-w-xl shrink">
+ <TableTabs
+ databaseId={databaseId}
+ tables={detail().tables}
+ activeTableId={props.activeTable?.table.id}
+ canEdit={props.canEdit}
+ onSelect={props.onSelectTable}
+ menuItems={
+ formsFlag().enabled && props.activeTable
+ ? () => (
+ <Suspense>
+ <DatabaseFormsEntry
+ databaseId={databaseId}
+ tableId={props.activeTable?.table.id}
+ tableName={props.activeTable?.table.name}
+ canCreate={props.detail?.grant === 'owner'}
+ enabled
+ />
+ </Suspense>
+ )
+ : undefined
+ }
+ />
+ </div>
+ </>
+ )}
+ </Show>
</SplitHeaderLeft>
<SplitHeaderRight>
<BlockLiveIndicators />
@@ -111,51 +144,20 @@ export function TopBar(props: {
</SplitHeaderRight>
<ResponsivePermissionsBadge />
<Show when={props.detail}>
- {(detail) => (
- <>
- <SplitToolbarLeft class="min-w-0">
- <TableTabs
- databaseId={databaseId}
- tables={detail().tables}
- activeTableId={props.activeTable?.table.id}
- canEdit={props.canEdit}
- onSelect={props.onSelectTable}
- />
- <Show when={formsFlag().enabled}>
- <Suspense>
- <DatabaseFormsEntry
- databaseId={databaseId}
- tableId={props.activeTable?.table.id}
- tableName={props.activeTable?.table.name}
- canCreate={props.detail?.grant === 'owner'}
- enabled
- />
- </Suspense>
- </Show>
- </SplitToolbarLeft>
- <SplitToolbarRight>
- <DatabasePageActions
- detail={detail()}
- table={props.activeTable}
- onRename={() => editTitle?.()}
- onDelete={props.onDelete}
- onImported={props.onSelectTable}
- />
- <Button
- variant="ghost"
- size="sm"
- class="gap-1.5 px-2 text-xs"
- disabled={props.openingChat}
- aria-label="Database AI"
- aria-busy={props.openingChat}
- onClick={props.onOpenChat}
- >
- <SparkleIcon class="size-4" />
- <span>AI</span>
- </Button>
- </SplitToolbarRight>
- </>
- )}
+ <SplitHeaderRight>
+ <Button
+ variant="ghost"
+ size="sm"
+ class="gap-1.5 px-2 text-xs"
+ disabled={props.openingChat}
+ aria-label="Database AI"
+ aria-busy={props.openingChat}
+ onClick={props.onOpenChat}
+ >
+ <SparkleIcon class="size-4" />
+ <span>AI</span>
+ </Button>
+ </SplitHeaderRight>
</Show>
</>
);
diff --git a/apps/web/src/features/block-form/database-forms-entry.test.tsx b/apps/web/src/features/block-form/database-forms-entry.test.tsx
index 0b5d814b3a..40ab9fa992 100644
--- a/apps/web/src/features/block-form/database-forms-entry.test.tsx
+++ b/apps/web/src/features/block-form/database-forms-entry.test.tsx
@@ -1,11 +1,10 @@
import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { Dropdown } from '@ui/components/Dropdown';
import { okAsync } from 'neverthrow';
-import { createRoot } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
DatabaseFormEditors,
DatabaseFormsEntry,
- useTableFormCreation,
} from './database-forms-entry';
const forms = vi.hoisted(() => ({
@@ -28,8 +27,12 @@ vi.mock('@app/signal/splitLayout', () => ({
globalSplitManager: () => ({ openWithSplit }),
}));
-afterEach(cleanup);
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
beforeEach(() => {
+ vi.stubGlobal('scrollTo', vi.fn());
forms.listed = [];
forms.createForm.mockReset();
replaceOrInsertSplit.mockReset();
@@ -41,24 +44,24 @@ describe('DatabaseFormsEntry', () => {
{ id: 'form-1', name: 'RSVP', tableId: 'table-1', status: 'open' },
];
render(() => (
- <DatabaseFormsEntry
- databaseId="database-1"
- tableId="table-1"
- tableName="Guests"
- canCreate
- enabled
- />
+ <Dropdown open>
+ <Dropdown.Trigger>Add</Dropdown.Trigger>
+ <Dropdown.Content>
+ <DatabaseFormsEntry
+ databaseId="database-1"
+ tableId="table-1"
+ tableName="Guests"
+ canCreate
+ enabled
+ />
+ </Dropdown.Content>
+ </Dropdown>
));
- const trigger = screen.getByRole('button', { name: 'Forms over Guests' });
- trigger.focus();
- fireEvent.keyDown(trigger, { key: 'ArrowDown' });
const form = await screen.findByRole('menuitem', { name: 'RSVP Open' });
expect(
screen.getByRole('group', { name: 'Forms writing to Guests' })
).toBeTruthy();
- expect(
- screen.queryByRole('menuitem', { name: 'New form from this table' })
- ).toBeNull();
+ expect(screen.queryByRole('menuitem', { name: 'New form' })).toBeNull();
form.focus();
fireEvent.keyDown(form, { key: 'Enter' });
expect(replaceOrInsertSplit).toHaveBeenCalledWith({
@@ -67,95 +70,74 @@ describe('DatabaseFormsEntry', () => {
});
});
- it('offers + Form to the database owner when no form writes to the table', () => {
+ it('creates a form over the current table from the add menu', async () => {
+ forms.createForm.mockReturnValue(okAsync({ form: { id: 'form-new' } }));
render(() => (
- <DatabaseFormsEntry
- databaseId="database-1"
- tableId="table-1"
- tableName="Guests"
- canCreate
- enabled
- />
+ <Dropdown open>
+ <Dropdown.Trigger>Add</Dropdown.Trigger>
+ <Dropdown.Content>
+ <DatabaseFormsEntry
+ databaseId="database-1"
+ tableId="table-1"
+ tableName="Guests"
+ canCreate
+ enabled
+ />
+ </Dropdown.Content>
+ </Dropdown>
));
- expect(screen.getByRole('button', { name: /Form/ })).toBeTruthy();
+ const create = screen.getByRole('menuitem', { name: 'New form' });
+ fireEvent.keyDown(create, { key: 'Enter' });
+ expect(forms.createForm).toHaveBeenCalledWith(
+ {
+ name: 'Guests form',
+ source: { kind: 'table', databaseId: 'database-1', tableId: 'table-1' },
+ },
+ 'database'
+ );
+ await vi.waitFor(() =>
+ expect(replaceOrInsertSplit).toHaveBeenCalledWith({
+ type: 'form',
+ id: 'form-new',
+ })
+ );
});
it('offers editors no creation, but keeps the forms that exist', () => {
const { unmount } = render(() => (
- <DatabaseFormsEntry
- databaseId="database-1"
- tableId="table-1"
- tableName="Guests"
- canCreate={false}
- enabled
- />
+ <Dropdown open>
+ <Dropdown.Trigger>Add</Dropdown.Trigger>
+ <Dropdown.Content>
+ <DatabaseFormsEntry
+ databaseId="database-1"
+ tableId="table-1"
+ tableName="Guests"
+ canCreate={false}
+ enabled
+ />
+ </Dropdown.Content>
+ </Dropdown>
));
- expect(screen.queryByRole('button')).toBeNull();
+ expect(screen.queryByRole('menuitem', { name: 'New form' })).toBeNull();
unmount();
forms.listed = [
{ id: 'form-1', name: 'RSVP', tableId: 'table-1', status: 'open' },
];
render(() => (
- <DatabaseFormsEntry
- databaseId="database-1"
- tableId="table-1"
- tableName="Guests"
- canCreate={false}
- enabled
- />
+ <Dropdown open>
+ <Dropdown.Trigger>Add</Dropdown.Trigger>
+ <Dropdown.Content>
+ <DatabaseFormsEntry
+ databaseId="database-1"
+ tableId="table-1"
+ tableName="Guests"
+ canCreate={false}
+ enabled
+ />
+ </Dropdown.Content>
+ </Dropdown>
));
- expect(
- screen.getByRole('button', { name: 'Forms over Guests' }).textContent
- ).toContain('1 form');
- });
-});
-
-describe('useTableFormCreation', () => {
- it('gives owners a Form choice that creates over the table and opens it', async () => {
- forms.createForm.mockReturnValue(
- okAsync({ form: { id: 'form-new', name: 'RSVP' } })
- );
- await createRoot(async (dispose) => {
- const choice = useTableFormCreation({
- databaseId: () => 'database-1',
- tableId: () => 'table-1',
- tableName: () => 'Guests',
- isOwner: () => true,
- enabled: () => true,
- });
- expect(choice()?.initialName).toBe('Guests form');
- expect(await choice()?.onCreate('RSVP')).toBeUndefined();
- expect(forms.createForm).toHaveBeenCalledWith(
- {
- name: 'RSVP',
- source: {
- kind: 'table',
- databaseId: 'database-1',
- tableId: 'table-1',
- },
- },
- 'database'
- );
- expect(replaceOrInsertSplit).toHaveBeenCalledWith({
- type: 'form',
- id: 'form-new',
- });
- dispose();
- });
- });
-
- it('gives editors no Form choice', () => {
- createRoot((dispose) => {
- const choice = useTableFormCreation({
- databaseId: () => 'database-1',
- tableId: () => 'table-1',
- tableName: () => 'Guests',
- isOwner: () => false,
- enabled: () => true,
- });
- expect(choice()).toBeUndefined();
- dispose();
- });
+ expect(screen.getByRole('menuitem', { name: 'RSVP Open' })).toBeTruthy();
});
});
diff --git a/apps/web/src/features/block-form/database-forms-entry.tsx b/apps/web/src/features/block-form/database-forms-entry.tsx
index 8260469f4e..355db7e693 100644
--- a/apps/web/src/features/block-form/database-forms-entry.tsx
+++ b/apps/web/src/features/block-form/database-forms-entry.tsx
@@ -1,7 +1,6 @@
/**
- * App adapter for the database page (RFC 02 §7): a "Forms" chip after the
- * table tabs listing the forms over the current table, and the creation of a
- * form over the table, offered here and in the "+ view" dialog. Creating
+ * App adapter for the database page (RFC 02 §7): the table selector’s add menu
+ * lists forms over the current table and offers form creation. Creating
* over an existing table needs database Owner; editors and viewers keep
* navigation to the forms that exist. Mounted only while forms are on.
*/
@@ -9,17 +8,9 @@ import { globalSplitManager } from '@app/signal/splitLayout';
import { useSplitLayout } from '@components/app/split-layout/layout';
import { toast } from '@core/component/Toast/Toast';
import ClipboardText from '@phosphor/clipboard-text.svg';
-import Plus from '@phosphor/plus.svg';
import { createForm, useFormsForDatabaseQuery } from '@queries/storage/forms';
import { Dropdown } from '@ui';
-import {
- type Accessor,
- createRenderEffect,
- createSignal,
- For,
- onCleanup,
- Show,
-} from 'solid-js';
+import { createSignal, For, Show } from 'solid-js';
/** Make a form over an existing table and open it; resolves why it was refused, if it was. */
async function createFormOverTable(
@@ -45,66 +36,6 @@ async function createFormOverTable(
return undefined;
}
-/**
- * The "+ view" dialog's Form choice: offered to the database's owner while
- * no form writes to the table. Each table has at most one form.
- */
-export function useTableFormCreation(props: {
- databaseId: Accessor<string>;
- tableId: Accessor<string | undefined>;
- tableName: Accessor<string | undefined>;
- isOwner: Accessor<boolean>;
- enabled: Accessor<boolean>;
-}): Accessor<NewFormChoice | undefined> {
- const { replaceOrInsertSplit } = useSplitLayout();
- const forms = useFormsForDatabaseQuery(() =>
- props.enabled() && props.isOwner() ? props.databaseId() : undefined
- );
- return () => {
- const tableId = props.tableId();
- if (!props.enabled() || !props.isOwner() || !tableId || !forms.isSuccess)
- return undefined;
- if (forms.data.some((form) => form.tableId === tableId)) return undefined;
- return {
- initialName: `${props.tableName() ?? 'Table'} form`,
- onCreate: (name) =>
- createFormOverTable(
- { databaseId: props.databaseId(), tableId, name },
- (formId) => replaceOrInsertSplit({ type: 'form', id: formId })
- ),
- };
- };
-}
-
-type NewFormChoice = {
- initialName: string;
- onCreate: (name: string) => Promise<string | undefined>;
-};
-
-/**
- * Hands the database page its "+ view" Form choice, so the page reaches
- * this feature only through a lazy import. Renders nothing.
- */
-export function DatabaseFormCreation(props: {
- databaseId: string;
- tableId: string | undefined;
- tableName: string | undefined;
- isOwner: boolean;
- onChoice: (choice: NewFormChoice | undefined) => void;
-}) {
- const choice = useTableFormCreation({
- databaseId: () => props.databaseId,
- tableId: () => props.tableId,
- tableName: () => props.tableName,
- isOwner: () => props.isOwner,
- enabled: () => true,
- });
- // Syncing out to the page that mounted this, not deriving local state.
- createRenderEffect(() => props.onChoice(choice()));
- onCleanup(() => props.onChoice(undefined));
- return null;
-}
-
/**
* The database share dialog's note on derived access (RFC 02 §6): each
* form's editors hold Edit on this database, revoked from the form.
@@ -163,7 +94,13 @@ function DatabaseFormsMenu(props: {
? forms.data.filter((form) => form.tableId === props.tableId)
: [];
async function createFromTable() {
- if (creating() || !forms.isSuccess || onTable().length > 0) return;
+ if (
+ !props.canCreate ||
+ creating() ||
+ !forms.isSuccess ||
+ onTable().length > 0
+ )
+ return;
setCreating(true);
const refusal = await createFormOverTable(
{
@@ -180,54 +117,49 @@ function DatabaseFormsMenu(props: {
<Show
when={onTable().length > 0}
fallback={
- <Show when={props.canCreate && forms.isSuccess}>
- <button
- type="button"
+ <Show
+ when={props.canCreate && forms.isSuccess}
+ fallback={
+ <Dropdown.Item disabled>
+ {forms.isError
+ ? 'Could not load forms'
+ : forms.isSuccess
+ ? 'No forms for this table'
+ : 'Loading forms…'}
+ </Dropdown.Item>
+ }
+ >
+ <Dropdown.Item
disabled={creating()}
- aria-busy={creating()}
- class="ml-1 inline-flex h-7 shrink-0 items-center gap-1 rounded-full px-2 text-xs text-ink-muted outline-none hover:bg-hover hover:text-ink focus-visible:ring-2 focus-visible:ring-edge-focus disabled:opacity-60"
- onClick={() => void createFromTable()}
+ closeOnSelect={false}
+ onSelect={() => void createFromTable()}
>
- <ClipboardText class="size-3.5 text-violet" aria-hidden="true" />
- <Plus class="size-3" aria-hidden="true" />
- Form
- </button>
+ <ClipboardText class="size-4 text-violet" aria-hidden="true" />
+ {creating() ? 'Creating form…' : 'New form'}
+ </Dropdown.Item>
</Show>
}
>
- <Dropdown>
- <Dropdown.Trigger
- variant="outline"
- size="sm"
- class="ml-1 h-7 shrink-0 gap-1.5 px-2 text-xs"
- aria-label={`Forms over ${props.tableName}`}
- >
- <ClipboardText class="size-3.5 text-violet" />
- {onTable().length === 1 ? '1 form' : `${onTable().length} forms`}
- </Dropdown.Trigger>
- <Dropdown.Content class="w-64">
- <Dropdown.Group>
- <Dropdown.GroupLabel>
- Forms writing to {props.tableName}
- </Dropdown.GroupLabel>
- <For each={onTable()}>
- {(form) => (
- <Dropdown.Item
- onSelect={() =>
- replaceOrInsertSplit({ type: 'form', id: form.id })
- }
- >
- <ClipboardText class="size-4 text-violet" />
- <span class="flex-1 truncate">{form.name}</span>
- <span class="text-xs text-ink-muted">
- {form.status === 'closed' ? 'Closed' : 'Open'}
- </span>
- </Dropdown.Item>
- )}
- </For>
- </Dropdown.Group>
- </Dropdown.Content>
- </Dropdown>
+ <Dropdown.Group>
+ <Dropdown.GroupLabel>
+ Forms writing to {props.tableName}
+ </Dropdown.GroupLabel>
+ <For each={onTable()}>
+ {(form) => (
+ <Dropdown.Item
+ onSelect={() =>
+ replaceOrInsertSplit({ type: 'form', id: form.id })
+ }
+ >
+ <ClipboardText class="size-4 text-violet" />
+ <span class="flex-1 truncate">{form.name}</span>
+ <span class="text-xs text-ink-muted">
+ {form.status === 'closed' ? 'Closed' : 'Open'}
+ </span>
+ </Dropdown.Item>
+ )}
+ </For>
+ </Dropdown.Group>
</Show>
);
}
diff --git a/apps/web/src/features/database/components/create-table-dialog.tsx b/apps/web/src/features/database/components/create-table-dialog.tsx
deleted file mode 100644
index 0c9dccfeb1..0000000000
--- a/apps/web/src/features/database/components/create-table-dialog.tsx
+++ /dev/null
@@ -1,143 +0,0 @@
-import TableIcon from '@phosphor/table.svg';
-import TextTIcon from '@phosphor/text-t.svg';
-import { Button } from '@ui/components/Button';
-import { Dialog } from '@ui/components/Dialog';
-import { Panel } from '@ui/components/Panel';
-import { TextField } from '@ui/components/TextField';
-import { createSignal, Show } from 'solid-js';
-import { tableCreateMessage } from '../core/column-schema';
-import { isDatabaseNameTaken } from '../core/property-creation';
-import type { CreateTable } from '../core/table-creation';
-
-export function CreateTableDialog(props: {
- existingNames: string[];
- onCreate: CreateTable;
- onOpenTable: (tableId: string) => void;
- onClose: () => void;
- returnFocus?: HTMLElement;
-}) {
- const [name, setName] = createSignal('');
- const [pending, setPending] = createSignal(false);
- const [error, setError] = createSignal('');
- const [createdTableId, setCreatedTableId] = createSignal<string>();
- const duplicate = () =>
- !createdTableId() &&
- name().trim() &&
- isDatabaseNameTaken(name(), props.existingNames);
-
- const openTable = (tableId: string) => {
- props.onOpenTable(tableId);
- props.onClose();
- };
- const submit = async (event: SubmitEvent) => {
- event.preventDefault();
- if (pending() || !name().trim() || duplicate()) return;
- setPending(true);
- setError('');
- const created = await props.onCreate(name().trim(), createdTableId());
- setPending(false);
- created.match(
- (result) => {
- if (result.ready) openTable(result.tableId);
- else {
- setCreatedTableId(result.tableId);
- setError(result.message);
- }
- },
- (errors) => setError(tableCreateMessage(errors))
- );
- };
-
- return (
- <Dialog
- open
- onOpenChange={(open) => !open && !pending() && props.onClose()}
- onCloseAutoFocus={(event) => {
- if (props.returnFocus?.isConnected) {
- event.preventDefault();
- props.returnFocus.focus();
- }
- }}
- class="w-108 max-w-[calc(100vw-2rem)]"
- >
- <Panel>
- <Panel.Body>
- <form
- class="flex flex-col gap-5 p-6 [&_button:focus-visible]:ring-2 [&_button:focus-visible]:ring-ink/50"
- onSubmit={submit}
- aria-busy={pending()}
- >
- <div>
- <div class="mb-3 grid size-10 place-items-center rounded-lg bg-hover text-ink-muted">
- <TableIcon class="size-5" />
- </div>
- <Dialog.Title class="text-lg font-semibold tracking-tight text-ink">
- New table
- </Dialog.Title>
- <Dialog.Description class="mt-1.5 text-sm leading-relaxed text-ink-muted">
- What would you like to organize?
- </Dialog.Description>
- </div>
- <TextField
- value={name()}
- onChange={(value) => {
- setName(value);
- setError('');
- }}
- readOnly={pending() || !!createdTableId()}
- required
- validationState={duplicate() ? 'invalid' : 'valid'}
- >
- <TextField.Label>Table name</TextField.Label>
- <TextField.Input
- maxlength={200}
- placeholder="Projects, People, Events…"
- />
- <TextField.ErrorMessage>
- A table with this name already exists. Try another name.
- </TextField.ErrorMessage>
- </TextField>
- <div class="rounded-lg border border-edge-muted bg-canvas-base">
- <div class="flex items-center gap-2 border-b border-edge-muted px-3 py-2 text-xs font-medium text-ink">
- <TextTIcon class="size-3.5 text-ink-muted" /> Name
- </div>
- <p class="px-3 py-3 text-xs leading-5 text-ink-muted">
- Starts with a Name column. Add more columns anytime.
- </p>
- </div>
- <Show when={error()}>
- <p role="alert" class="text-sm text-failure">
- {error()}
- </p>
- </Show>
- <div class="flex items-center justify-end gap-2">
- <Button
- type="button"
- variant="ghost"
- disabled={pending()}
- onClick={() => {
- const tableId = createdTableId();
- if (tableId) openTable(tableId);
- else props.onClose();
- }}
- >
- {createdTableId() ? 'Open table' : 'Cancel'}
- </Button>
- <Button
- type="submit"
- variant="strong"
- disabled={pending() || !name().trim() || !!duplicate()}
- >
- {pending()
- ? 'Creating…'
- : createdTableId()
- ? 'Retry setup'
- : 'Create table'}
- </Button>
- </div>
- </form>
- </Panel.Body>
- </Panel>
- </Dialog>
- );
-}
diff --git a/apps/web/src/features/database/components/database-table-summary.tsx b/apps/web/src/features/database/components/database-table-summary.tsx
new file mode 100644
index 0000000000..80d31d6364
--- /dev/null
+++ b/apps/web/src/features/database/components/database-table-summary.tsx
@@ -0,0 +1,125 @@
+import PlusIcon from '@phosphor/plus.svg';
+import { Key } from '@solid-primitives/keyed';
+import { Dropdown } from '@ui/components/Dropdown';
+import { createMemo, createSignal, For, Show } from 'solid-js';
+import {
+ type ColumnCalculation,
+ summarizeColumn,
+} from '../core/column-summary';
+import type { DatabaseViewColumn } from '../core/database-view';
+import type { DatabaseRow } from '../core/table';
+
+const calculations: {
+ value: ColumnCalculation;
+ label: string;
+ numeric?: boolean;
+}[] = [
+ { value: 'none', label: 'None' },
+ { value: 'count', label: 'Count filled' },
+ { value: 'unique', label: 'Count unique' },
+ { value: 'sum', label: 'Sum', numeric: true },
+ { value: 'average', label: 'Average', numeric: true },
+ { value: 'min', label: 'Min', numeric: true },
+ { value: 'max', label: 'Max', numeric: true },
+];
+const format = new Intl.NumberFormat(undefined, { maximumFractionDigits: 6 });
+
+/** Shares the grid's column tracks and scroll container so totals stay aligned. */
+export function DatabaseTableSummary(props: {
+ columns: DatabaseViewColumn[];
+ rows: DatabaseRow[];
+ template: string;
+ addColumn: boolean;
+}) {
+ return (
+ <div
+ role="row"
+ aria-label="Table summary"
+ class="sticky bottom-0 z-2 grid h-10 shrink-0 border-t border-edge-muted bg-panel text-xs"
+ style={{ 'grid-template-columns': props.template }}
+ >
+ <div
+ role="gridcell"
+ aria-colspan={props.columns.length ? 2 : 1}
+ class="sticky left-0 z-1 flex min-w-0 items-center gap-1 border-r border-edge-muted/40 bg-panel px-4 text-ink-muted"
+ style={{ 'grid-column': props.columns.length ? 'span 2' : 'span 1' }}
+ >
+ <span class="tabular-nums text-ink">
+ {format.format(props.rows.length)}
+ </span>
+ <span>{props.rows.length === 1 ? 'record' : 'records'} in view</span>
+ </div>
+ <Key each={props.columns.slice(1)} by="id">
+ {(column) => <SummaryCell column={column()} rows={props.rows} />}
+ </Key>
+ <Show when={props.addColumn}>
+ <div role="gridcell" />
+ </Show>
+ </div>
+ );
+}
+
+function SummaryCell(props: {
+ column: DatabaseViewColumn;
+ rows: DatabaseRow[];
+}) {
+ const numeric = () =>
+ props.column.dataType === 'NUMBER' &&
+ !props.column.isMultiSelect &&
+ !props.column.relation;
+ const [choice, setChoice] = createSignal<ColumnCalculation>();
+ const options = () =>
+ calculations.filter((option) => !option.numeric || numeric());
+ const calculation = () =>
+ options().find(
+ (option) => option.value === (choice() ?? (numeric() ? 'sum' : 'none'))
+ ) ?? calculations[0];
+ const value = createMemo(() =>
+ summarizeColumn(
+ props.rows.map((row) => row.cells[props.column.id] ?? null),
+ calculation().value
+ )
+ );
+ return (
+ <div
+ role="gridcell"
+ class="flex min-w-0 items-center justify-start border-r border-edge-muted/40 px-2"
+ >
+ <Dropdown>
+ <Dropdown.Trigger
+ size="sm"
+ variant="ghost"
+ class="h-7 min-w-0 gap-1.5 rounded-none border-0 px-2 text-xs font-normal text-ink-muted"
+ aria-label={`${props.column.name} calculation: ${calculation().label}`}
+ >
+ <Show
+ when={calculation().value !== 'none'}
+ fallback={
+ <>
+ <PlusIcon class="size-3.5 shrink-0" />
+ <span>Add calculation</span>
+ </>
+ }
+ >
+ <span class="tabular-nums text-ink">
+ {value() === null ? '—' : format.format(value()!)}
+ </span>
+ <span class="truncate lowercase">{calculation().label}</span>
+ </Show>
+ </Dropdown.Trigger>
+ <Dropdown.Content>
+ <Dropdown.Group>
+ <Dropdown.GroupLabel>{props.column.name}</Dropdown.GroupLabel>
+ <For each={options()}>
+ {(option) => (
+ <Dropdown.Item onSelect={() => setChoice(option.value)}>
+ {option.label}
+ </Dropdown.Item>
+ )}
+ </For>
+ </Dropdown.Group>
+ </Dropdown.Content>
+ </Dropdown>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/database/components/database-table.tsx b/apps/web/src/features/database/components/database-table.tsx
index 951031d993..bd2681a439 100644
--- a/apps/web/src/features/database/components/database-table.tsx
+++ b/apps/web/src/features/database/components/database-table.tsx
@@ -52,6 +52,7 @@ import {
import type { DatabaseTableModel } from '../primitives/table-model';
import type { DatabaseColumnHeaderProps } from './database-column-header';
import { DatabaseColumnHeader } from './database-column-header';
+import { DatabaseTableSummary } from './database-table-summary';
/** The cell this client has focused, as shared with the table's other viewers. */
export type DatabaseCellFocus = {
@@ -146,6 +147,11 @@ export function DatabaseTable(props: DatabaseTableProps) {
.toArray()
.some((child) => child != null && typeof child !== 'boolean');
const rows = () => props.model.table.getRowModel().rows;
+ const summaryRows = createMemo(() =>
+ rows()
+ .filter((row) => !props.isUnsavedRow?.(row.id))
+ .map((row) => row.original)
+ );
let scrollContainer!: HTMLDivElement;
let gridElement!: HTMLDivElement;
const columnReorder = createHorizontalReorder({
@@ -454,7 +460,7 @@ export function DatabaseTable(props: DatabaseTableProps) {
/>
<div
ref={scrollContainer}
- class="@container/database-grid min-h-0 flex-1 overflow-auto overscroll-x-none"
+ class="@container/database-grid min-h-0 flex-1 overflow-auto overscroll-x-none scroll-py-10"
>
<div
ref={(grid) => {
@@ -485,7 +491,7 @@ export function DatabaseTable(props: DatabaseTableProps) {
tabIndex={-1}
aria-multiselectable="true"
aria-label={props.name}
- aria-rowcount={rows().length + 1}
+ aria-rowcount={rows().length + 2}
aria-colcount={columns().length + 1 + Number(hasAddColumn())}
data-grid
class="relative flex min-h-full min-w-fit flex-col"
@@ -889,6 +895,12 @@ export function DatabaseTable(props: DatabaseTableProps) {
<div />
</Show>
</div>
+ <DatabaseTableSummary
+ columns={columns()}
+ rows={summaryRows()}
+ template={template()}
+ addColumn={hasAddColumn()}
+ />
<Show when={columnReorder.drop()}>
{(drop) => (
<InsertionLine
diff --git a/apps/web/src/features/database/components/database-toolbar.test.tsx b/apps/web/src/features/database/components/database-toolbar.test.tsx
index fdadec63ff..2c2788ccf0 100644
--- a/apps/web/src/features/database/components/database-toolbar.test.tsx
+++ b/apps/web/src/features/database/components/database-toolbar.test.tsx
@@ -477,7 +477,7 @@ describe('database toolbar views', () => {
);
});
- it('creates a view from the New view dialog', async () => {
+ it('creates a table view directly from the New view menu', async () => {
const create = vi.fn(() => okAsync(undefined));
render(() => (
<DatabaseToolbar
@@ -513,19 +513,16 @@ describe('database toolbar views', () => {
onReorderViews={vi.fn()}
/>
));
- fireEvent.click(screen.getByRole('button', { name: 'New view' }));
- await screen.findByRole('dialog', { name: 'New view' });
- const name = screen.getByRole('textbox', {
- name: 'View name',
- }) as HTMLInputElement;
- expect(name.value).toBe('Table view');
- fireEvent.input(name, { target: { value: 'Planning' } });
- fireEvent.submit(name.closest('form')!);
- await waitFor(() =>
- expect(screen.queryByRole('dialog', { name: 'New view' })).toBeNull()
- );
+ fireEvent.keyDown(screen.getByRole('button', { name: 'New view' }), {
+ key: 'Enter',
+ });
+ expect(screen.queryByRole('dialog')).toBeNull();
+ fireEvent.keyDown(await screen.findByRole('menuitem', { name: 'Table' }), {
+ key: 'Enter',
+ });
+ await waitFor(() => expect(create).toHaveBeenCalledOnce());
expect(create).toHaveBeenCalledExactlyOnceWith({
- name: 'Planning',
+ name: 'Table view',
layout: 'table',
});
});
@@ -805,3 +802,116 @@ describe('database toolbar view controls', () => {
expect(screen.queryByRole('button', { name: 'New record' })).toBeNull();
});
});
+
+describe('quick view creation and board grouping', () => {
+ const view: DatabaseView = {
+ id: 'board',
+ databaseId: 'database',
+ tableId: 'table',
+ name: 'Board view',
+ position: 'a0',
+ query: { filter: null, sort: [] },
+ layout: {
+ kind: 'board',
+ groupBy: 'priority',
+ title: 'name',
+ cardFields: ['name'],
+ lanes: [],
+ hideEmptyLanes: true,
+ },
+ createdAt: '2026-09-01T00:00:00Z',
+ updatedAt: '2026-09-01T00:00:00Z',
+ };
+ const columns = ['Priority', 'Status'].map((name) => ({
+ id: name.toLowerCase(),
+ name,
+ dataType: 'SELECT_STRING' as const,
+ isMultiSelect: false,
+ writable: true,
+ options: [],
+ }));
+ function toolbar(
+ options: { noGroups?: boolean; canEdit?: boolean; fail?: boolean } = {}
+ ) {
+ const create = vi.fn(() =>
+ options.fail
+ ? errAsync({
+ kind: 'ops' as const,
+ error: {
+ code: 'NETWORK_ERROR' as const,
+ message: 'Offline',
+ refusal: null,
+ },
+ })
+ : okAsync(undefined)
+ );
+ const change = vi.fn();
+ render(() => (
+ <DatabaseToolbar
+ columns={options.noGroups ? [] : columns}
+ views={[view]}
+ view={view}
+ selectedViewId={view.id}
+ canEdit={options.canEdit ?? true}
+ onSelectView={vi.fn()}
+ onChangeView={change}
+ onCreateView={create}
+ onRenameView={vi.fn(() => okAsync(undefined))}
+ onDeleteView={vi.fn(() => okAsync(undefined))}
+ onShowViewAs={vi.fn(() => okAsync(undefined))}
+ onReorderViews={vi.fn()}
+ />
+ ));
+ return { create, change };
+ }
+ async function newBoard() {
+ fireEvent.keyDown(screen.getByRole('button', { name: 'New view' }), {
+ key: 'Enter',
+ });
+ fireEvent.keyDown(await screen.findByRole('menuitem', { name: 'Board' }), {
+ key: 'Enter',
+ });
+ }
+ it('creates a uniquely named board with an existing grouping column', async () => {
+ const { create } = toolbar();
+ await newBoard();
+ expect(create).toHaveBeenCalledExactlyOnceWith({
+ name: 'Board view 2',
+ layout: 'board',
+ groupBy: { kind: 'column', columnId: 'priority' },
+ });
+ expect(screen.queryByRole('dialog')).toBeNull();
+ });
+ it('creates a Status column when no column can group a board', async () => {
+ const { create } = toolbar({ noGroups: true });
+ await newBoard();
+ expect(create).toHaveBeenCalledExactlyOnceWith({
+ name: 'Board view 2',
+ layout: 'board',
+ groupBy: { kind: 'new-status' },
+ });
+ });
+ it('reports a refused creation', async () => {
+ toolbar({ fail: true });
+ await newBoard();
+ expect(await screen.findByRole('alert')).toBeTruthy();
+ });
+ it('changes grouping after creation while preserving card settings', async () => {
+ const { change } = toolbar();
+ fireEvent.keyDown(screen.getByRole('button', { name: 'Group board by' }), {
+ key: 'Enter',
+ });
+ fireEvent.keyDown(
+ await screen.findByRole('menuitemradio', { name: 'Status' }),
+ { key: 'Enter' }
+ );
+ expect(change).toHaveBeenCalledExactlyOnceWith({
+ layout: { ...view.layout, groupBy: 'status', lanes: [] },
+ });
+ });
+ it('does not offer shared grouping changes to viewers', () => {
+ toolbar({ canEdit: false });
+ expect(screen.queryByRole('button', { name: 'Group board by' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'New view' })).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/database/components/database-toolbar.tsx b/apps/web/src/features/database/components/database-toolbar.tsx
index 50109511b2..a070cb9588 100644
--- a/apps/web/src/features/database/components/database-toolbar.tsx
+++ b/apps/web/src/features/database/components/database-toolbar.tsx
@@ -1,8 +1,10 @@
import { ContextMenu } from '@kobalte/core/context-menu';
+import CheckIcon from '@phosphor/check.svg';
import FunnelIcon from '@phosphor/funnel.svg';
import KanbanIcon from '@phosphor/kanban.svg';
import PlusIcon from '@phosphor/plus.svg';
import SortAscendingIcon from '@phosphor/sort-ascending.svg';
+import StackIcon from '@phosphor/stack.svg';
import TableIcon from '@phosphor/table.svg';
import type { DatabaseView } from '@service-storage/generated/schemas/databaseView';
import { Key } from '@solid-primitives/keyed';
@@ -15,6 +17,7 @@ import {
} from '@thisbeyond/solid-dnd';
import { Button } from '@ui/components/Button';
import { DeleteDialog } from '@ui/components/DeleteDialog';
+import { Dropdown } from '@ui/components/Dropdown';
import { Tooltip } from '@ui/components/Tooltip';
import type { ResultAsync } from 'neverthrow';
import { createSignal, For, type JSX, Show } from 'solid-js';
@@ -25,6 +28,8 @@ import {
} from '../../../lib/core/component/ContextMenu';
import type { BoardGrouping } from '../core/board-grouping';
import type { DatabaseViewColumn } from '../core/database-view';
+import { isDatabaseNameTaken } from '../core/property-creation';
+import type { NewView } from '../core/view-creation';
import type { ViewChange } from '../core/view-state';
import { boardGroupColumns, movedViewOrder } from '../core/views';
import {
@@ -33,11 +38,6 @@ import {
} from '../core/write-failure';
import { FilterPanel, filterConditionCount } from './database-view-filters';
import { createInlineRename } from './inline-rename';
-import {
- type NewFormChoice,
- type NewView,
- NewViewDialog,
-} from './new-view-dialog';
import { SortPanel } from './sort-panel';
import { ToolbarPopover } from './view-control-popover';
@@ -74,13 +74,11 @@ type DatabaseToolbarProps = {
onCreateRecord?: () => void;
canCreateRecord?: boolean;
creating?: boolean;
- /** A form over this table, offered in the new-view dialog when given. */
- newForm?: NewFormChoice;
};
/** View controls contain no data fetching or mutation implementation. */
export function DatabaseToolbar(props: DatabaseToolbarProps) {
- const [creating, setCreating] = createSignal<HTMLElement>();
+ const [creating, setCreating] = createSignal(false);
const [deleting, setDeleting] = createSignal<{ view: DatabaseView }>();
let renameInput: HTMLInputElement | undefined;
let allRecordsButton: HTMLButtonElement | undefined;
@@ -108,6 +106,33 @@ export function DatabaseToolbar(props: DatabaseToolbarProps) {
});
const viewError = viewRename.error;
const setViewError = viewRename.setError;
+ const groupColumns = () => boardGroupColumns(props.columns);
+ const createView = async (kind: 'table' | 'board') => {
+ if (creating() || !props.canEdit) return;
+ const base = kind === 'table' ? 'Table view' : 'Board view';
+ const names = props.views.map((view) => view.name);
+ let name = base;
+ for (let suffix = 2; isDatabaseNameTaken(name, names); suffix += 1)
+ name = `${base} ${suffix}`;
+ const column = groupColumns()[0];
+ const view: NewView =
+ kind === 'table'
+ ? { name, layout: 'table' }
+ : {
+ name,
+ layout: 'board',
+ groupBy: column
+ ? { kind: 'column', columnId: column.id }
+ : { kind: 'new-status' },
+ };
+ setCreating(true);
+ setViewError('');
+ const created = await props.onCreateView(view);
+ setCreating(false);
+ created.mapErr((failure) =>
+ setViewError(databaseOpMessage(failure, 'this view'))
+ );
+ };
function reorder(id: string, targetId: string) {
const order = props.views.map((view) => view.id);
const moved = movedViewOrder(order, id, targetId);
@@ -116,14 +141,11 @@ export function DatabaseToolbar(props: DatabaseToolbarProps) {
}
return (
<div
- class="@container/view-toolbar shrink-0 border-b border-edge-muted bg-canvas-base [&_button:focus-visible]:ring-2 [&_button:focus-visible]:ring-ink/50"
+ class="@container/view-toolbar shrink-0 bg-canvas-base [&_button:focus-visible]:ring-2 [&_button:focus-visible]:ring-ink/50"
data-database-toolbar
>
- <div class="flex items-center gap-2 px-3 py-1.5 @max-[520px]/view-toolbar:flex-wrap @min-[640px]/view-toolbar:px-4">
+ <div class="flex items-center gap-2 px-4 py-1.5 @max-[520px]/view-toolbar:flex-wrap">
<div class="flex min-w-0 flex-1 items-center gap-0.5 @max-[520px]/view-toolbar:basis-full">
- <span class="mr-1.5 shrink-0 text-[10px] text-ink-placeholder @max-[640px]/view-toolbar:sr-only">
- Views
- </span>
<div
ref={viewRail}
class="flex min-w-0 items-center gap-0.5 overflow-x-auto"
@@ -134,12 +156,8 @@ export function DatabaseToolbar(props: DatabaseToolbarProps) {
type="button"
aria-pressed={!props.selectedViewId}
onClick={() => props.onSelectView()}
- class="flex h-8 max-w-40 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs text-ink-muted outline-none hover:bg-hover focus-visible:ring-2 focus-visible:ring-ink/50"
- classList={{
- 'bg-hover font-medium text-ink': !props.selectedViewId,
- }}
+ class="flex h-8 max-w-40 shrink-0 items-center gap-1.5 rounded-full border border-transparent aria-pressed:border-edge-frame aria-pressed:bg-active aria-pressed:text-ink px-4 text-xs font-medium text-ink-extra-muted outline-none hover:text-ink focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-edge-focus transition-colors duration-120 motion-reduce:transition-none"
>
- <TableIcon class="size-3.5" />
<span class="truncate">All records</span>
</button>
<DragDropProvider
@@ -194,18 +212,79 @@ export function DatabaseToolbar(props: DatabaseToolbarProps) {
</DragDropProvider>
</div>
<Show when={props.canEdit}>
- <Button
- size="icon-sm"
- label="New view"
- class="shrink-0"
- onClick={(event) => setCreating(event.currentTarget)}
- >
- <PlusIcon class="size-3.5" />
- </Button>
+ <Dropdown placement="bottom-start">
+ <Dropdown.Trigger
+ size="icon-sm"
+ variant="ghost"
+ aria-label="New view"
+ class="ml-2 shrink-0"
+ disabled={creating()}
+ >
+ <PlusIcon class="size-3.5" />
+ </Dropdown.Trigger>
+ <Dropdown.Content class="min-w-40">
+ <Dropdown.Item
+ onSelect={() => void createView('table')}
+ disabled={creating()}
+ >
+ <TableIcon class="size-4" />
+ Table
+ </Dropdown.Item>
+ <Dropdown.Item
+ onSelect={() => void createView('board')}
+ disabled={creating()}
+ >
+ <KanbanIcon class="size-4" />
+ Board
+ </Dropdown.Item>
+ </Dropdown.Content>
+ </Dropdown>
</Show>
</div>
<div class="flex shrink-0 items-center gap-0.5 @max-[520px]/view-toolbar:w-full @max-[520px]/view-toolbar:justify-end">
<Show when={canChangeView()}>
+ <Show when={board()}>
+ {(current) => (
+ <Dropdown placement="bottom-start">
+ <Dropdown.Trigger
+ aria-label="Group board by"
+ title="Group by"
+ size="icon-md"
+ variant="ghost"
+ class="h-8 w-auto rounded-md px-2 text-ink-muted hover:bg-hover data-expanded:bg-hover"
+ >
+ <StackIcon class="size-3.5" />
+ </Dropdown.Trigger>
+ <Dropdown.Content class="min-w-48">
+ <Dropdown.RadioGroup
+ value={current().groupBy}
+ onChange={(columnId) => {
+ if (columnId !== current().groupBy)
+ props.onChangeView({
+ layout: {
+ ...current(),
+ groupBy: columnId,
+ lanes: [],
+ },
+ });
+ }}
+ >
+ <For each={groupColumns()}>
+ {(column) => (
+ <Dropdown.RadioItem closeOnSelect value={column.id}>
+ <span class="flex-1">{column.name}</span>
+ <Dropdown.ItemIndicator>
+ <CheckIcon class="size-3.5 text-accent" />
+ </Dropdown.ItemIndicator>
+ </Dropdown.RadioItem>
+ )}
+ </For>
+ </Dropdown.RadioGroup>
+ </Dropdown.Content>
+ </Dropdown>
+ )}
+ </Show>
+
<ToolbarPopover
label="Filter"
compact
@@ -260,19 +339,6 @@ export function DatabaseToolbar(props: DatabaseToolbarProps) {
{viewError()}
</p>
</Show>
- <Show when={creating()} keyed>
- {(origin) => (
- <NewViewDialog
- initialName="Table view"
- columns={props.columns}
- form={props.newForm}
- returnFocus={origin}
- returnFocusFallback={allRecordsButton}
- onClose={() => setCreating(undefined)}
- onSubmit={props.onCreateView}
- />
- )}
- </Show>
<DeleteDialog
open={!!deleting()}
onOpenChange={(open) => {
@@ -384,15 +450,8 @@ function ViewTab(props: {
props.onRename();
}
}}
- class="flex h-8 max-w-40 items-center gap-1.5 rounded-md px-2 text-xs text-ink-muted outline-none hover:bg-hover focus-visible:ring-2 focus-visible:ring-ink/50"
- classList={{ 'bg-hover font-medium text-ink': props.selected }}
+ class="flex h-8 max-w-40 items-center gap-1.5 rounded-full border border-transparent aria-pressed:border-edge-frame aria-pressed:bg-active aria-pressed:text-ink px-4 text-xs font-medium text-ink-extra-muted outline-none hover:text-ink focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-edge-focus transition-colors duration-120 motion-reduce:transition-none"
>
- <Show
- when={props.view.layout.kind === 'board'}
- fallback={<TableIcon class="size-3.5 shrink-0" />}
- >
- <KanbanIcon class="size-3.5 shrink-0" />
- </Show>
<span class="truncate">{props.view.name}</span>
</ContextMenu.Trigger>
</Tooltip>
diff --git a/apps/web/src/features/database/components/grid-cell.test.tsx b/apps/web/src/features/database/components/grid-cell.test.tsx
index 2bd6828515..1b8740d0e6 100644
--- a/apps/web/src/features/database/components/grid-cell.test.tsx
+++ b/apps/web/src/features/database/components/grid-cell.test.tsx
@@ -140,6 +140,42 @@ describe('grid cell', () => {
}
);
+ it('toggles the shared checkbox with pointer and keyboard and keeps grid Tab navigation', async () => {
+ const [value, setValue] = createSignal<DatabaseCellValue>(0);
+ const write = vi.fn(async (next: DatabaseCellValue) => {
+ setValue(next);
+ return true;
+ });
+ const navigate = vi.fn(() => true);
+ let control: GridCellControl | undefined;
+ render(() => (
+ <GridCell
+ column={{ ...column, dataType: 'BOOLEAN' }}
+ value={value()}
+ canEdit
+ onWrite={write}
+ onNavigate={navigate}
+ onAddOption={vi.fn(async () => true)}
+ onReady={(ready) => {
+ control = ready;
+ }}
+ />
+ ));
+ const checkbox = screen.getByRole('checkbox', {
+ name: 'Name',
+ }) as HTMLInputElement;
+ await userEvent.click(screen.getByText('Name', { selector: 'label' }));
+ expect(write).toHaveBeenLastCalledWith(1);
+ expect(checkbox.checked).toBe(true);
+ control?.focus();
+ expect(document.activeElement).toBe(checkbox);
+ await userEvent.keyboard(' ');
+ expect(write).toHaveBeenLastCalledWith(0);
+ expect(checkbox.checked).toBe(false);
+ await userEvent.tab();
+ expect(navigate).toHaveBeenCalledWith(1);
+ });
+
it('focuses the read-only boolean wrapper without enabling its checkbox', () => {
let control: GridCellControl | undefined;
const onWrite = vi.fn(async () => true);
diff --git a/apps/web/src/features/database/components/grid-cell.tsx b/apps/web/src/features/database/components/grid-cell.tsx
index a46cda153b..5e10a322ba 100644
--- a/apps/web/src/features/database/components/grid-cell.tsx
+++ b/apps/web/src/features/database/components/grid-cell.tsx
@@ -1,6 +1,7 @@
import { Popover } from '@kobalte/core/popover';
import CaretDownIcon from '@phosphor/caret-down.svg';
import { PropertyDateSelector } from '@property/editors/selectors/PropertyDateSelector';
+import { Checkbox } from '@ui/components/Checkbox';
import { Dropdown } from '@ui/components/Dropdown';
import {
createMemo,
@@ -432,27 +433,31 @@ function BooleanCell(props: {
onNavigate?: (direction: 1 | -1) => boolean;
onWrite: (value: DatabaseCellValue) => Promise<boolean>;
}) {
+ let wrapper: HTMLDivElement | undefined;
+ onMount(() => {
+ const input = wrapper?.querySelector<HTMLInputElement>(
+ 'input[type="checkbox"]'
+ );
+ if (input) props.inputRef(input);
+ });
return (
- <div
- ref={props.wrapperRef}
+ <Checkbox
+ ref={(element: HTMLDivElement) => {
+ wrapper = element;
+ props.wrapperRef(element);
+ }}
tabindex={props.editable ? undefined : -1}
class="flex min-h-9 items-center px-3 outline-none focus-visible:ring-2 focus-visible:ring-ink/50"
+ checked={Boolean(props.value)}
+ disabled={!props.editable}
+ onChange={(checked) => void props.onWrite(checked ? 1 : 0)}
+ onKeyDown={(event: KeyboardEvent) => {
+ if (!isComposingKey(event)) navigateOnTab(event, props.onNavigate);
+ }}
>
- <input
- ref={props.inputRef}
- type="checkbox"
- checked={Boolean(props.value)}
- disabled={!props.editable}
- aria-label={props.column.name}
- class="size-3.5 rounded border-edge-muted accent-ink outline-none focus-visible:ring-2 focus-visible:ring-ink/50 disabled:opacity-50"
- onChange={(event) =>
- void props.onWrite(event.currentTarget.checked ? 1 : 0)
- }
- onKeyDown={(event) => {
- if (!isComposingKey(event)) navigateOnTab(event, props.onNavigate);
- }}
- />
- </div>
+ <Checkbox.Control />
+ <Checkbox.Label class="sr-only">{props.column.name}</Checkbox.Label>
+ </Checkbox>
);
}
diff --git a/apps/web/src/features/database/components/new-table-tab.tsx b/apps/web/src/features/database/components/new-table-tab.tsx
new file mode 100644
index 0000000000..67330c2ec6
--- /dev/null
+++ b/apps/web/src/features/database/components/new-table-tab.tsx
@@ -0,0 +1,92 @@
+import { createSignal } from 'solid-js';
+import { tableCreateMessage } from '../core/column-schema';
+import { isDatabaseNameTaken } from '../core/property-creation';
+import type { CreateTable } from '../core/table-creation';
+
+export function NewTableTab(props: {
+ existingNames: string[];
+ onCreate: CreateTable;
+ onOpenTable: (tableId: string) => void;
+ onClose: (restoreFocus: boolean) => void;
+ onError: (message: string) => void;
+ onCreated: (tableId: string) => void;
+ errorId: string;
+}) {
+ const [name, setName] = createSignal('');
+ const [pending, setPending] = createSignal(false);
+ const setError = props.onError;
+ const [createdTableId, setCreatedTableId] = createSignal<string>();
+ const duplicate = () =>
+ !createdTableId() &&
+ name().trim() &&
+ isDatabaseNameTaken(name(), props.existingNames);
+
+ const openTable = (tableId: string) => {
+ props.onOpenTable(tableId);
+ props.onClose(false);
+ };
+ const submit = async (event: SubmitEvent) => {
+ event.preventDefault();
+ if (pending()) return;
+ if (!name().trim()) return;
+ if (duplicate()) {
+ setError('A table with this name already exists. Try another name.');
+ return;
+ }
+ setPending(true);
+ setError('');
+ const created = await props.onCreate(name().trim(), createdTableId());
+ setPending(false);
+ created.match(
+ (result) => {
+ if (result.ready) openTable(result.tableId);
+ else {
+ setCreatedTableId(result.tableId);
+ props.onCreated(result.tableId);
+ setError(result.message);
+ }
+ },
+ (errors) => setError(tableCreateMessage(errors))
+ );
+ };
+
+ return (
+ <form
+ class="flex h-6 shrink-0 items-center rounded-full bg-input px-3 ring-1 ring-inset ring-edge-muted"
+ aria-label="New table"
+ onSubmit={submit}
+ aria-busy={pending()}
+ >
+ <input
+ aria-label="Table name"
+ placeholder="Table name"
+ class="w-32 min-w-0 bg-transparent text-xs font-medium text-ink outline-none placeholder:text-ink-placeholder"
+ value={name()}
+ maxLength={200}
+ readOnly={pending() || !!createdTableId()}
+ aria-invalid={!!duplicate()}
+ aria-describedby={props.errorId}
+ onFocusIn={(event) => event.stopPropagation()}
+ onMouseDown={(event) => event.stopPropagation()}
+ onInput={(event) => {
+ setName(event.currentTarget.value);
+ setError('');
+ }}
+ onBlur={(event) => {
+ event.stopPropagation();
+ if (pending()) return;
+ if (!name().trim()) props.onClose(false);
+ else event.currentTarget.form?.requestSubmit();
+ }}
+ onKeyDown={(event) => {
+ event.stopPropagation();
+ if (event.isComposing || event.keyCode === 229) return;
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ if (!pending()) props.onClose(true);
+ }
+ }}
+ />
+ </form>
+ );
+}
diff --git a/apps/web/src/features/database/components/new-view-dialog.test.tsx b/apps/web/src/features/database/components/new-view-dialog.test.tsx
deleted file mode 100644
index 3ab2d36024..0000000000
--- a/apps/web/src/features/database/components/new-view-dialog.test.tsx
+++ /dev/null
@@ -1,258 +0,0 @@
-import {
- cleanup,
- fireEvent,
- render,
- screen,
- waitFor,
-} from '@solidjs/testing-library';
-import userEvent from '@testing-library/user-event';
-import { errAsync, okAsync } from 'neverthrow';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import type { DatabaseViewColumn } from '../core/database-view';
-import { NewViewDialog } from './new-view-dialog';
-
-vi.mock('../../../lib/core/mobile/isMobile', () => ({ isMobile: () => false }));
-
-afterEach(cleanup);
-
-const priority: DatabaseViewColumn = {
- id: 'priority',
- name: 'Priority',
- dataType: 'SELECT_STRING',
- isMultiSelect: false,
- writable: true,
- options: [
- { id: 'high', label: 'High', color: null },
- { id: 'low', label: 'Low', color: null },
- ],
-};
-
-describe('new database view', () => {
- it('focuses and selects the name, then tabs to Cancel', async () => {
- render(() => (
- <NewViewDialog
- initialName="Planning"
- columns={[]}
- onSubmit={vi.fn(() => okAsync(undefined))}
- onClose={vi.fn()}
- />
- ));
- const name = screen.getByRole('textbox', {
- name: 'View name',
- }) as HTMLInputElement;
- await waitFor(() => expect(document.activeElement).toBe(name));
- expect(name.selectionStart).toBe(0);
- expect(name.selectionEnd).toBe(name.value.length);
- await userEvent.tab();
- expect(document.activeElement).toBe(
- screen.getByRole('button', { name: 'Cancel' })
- );
- });
-
- it('creates a board grouped by the first single select, keeping a custom name', async () => {
- const submit = vi.fn(() => okAsync(undefined));
- const close = vi.fn();
- render(() => (
- <NewViewDialog
- initialName="Table view"
- initialLayout="table"
- columns={[priority]}
- onSubmit={submit}
- onClose={close}
- />
- ));
- const input = screen.getByRole('textbox', { name: 'View name' });
- fireEvent.input(input, { target: { value: 'Delivery board' } });
- fireEvent.click(screen.getByRole('button', { name: /Board Cards/ }));
- fireEvent.submit(input.closest('form')!);
- await waitFor(() => expect(close).toHaveBeenCalledOnce());
- expect(submit).toHaveBeenCalledExactlyOnceWith({
- name: 'Delivery board',
- layout: 'board',
- groupBy: { kind: 'column', columnId: 'priority' },
- });
- });
-
- it('keeps the layout and draft, and says why, when creating fails', async () => {
- const submit = vi
- .fn()
- .mockReturnValueOnce(
- errAsync({
- kind: 'ops',
- error: {
- code: 'INVALID_OP',
- message: 'a view named `Board view` already exists on this table',
- refusal: {
- op: 0,
- row: null,
- column: null,
- message: 'a view named `Board view` already exists on this table',
- },
- },
- })
- )
- .mockReturnValueOnce(okAsync(undefined));
- const close = vi.fn();
- render(() => (
- <NewViewDialog
- initialName="Table view"
- initialLayout="table"
- columns={[priority]}
- onSubmit={submit}
- onClose={close}
- />
- ));
- fireEvent.click(screen.getByRole('button', { name: /Board Cards/ }));
- const input = screen.getByRole('textbox', { name: 'View name' });
- fireEvent.submit(input.closest('form')!);
- expect((await screen.findByRole('alert')).textContent).toBe(
- 'a view named `Board view` already exists on this table'
- );
- expect(close).not.toHaveBeenCalled();
- expect((input as HTMLInputElement).value).toBe('Board view');
- expect(
- screen
- .getByRole('button', { name: /Board Cards/ })
- .getAttribute('aria-pressed')
- ).toBe('true');
- fireEvent.submit(input.closest('form')!);
- await waitFor(() => expect(close).toHaveBeenCalledOnce());
- expect(submit).toHaveBeenLastCalledWith({
- name: 'Board view',
- layout: 'board',
- groupBy: { kind: 'column', columnId: 'priority' },
- });
- });
-
- it('offers to create a Status column when nothing can group a board, chosen already', async () => {
- const submit = vi.fn(() => okAsync(undefined));
- const close = vi.fn();
- render(() => (
- <NewViewDialog
- initialName="Board view"
- initialLayout="board"
- columns={[
- {
- id: 'name',
- name: 'Name',
- dataType: 'STRING',
- isMultiSelect: false,
- writable: true,
- options: [],
- },
- ]}
- onSubmit={submit}
- onClose={close}
- />
- ));
-
- expect(screen.getByLabelText('Group board by').textContent).toContain(
- 'Create a Status column'
- );
- fireEvent.submit(
- screen.getByRole('textbox', { name: 'View name' }).closest('form')!
- );
- await waitFor(() => expect(close).toHaveBeenCalledOnce());
- expect(submit).toHaveBeenCalledExactlyOnceWith({
- name: 'Board view',
- layout: 'board',
- groupBy: { kind: 'new-status' },
- });
- });
-
- it('groups a board by a single-person column', async () => {
- const submit = vi.fn(() => okAsync(undefined));
- render(() => (
- <NewViewDialog
- initialName="By owner"
- initialLayout="board"
- columns={[
- {
- id: 'owner',
- name: 'Owner',
- dataType: 'ENTITY',
- specificEntityType: 'USER',
- isMultiSelect: false,
- writable: true,
- options: [],
- },
- ]}
- onSubmit={submit}
- onClose={vi.fn()}
- />
- ));
-
- fireEvent.submit(
- screen.getByRole('textbox', { name: 'View name' }).closest('form')!
- );
- await waitFor(() =>
- expect(submit).toHaveBeenCalledExactlyOnceWith({
- name: 'By owner',
- layout: 'board',
- groupBy: { kind: 'column', columnId: 'owner' },
- })
- );
- });
-
- it('offers a Form beside table and board when given one, creating it under its own name without a view', async () => {
- const submit = vi.fn(() => okAsync(undefined));
- const createForm = vi.fn(async () => undefined);
- const close = vi.fn();
- render(() => (
- <NewViewDialog
- initialName="Table view"
- columns={[priority]}
- form={{ initialName: 'Guests form', onCreate: createForm }}
- onSubmit={submit}
- onClose={close}
- />
- ));
- fireEvent.click(screen.getByRole('button', { name: /Form Collect/ }));
- const input = screen.getByRole('textbox', {
- name: 'Form name',
- }) as HTMLInputElement;
- expect(input.value).toBe('Guests form');
- fireEvent.input(input, { target: { value: 'RSVP' } });
- fireEvent.submit(input.closest('form')!);
- await waitFor(() => expect(close).toHaveBeenCalledOnce());
- expect(createForm).toHaveBeenCalledExactlyOnceWith('RSVP');
- expect(submit).not.toHaveBeenCalled();
- });
-
- it('keeps the dialog open and says why when the form is refused', async () => {
- const close = vi.fn();
- render(() => (
- <NewViewDialog
- initialName="Table view"
- columns={[]}
- form={{
- initialName: 'Guests form',
- onCreate: async () =>
- 'Only the database owner can make a form over this table.',
- }}
- onSubmit={vi.fn(() => okAsync(undefined))}
- onClose={close}
- />
- ));
- fireEvent.click(screen.getByRole('button', { name: /Form Collect/ }));
- fireEvent.submit(
- screen.getByRole('textbox', { name: 'Form name' }).closest('form')!
- );
- expect((await screen.findByRole('alert')).textContent).toBe(
- 'Only the database owner can make a form over this table.'
- );
- expect(close).not.toHaveBeenCalled();
- });
-
- it('offers no Form when not given one', () => {
- render(() => (
- <NewViewDialog
- initialName="Table view"
- columns={[]}
- onSubmit={vi.fn(() => okAsync(undefined))}
- onClose={vi.fn()}
- />
- ));
- expect(screen.queryByRole('button', { name: /Form Collect/ })).toBeNull();
- });
-});
diff --git a/apps/web/src/features/database/components/new-view-dialog.tsx b/apps/web/src/features/database/components/new-view-dialog.tsx
deleted file mode 100644
index 768b35c134..0000000000
--- a/apps/web/src/features/database/components/new-view-dialog.tsx
+++ /dev/null
@@ -1,280 +0,0 @@
-import ClipboardText from '@phosphor/clipboard-text.svg';
-import KanbanIcon from '@phosphor/kanban.svg';
-import TableIcon from '@phosphor/table.svg';
-import { Button } from '@ui/components/Button';
-import { Dialog } from '@ui/components/Dialog';
-import { Panel } from '@ui/components/Panel';
-import { TextField } from '@ui/components/TextField';
-import type { ResultAsync } from 'neverthrow';
-import { createSignal, Show } from 'solid-js';
-import { type BoardGrouping, STATUS_OPTIONS } from '../core/board-grouping';
-import type { DatabaseViewColumn } from '../core/database-view';
-import { boardGroupColumns } from '../core/views';
-import {
- type DatabaseOpFailure,
- databaseOpMessage,
-} from '../core/write-failure';
-import { ViewSelect } from './view-select';
-
-type NewViewLayout = 'table' | 'board';
-type NewViewChoice = NewViewLayout | 'form';
-
-/** A form over the current table, offered beside the views (RFC 02 §7). */
-export type NewFormChoice = {
- initialName: string;
- /** Resolves a message saying why the form was refused, or undefined once made. */
- onCreate: (name: string) => Promise<string | undefined>;
-};
-
-import type { NewView } from '../core/view-creation';
-
-export type { NewView } from '../core/view-creation';
-
-/** The grouping choice that creates a Status column; column ids are UUIDs, so it names none. */
-const NEW_STATUS_COLUMN = 'new-status-column';
-
-/**
- * Creates a table or board view of the current table, named and, for a
- * board, grouped; given `form`, it also offers a form whose answers land as
- * the table's rows.
- */
-export function NewViewDialog(props: {
- initialName: string;
- initialLayout?: NewViewLayout;
- columns: DatabaseViewColumn[];
- form?: NewFormChoice;
- onSubmit: (view: NewView) => ResultAsync<void, DatabaseOpFailure>;
- onClose: () => void;
- returnFocus?: HTMLElement;
- returnFocusFallback?: HTMLElement;
-}) {
- let nameInput: HTMLInputElement | undefined;
- const [name, setName] = createSignal(props.initialName);
- const [layout, setLayout] = createSignal<NewViewChoice>(
- props.initialLayout ?? 'table'
- );
- const [formName, setFormName] = createSignal(props.form?.initialName ?? '');
- const groups = () => boardGroupColumns(props.columns);
- /** The columns a board can group by, or, when there are none, a Status column to create. */
- const groupChoices = () =>
- groups().length
- ? groups().map((column) => ({ value: column.id, label: column.name }))
- : [{ value: NEW_STATUS_COLUMN, label: 'Create a Status column' }];
- const [groupBy, setGroupBy] = createSignal(groupChoices()[0]?.value);
- const grouping = (): BoardGrouping | undefined => {
- const chosen = groupBy();
- if (chosen === NEW_STATUS_COLUMN) return { kind: 'new-status' };
- return groups().some((column) => column.id === chosen) && chosen
- ? { kind: 'column', columnId: chosen }
- : undefined;
- };
- const [pending, setPending] = createSignal(false);
- const [error, setError] = createSignal('');
- const request = (): NewView | undefined => {
- const trimmed = name().trim();
- if (!trimmed) return undefined;
- if (layout() === 'table') return { name: trimmed, layout: 'table' };
- const group = grouping();
- return group
- ? { name: trimmed, layout: 'board', groupBy: group }
- : undefined;
- };
- const incomplete = () =>
- layout() === 'form' ? !formName().trim() : !request();
- const submitForm = async (form: NewFormChoice) => {
- const trimmed = formName().trim();
- if (pending() || !trimmed) return;
- setPending(true);
- setError('');
- const refusal = await form.onCreate(trimmed);
- setPending(false);
- if (refusal) setError(refusal);
- else props.onClose();
- };
- const submit = async (event: SubmitEvent) => {
- event.preventDefault();
- if (layout() === 'form' && props.form) {
- await submitForm(props.form);
- return;
- }
- const view = request();
- if (pending() || !view) return;
- setPending(true);
- setError('');
- const created = await props.onSubmit(view);
- setPending(false);
- created.match(props.onClose, (failure) =>
- setError(databaseOpMessage(failure, 'this view'))
- );
- };
- return (
- <Dialog
- open
- onOpenChange={(open) => !open && !pending() && props.onClose()}
- onOpenAutoFocus={(event) => {
- event.preventDefault();
- nameInput?.focus();
- nameInput?.select();
- }}
- onCloseAutoFocus={(event) => {
- const target = props.returnFocus?.isConnected
- ? props.returnFocus
- : props.returnFocusFallback;
- if (target?.isConnected) {
- event.preventDefault();
- target.focus();
- }
- }}
- class="w-100 max-w-[calc(100vw-2rem)]"
- >
- <Panel>
- <Panel.Body>
- <form class="flex flex-col gap-5 p-5" onSubmit={submit}>
- <div class="flex flex-col gap-1">
- <Dialog.Title class="text-base font-semibold text-ink">
- New view
- </Dialog.Title>
- <Dialog.Description class="text-sm text-ink-muted">
- A different way to see the same records, shared with everyone
- who can open this database.
- </Dialog.Description>
- </div>
- <div
- class="grid gap-2"
- classList={{
- 'grid-cols-2': !props.form,
- 'grid-cols-3': !!props.form,
- }}
- role="group"
- aria-label="View layout"
- >
- <button
- type="button"
- disabled={pending()}
- aria-pressed={layout() === 'table'}
- onClick={() => {
- setLayout('table');
- if (name() === 'Board view') setName('Table view');
- }}
- class="flex items-start gap-2.5 rounded-lg border px-3 py-2.5 text-left text-sm outline-none hover:bg-hover focus-visible:ring-2 focus-visible:ring-ink/50"
- classList={{
- 'border-edge bg-hover': layout() === 'table',
- 'border-edge-muted': layout() !== 'table',
- }}
- >
- <TableIcon class="mt-0.5 size-4 shrink-0 text-ink-muted" />
- <span class="flex flex-col gap-0.5">
- <span class="font-medium text-ink">Table</span>
- <span class="text-xs text-ink-muted">Rows and columns</span>
- </span>
- </button>
- <button
- type="button"
- disabled={pending()}
- aria-pressed={layout() === 'board'}
- onClick={() => {
- setLayout('board');
- if (name() === 'Table view') setName('Board view');
- }}
- class="flex items-start gap-2.5 rounded-lg border px-3 py-2.5 text-left text-sm outline-none hover:bg-hover focus-visible:ring-2 focus-visible:ring-ink/50"
- classList={{
- 'border-edge bg-hover': layout() === 'board',
- 'border-edge-muted': layout() !== 'board',
- }}
- >
- <KanbanIcon class="mt-0.5 size-4 shrink-0 text-ink-muted" />
- <span class="flex flex-col gap-0.5">
- <span class="font-medium text-ink">Board</span>
- <span class="text-xs text-ink-muted">
- Cards grouped by a column
- </span>
- </span>
- </button>
- <Show when={props.form}>
- <button
- type="button"
- disabled={pending()}
- aria-pressed={layout() === 'form'}
- onClick={() => setLayout('form')}
- class="flex items-start gap-2.5 rounded-lg border px-3 py-2.5 text-left text-sm outline-none hover:bg-hover focus-visible:ring-2 focus-visible:ring-ink/50"
- classList={{
- 'border-edge bg-hover': layout() === 'form',
- 'border-edge-muted': layout() !== 'form',
- }}
- >
- <ClipboardText class="mt-0.5 size-4 shrink-0 text-violet" />
- <span class="flex flex-col gap-0.5">
- <span class="font-medium text-ink">Form</span>
- <span class="text-xs text-ink-muted">
- Collect answers as new rows
- </span>
- </span>
- </button>
- </Show>
- </div>
- <Show when={layout() === 'form'}>
- <p class="text-xs text-ink-muted">
- A question for each column. Opens the form builder.
- </p>
- </Show>
- <Show when={layout() === 'board'}>
- <div class="flex items-center justify-between gap-3 text-sm">
- <span class="font-medium text-ink">Group by</span>
- <ViewSelect
- label="Group board by"
- value={groupBy()}
- options={groupChoices()}
- onChange={setGroupBy}
- placeholder="Choose a column"
- />
- </div>
- <Show when={groupBy() === NEW_STATUS_COLUMN}>
- <p class="text-xs text-ink-muted">
- No Select or Person column groups cards yet. A new Status
- column starts with {STATUS_OPTIONS.join(', ')}.
- </p>
- </Show>
- </Show>
- <TextField
- value={layout() === 'form' ? formName() : name()}
- onChange={layout() === 'form' ? setFormName : setName}
- readOnly={pending()}
- required
- >
- <TextField.Label>
- {layout() === 'form' ? 'Form name' : 'View name'}
- </TextField.Label>
- <TextField.Input
- ref={nameInput}
- maxlength={100}
- onFocus={(event) => event.currentTarget.select()}
- placeholder="e.g. In progress"
- />
- </TextField>
- <Show when={error()}>
- <p role="alert" class="text-xs text-failure">
- {error()}
- </p>
- </Show>
- <div class="flex justify-end gap-2">
- <Button
- variant="ghost"
- disabled={pending()}
- onClick={props.onClose}
- >
- Cancel
- </Button>
- <Button
- type="submit"
- variant="cta"
- disabled={pending() || incomplete()}
- >
- {layout() === 'form' ? 'Create form' : 'Create view'}
- </Button>
- </div>
- </form>
- </Panel.Body>
- </Panel>
- </Dialog>
- );
-}
diff --git a/apps/web/src/features/database/components/table-navigation.test.tsx b/apps/web/src/features/database/components/table-navigation.test.tsx
index ca9e4cc0e5..b509d0a275 100644
--- a/apps/web/src/features/database/components/table-navigation.test.tsx
+++ b/apps/web/src/features/database/components/table-navigation.test.tsx
@@ -78,6 +78,16 @@ function navigation(onCreate: CreateTable, onSelect = vi.fn()) {
return onSelect;
}
+async function openNewTable() {
+ fireEvent.keyDown(screen.getByRole('button', { name: 'Add table or form' }), {
+ key: 'Enter',
+ });
+ fireEvent.keyDown(
+ await screen.findByRole('menuitem', { name: 'New table' }),
+ { key: 'Enter' }
+ );
+}
+
describe('table creation and navigation', () => {
it('renames an inactive tab by double click even when the first click refreshes table objects', async () => {
const [tables, setTables] = createSignal([
@@ -330,9 +340,13 @@ describe('table creation and navigation', () => {
entry.targets.has(rail)
);
expect(observer).toBeDefined();
- observer!.resize(rail);
+ for (const entry of ResizeObserverMock.instances) {
+ if (entry.targets.has(rail)) entry.resize(rail);
+ }
expect(rail.scrollLeft).toBe(230);
- expect(screen.getByRole('button', { name: 'New table' })).toBeTruthy();
+ expect(
+ screen.getByRole('button', { name: 'Add table or form' })
+ ).toBeTruthy();
});
it('focuses the name, validates duplicates, creates the named table and opens it', async () => {
@@ -343,7 +357,7 @@ describe('table creation and navigation', () => {
expect(
screen.getByRole('tab', { name: 'Tasks' }).getAttribute('aria-selected')
).toBe('true');
- fireEvent.click(screen.getByRole('button', { name: 'New table' }));
+ await openNewTable();
const name = await screen.findByLabelText('Table name');
await waitFor(() => expect(document.activeElement).toBe(name));
fireEvent.input(name, { target: { value: ' tasks ' } });
@@ -358,7 +372,26 @@ describe('table creation and navigation', () => {
fireEvent.submit(name.closest('form')!);
await waitFor(() => expect(select).toHaveBeenCalledWith('projects'));
expect(create).toHaveBeenCalledWith('Projects', undefined);
- await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await waitFor(() =>
+ expect(screen.queryByLabelText('Table name')).toBeNull()
+ );
+ });
+
+ it('saves an inline table draft on blur and cancels an empty one', async () => {
+ const create = vi.fn<CreateTable>(() =>
+ okAsync({ tableId: 'projects', ready: true })
+ );
+ const select = navigation(create);
+ await openNewTable();
+ fireEvent.blur(await screen.findByLabelText('Table name'));
+ expect(screen.queryByLabelText('Table name')).toBeNull();
+ expect(create).not.toHaveBeenCalled();
+ await openNewTable();
+ const name = await screen.findByLabelText('Table name');
+ fireEvent.input(name, { target: { value: 'Projects' } });
+ fireEvent.blur(name);
+ await waitFor(() => expect(select).toHaveBeenCalledWith('projects'));
+ expect(create).toHaveBeenCalledExactlyOnceWith('Projects', undefined);
});
it('keeps the draft after a failed create and prevents double submission', async () => {
@@ -374,7 +407,7 @@ describe('table creation and navigation', () => {
)
);
navigation(create);
- fireEvent.click(screen.getByRole('button', { name: 'New table' }));
+ await openNewTable();
const name = await screen.findByLabelText('Table name');
fireEvent.input(name, { target: { value: 'Projects' } });
fireEvent.submit(name.closest('form')!);
@@ -400,26 +433,28 @@ describe('table creation and navigation', () => {
)
.mockReturnValueOnce(okAsync({ tableId: 'projects', ready: true }));
const select = navigation(create);
- fireEvent.click(screen.getByRole('button', { name: 'New table' }));
+ await openNewTable();
const name = await screen.findByLabelText('Table name');
fireEvent.input(name, { target: { value: 'Projects' } });
fireEvent.submit(name.closest('form')!);
await screen.findByRole('alert');
expect((name as HTMLInputElement).readOnly).toBe(true);
expect(select).not.toHaveBeenCalled();
- fireEvent.click(screen.getByRole('button', { name: 'Retry setup' }));
+ fireEvent.submit(name.closest('form')!);
await waitFor(() => expect(select).toHaveBeenCalledWith('projects'));
expect(create).toHaveBeenLastCalledWith('Projects', 'projects');
});
it('restores focus on cancel and focuses the name when reopening', async () => {
navigation(vi.fn<CreateTable>());
- const trigger = screen.getByRole('button', { name: 'New table' });
- fireEvent.click(trigger);
- await screen.findByLabelText('Table name');
- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ const trigger = screen.getByRole('button', { name: 'Add table or form' });
+ await openNewTable();
+ const draft = await screen.findByLabelText('Table name');
+ expect(draft.closest('[role=tablist]')).toBeTruthy();
+ expect(screen.queryByRole('dialog')).toBeNull();
+ fireEvent.keyDown(draft, { key: 'Escape' });
await waitFor(() => expect(document.activeElement).toBe(trigger));
- fireEvent.click(trigger);
+ await openNewTable();
const name = await screen.findByLabelText('Table name');
await waitFor(() => expect(document.activeElement).toBe(name));
});
diff --git a/apps/web/src/features/database/components/table-navigation.tsx b/apps/web/src/features/database/components/table-navigation.tsx
index 60bd86d7c5..a46f0cf459 100644
--- a/apps/web/src/features/database/components/table-navigation.tsx
+++ b/apps/web/src/features/database/components/table-navigation.tsx
@@ -2,14 +2,14 @@ import { ContextMenu } from '@kobalte/core/context-menu';
import { Tabs } from '@kobalte/core/tabs';
import ArrowLeftIcon from '@phosphor/arrow-left.svg';
import ArrowRightIcon from '@phosphor/arrow-right.svg';
-import PlusIcon from '@phosphor/plus.svg';
import TableIcon from '@phosphor/table.svg';
import TrashIcon from '@phosphor/trash.svg';
import { Key } from '@solid-primitives/keyed';
import { createResizeObserver } from '@solid-primitives/resize-observer';
import { DragDropProvider, DragOverlay } from '@thisbeyond/solid-dnd';
-import { Button } from '@ui/components/Button';
import { DeleteDialog } from '@ui/components/DeleteDialog';
+import { Dropdown } from '@ui/components/Dropdown';
+import { TabSelector } from '@ui/components/TabSelector';
import { Tooltip } from '@ui/components/Tooltip';
import {
createEffect,
@@ -34,13 +34,15 @@ import {
} from '../core/column-schema';
import { isDatabaseNameTaken } from '../core/property-creation';
import type { CreateTable } from '../core/table-creation';
-import { CreateTableDialog } from './create-table-dialog';
import { createInlineRename } from './inline-rename';
+import { NewTableTab } from './new-table-tab';
export function TableNavigation(props: {
tables: { id: string; name: string }[];
activeTableId: string | undefined;
canCreate: boolean;
+ /** Additional feature-owned creation/navigation items in the add menu. */
+ menuItems?: () => JSX.Element;
onSelect: (tableId: string) => void;
onCreate: CreateTable;
onRename?: (
@@ -57,6 +59,15 @@ export function TableNavigation(props: {
}) {
const [deleting, setDeleting] = createSignal<{ id: string; name: string }>();
const [open, setOpen] = createSignal(false);
+ const [createError, setCreateError] = createSignal('');
+ const [createdTableId, setCreatedTableId] = createSignal<string>();
+ const createErrorId = createUniqueId();
+ const closeDraft = (restoreFocus: boolean) => {
+ setOpen(false);
+ setCreateError('');
+ setCreatedTableId(undefined);
+ if (restoreFocus) queueMicrotask(() => createButton?.focus());
+ };
const [tabRail, setTabRail] = createSignal<HTMLDivElement>();
const renameErrorId = createUniqueId();
const [menuTarget, setMenuTarget] = createSignal<{
@@ -192,10 +203,10 @@ export function TableNavigation(props: {
class="hidden"
aria-hidden="true"
/>
- <div class="flex min-w-0 items-center gap-1.5">
+ <TabSelector>
<span class="sr-only">Tables</span>
<Show
- when={props.tables.length > 0}
+ when={props.tables.length > 0 || open()}
fallback={
<span class="min-w-0 flex-1 text-xs text-ink-placeholder">
No tables yet
@@ -218,12 +229,13 @@ export function TableNavigation(props: {
activationMode="manual"
class="min-w-0"
>
- <Tabs.List
- ref={setTabRail}
- aria-label="Database tables"
- class="relative flex min-h-8 items-center gap-0.5 overflow-x-auto"
- >
- <Key each={props.tables} by="id">
+ <TabSelector.List ref={setTabRail} aria-label="Database tables">
+ <Key
+ each={props.tables.filter(
+ (table) => table.id !== createdTableId()
+ )}
+ by="id"
+ >
{(table) => (
<DraggableTab
id={table().id}
@@ -237,7 +249,7 @@ export function TableNavigation(props: {
}}
>
<Tooltip label={table().name}>
- <Tabs.Trigger
+ <TabSelector.Tab
value={table().id}
aria-haspopup={
canRename() || canReorder() ? 'menu' : undefined
@@ -245,13 +257,21 @@ export function TableNavigation(props: {
aria-keyshortcuts={
canRename() ? 'F2 Shift+F10' : undefined
}
- onDblClick={(event) => {
+ onDblClick={(
+ event: MouseEvent & {
+ currentTarget: HTMLButtonElement;
+ }
+ ) => {
if (!canRename()) return;
event.preventDefault();
event.stopPropagation();
rename(table(), event.currentTarget);
}}
- onContextMenu={(event) => {
+ onContextMenu={(
+ event: MouseEvent & {
+ currentTarget: HTMLButtonElement;
+ }
+ ) => {
if (!canRename() && !canReorder()) return;
event.preventDefault();
event.stopPropagation();
@@ -284,12 +304,11 @@ export function TableNavigation(props: {
);
}
}}
- class="relative flex h-8 max-w-40 shrink-0 items-center gap-1.5 rounded-md px-2.5 text-xs text-ink-muted outline-none hover:bg-hover hover:text-ink focus-visible:ring-2 focus-visible:ring-ink/50 data-selected:bg-hover data-selected:font-medium data-selected:text-ink"
classList={{ hidden: renaming()?.id === table().id }}
>
<TableIcon class="size-3.5 shrink-0" />
<span class="truncate">{table().name}</span>
- </Tabs.Trigger>
+ </TabSelector.Tab>
</Tooltip>
<Show when={renaming()?.id === table().id}>
<input
@@ -330,6 +349,17 @@ export function TableNavigation(props: {
</DraggableTab>
)}
</Key>
+ <Show when={open()}>
+ <NewTableTab
+ existingNames={props.tables.map((table) => table.name)}
+ onCreate={props.onCreate}
+ onOpenTable={props.onSelect}
+ onClose={closeDraft}
+ onError={setCreateError}
+ onCreated={setCreatedTableId}
+ errorId={createErrorId}
+ />
+ </Show>
<Show when={tabReorder.drop()}>
{(drop) => (
<InsertionLine
@@ -339,7 +369,7 @@ export function TableNavigation(props: {
/>
)}
</Show>
- </Tabs.List>
+ </TabSelector.List>
</Tabs>
<DragOverlay
class="pointer-events-none select-none rounded-md bg-panel shadow-md"
@@ -349,20 +379,37 @@ export function TableNavigation(props: {
</DragOverlay>
</DragDropProvider>
</Show>
- <Show when={props.canCreate}>
- <Button
- ref={createButton}
- type="button"
- size="sm"
- variant={props.tables.length ? 'ghost' : 'strong'}
- class="shrink-0 gap-1.5 text-xs focus-visible:ring-2 focus-visible:ring-ink/50"
- onClick={() => setOpen(true)}
+ <Show when={props.canCreate || props.menuItems}>
+ <TabSelector.AddMenu
+ label="Add table or form"
+ onCloseAutoFocus={(event) => {
+ if (!open()) return;
+ event.preventDefault();
+ queueMicrotask(() =>
+ tabRail()
+ ?.querySelector<HTMLInputElement>('form input')
+ ?.focus()
+ );
+ }}
+ ref={(element) => {
+ createButton = element;
+ }}
>
- <PlusIcon class="size-3.5" />
- New table
- </Button>
+ <Show when={props.canCreate}>
+ <Dropdown.Item onSelect={() => setOpen(true)}>
+ <TableIcon class="size-4" />
+ New table
+ </Dropdown.Item>
+ </Show>
+ {props.menuItems?.()}
+ </TabSelector.AddMenu>
</Show>
- </div>
+ </TabSelector>
+ <Show when={createError()}>
+ <p id={createErrorId} role="alert" class="mt-1 text-xs text-failure">
+ {createError()}
+ </p>
+ </Show>
<Show when={tableRename.error()}>
<p id={renameErrorId} role="alert" class="mt-1 text-xs text-failure">
{tableRename.error()}
@@ -453,15 +500,6 @@ export function TableNavigation(props: {
</>
}
/>
- <Show when={open()}>
- <CreateTableDialog
- existingNames={props.tables.map((table) => table.name)}
- onCreate={props.onCreate}
- onOpenTable={props.onSelect}
- onClose={() => setOpen(false)}
- returnFocus={createButton}
- />
- </Show>
</ContextMenu>
);
}
diff --git a/apps/web/src/features/database/core/column-summary.test.ts b/apps/web/src/features/database/core/column-summary.test.ts
new file mode 100644
index 0000000000..6137f3c500
--- /dev/null
+++ b/apps/web/src/features/database/core/column-summary.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+import { summarizeColumn } from './column-summary';
+
+describe('column summaries', () => {
+ it('counts filled and distinct values without counting empty cells', () => {
+ const values = [null, '', 'Books', 'Books', 'Authors', 0];
+ expect(summarizeColumn(values, 'count')).toBe(4);
+ expect(summarizeColumn(values, 'unique')).toBe(3);
+ });
+ it('aggregates finite numbers without coercing blanks or text', () => {
+ const values = [null, '', '100', 0, -2, 8, Infinity, NaN];
+ expect(summarizeColumn(values, 'sum')).toBe(6);
+ expect(summarizeColumn(values, 'average')).toBe(2);
+ expect(summarizeColumn(values, 'min')).toBe(-2);
+ expect(summarizeColumn(values, 'max')).toBe(8);
+ });
+ it('distinguishes no numeric values from a real zero total', () => {
+ expect(summarizeColumn([], 'sum')).toBeNull();
+ expect(summarizeColumn([null, ''], 'average')).toBeNull();
+ expect(summarizeColumn([0], 'sum')).toBe(0);
+ expect(summarizeColumn([], 'count')).toBe(0);
+ expect(summarizeColumn([5], 'none')).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/database/core/column-summary.ts b/apps/web/src/features/database/core/column-summary.ts
new file mode 100644
index 0000000000..dbe31273ad
--- /dev/null
+++ b/apps/web/src/features/database/core/column-summary.ts
@@ -0,0 +1,46 @@
+import { match } from 'ts-pattern';
+import type { DatabaseCellValue } from './database-view';
+
+export type ColumnCalculation =
+ | 'none'
+ | 'count'
+ | 'unique'
+ | 'sum'
+ | 'average'
+ | 'min'
+ | 'max';
+
+/** Summarize the records in view; empty cells never become numeric zeroes. */
+export function summarizeColumn(
+ values: DatabaseCellValue[],
+ calculation: ColumnCalculation
+): number | null {
+ const filled = values.filter((value) => value !== null && value !== '');
+ const numbers = filled.filter(
+ (value): value is number =>
+ typeof value === 'number' && Number.isFinite(value)
+ );
+ return match(calculation)
+ .with('none', () => null)
+ .with('count', () => filled.length)
+ .with('unique', () => new Set(filled).size)
+ .with('sum', () =>
+ numbers.length ? numbers.reduce((sum, value) => sum + value, 0) : null
+ )
+ .with('average', () =>
+ numbers.length
+ ? numbers.reduce((sum, value) => sum + value, 0) / numbers.length
+ : null
+ )
+ .with('min', () =>
+ numbers.length
+ ? numbers.reduce((min, value) => Math.min(min, value))
+ : null
+ )
+ .with('max', () =>
+ numbers.length
+ ? numbers.reduce((max, value) => Math.max(max, value))
+ : null
+ )
+ .exhaustive();
+}
diff --git a/apps/web/src/features/database/views/database-records-view.tsx b/apps/web/src/features/database/views/database-records-view.tsx
index df97017b9d..0fcb463e28 100644
--- a/apps/web/src/features/database/views/database-records-view.tsx
+++ b/apps/web/src/features/database/views/database-records-view.tsx
@@ -1,6 +1,7 @@
import { until } from '@solid-primitives/promise';
import { Button } from '@ui/components/Button';
import { DeleteDialog } from '@ui/components/DeleteDialog';
+import { cn } from '@ui/utils/classname';
import {
type Accessor,
type JSX,
@@ -90,6 +91,8 @@ export type RelationCellProps = GridCellEditorOptions & {
/** A table's records in the view's layout — a grid or a board — with the record panel over them. */
export type DatabaseRecordsViewProps = {
+ /** Host framing for the records area, below the toolbar. */
+ contentClass?: string;
name: string;
source: DatabaseRowsSource;
canEdit: boolean;
@@ -355,7 +358,12 @@ export function DatabaseRecordsView(props: DatabaseRecordsViewProps) {
<>
{/* Rendered once: the toolbar's own props keep it current, and a rerun would close its open popovers. */}
{untrack(() => props.renderToolbar?.(actions))}
- <div class="relative flex min-h-0 flex-1 flex-col overflow-hidden">
+ <div
+ class={cn(
+ 'relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden',
+ props.contentClass
+ )}
+ >
<Show when={columnLayout.schemaError()}>
{(message) => <SchemaErrorNotice message={message()} />}
</Show>
diff --git a/docs/AGENT_GUIDE/databases.md b/docs/AGENT_GUIDE/databases.md
index f1cf4d13f2..0f759f4d33 100644
--- a/docs/AGENT_GUIDE/databases.md
+++ b/docs/AGENT_GUIDE/databases.md
@@ -7,8 +7,8 @@ Opening **Ctrl-K** refreshes database discovery so a database created by AI or
another client appears without reloading. **All** and **Documents** categories
match its name, including databases with no view history.
-Creating from Home immediately shows the table tabs, **New table**, **Database
-actions**, and **AI**; no reload is needed to use them.
+Creating from Home immediately shows the table selector with its **+** menu, **Database
+actions**, and **AI** in the top bar; no reload is needed to use them.
Databases open at
`/app/database/<uuid>`. A database contains tables; records belong to a table and
its properties describe each record. The database name in the split header is an
@@ -56,6 +56,15 @@ PostHog unless the variable was set when it was built. With the flag off:
`showDatabaseSql` (`VITE_SHOW_DATABASE_SQL`) is separate and only hides SQL.
+The table selector matches the inset project/channel navigation. In narrow panes,
+scroll its tabs horizontally with a trackpad, mouse wheel, or the arrow buttons.
+The **+** menu stays visible, and focusing or selecting a table reveals its tab.
+
+The grid’s sticky bottom summary shows the saved records in the current view.
+Choose **+ Add calculation** in a column’s footer for filled/unique counts, or
+sum, average, min, and max on numeric columns. Numeric columns default to Sum.
+Calculation choices are local to the open table, not saved with the view.
+
## CRM pipelines
Pipelines are created from the CRM sidebar's **New pipeline** action. Their
@@ -165,10 +174,12 @@ When the column's property is used outside this database, the editor says
header's **Edit options** menu item and from a board lane header. Changes show at
once and are rolled back if the server refuses them.
-**New table**, beside the table tabs in the toolbar under the split header, creates another table
-with a Name column. Enter a table name and press Enter. The table and its
-column are one request, so a failure creates neither and the dialog stays open
-to retry.
+**+ → New table**, at the right edge of the table selector in the split header,
+adds an inline name field to the tab strip and focuses it immediately. Enter a
+name and press Enter or leave the field to create the table with a Name column.
+Escape cancels the draft; leaving an empty name also cancels. Duplicate names
+are rejected inline. The table and its column are one request, so a failure
+creates neither and keeps the draft available to retry with Enter.
To rename a table, right-click its tab and choose **Rename table**, double-click
the tab, or focus it and press F2. These actions also work on inactive tabs.
The tab itself becomes an input. Enter or leaving the input saves; Escape cancels.
@@ -275,10 +286,13 @@ the table in its own order. Filters, sorts and column changes made on All record
change only what you see, until you make a view of them. Viewers can search and use
All records; only editors change stored views.
-**New view** (the **+** beside the tabs) offers **Table** or **Board**, a name, and
-for a board **Group by**, then **Create view**. The new view starts from what is on
-screen (its filter and sort) and opens. A board groups by a single **Select**
-column; multi-selects and checkboxes cannot group one. Double-click a view tab, press
+**New view** (the **+** beside the tabs) opens a dropdown with **Table** and
+**Board**. Choosing one immediately creates and opens it with an available default
+name, keeping the current filter and sort. A board starts grouped by the first
+single-select or single-person column, or creates a Status column if there are
+none. After creation, use the **Group by** dropdown in the board toolbar to change
+the grouping column. Card settings stay; lane ordering resets for the new groups.
+Multi-selects and checkboxes cannot group a board. Double-click a view tab, press
F2, or right-click it and choose **Rename view** to rename it in place (Enter saves,
Escape cancels). **Delete view** asks for confirmation; the records stay. Drag a tab
to reorder the views.
@@ -307,7 +321,7 @@ not show it. Escape closes the search and returns focus to where it was opened
from. The term is kept while you switch tables.
A view's layout, Table or Board, is chosen when the view is created. Creating a
-view closes the dialog and opens its tab immediately while saving. If saving
+view closes the menu and opens its tab immediately while saving. If saving
fails, the view shows **Retry** and **Dismiss**; retry checks whether the first
attempt committed before creating anything again. Columns
cannot be hidden, and they are added only from **Add column** after the headers or
@@ -502,8 +516,9 @@ completed import does not create a second table.
## Side panel and activity
-The split header's `Show Side Panel` toggle (or `]`) opens the database side panel,
-closed by default. **Details** shows the Owner and Created time. **Activity** (behind
+The split header's `Show Side Panel` toggle (or `]`) opens the shared floating details panel,
+closed by default. It overlays the database without resizing its content; click
+outside to dismiss it. **Details** shows the Owner and Created time. **Activity** (behind
the `enable-entity-activity-section` flag, like documents) lists who created,
renamed, edited, shared, trashed, or restored the database, with the same glyph rail
and folding as a document's Activity section. Every write is one entry: a cell edit,
diff --git a/docs/AGENT_GUIDE/forms.md b/docs/AGENT_GUIDE/forms.md
index 056a03e7cd..d2781eab88 100644
--- a/docs/AGENT_GUIDE/forms.md
+++ b/docs/AGENT_GUIDE/forms.md
@@ -16,10 +16,9 @@ decides who may respond.
- **Create → Form** (shortcut **C → Q**, **Shift** opens it in a new split)
creates "Untitled form" with a new database whose table is "Responses",
and opens the builder at `/app/form/<uuid>`.
-- On a database page you own, **+ view** offers **Form** beside Table and
- Board while no form writes to the current table, and the control after the
- table tabs is **+ Form**; both make a form with a question per existing
- column. Each table has at most one form; the control opens that form once created.
+- On a database page you own, **+ → New form** in the table selector makes
+ a form with a question per existing column while no form writes to the current
+ table. Each table has at most one form; the control opens that form once created.
A trashed form reserves its table until restored or permanently deleted.
Creating over an existing table needs
database Owner: editors and viewers see the existing forms only.