Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
refactor(ok): compose empty states from shadcn Empty (PRD-7910) (#3385)
Andrew Mikofalvy77a966659a15
diff --git a/packages/app/src/components/FileTreeFilteredToZeroNotice.tsx b/packages/app/src/components/FileTreeFilteredToZeroNotice.tsxindex 43405af7e..7b02a889d 100644--- a/packages/app/src/components/FileTreeFilteredToZeroNotice.tsx+++ b/packages/app/src/components/FileTreeFilteredToZeroNotice.tsx@@ -2,6 +2,7 @@ import { humanFormat } from '@inkeep/open-knowledge-core';import { useLingui } from '@lingui/react/macro';import { toast } from 'sonner';import { Button } from '@/components/ui/button';+import { Empty, EmptyContent, EmptyDescription } from '@/components/ui/empty';import { useConfigContext } from '@/lib/config-provider';/**@@ -45,23 +46,22 @@ export function FileTreeFilteredToZeroNotice() {};return (- <div- data-testid="file-tree-filtered-to-zero"- className="flex flex-1 flex-col items-center justify-center gap-3 py-8"- >- <span className="select-none text-sidebar-foreground/30 text-sm">+ <Empty data-testid="file-tree-filtered-to-zero" className="gap-3 p-0 py-8">+ <EmptyDescription className="select-none text-sidebar-foreground/30">{t`All files are hidden by view filters.`}- </span>- <Button- variant="link"- size="sm"- className="font-mono uppercase"- disabled={projectLocalBinding === null}- onClick={handleReset}- data-testid="reset-view-filters"- >- {t`Reset view filters`}- </Button>- </div>+ </EmptyDescription>+ <EmptyContent>+ <Button+ variant="link"+ size="sm"+ className="font-mono uppercase"+ disabled={projectLocalBinding === null}+ onClick={handleReset}+ data-testid="reset-view-filters"+ >+ {t`Reset view filters`}+ </Button>+ </EmptyContent>+ </Empty>);}diff --git a/packages/app/src/components/LargeFileEditorState.dom.test.tsx b/packages/app/src/components/LargeFileEditorState.dom.test.tsxindex c1df429ae..4e4f0a2d8 100644--- a/packages/app/src/components/LargeFileEditorState.dom.test.tsx+++ b/packages/app/src/components/LargeFileEditorState.dom.test.tsx@@ -25,6 +25,58 @@ describe('LargeFileEditorState', () => {expect(screen.queryByRole('button', { name: /go back/i })).toBeNull();});+ test('two panes showing a large file each label their own heading', () => {+ const { container } = render(+ <>+ <LargeFileEditorState docName="one" size={768 * 1024} limit={DOCUMENT_OPEN_BYTE_LIMIT} />+ <LargeFileEditorState docName="two" size={768 * 1024} limit={DOCUMENT_OPEN_BYTE_LIMIT} />+ </>,+ );++ const labelledBy = [...container.querySelectorAll('[role="status"]')].map((node) =>+ node.getAttribute('aria-labelledby'),+ );+ expect(labelledBy.filter(Boolean).length).toBe(2);+ expect(new Set(labelledBy).size).toBe(2);++ const ids = [...container.querySelectorAll('[id]')].map((node) => node.id);+ expect(new Set(ids).size).toBe(ids.length);+ for (const id of labelledBy) {+ expect(ids.filter((candidate) => candidate === id)).toHaveLength(1);+ }+ });++ // The heading's ref now travels through EmptyTitle's Slot before it reaches+ // the h2, so mount-time focus depends on Slot forwarding the child's own ref+ // when the wrapper supplies none. Nothing else pins that, and a radix bump or+ // a shadcn re-sync could silently take it away.+ test('heading takes focus on mount when there is no back button', () => {+ render(+ <LargeFileEditorState+ docName="big-note"+ size={768 * 1024}+ limit={DOCUMENT_OPEN_BYTE_LIMIT}+ />,+ );++ expect(document.activeElement).toBe(+ screen.getByRole('heading', { name: /file too large to open/i }),+ );+ });++ test('back button takes focus on mount when it is present', () => {+ render(+ <LargeFileEditorState+ docName="big-note"+ size={768 * 1024}+ limit={DOCUMENT_OPEN_BYTE_LIMIT}+ backNav={{ previousDocName: 'small-note', onNavigateBack: vi.fn() }}+ />,+ );++ expect(document.activeElement).toBe(screen.getByRole('button', { name: /go back/i }));+ });+test('go back action routes to the previous document', async () => {const onNavigateBack = vi.fn(() => {});render(diff --git a/packages/app/src/components/LargeFileEditorState.tsx b/packages/app/src/components/LargeFileEditorState.tsxindex 52ffdfdea..2ec715eba 100644--- a/packages/app/src/components/LargeFileEditorState.tsx+++ b/packages/app/src/components/LargeFileEditorState.tsx@@ -1,8 +1,16 @@import { formatFileSize } from '@inkeep/open-knowledge-core';import { Trans } from '@lingui/react/macro';import { ArrowLeft, FileWarning } from 'lucide-react';-import { useEffect, useRef } from 'react';+import { useEffect, useId, useRef } from 'react';import { Button } from '@/components/ui/button';+import {+ Empty,+ EmptyContent,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+} from '@/components/ui/empty';interface LargeFileEditorStateProps {docName: string;@@ -18,6 +26,10 @@ export function LargeFileEditorState({ docName, size, limit, backNav }: LargeFilconst canGoBack = backNav !== undefined;const backButtonRef = useRef<HTMLButtonElement>(null);const headingRef = useRef<HTMLHeadingElement>(null);+ // Two panes can show a large-file state at once in a split view, so the+ // label target has to be unique per instance or the second pane's status+ // region resolves aria-labelledby to the first pane's heading.+ const titleId = useId();useEffect(() => {if (canGoBack) {@@ -28,41 +40,49 @@ export function LargeFileEditorState({ docName, size, limit, backNav }: LargeFil}, [canGoBack]);return (- <div+ <Emptyrole="status"- aria-labelledby="large-file-title"+ aria-labelledby={titleId}+ // Overrides the primitive's own slot: the pane identifies itself by this+ // value, which predates the primitive.data-slot="large-file-editor-state"- className="flex h-full flex-col items-center justify-center gap-8 p-8 text-center"+ className="h-full gap-8 p-8">- <div className="flex size-16 items-center justify-center rounded-full border bg-muted/40 text-muted-foreground">+ <EmptyMedia+ variant="icon"+ className="mb-0 size-16 rounded-full border bg-muted/40 text-muted-foreground"+ ><FileWarning className="size-9" aria-hidden="true" />- </div>- <div className="flex flex-col items-center gap-1">- <h2- ref={headingRef}- id="large-file-title"- tabIndex={canGoBack ? undefined : -1}- className="text-2xl font-light text-balance outline-none"- >- <Trans>File too large to open</Trans>- </h2>- <p className="max-w-md text-sm text-muted-foreground">+ </EmptyMedia>+ <EmptyHeader className="max-w-md gap-1">+ {/* Classes go on EmptyTitle, not the h2: Slot concatenates the two+ className strings without resolving Tailwind conflicts, so the+ primitive's own text-sm/font-medium would win over this heading's+ size and weight. Routing them through EmptyTitle lets `cn` merge. */}+ <EmptyTitle asChild className="text-2xl font-light outline-none">+ <h2 ref={headingRef} id={titleId} tabIndex={canGoBack ? undefined : -1}>+ <Trans>File too large to open</Trans>+ </h2>+ </EmptyTitle>+ <EmptyDescription><Trans>{docName} is {formatFileSize(size)}. OpenKnowledge currently opens files up to{' '}{formatFileSize(limit)}.</Trans>- </p>- </div>+ </EmptyDescription>+ </EmptyHeader>{canGoBack ? (- <Button- ref={backButtonRef}- variant="default"- onClick={() => backNav.onNavigateBack(backNav.previousDocName)}- >- <ArrowLeft className="size-4" aria-hidden="true" />- <Trans>Go back</Trans>- </Button>+ <EmptyContent>+ <Button+ ref={backButtonRef}+ variant="default"+ onClick={() => backNav.onNavigateBack(backNav.previousDocName)}+ >+ <ArrowLeft className="size-4" aria-hidden="true" />+ <Trans>Go back</Trans>+ </Button>+ </EmptyContent>) : null}- </div>+ </Empty>);}diff --git a/packages/app/src/components/ui/empty.dom.test.tsx b/packages/app/src/components/ui/empty.dom.test.tsxnew file mode 100644index 000000000..0bdc76dd3--- /dev/null+++ b/packages/app/src/components/ui/empty.dom.test.tsx@@ -0,0 +1,172 @@+/**+ * DOM-substrate tests for the Empty layout primitive. Call sites style+ * themselves through `className` and identify their parts through `data-slot`,+ * so those two are the primitive's whole contract; the `asChild` title is the+ * one place we diverge from upstream and therefore the one place a silent+ * regression would go unnoticed.+ */++import { cleanup, render, screen } from '@testing-library/react';+import { afterEach, describe, expect, test } from 'vitest';+import { expectVisualClassTokens } from '@/test-utils/visual-contract';+import {+ Empty,+ EmptyContent,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+} from './empty';++afterEach(cleanup);++function slot(container: HTMLElement, name: string): HTMLElement {+ const found = container.querySelector<HTMLElement>(`[data-slot="${name}"]`);+ if (!found) throw new Error(`no element with data-slot="${name}"`);+ return found;+}++describe('Empty', () => {+ test('renders every part under its own slot, nested as composed', () => {+ const { container } = render(+ <Empty>+ <EmptyMedia variant="icon">+ <svg aria-hidden="true" />+ </EmptyMedia>+ <EmptyHeader>+ <EmptyTitle>Nothing here</EmptyTitle>+ <EmptyDescription>Add something to get started.</EmptyDescription>+ </EmptyHeader>+ <EmptyContent>+ <span>action</span>+ </EmptyContent>+ </Empty>,+ );++ const root = slot(container, 'empty');+ for (const name of ['empty-icon', 'empty-header', 'empty-title', 'empty-description']) {+ expect(root.contains(slot(container, name))).toBe(true);+ }+ expect(slot(container, 'empty-header').contains(slot(container, 'empty-title'))).toBe(true);+ expect(screen.getByText('Nothing here')).toBeTruthy();+ expect(screen.getByText('Add something to get started.')).toBeTruthy();+ });++ test('caller className composes with the base classes rather than replacing them', () => {+ const { container } = render(<Empty className="h-full gap-8">empty</Empty>);++ expectVisualClassTokens(slot(container, 'empty').getAttribute('class'), [+ 'flex-col',+ 'items-center',+ 'justify-center',+ 'h-full',+ 'gap-8',+ ]);+ });++ test('conflicting caller utilities win over the base classes', () => {+ const { container } = render(<Empty className="gap-8 p-8">empty</Empty>);++ const className = slot(container, 'empty').getAttribute('class') ?? '';+ expect(className).not.toContain('gap-4');+ expect(className).not.toContain('p-6');+ });++ // The merge only resolves within a class group, and px/py do not supersede p.+ // A call site that spells its padding override in longhand alone leaves the+ // base p-6 in the class list and hands the outcome to Tailwind's stylesheet+ // order instead. Lead with a shorthand and the base is actually displaced.+ test('replacing the root padding needs a shorthand, not longhand alone', () => {+ const { container: longhandOnly } = render(<Empty className="px-0 py-8">empty</Empty>);+ expect(slot(longhandOnly, 'empty').getAttribute('class')).toContain('p-6');++ cleanup();++ const { container: withShorthand } = render(<Empty className="p-0 py-8">empty</Empty>);+ const className = slot(withShorthand, 'empty').getAttribute('class') ?? '';+ expect(className).not.toContain('p-6');+ expectVisualClassTokens(className, ['p-0', 'py-8']);+ });++ test('caller props override the primitive defaults, including its own slot', () => {+ render(+ <Empty role="status" aria-label="Nothing to show" data-slot="large-file-editor-state">+ empty+ </Empty>,+ );++ const root = screen.getByRole('status');+ expect(root.getAttribute('data-slot')).toBe('large-file-editor-state');+ expect(root.getAttribute('aria-label')).toBe('Nothing to show');+ });++ test('media records its variant so call sites can target the icon treatment', () => {+ const { container: iconVariant } = render(+ <EmptyMedia variant="icon">+ <svg aria-hidden="true" />+ </EmptyMedia>,+ );+ expect(slot(iconVariant, 'empty-icon').getAttribute('data-variant')).toBe('icon');++ cleanup();++ const { container: defaultVariant } = render(+ <EmptyMedia>+ <svg aria-hidden="true" />+ </EmptyMedia>,+ );+ expect(slot(defaultVariant, 'empty-icon').getAttribute('data-variant')).toBe('default');+ });+});++describe('EmptyTitle', () => {+ test('renders a plain container by default', () => {+ const { container } = render(<EmptyTitle>Nothing here</EmptyTitle>);++ expect(slot(container, 'empty-title').tagName).toBe('DIV');+ expect(screen.queryByRole('heading')).toBeNull();+ });++ test('asChild keeps the caller element, so a heading stays a heading', () => {+ const { container } = render(+ <EmptyTitle asChild>+ <h2>Nothing here</h2>+ </EmptyTitle>,+ );++ const title = slot(container, 'empty-title');+ expect(title.tagName).toBe('H2');+ expect(screen.getByRole('heading', { name: 'Nothing here' })).toBe(title);+ });++ test('asChild forwards the caller attributes needed to label and focus the title', () => {+ render(+ <EmptyTitle asChild>+ <h2 id="empty-title-probe" tabIndex={-1}>+ Nothing here+ </h2>+ </EmptyTitle>,+ );++ const heading = screen.getByRole('heading', { name: 'Nothing here' });+ expect(heading.id).toBe('empty-title-probe');+ heading.focus();+ expect(document.activeElement).toBe(heading);+ });++ test('asChild still merges the title className, so caller sizing wins', () => {+ const { container } = render(+ <EmptyTitle asChild className="text-2xl font-light">+ <h2>Nothing here</h2>+ </EmptyTitle>,+ );++ const className = slot(container, 'empty-title').getAttribute('class') ?? '';+ // The merge has to resolve conflicts, not concatenate: Tailwind's own+ // stylesheet order would otherwise let the primitive's font-medium beat the+ // caller's font-light regardless of which class is written last.+ expect(className).not.toContain('text-sm');+ expect(className).not.toContain('font-medium');+ expectVisualClassTokens(className, ['text-2xl', 'font-light', 'tracking-tight']);+ });+});diff --git a/packages/app/src/components/ui/empty.tsx b/packages/app/src/components/ui/empty.tsxnew file mode 100644index 000000000..0d27a934b--- /dev/null+++ b/packages/app/src/components/ui/empty.tsx@@ -0,0 +1,119 @@+import { cva, type VariantProps } from 'class-variance-authority';+import { Slot } from 'radix-ui';+import type * as React from 'react';++import { cn } from '@/lib/utils';++/**+ * Empty-state layout primitive: a centered media / title / description column+ * with an optional action block underneath.+ *+ * Installed from the project's configured `radix-nova` style, unmodified apart+ * from the `asChild` escape hatch on `EmptyTitle` described below. Every part is+ * an unstyled-ish `div` carrying a `data-slot`, so call sites whose visual+ * design predates the primitive keep their own spacing and colors by passing+ * `className` and still gain the shared structure and styling hooks.+ *+ * Deliberate divergence from upstream, recorded so a future `shadcn diff`+ * reviewer knows the drift is intentional rather than rot: `EmptyTitle` accepts+ * `asChild`. Upstream renders it as a plain `div`, which would strip heading+ * semantics from any empty state whose title is a real `<h2>` — a regression for+ * screen-reader users navigating by heading. `asChild` lets such a call site+ * keep its heading element and still pick up the title slot and styles.+ */+function Empty({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="empty"+ className={cn(+ 'flex w-full min-w-0 flex-1 flex-col items-center justify-center gap-4 rounded-xl border-dashed p-6 text-center text-balance',+ className,+ )}+ {...props}+ />+ );+}++function EmptyHeader({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="empty-header"+ className={cn('flex max-w-sm flex-col items-center gap-2', className)}+ {...props}+ />+ );+}++const emptyMediaVariants = cva(+ 'mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0',+ {+ variants: {+ variant: {+ default: 'bg-transparent',+ icon: "flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground [&_svg:not([class*='size-'])]:size-4",+ },+ },+ defaultVariants: {+ variant: 'default',+ },+ },+);++function EmptyMedia({+ className,+ variant = 'default',+ ...props+}: React.ComponentProps<'div'> & VariantProps<typeof emptyMediaVariants>) {+ return (+ <div+ data-slot="empty-icon"+ data-variant={variant}+ className={cn(emptyMediaVariants({ variant, className }))}+ {...props}+ />+ );+}++function EmptyTitle({+ className,+ asChild = false,+ ...props+}: React.ComponentProps<'div'> & { asChild?: boolean }) {+ const Comp = asChild ? Slot.Root : 'div';++ return (+ <Comp+ data-slot="empty-title"+ className={cn('font-heading text-sm font-medium tracking-tight', className)}+ {...props}+ />+ );+}++function EmptyDescription({ className, ...props }: React.ComponentProps<'p'>) {+ return (+ <div+ data-slot="empty-description"+ className={cn(+ 'text-sm/relaxed text-muted-foreground [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary',+ className,+ )}+ {...props}+ />+ );+}++function EmptyContent({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="empty-content"+ className={cn(+ 'flex w-full max-w-sm min-w-0 flex-col items-center gap-2.5 text-sm text-balance',+ className,+ )}+ {...props}+ />+ );+}++export { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle };