Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): schema-aware property adding (#3170)

serafin-garcia2a304fc772c8
diff --git a/.changeset/schema-aware-property-adding.md b/.changeset/schema-aware-property-adding.md
new file mode 100644
index 000000000..9e3201f4d
--- /dev/null
+++ b/.changeset/schema-aware-property-adding.md
@@ -0,0 +1,20 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Adding a frontmatter property now knows what the document's schema declares.
+
+The **Add properties** button already counted the schema-required properties a
+document was missing, but clicking it opened one blank row — you still had to go
+read the schema and retype every name it had already stated. It now stages a
+pre-named row for each missing property, with the widget type taken from the
+schema and the cursor in the first value. Nothing is written until you fill a
+row in and add it, so a half-finished batch never leaves empty properties behind
+(and never clears the "required" warning with a blank value).
+
+The name field on any add-row also offers the fields the governing schemas
+declare — filtered as you type, showing each field's type and description, and
+marking the required ones. Picking one fills in the name and its type together.
+It stays a free-text field: schemas don't own the whole vocabulary, and a
+document governed by no schema is unchanged. Enum-constrained fields now offer
+their vocabulary while being added, not only after.
diff --git a/docs/content/advanced/content-rules/frontmatter.mdx b/docs/content/advanced/content-rules/frontmatter.mdx
index e39922e3d..7b157431a 100644
--- a/docs/content/advanced/content-rules/frontmatter.mdx
+++ b/docs/content/advanced/content-rules/frontmatter.mdx
@@ -114,6 +114,8 @@ Edits are **non-destructive**: the editor merges only the field you changed, and
The document panel's property editor reads the same schemas through the same `appliesTo` matching as the linter, so the two can never disagree. A field constrained by `enum` renders as a select instead of free text; an array field with `items.enum` renders as a multi-select. When several schemas govern a doc, the offered values are the intersection — and if no value could satisfy them all, the field falls back to free text while the linter reports the conflict.
+Adding a property is schema-aware too. The **Add properties** button carries a badge counting the schema-required properties the document is missing, and clicking it stages one pre-named row per missing property — the widget type taken from the schema, the cursor in the first value. Nothing is written until you fill a row in and add it, so a half-finished batch never leaves an empty property behind or clears a `required` warning with a blank value. The name field on any add-row also offers the fields the governing schemas declare — filtered as you type, each showing its type and description and marking the required ones; picking one fills in the name and type together. It stays free text, so a property no schema declares is still yours to add, and enum-constrained fields offer their vocabulary while being added, not only once they exist.
+
## AI agents
Beyond the shared `lint` tool and write advisories (see the [overview](/docs/advanced/content-rules/overview#ai-agents)), reads advertise the contract up front: `exec` listings and reads carry a `schemas:` entry naming the schema files that govern each doc — and each folder, so an agent learns the expected shape **before** writing the first doc there. An `exec("ls docs/")` comes back with:
diff --git a/packages/app/src/components/AddPropertiesButton.dom.test.tsx b/packages/app/src/components/AddPropertiesButton.dom.test.tsx
index ee263a3d5..222020262 100644
--- a/packages/app/src/components/AddPropertiesButton.dom.test.tsx
+++ b/packages/app/src/components/AddPropertiesButton.dom.test.tsx
@@ -90,4 +90,17 @@ describe('AddPropertiesButton frontmatter badge', () => {
expect(tooltip.textContent).toContain('Frontmatter property "status" is required');
expect(tooltip.textContent).toContain('Frontmatter property "owner" is required');
});
+
+ test('tells the user the button acts on the problems it reports', async () => {
+ // A count and a list alone read as a report. Clicking is what stages the
+ // rows, and nothing else on the surface says so.
+ const user = userEvent.setup();
+ await renderButton({
+ problemCount: 1,
+ problemMessages: ['Frontmatter property "status" is required'],
+ });
+ await user.hover(screen.getByRole('button'));
+ const tooltip = await screen.findByRole('tooltip');
+ expect(tooltip.textContent).toMatch(/click to add/i);
+ });
});
diff --git a/packages/app/src/components/AddPropertiesButton.tsx b/packages/app/src/components/AddPropertiesButton.tsx
index 7c462470b..b8f95d992 100644
--- a/packages/app/src/components/AddPropertiesButton.tsx
+++ b/packages/app/src/components/AddPropertiesButton.tsx
@@ -88,6 +88,13 @@ export function AddPropertiesButton({
{message}
</span>
))}
+ {/* The badge says something is wrong; without this the button reads
+ as a report rather than the thing that acts on it. "Fill them
+ in" is load-bearing — clicking stages the rows, it does not
+ write the properties. */}
+ <span className="pt-0.5 opacity-70">
+ <Trans>Click to add and fill them in</Trans>
+ </span>
</span>
) : (
<Trans>Add properties</Trans>
diff --git a/packages/app/src/components/AddPropertyNameField.dom.test.tsx b/packages/app/src/components/AddPropertyNameField.dom.test.tsx
new file mode 100644
index 000000000..6697663ab
--- /dev/null
+++ b/packages/app/src/components/AddPropertyNameField.dom.test.tsx
@@ -0,0 +1,377 @@
+/**
+ * The add-property name field offers the fields the doc's governing schemas
+ * declare, so adding a schema-governed property doesn't mean leaving the doc to
+ * look up its name and type.
+ *
+ * Two properties carry the design. The field stays FREE TEXT — schemas leave
+ * `additionalProperties` open and most docs have no schema at all, so a select
+ * would take away more than it gives. And picking supplies the type as well as
+ * the name, which is the half that saves the user a trip to the schema.
+ */
+
+import type { FrontmatterType } from '@inkeep/open-knowledge-core';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { useRef, useState } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { type AddPropertyFieldSuggestion, AddPropertyNameField } from './AddPropertyNameField';
+
+const FIELDS: AddPropertyFieldSuggestion[] = [
+ { name: 'status', type: 'text', required: true, description: 'Lifecycle stage' },
+ { name: 'tags', type: 'list', required: false },
+ { name: 'reviewedAt', type: 'date', required: false },
+];
+
+function Harness({
+ suggestions = FIELDS,
+ autoFocus = false,
+ onPick = () => {},
+ onCommit = () => {},
+ onCancel = () => {},
+}: {
+ suggestions?: readonly AddPropertyFieldSuggestion[];
+ autoFocus?: boolean;
+ onPick?: (s: AddPropertyFieldSuggestion) => void;
+ onCommit?: () => void;
+ onCancel?: () => void;
+}) {
+ const [value, setValue] = useState('');
+ const inputRef = useRef<HTMLInputElement>(null);
+ return (
+ <AddPropertyNameField
+ rowId="row-1"
+ value={value}
+ suggestions={suggestions}
+ inputRef={inputRef}
+ autoFocus={autoFocus}
+ error={false}
+ onChange={setValue}
+ onPick={(suggestion) => {
+ setValue(suggestion.name);
+ onPick(suggestion);
+ }}
+ onCommit={onCommit}
+ onCancel={onCancel}
+ />
+ );
+}
+
+function input(): HTMLInputElement {
+ return screen.getByTestId('add-property-name-input');
+}
+
+function options(): HTMLElement[] {
+ return screen.queryAllByTestId('add-property-field-suggestion');
+}
+
+afterEach(() => cleanup());
+
+describe('AddPropertyNameField — schema field picker', () => {
+ test('a row that mounts focused shows the list without a keystroke', async () => {
+ // `autoFocus` is a mount-time attribute and fires no `focus` event, so an
+ // open-on-focus-only field would stay shut on the row the user was just
+ // dropped into — hiding the schema's fields behind a keypress they have no
+ // reason to guess.
+ render(<Harness autoFocus />);
+ await waitFor(() => expect(options()).toHaveLength(3));
+ });
+
+ test('a row that mounts focused with no schema opens nothing', async () => {
+ render(<Harness autoFocus suggestions={[]} />);
+ expect(options()).toHaveLength(0);
+ });
+
+ test('focusing offers every declared field', async () => {
+ render(<Harness />);
+ await userEvent.click(input());
+ await waitFor(() => expect(options()).toHaveLength(3));
+ expect(options().map((el) => el.getAttribute('data-key'))).toEqual([
+ 'status',
+ 'tags',
+ 'reviewedAt',
+ ]);
+ });
+
+ test('typing narrows the list case-insensitively', async () => {
+ render(<Harness />);
+ await userEvent.click(input());
+ await userEvent.type(input(), 'TAG');
+ await waitFor(() => expect(options()).toHaveLength(1));
+ expect(options()[0]?.getAttribute('data-key')).toBe('tags');
+ });
+
+ test('picking supplies the name and the schema type together', async () => {
+ const onPick = vi.fn();
+ render(<Harness onPick={onPick} />);
+ await userEvent.click(input());
+ await waitFor(() => expect(options().length).toBeGreaterThan(0));
+
+ const tags = options().find((el) => el.getAttribute('data-key') === 'tags');
+ if (!tags) throw new Error('no `tags` option');
+ await userEvent.click(tags);
+
+ expect(onPick).toHaveBeenCalledTimes(1);
+ const picked = onPick.mock.calls[0]?.[0] as AddPropertyFieldSuggestion;
+ expect(picked.name).toBe('tags');
+ // The point of the ticket: the type rides along, so the user never picks it.
+ expect(picked.type satisfies FrontmatterType).toBe('list');
+ expect(input().value).toBe('tags');
+ });
+
+ test('picking closes the list', async () => {
+ render(<Harness />);
+ await userEvent.click(input());
+ await waitFor(() => expect(options().length).toBeGreaterThan(0));
+ await userEvent.click(options()[0] as HTMLElement);
+ await waitFor(() => expect(options()).toHaveLength(0));
+ });
+
+ test('arrow keys move the highlight and Enter takes it', async () => {
+ const onPick = vi.fn();
+ const onCommit = vi.fn();
+ render(<Harness onPick={onPick} onCommit={onCommit} />);
+ await userEvent.click(input());
+ await waitFor(() => expect(options().length).toBeGreaterThan(0));
+
+ // Nothing is highlighted until the user moves into the list, so the first
+ // ArrowDown lands on the first option rather than stepping past it.
+ await userEvent.keyboard('{ArrowDown}{Enter}');
+
+ expect(onPick).toHaveBeenCalledTimes(1);
+ expect((onPick.mock.calls[0]?.[0] as AddPropertyFieldSuggestion).name).toBe('status');
+ // Enter belonged to the option the user had moved onto, so it must not have
+ // also committed.
+ expect(onCommit).not.toHaveBeenCalled();
+ });
+
+ test('ArrowDown then ArrowDown reaches the second option', async () => {
+ // Guards the off-by-one the other direction: entering the list must not cost
+ // a keypress that leaves the first option unreachable or skipped.
+ const onPick = vi.fn();
+ render(<Harness onPick={onPick} />);
+ await userEvent.click(input());
+ await waitFor(() => expect(options().length).toBeGreaterThan(0));
+
+ await userEvent.keyboard('{ArrowDown}{ArrowDown}{Enter}');
+
+ expect((onPick.mock.calls[0]?.[0] as AddPropertyFieldSuggestion).name).toBe('tags');
+ });
+
+ test('ArrowUp enters the list at the last option', async () => {
+ // Reaching upward into an unselected list lands at the bottom, the same way
+ // ArrowDown lands at the top — not one step above the first option.
+ const onPick = vi.fn();
+ render(<Harness onPick={onPick} />);
+ await userEvent.click(input());
+ await waitFor(() => expect(options().length).toBeGreaterThan(0));
+
+ await userEvent.keyboard('{ArrowUp}{Enter}');
+
+ expect((onPick.mock.calls[0]?.[0] as AddPropertyFieldSuggestion).name).toBe('reviewedAt');
+ });
+
+ test('typing after arrowing into the list drops back out of it', async () => {
+ // The highlight is the user's position in the list; a keystroke restates the
+ // name instead, so Enter must go back to committing what is typed.
+ const onCommit = vi.fn();
+ const onPick = vi.fn();
+ render(<Harness onCommit={onCommit} onPick={onPick} />);
+ await userEvent.click(input());
+ await waitFor(() => expect(options().length).toBeGreaterThan(0));
+
+ await userEvent.keyboard('{ArrowDown}');
+ await userEvent.type(input(), 'stat');
+ await userEvent.keyboard('{Enter}');
+
+ expect(onPick).not.toHaveBeenCalled();
+ expect(onCommit).toHaveBeenCalledTimes(1);
+ expect(input().value).toBe('stat');
+ });
+
+ test('arrow navigation scrolls the highlighted option into view', async () => {
+ // Focus stays in the input, so the browser will not scroll the
+ // aria-activedescendant target the way it scrolls a focused element — a long
+ // list would leave the highlight below the `max-h-64` fold. jsdom stubs
+ // scrollIntoView, so this pins the call the ARIA APG pattern requires.
+ const scrollIntoView = vi.spyOn(HTMLElement.prototype, 'scrollIntoView');
+ try {
+ render(<Harness />);
+ await userEvent.click(input());
+ await waitFor(() => expect(options().length).toBeGreaterThan(0));
+ scrollIntoView.mockClear();
+
+ await userEvent.keyboard('{ArrowDown}');
+
+ expect(scrollIntoView).toHaveBeenCalled();
+ } finally {
+ scrollIntoView.mockRestore();
+ }
+ });
+
+ test('Enter commits a free-typed name the schema does not declare', async () => {
+ const onCommit = vi.fn();
+ const onPick = vi.fn();
+ render(<Harness onCommit={onCommit} onPick={onPick} />);
+ await userEvent.click(input());
+ await userEvent.type(input(), 'notInSchema');
+ await userEvent.keyboard('{Enter}');
+
+ // No match means no list, so Enter keeps the row's own commit semantics —
+ // a schema must not be able to block a property it never declared.
+ expect(onCommit).toHaveBeenCalledTimes(1);
+ expect(onPick).not.toHaveBeenCalled();
+ });
+
+ test('Enter commits a name that merely contains a declared field name', async () => {
+ // `tag` is a substring of `tags`, so the list stays up — but the user typed
+ // `tag` and no schema owns the name well enough to overwrite it. Substituting
+ // the suggestion here silently renames the property AND replaces the type the
+ // user may already have drafted.
+ const onCommit = vi.fn();
+ const onPick = vi.fn();
+ render(<Harness onCommit={onCommit} onPick={onPick} />);
+ await userEvent.click(input());
+ await userEvent.type(input(), 'tag');
+ await waitFor(() => expect(options()).toHaveLength(1));
+
+ await userEvent.keyboard('{Enter}');
+
+ expect(onPick).not.toHaveBeenCalled();
+ expect(onCommit).toHaveBeenCalledTimes(1);
+ expect(input().value).toBe('tag');
+ // A row the host declines to commit must not be left under a popup the user
+ // has already answered.
+ await waitFor(() => expect(options()).toHaveLength(0));
+ });
+
+ test('Enter keeps the typed casing of a name a field declares differently', async () => {
+ // The list matches case-insensitively, so `STATUS` keeps `status` on offer.
+ // Taking it on a bare Enter would silently re-case a name the user typed out
+ // in full.
+ const onCommit = vi.fn();
+ const onPick = vi.fn();
+ render(<Harness onCommit={onCommit} onPick={onPick} />);
+ await userEvent.click(input());
+ await userEvent.type(input(), 'STATUS');
+ await waitFor(() => expect(options()).toHaveLength(1));
+
+ await userEvent.keyboard('{Enter}');
+
+ expect(onPick).not.toHaveBeenCalled();
+ expect(onCommit).toHaveBeenCalledTimes(1);
+ expect(input().value).toBe('STATUS');
+ });
+
+ test('Enter on an exactly-typed field name commits rather than re-picking it', async () => {
+ const onCommit = vi.fn();
+ const onPick = vi.fn();
+ render(<Harness onCommit={onCommit} onPick={onPick} />);
+ await userEvent.click(input());
+ await userEvent.type(input(), 'tags');
+ await userEvent.keyboard('{Enter}');
+
+ expect(onCommit).toHaveBeenCalledTimes(1);
+ expect(onPick).not.toHaveBeenCalled();
+ });
+
+ test('an arrow key stays native when an exact name has closed the list', async () => {
+ // With nothing to navigate, the key must keep its caret-movement meaning.
+ // Guarding only on an empty filter misses this: an exact match leaves the
+ // filter non-empty, so the handler swallowed the key and then failed to
+ // open a list that `exactlyTyped` holds shut — a keypress that did nothing
+ // at all.
+ render(<Harness />);
+ await userEvent.click(input());
+ await userEvent.type(input(), 'tags');
+ await waitFor(() => expect(options()).toHaveLength(0));
+
+ // `fireEvent` returns false when a handler called preventDefault.
+ expect(fireEvent.keyDown(input(), { key: 'ArrowDown' })).toBe(true);
+ expect(fireEvent.keyDown(input(), { key: 'ArrowUp' })).toBe(true);
+ expect(options()).toHaveLength(0);
+ });
+
+ test('Escape closes the list before it abandons the row', async () => {
+ const onCancel = vi.fn();
+ render(<Harness onCancel={onCancel} />);
+ await userEvent.click(input());
+ await waitFor(() => expect(options().length).toBeGreaterThan(0));
+
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(options()).toHaveLength(0));
+ expect(onCancel).not.toHaveBeenCalled();
+
+ await userEvent.keyboard('{Escape}');
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ });
+
+ test('the input keeps focus while the list is open', async () => {
+ // Focus moving into the popup would send the next keystroke nowhere.
+ render(<Harness />);
+ await userEvent.click(input());
+ await waitFor(() => expect(options().length).toBeGreaterThan(0));
+ expect(document.activeElement).toBe(input());
+ });
+
+ test('with no declared fields it is a plain text input', async () => {
+ render(<Harness suggestions={[]} />);
+ await userEvent.click(input());
+ await userEvent.type(input(), 'anything');
+ expect(options()).toHaveLength(0);
+ // No combobox semantics to announce when there is nothing to offer.
+ expect(input().getAttribute('role')).toBeNull();
+ expect(input().getAttribute('aria-expanded')).toBeNull();
+ expect(input().value).toBe('anything');
+ });
+
+ test('the open list is announced as a combobox popup', async () => {
+ render(<Harness />);
+ await userEvent.click(input());
+ await waitFor(() => expect(options().length).toBeGreaterThan(0));
+
+ expect(input().getAttribute('role')).toBe('combobox');
+ expect(input().getAttribute('aria-expanded')).toBe('true');
+ expect(input().getAttribute('aria-autocomplete')).toBe('list');
+ const listboxId = input().getAttribute('aria-controls');
+ expect(listboxId).toBeTruthy();
+ expect(document.getElementById(listboxId ?? '')?.getAttribute('role')).toBe('listbox');
+ // Merely opening selects nothing, so there is no option for
+ // aria-activedescendant to point at yet.
+ expect(input().getAttribute('aria-activedescendant')).toBeNull();
+ expect(options().some((el) => el.getAttribute('aria-selected') === 'true')).toBe(false);
+
+ await userEvent.keyboard('{ArrowDown}');
+
+ // Once the user is in the list the highlighted option is reachable by id,
+ // which is how a screen reader follows the selection while focus stays in
+ // the input.
+ const activeId = input().getAttribute('aria-activedescendant');
+ expect(activeId).toBeTruthy();
+ expect(document.getElementById(activeId ?? '')?.getAttribute('aria-selected')).toBe('true');
+ });
+
+ test('hovering an option makes it the one Enter takes', async () => {
+ // Hover is the pointer's version of arrowing in — an explicit move onto an
+ // option, so it arms Enter the same way.
+ const onPick = vi.fn();
+ render(<Harness onPick={onPick} />);
+ await userEvent.click(input());
+ await waitFor(() => expect(options().length).toBeGreaterThan(0));
+
+ const tags = options().find((el) => el.getAttribute('data-key') === 'tags');
+ if (!tags) throw new Error('no `tags` option');
+ await userEvent.hover(tags);
+ await userEvent.keyboard('{Enter}');
+
+ expect((onPick.mock.calls[0]?.[0] as AddPropertyFieldSuggestion).name).toBe('tags');
+ });
+
+ test('a required field is marked in the list', async () => {
+ render(<Harness />);
+ await userEvent.click(input());
+ await waitFor(() => expect(options().length).toBeGreaterThan(0));
+ const status = options().find((el) => el.getAttribute('data-key') === 'status');
+ expect(status?.textContent).toContain('required');
+ expect(status?.textContent).toContain('Lifecycle stage');
+ });
+});
diff --git a/packages/app/src/components/AddPropertyNameField.tsx b/packages/app/src/components/AddPropertyNameField.tsx
new file mode 100644
index 000000000..2dfeae8bc
--- /dev/null
+++ b/packages/app/src/components/AddPropertyNameField.tsx
@@ -0,0 +1,291 @@
+/**
+ * The add-property row's name field: a free-text input that also offers the
+ * fields the doc's governing schemas declare.
+ *
+ * Adding a schema-governed property otherwise means leaving the doc to read the
+ * schema, coming back, retyping the name, and hand-picking a type the schema
+ * already states. Picking a suggestion fills both.
+ *
+ * Free text is preserved rather than replaced by a select: schemas do not own
+ * the whole vocabulary (`additionalProperties` is open by default, and most
+ * docs are governed by no schema at all). With no suggestions to offer this is
+ * exactly the plain input it replaced — the popup never mounts.
+ *
+ * Shape is the ARIA 1.2 combobox-with-listbox-popup pattern, hand-driven rather
+ * than delegated to `cmdk`: focus has to stay in the input for typing to work,
+ * and cmdk listens for keys on its own root, so its navigation never sees them.
+ * The popup is a Radix popover because the properties disclosure clips
+ * overflow — an in-flow dropdown would be cut off.
+ */
+
+import { Trans, useLingui } from '@lingui/react/macro';
+import { type KeyboardEvent, type RefObject, useId, useState } from 'react';
+import { TYPE_ICON } from '@/components/PropertyWidgets';
+import { Badge } from '@/components/ui/badge';
+import { Input } from '@/components/ui/input';
+import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover';
+import type { SchemaField } from '@/lib/frontmatter-schema-fields';
+
+/**
+ * One schema-declared field the picker can offer — a `SchemaField` plus the name
+ * it is declared under. Derived rather than redeclared: the host builds these by
+ * spreading a `SchemaField`, so a member added there should reach the picker
+ * without anyone remembering to widen this too.
+ */
+export interface AddPropertyFieldSuggestion extends SchemaField {
+ name: string;
+}
+
+/** Case-insensitive substring match on the field name. */
+function matches(suggestion: AddPropertyFieldSuggestion, query: string): boolean {
+ if (query === '') return true;
+ return suggestion.name.toLowerCase().includes(query.trim().toLowerCase());
+}
+
+/**
+ * The list is up but the user has not moved into it, so nothing is highlighted.
+ *
+ * Without a state for this, an open list always has an active option and Enter
+ * always takes it — which substitutes a schema field for any name that merely
+ * contains one (`tag` becomes `tags`), overwriting the drafted type along with
+ * the name. Matches the ARIA APG editable combobox: opening does not select, and
+ * Enter adopts an option only once the user has arrowed or hovered onto it.
+ */
+const NO_HIGHLIGHT = -1;
+
+export function AddPropertyNameField({
+ rowId,
+ value,
+ suggestions,
+ inputRef,
+ autoFocus,
+ error,
+ errorId,
+ onChange,
+ onPick,
+ onCommit,
+ onCancel,
+}: {
+ /** Scopes this field's DOM ids so sibling add-rows can't collide. */
+ rowId: string;
+ value: string;
+ /** Offerable fields — the host excludes the ones the doc already has. */
+ suggestions: readonly AddPropertyFieldSuggestion[];
+ inputRef: RefObject<HTMLInputElement | null>;
+ autoFocus: boolean;
+ error: boolean;
+ errorId?: string;
+ onChange: (next: string) => void;
+ /** Picking sets the name AND the schema's type in one update. */
+ onPick: (suggestion: AddPropertyFieldSuggestion) => void;
+ onCommit: () => void;
+ onCancel: () => void;
+}) {
+ const { t } = useLingui();
+ const baseId = useId();
+ const listboxId = `${baseId}-fields`;
+ // A row that mounts already focused starts with its list up. `autoFocus` is a
+ // mount-time attribute, so no `focus` event ever fires for it — waiting on
+ // one would hide the schema's fields behind a keystroke the user has no
+ // reason to guess, which is most of what the picker is for.
+ const [open, setOpen] = useState(() => autoFocus && suggestions.length > 0);
+ const [highlight, setHighlight] = useState(NO_HIGHLIGHT);
+
+ const filtered = suggestions.filter((suggestion) => matches(suggestion, value));
+ // An exact hit is the field the user already typed out; keeping the popup up
+ // would just offer them what they have and swallow the Enter that commits it.
+ const exactlyTyped = filtered.some((s) => s.name === value.trim());
+ const isOpen = open && filtered.length > 0 && !exactlyTyped;
+
+ // Typing narrows the list, so a held index would leave the highlight on
+ // whatever field happens to sit at that position afterwards. Each keystroke
+ // is also a fresh statement of intent, so it drops the user back out of the
+ // list and Enter goes back to committing what they typed. Adjusted during
+ // render (React's documented reset-on-prop-change pattern) instead of in an
+ // effect, which would paint the stale highlight for a frame first.
+ const [queryAtLastReset, setQueryAtLastReset] = useState(value);
+ if (value !== queryAtLastReset) {
+ setQueryAtLastReset(value);
+ setHighlight(NO_HIGHLIGHT);
+ }
+
+ const active =
+ isOpen && highlight !== NO_HIGHLIGHT
+ ? filtered[Math.min(highlight, filtered.length - 1)]
+ : undefined;
+
+ function pick(suggestion: AddPropertyFieldSuggestion): void {
+ onPick(suggestion);
+ setOpen(false);
+ }
+
+ function handleKeyDown(event: KeyboardEvent<HTMLInputElement>): void {
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
+ // Nothing to navigate — including when an exact match holds the list shut,
+ // which leaves the filter non-empty. Claiming the key here would swallow
+ // its caret movement to open a list that cannot open.
+ if (filtered.length === 0 || exactlyTyped) return;
+ event.preventDefault();
+ const delta = event.key === 'ArrowDown' ? 1 : -1;
+ // Entering the list — from closed, or from open-but-unselected — lands on
+ // the end the user reached toward, rather than stepping off a phantom
+ // position before the first option.
+ const entryIndex = delta === 1 ? 0 : filtered.length - 1;
+ if (!isOpen) {
+ setOpen(true);
+ setHighlight(entryIndex);
+ return;
+ }
+ const nextIndex =
+ highlight === NO_HIGHLIGHT
+ ? entryIndex
+ : (highlight + delta + filtered.length) % filtered.length;
+ setHighlight(nextIndex);
+ // Focus stays in the input, so the browser won't scroll the
+ // `aria-activedescendant` target into view the way it does a focused
+ // element — on the `max-h-64` popup the highlighted option can slip below
+ // the fold. Scroll it in by hand, per the ARIA APG combobox pattern. `?.`
+ // covers jsdom, which stubs `scrollIntoView`. The option elements already
+ // exist this render (only the highlight class changes), so no rAF needed.
+ const next = filtered[nextIndex];
+ if (next) {
+ document
+ .getElementById(`${listboxId}-${next.name}`)
+ ?.scrollIntoView?.({ block: 'nearest' });
+ }
+ return;
+ }
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ // Enter takes a suggestion only once the user has moved onto it. An open
+ // list on its own does not claim the key — the name field is free text,
+ // so a name the schema merely resembles still commits as typed.
+ if (active) {
+ pick(active);
+ return;
+ }
+ // Committing dismisses the list either way, per the APG textbox contract.
+ // Reachable with the list still up now that an open list no longer claims
+ // Enter, so a row the host declines to commit must not be left sitting
+ // under a popup the user already answered.
+ setOpen(false);
+ onCommit();
+ return;
+ }
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ // Escape dismisses the popup first; a second press abandons the row.
+ if (isOpen) setOpen(false);
+ else onCancel();
+ }
+ }
+
+ return (
+ <Popover open={isOpen} onOpenChange={setOpen}>
+ <PopoverAnchor asChild>
+ <Input
+ ref={inputRef}
+ data-testid="add-property-name-input"
+ data-key={rowId}
+ type="text"
+ value={value}
+ autoFocus={autoFocus}
+ placeholder={t`Property name`}
+ aria-label={t`New property name`}
+ aria-invalid={error ? true : undefined}
+ aria-describedby={errorId}
+ role={suggestions.length > 0 ? 'combobox' : undefined}
+ aria-expanded={suggestions.length > 0 ? isOpen : undefined}
+ aria-controls={isOpen ? listboxId : undefined}
+ aria-autocomplete={suggestions.length > 0 ? 'list' : undefined}
+ aria-activedescendant={active ? `${listboxId}-${active.name}` : undefined}
+ onChange={(e) => {
+ onChange(e.target.value);
+ if (suggestions.length > 0) setOpen(true);
+ }}
+ // Opening on focus is the discovery half: a user who does not know
+ // the schema declares anything sees the list without typing. Guarded
+ // so a field with nothing to offer never re-renders for it.
+ onFocus={() => {
+ if (suggestions.length > 0) setOpen(true);
+ }}
+ onKeyDown={handleKeyDown}
+ className="h-7 w-32 border-transparent bg-transparent px-2 text-sm shadow-none placeholder:text-muted-foreground/60 focus-visible:border-transparent focus-visible:bg-muted focus-visible:ring-0 rounded-sm @max-[26rem]/prow:w-auto @max-[26rem]/prow:flex-1"
+ />
+ </PopoverAnchor>
+ <PopoverContent
+ align="start"
+ sideOffset={2}
+ // The input is the typing surface; the popup must never take focus off
+ // it, or the next keystroke lands nowhere. Radix would also send focus
+ // back on close, fighting the type-picker's own refocus.
+ onOpenAutoFocus={(event) => event.preventDefault()}
+ onCloseAutoFocus={(event) => event.preventDefault()}
+ // The input is an anchor, which lives OUTSIDE the content — so Radix
+ // counts a click on it as an outside interaction and closes the list.
+ // For a type-ahead that is backwards: clicking into the field, or
+ // clicking to reposition the caret, must not dismiss what you are
+ // choosing from. (Only reproducible in a real browser; jsdom does not
+ // fire Radix's outside-pointer detection.)
+ onInteractOutside={(event) => {
+ const target = event.detail.originalEvent.target;
+ if (target instanceof Node && inputRef.current?.contains(target)) {
+ event.preventDefault();
+ }
+ }}
+ className="w-64 max-h-64 overflow-y-auto p-1"
+ >
+ {/* Visual section label only — the listbox below carries the same text
+ as its `aria-label`, so leaving this exposed announces it twice. */}
+ <div
+ aria-hidden
+ className="px-2 py-1 text-[10px] font-medium text-muted-foreground uppercase tracking-wide"
+ >
+ <Trans>Schema fields</Trans>
+ </div>
+ <div id={listboxId} role="listbox" aria-label={t`Schema fields`}>
+ {filtered.map((suggestion, index) => {
+ const Icon = TYPE_ICON[suggestion.type];
+ const isActive = suggestion.name === active?.name;
+ return (
+ // biome-ignore lint/a11y/useFocusableInteractive: options in this pattern are deliberately not focusable — focus stays in the input and `aria-activedescendant` conveys the selection. Keyboard access runs through the input's own handler.
+ <div
+ key={suggestion.name}
+ id={`${listboxId}-${suggestion.name}`}
+ role="option"
+ aria-selected={isActive}
+ data-testid="add-property-field-suggestion"
+ data-key={suggestion.name}
+ // Commit on mousedown: a click would blur the input first, and
+ // the blur closes the popup out from under the pointer.
+ onMouseDown={(event) => {
+ event.preventDefault();
+ pick(suggestion);
+ }}
+ onMouseEnter={() => setHighlight(index)}
+ className={`flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-sm ${
+ isActive ? 'bg-accent text-accent-foreground' : ''
+ }`}
+ >
+ <Icon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="flex min-w-0 flex-col">
+ <span className="truncate">{suggestion.name}</span>
+ {suggestion.description ? (
+ <span className="truncate text-[11px] text-muted-foreground">
+ {suggestion.description}
+ </span>
+ ) : null}
+ </span>
+ {suggestion.required ? (
+ <Badge variant="gray" className="ml-auto shrink-0 text-2xs">
+ <Trans>required</Trans>
+ </Badge>
+ ) : null}
+ </div>
+ );
+ })}
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/packages/app/src/components/AddPropertyRow.add-property-focus.dom.test.tsx b/packages/app/src/components/AddPropertyRow.add-property-focus.dom.test.tsx
index 54c0a512a..dbb65870e 100644
--- a/packages/app/src/components/AddPropertyRow.add-property-focus.dom.test.tsx
+++ b/packages/app/src/components/AddPropertyRow.add-property-focus.dom.test.tsx
@@ -8,13 +8,15 @@
* type. Radix's default close-auto-focus returns focus to the trigger;
* AddPropertyRow's onCloseAutoFocus handler redirects it to the name input.
*
- * Both consumers duplicate the same add-property reducer (`beginAdd` /
+ * Both consumers reduce add-property state the same way (`beginAdd` /
* `changeAddType`): PropertyPanel (file frontmatter) and FolderPropertiesCard
* (folder cascade). Two harnesses exercise each consumer's reducer so a
- * per-consumer fix that diverges between callers is caught.
+ * per-consumer fix that diverges between callers is caught. The panel keeps a
+ * LIST of drafts — it stages one per schema-required property the doc lacks —
+ * so its harness models one entry of that list; the folder card stays single.
*
* Exercises `render` + `userEvent` under the jsdom substrate; invocation via
- * `bun run test:dom` from `packages/app/`.
+ * `pnpm run test:dom` from `packages/app/`.
*/
import type { FrontmatterType } from '@inkeep/open-knowledge-core';
diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsx
index 6d3a6c46f..e160618fd 100644
--- a/packages/app/src/components/EditorArea.tsx
+++ b/packages/app/src/components/EditorArea.tsx
@@ -1227,8 +1227,7 @@ function EditorAreaInner({
onModeChange={onModeChange}
showAddPropertyButton={!isSourceMode}
onAddProperty={openAddPropertyForm}
- frontmatterProblemCount={missingProperties.length}
- frontmatterProblemMessages={missingProperties.map((d) => d.message)}
+ frontmatterProblems={missingProperties}
isPanelCollapsed={isPanelCollapsed}
onTogglePanel={togglePanel}
// When the doc panel is collapsed, the action cluster reaches the
diff --git a/packages/app/src/components/EditorToolbar.dom.test.tsx b/packages/app/src/components/EditorToolbar.dom.test.tsx
index d4b3300ff..eac43b9cf 100644
--- a/packages/app/src/components/EditorToolbar.dom.test.tsx
+++ b/packages/app/src/components/EditorToolbar.dom.test.tsx
@@ -1,3 +1,4 @@
+import type { LintDiagnostic } from '@inkeep/open-knowledge-core';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
@@ -30,10 +31,57 @@ vi.doMock('@/lib/config-provider', () => ({
}),
}));
+// The skill cluster's real children fetch the skills list and the install
+// state, none of which this toolbar's contract depends on. The stub keeps the
+// REAL Add-properties button so the badge it renders is the one under test.
+vi.doMock('./SkillToolbarControls', async () => {
+ const { AddPropertiesButton } = await import('./AddPropertiesButton');
+ return {
+ SkillToolbarControls: ({
+ showAddPropertyButton,
+ onAddProperty,
+ problemCount,
+ problemMessages,
+ }: {
+ showAddPropertyButton: boolean;
+ onAddProperty: () => void;
+ problemCount?: number;
+ problemMessages?: readonly string[];
+ }) =>
+ showAddPropertyButton ? (
+ <AddPropertiesButton
+ onAddProperty={onAddProperty}
+ problemCount={problemCount}
+ problemMessages={problemMessages}
+ />
+ ) : null,
+ };
+});
+
+vi.doMock('./SkillOriginInline', () => ({
+ SkillOriginInline: () => null,
+}));
+
+/** A schema-required property the document does not have. */
+function missing(property: string): LintDiagnostic {
+ return {
+ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } },
+ severity: 'warning',
+ source: 'frontmatter',
+ code: 'required',
+ message: `Frontmatter property "${property}" is required`,
+ frontmatterScope: 'missing',
+ frontmatterProperty: property,
+ };
+}
+
describe('EditorToolbar runtime layout', () => {
afterEach(() => cleanup());
- async function renderToolbar(activeDocName = 'docs/Page.md') {
+ async function renderToolbar(
+ activeDocName = 'docs/Page.md',
+ frontmatterProblems?: readonly LintDiagnostic[],
+ ) {
const { EditorToolbar } = await import('./EditorToolbar');
render(
@@ -45,6 +93,7 @@ describe('EditorToolbar runtime layout', () => {
onModeChange={() => {}}
showAddPropertyButton={true}
onAddProperty={() => {}}
+ frontmatterProblems={frontmatterProblems}
isPanelCollapsed={false}
onTogglePanel={() => {}}
/>
@@ -129,4 +178,28 @@ describe('EditorToolbar runtime layout', () => {
expect(screen.queryByTestId('not-in-sidebar-indicator')).toBeNull();
});
+
+ // The button's tooltip promises "click to add and fill them in", and clicking
+ // stages a row per missing property EXCEPT the ones reserved for the doc — a
+ // skill's `name` is its folder identity, renamed by moving the folder. Badging
+ // one would advertise an action the click will not take. The schema violation
+ // is not hidden: the Problems panel still reports it.
+ test('a skill badges only the missing properties clicking will stage', async () => {
+ const user = userEvent.setup();
+ await renderToolbar('__skill__/global/foo', [missing('name'), missing('description')]);
+
+ const badge = await screen.findByTestId('add-properties-problem-badge');
+ expect(badge.textContent).toBe('1');
+
+ await user.hover(screen.getByTestId('add-properties-button'));
+ const tooltip = await screen.findByRole('tooltip');
+ expect(tooltip.textContent).toContain('Frontmatter property "description" is required');
+ expect(tooltip.textContent).not.toContain('Frontmatter property "name" is required');
+ });
+
+ test('an ordinary document reserves nothing, so `name` still badges', async () => {
+ await renderToolbar('docs/Page.md', [missing('name'), missing('description')]);
+
+ expect((await screen.findByTestId('add-properties-problem-badge')).textContent).toBe('2');
+ });
});
diff --git a/packages/app/src/components/EditorToolbar.tsx b/packages/app/src/components/EditorToolbar.tsx
index ca6347e55..5a63468d7 100644
--- a/packages/app/src/components/EditorToolbar.tsx
+++ b/packages/app/src/components/EditorToolbar.tsx
@@ -1,5 +1,6 @@
import {
isEditableTextDocFile,
+ type LintDiagnostic,
parseExternalSkillDocName,
parseManagedArtifactName,
type SkillScope,
@@ -14,6 +15,11 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip
import type { EditorModeValue } from '@/editor/use-editor-mode.ts';
import { formatShortcut, formatShortcutLabel } from '@/lib/keyboard-shortcuts';
import { parseProjectSkillContentDocName } from '@/lib/managed-artifact-doc-name';
+import {
+ NO_RESERVED_KEYS,
+ SKILL_RESERVED_KEYS,
+ withoutReservedProperties,
+} from '@/lib/reserved-property-keys';
import { cn } from '@/lib/utils';
import { EditorBreadcrumb } from './EditorBreadcrumb';
import { EditorModeToggle } from './EditorModeToggle';
@@ -32,6 +38,8 @@ const SkillOriginInline = lazy(async () => ({
default: (await import('./SkillOriginInline')).SkillOriginInline,
}));
+const NO_FRONTMATTER_PROBLEMS: readonly LintDiagnostic[] = [];
+
interface EditorToolbarProps {
activeDocName: string | null;
isSourceMode: boolean;
@@ -39,11 +47,12 @@ interface EditorToolbarProps {
onModeChange: (mode: EditorModeValue) => void;
showAddPropertyButton: boolean;
onAddProperty: () => void;
- /** Frontmatter-schema violations on the active doc — badged on the
- * Add-properties button, which is where those errors report (they have no
- * body anchor to squiggle). */
- frontmatterProblemCount?: number;
- frontmatterProblemMessages?: readonly string[];
+ /** Schema-required properties the active doc is missing — badged on the
+ * Add-properties button, which is where those report (they have no body
+ * anchor to squiggle). Handed over as diagnostics rather than a count and
+ * messages because only this component knows whether the doc reserves any of
+ * those keys, and a reserved one is not the button's to offer. */
+ frontmatterProblems?: readonly LintDiagnostic[];
isPanelCollapsed: boolean;
onTogglePanel: () => void;
/** Reserve right-side room in the action cluster so it sits left of the
@@ -60,8 +69,7 @@ export function EditorToolbar({
onModeChange,
showAddPropertyButton,
onAddProperty,
- frontmatterProblemCount = 0,
- frontmatterProblemMessages,
+ frontmatterProblems = NO_FRONTMATTER_PROBLEMS,
isPanelCollapsed,
onTogglePanel,
reserveRightGutter = false,
@@ -83,6 +91,15 @@ export function EditorToolbar({
: projectSkillName
? { scope: 'project', name: projectSkillName }
: null;
+ // The button's tooltip promises the click will add and fill these in, so it
+ // may only advertise what the property panel will actually stage. A skill's
+ // reserved `name` is not the panel's to add, so it is dropped here — the
+ // Problems panel still carries the schema violation.
+ const stageableProblems = withoutReservedProperties(
+ frontmatterProblems,
+ activeSkill ? SKILL_RESERVED_KEYS : NO_RESERVED_KEYS,
+ );
+ const problemMessages = stageableProblems.map((diagnostic) => diagnostic.message);
// A detected-skill edit buffer (`__extskill__/<name>`): reduced mode —
// no level/install/history/scope-move/provenance chrome; the edit-in-place
// banner above the editor carries the messaging.
@@ -175,8 +192,8 @@ export function EditorToolbar({
name={activeSkill.name}
showAddPropertyButton={showAddPropertyButton}
onAddProperty={onAddProperty}
- problemCount={frontmatterProblemCount}
- problemMessages={frontmatterProblemMessages}
+ problemCount={stageableProblems.length}
+ problemMessages={problemMessages}
/>
</Suspense>
) : externalSkill ? // Detected-skill edit buffer: reduced mode. Messaging lives in the
@@ -187,8 +204,8 @@ export function EditorToolbar({
showAddPropertyButton && (
<AddPropertiesButton
onAddProperty={onAddProperty}
- problemCount={frontmatterProblemCount}
- problemMessages={frontmatterProblemMessages}
+ problemCount={stageableProblems.length}
+ problemMessages={problemMessages}
/>
)
)}
diff --git a/packages/app/src/components/FrontmatterRow.tsx b/packages/app/src/components/FrontmatterRow.tsx
index 9a0701c84..cd837226f 100644
--- a/packages/app/src/components/FrontmatterRow.tsx
+++ b/packages/app/src/components/FrontmatterRow.tsx
@@ -27,7 +27,11 @@ import {
import { Trans, useLingui } from '@lingui/react/macro';
import { AlertTriangle, GripVertical, Trash2, X } from 'lucide-react';
import type { CSSProperties, ReactNode } from 'react';
-import { useRef } from 'react';
+import { useEffect, useRef } from 'react';
+import {
+ type AddPropertyFieldSuggestion,
+ AddPropertyNameField,
+} from '@/components/AddPropertyNameField';
import { ArrayOfObjectsWidget } from '@/components/ArrayOfObjectsWidget';
import { ObjectWidget } from '@/components/ObjectWidget';
import { PageCoverWidget, PageIconWidget } from '@/components/PageHeaderWidgets';
@@ -580,6 +584,44 @@ interface AddPropertyRowProps {
*/
onCommit: (valueOverride?: FrontmatterValue) => void;
onCancel: () => void;
+ /**
+ * Distinguishes one add-row from its siblings when a host renders several at
+ * once (the panel stages one per schema-required property the doc lacks).
+ * Scopes this row's DOM ids and `data-key`, so two rows can't collide on an
+ * `aria-describedby` target. Single-row hosts can leave it at the default.
+ */
+ rowId?: string;
+ /**
+ * Which control takes focus on mount. `name` is the default and what a blank
+ * row wants. A row that arrives pre-named wants `value` — the name is already
+ * filled, so the value is the only thing left to type. `none` keeps focus
+ * where it is, which is what every row but the first of a staged batch needs:
+ * `autoFocus` is last-one-wins, so several rows each claiming it would land
+ * focus on the bottom row.
+ */
+ autoFocus?: 'name' | 'value' | 'none';
+ /**
+ * Schema-derived vocabulary for the property being added, resolved by the
+ * host from the same schemas the linter uses. Present when the drafted name
+ * names an enum-constrained field: the value editor becomes that field's
+ * select instead of free text, matching how the field will render once it is
+ * a real row.
+ */
+ enumConstraint?: { values: string[]; multi: boolean };
+ /**
+ * Fields the doc's governing schemas declare and the doc does not yet have,
+ * offered as type-ahead suggestions on the name input. Empty (the default)
+ * leaves the name a plain free-text field — which is what an unschema'd doc,
+ * and the folder card, get.
+ */
+ fieldSuggestions?: readonly AddPropertyFieldSuggestion[];
+ /**
+ * Applies a picked suggestion's name AND type as one update. Optional: the
+ * fallback drives the existing name/type callbacks instead, which is correct
+ * but applies the two in separate updates rather than one atomic change (React
+ * batches the render either way).
+ */
+ onPickField?: (suggestion: AddPropertyFieldSuggestion) => void;
}
/**
@@ -595,10 +637,45 @@ export function AddPropertyRow({
onChangeValue,
onCommit,
onCancel,
+ rowId = '__add__',
+ autoFocus = 'name',
+ enumConstraint,
+ fieldSuggestions = [],
+ onPickField,
}: AddPropertyRowProps) {
const { t } = useLingui();
- const errorId = draft.error ? 'add-property-error-id' : undefined;
+ const errorId = draft.error ? `add-property-error-${rowId}` : undefined;
const nameInputRef = useRef<HTMLInputElement>(null);
+ const valueCellRef = useRef<HTMLDivElement>(null);
+
+ // Focusing the VALUE means reaching into whichever widget the drafted type
+ // renders — a text input, a select trigger, a chip input, a checkbox. Taking
+ // the first focusable descendant of the value cell covers every one of them
+ // without each widget having to forward a ref it otherwise has no use for.
+ //
+ // Latched to fire at most once per mounted row. `autoFocus` describes where
+ // the row OPENS, so a later flip of it must not move a caret the user has
+ // since placed somewhere else — moving focus mid-word swallows keystrokes
+ // into whatever it lands on.
+ const wantsValueFocus = autoFocus === 'value';
+ const valueFocusClaimed = useRef(false);
+ useEffect(() => {
+ if (!wantsValueFocus || valueFocusClaimed.current) return;
+ valueFocusClaimed.current = true;
+ const focusable = valueCellRef.current?.querySelector<HTMLElement>(
+ 'input:not([type="hidden"]), select, textarea, button, [tabindex]:not([tabindex="-1"])',
+ );
+ focusable?.focus();
+ }, [wantsValueFocus]);
+
+ function handlePickField(suggestion: AddPropertyFieldSuggestion): void {
+ if (onPickField) {
+ onPickField(suggestion);
+ return;
+ }
+ onChangeName(suggestion.name);
+ onChangeType(suggestion.type);
+ }
// Gate the commit affordance: non-empty name AND non-empty value (matches
// the server's mergePatch drop-on-empty semantic via the shared core
// predicate; `0` and `false` count as non-empty).
@@ -608,6 +685,7 @@ export function AddPropertyRow({
<div
className="mt-1 rounded border border-dashed bg-background/40 p-1 @container/prow"
data-testid="add-property-row"
+ data-key={rowId}
>
<div className="flex items-start gap-1 @max-[26rem]/prow:flex-wrap">
<TypeIconButton
@@ -624,37 +702,52 @@ export function AddPropertyRow({
nameInputRef.current?.focus();
}}
/>
- <Input
- ref={nameInputRef}
- data-testid="add-property-name-input"
- type="text"
+ <AddPropertyNameField
+ rowId={rowId}
value={draft.name}
- autoFocus
- placeholder={t`Property name`}
- aria-label={t`New property name`}
- aria-invalid={draft.error ? true : undefined}
- aria-describedby={errorId}
- onChange={(e) => onChangeName(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- onCommit();
- } else if (e.key === 'Escape') {
- e.preventDefault();
- onCancel();
- }
- }}
- className="h-7 w-32 border-transparent bg-transparent px-2 text-sm shadow-none placeholder:text-muted-foreground/60 focus-visible:border-transparent focus-visible:bg-muted focus-visible:ring-0 rounded-sm @max-[26rem]/prow:w-auto @max-[26rem]/prow:flex-1"
+ suggestions={fieldSuggestions}
+ inputRef={nameInputRef}
+ autoFocus={autoFocus === 'name'}
+ error={draft.error !== null}
+ errorId={errorId}
+ onChange={onChangeName}
+ onPick={handlePickField}
+ onCommit={onCommit}
+ onCancel={onCancel}
/>
- <div className="min-w-0 flex-1 @max-[26rem]/prow:order-last @max-[26rem]/prow:mt-0.5 @max-[26rem]/prow:basis-full @max-[26rem]/prow:pl-[2rem]">
- <Widget
- keyName="__add__"
- value={draft.value}
- widgetType={draft.type}
- path={ADD_ROW_PATH}
- onCommit={onChangeValue}
- onSubmit={onCommit}
- />
+ <div
+ ref={valueCellRef}
+ className="min-w-0 flex-1 @max-[26rem]/prow:order-last @max-[26rem]/prow:mt-0.5 @max-[26rem]/prow:basis-full @max-[26rem]/prow:pl-[2rem]"
+ >
+ {/* Enum-constrained fields get the same select they will render as a
+ committed row — a fixed vocabulary is not something to retype from
+ memory. Both selects commit through `onChangeValue`, so the draft
+ plumbing below is unchanged; only free-text/complex drafts fall
+ through to the type-dispatched widget. */}
+ {enumConstraint && !enumConstraint.multi ? (
+ <EnumSelectWidget
+ keyName="__add__"
+ value={draft.value}
+ values={enumConstraint.values}
+ onCommit={onChangeValue}
+ />
+ ) : enumConstraint ? (
+ <EnumMultiSelectWidget
+ keyName="__add__"
+ value={draft.value}
+ values={enumConstraint.values}
+ onCommit={onChangeValue}
+ />
+ ) : (
+ <Widget
+ keyName="__add__"
+ value={draft.value}
+ widgetType={draft.type}
+ path={ADD_ROW_PATH}
+ onCommit={onChangeValue}
+ onSubmit={onCommit}
+ />
+ )}
</div>
<Button
diff --git a/packages/app/src/components/PropertyPanel.staged-required.dom.test.tsx b/packages/app/src/components/PropertyPanel.staged-required.dom.test.tsx
new file mode 100644
index 000000000..e60d5f8a4
--- /dev/null
+++ b/packages/app/src/components/PropertyPanel.staged-required.dom.test.tsx
@@ -0,0 +1,530 @@
+/**
+ * Acting on the toolbar's Add-properties button lands here: one pre-named
+ * add-row per schema-required property the document lacks, so the user fills in
+ * values instead of retyping names the schema already states.
+ *
+ * The load-bearing half is what does NOT happen. Staging writes nothing — a row
+ * reaches the file only once it carries a value. Seeding empty placeholders
+ * instead would put `status: ""` in the document and clear the very `required`
+ * warning that produced the row, reporting the problem fixed while the field
+ * is blank.
+ */
+
+import { HocuspocusProvider } from '@hocuspocus/provider';
+import type { LintDiagnostic, LinterConfig } from '@inkeep/open-knowledge-core';
+import { cleanup, render, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { Button } from '@/components/ui/button';
+import { TooltipProvider } from '@/components/ui/tooltip';
+
+function missingDiagnostic(property: string): LintDiagnostic {
+ return {
+ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 3 } },
+ severity: 'warning',
+ source: 'frontmatter',
+ code: 'required',
+ message: `Frontmatter property "${property}" is required`,
+ frontmatterScope: 'missing',
+ frontmatterProperty: property,
+ };
+}
+
+const SCHEMA = {
+ type: 'object',
+ required: ['status', 'tags'],
+ properties: {
+ status: { type: 'string', description: 'Lifecycle stage' },
+ tags: { type: 'array', items: { type: 'string' } },
+ summary: { type: 'string' },
+ },
+};
+
+/** Same shape, with `status` given a fixed vocabulary. */
+const ENUM_SCHEMA = {
+ type: 'object',
+ required: ['status'],
+ properties: { status: { enum: ['draft', 'published'] } },
+};
+
+/** A required `date`-format field — the widget type a staged row drafts as `date`. */
+const DATE_SCHEMA = {
+ type: 'object',
+ required: ['publishedAt'],
+ properties: { publishedAt: { type: 'string', format: 'date' } },
+};
+
+function configWithSchema(schema: Record<string, unknown> = SCHEMA): LinterConfig {
+ return {
+ enabled: true,
+ plugins: {
+ markdownlint: { enabled: false, rules: {} },
+ frontmatter: {
+ enabled: true,
+ schemas: [{ appliesTo: '**', file: 'doc.json', schema }],
+ },
+ },
+ };
+}
+
+let diagnostics: LintDiagnostic[] = [];
+let lintConfig: LinterConfig | null = null;
+
+vi.doMock('@/editor/useFrontmatterDiagnostics', async () => {
+ const actual = await vi.importActual<typeof import('@/editor/useFrontmatterDiagnostics')>(
+ '@/editor/useFrontmatterDiagnostics',
+ );
+ return { ...actual, useFrontmatterDiagnostics: () => diagnostics };
+});
+
+vi.doMock('@/editor/lint-config-client', async () => {
+ const actual = await vi.importActual<typeof import('@/editor/lint-config-client')>(
+ '@/editor/lint-config-client',
+ );
+ return { ...actual, useDocLintConfig: () => ({ data: { effective: lintConfig } }) };
+});
+
+const providers: HocuspocusProvider[] = [];
+
+function makeProvider(docName: string): HocuspocusProvider {
+ const p = new HocuspocusProvider({ url: 'ws://localhost:1/collab', name: docName });
+ providers.push(p);
+ return p;
+}
+
+function seedYTextFm(provider: HocuspocusProvider, fenced: string): void {
+ const ytext = provider.document.getText('source');
+ provider.document.transact(() => {
+ ytext.delete(0, ytext.length);
+ ytext.insert(0, fenced);
+ });
+}
+
+function readSource(provider: HocuspocusProvider): string {
+ return provider.document.getText('source').toString();
+}
+
+/**
+ * Mounts the panel beside the toolbar's dispatcher, so a batch add arrives the
+ * way it does in the app — the cross-tree signal. The panel renders its own
+ * inline "Add" button, so both entry points are reachable from one render.
+ */
+async function renderPanel(provider: HocuspocusProvider, reservedKeys?: readonly string[]) {
+ const { PropertyProvider, useProperties } = await import('./PropertyContext');
+ const { PropertyPanel } = await import('./PropertyPanel');
+ const docName = provider.configuration.name ?? '';
+
+ function ToolbarTrigger() {
+ const { requestAddProperty } = useProperties();
+ return (
+ <Button data-testid="toolbar-add-properties" onClick={() => requestAddProperty(docName)}>
+ add
+ </Button>
+ );
+ }
+
+ return render(
+ <TooltipProvider>
+ <PropertyProvider>
+ <ToolbarTrigger />
+ <PropertyPanel provider={provider} reservedKeys={reservedKeys} />
+ </PropertyProvider>
+ </TooltipProvider>,
+ );
+}
+
+function addRows(): HTMLElement[] {
+ return screen.queryAllByTestId('add-property-row');
+}
+
+function rowFor(name: string): HTMLElement {
+ const row = document.querySelector<HTMLElement>(
+ `[data-testid="add-property-row"][data-key="staged-${name}"]`,
+ );
+ if (!row) throw new Error(`no staged row for "${name}"`);
+ return row;
+}
+
+function nameValueOf(row: HTMLElement): string {
+ return within(row).getByTestId<HTMLInputElement>('add-property-name-input').value;
+}
+
+beforeEach(() => {
+ diagnostics = [];
+ lintConfig = configWithSchema();
+});
+
+afterEach(() => {
+ cleanup();
+ for (const p of providers.splice(0)) p.destroy();
+});
+
+describe('PropertyPanel — staging schema-required properties', () => {
+ test('stages one pre-named row per missing property without touching the file', async () => {
+ diagnostics = [missingDiagnostic('status'), missingDiagnostic('tags')];
+ const provider = makeProvider('staged-two');
+ seedYTextFm(provider, '---\ntitle: Doc\n---\n\nBody\n');
+ const before = readSource(provider);
+ await renderPanel(provider);
+
+ await userEvent.click(screen.getByTestId('toolbar-add-properties'));
+
+ await waitFor(() => expect(addRows()).toHaveLength(2));
+ expect(nameValueOf(rowFor('status'))).toBe('status');
+ expect(nameValueOf(rowFor('tags'))).toBe('tags');
+ // The whole point: a staged row is a draft, not a write.
+ expect(readSource(provider)).toBe(before);
+ });
+
+ test('the staged row takes its widget type from the schema', async () => {
+ diagnostics = [missingDiagnostic('tags')];
+ const provider = makeProvider('staged-type');
+ seedYTextFm(provider, '---\ntitle: Doc\n---\n');
+ await renderPanel(provider);
+
+ await userEvent.click(screen.getByTestId('toolbar-add-properties'));
+
+ await waitFor(() => expect(addRows()).toHaveLength(1));
+ // `tags` is declared `array`, so it drafts as a chip list rather than the
+ // text box a type-blind stage would produce.
+ expect(within(rowFor('tags')).getByTestId('list-widget')).toBeTruthy();
+ });
+
+ test('a staged required date row opens empty, not committable with today', async () => {
+ // A date field seeded with today's date is committable without the user
+ // choosing anything: one Add click writes a plausible-but-unchosen date and
+ // clears the required warning that produced the row. It must open empty so
+ // the commit gate stays shut until the user picks the real date — the same
+ // block text/list rows already get from their empty defaults.
+ lintConfig = configWithSchema(DATE_SCHEMA);
+ diagnostics = [missingDiagnostic('publishedAt')];
+ const provider = makeProvider('staged-date-empty');
+ seedYTextFm(provider, '---\ntitle: Doc\n---\n');
+ await renderPanel(provider);
+
+ await userEvent.click(screen.getByTestId('toolbar-add-properties'));
+
+ await waitFor(() => expect(addRows()).toHaveLength(1));
+ const row = rowFor('publishedAt');
+ // The date input opens with no value…
+ expect(within(row).getByTestId('date-widget').querySelector('input')?.value).toBe('');
+ // …so the Add button stays disabled until a date is chosen.
+ expect(within(row).getByTestId<HTMLButtonElement>('add-property-commit').disabled).toBe(true);
+ });
+
+ test('filling one row writes only that property and leaves its siblings staged', async () => {
+ diagnostics = [missingDiagnostic('status'), missingDiagnostic('tags')];
+ const provider = makeProvider('staged-commit-one');
+ seedYTextFm(provider, '---\ntitle: Doc\n---\n');
+ await renderPanel(provider);
+ await userEvent.click(screen.getByTestId('toolbar-add-properties'));
+ await waitFor(() => expect(addRows()).toHaveLength(2));
+
+ const row = rowFor('status');
+ const valueInput = within(row).getByTestId('text-widget');
+ await userEvent.click(valueInput);
+ await userEvent.type(valueInput, 'draft');
+ await userEvent.click(within(row).getByTestId('add-property-commit'));
+
+ await waitFor(() => expect(readSource(provider)).toContain('status: draft'));
+ // `tags` was never filled, so it must not have been written alongside.
+ expect(readSource(provider)).not.toContain('tags:');
+ expect(addRows()).toHaveLength(1);
+ expect(nameValueOf(rowFor('tags'))).toBe('tags');
+ });
+
+ test('a property the document already has is not staged', async () => {
+ // The count is rendered from a debounced pass, so the doc can gain the
+ // property between the badge and the click. Re-staging it would offer to
+ // add a property that is already there and fail on commit.
+ diagnostics = [missingDiagnostic('status'), missingDiagnostic('tags')];
+ const provider = makeProvider('staged-already-present');
+ seedYTextFm(provider, '---\nstatus: draft\n---\n');
+ await renderPanel(provider);
+
+ await userEvent.click(screen.getByTestId('toolbar-add-properties'));
+
+ await waitFor(() => expect(addRows()).toHaveLength(1));
+ expect(nameValueOf(addRows()[0] as HTMLElement)).toBe('tags');
+ });
+
+ test('two schemas requiring the same property stage one row', async () => {
+ diagnostics = [missingDiagnostic('status'), missingDiagnostic('status')];
+ const provider = makeProvider('staged-dedup');
+ seedYTextFm(provider, '---\ntitle: Doc\n---\n');
+ await renderPanel(provider);
+
+ await userEvent.click(screen.getByTestId('toolbar-add-properties'));
+
+ await waitFor(() => expect(addRows()).toHaveLength(1));
+ });
+
+ test('a reserved property is never staged', async () => {
+ // The skill panel reserves `name` as the skill's folder identity — renamed
+ // by moving the folder, never patched — so a schema that requires `name`
+ // must not stage a row that would add it as a plain property.
+ lintConfig = configWithSchema({
+ type: 'object',
+ required: ['name', 'status'],
+ properties: { name: { type: 'string' }, status: { type: 'string' } },
+ });
+ diagnostics = [missingDiagnostic('name'), missingDiagnostic('status')];
+ const provider = makeProvider('staged-reserved');
+ seedYTextFm(provider, '---\ntitle: Doc\n---\n');
+ await renderPanel(provider, ['name']);
+
+ await userEvent.click(screen.getByTestId('toolbar-add-properties'));
+
+ await waitFor(() => expect(addRows()).toHaveLength(1));
+ // Only `status` stages; `name` is reserved and gets no row.
+ expect(nameValueOf(addRows()[0] as HTMLElement)).toBe('status');
+ expect(document.querySelector('[data-key="staged-name"]')).toBeNull();
+ });
+
+ test('nothing missing still opens one blank row', async () => {
+ diagnostics = [];
+ const provider = makeProvider('staged-none-missing');
+ seedYTextFm(provider, '---\ntitle: Doc\n---\n');
+ await renderPanel(provider);
+
+ await userEvent.click(screen.getByTestId('toolbar-add-properties'));
+
+ await waitFor(() => expect(addRows()).toHaveLength(1));
+ expect(nameValueOf(addRows()[0] as HTMLElement)).toBe('');
+ });
+
+ test("the panel's own Add opens one blank row even when properties are missing", async () => {
+ // Batch staging is the toolbar button's affordance. This control's object
+ // is a single property — its label says "Add property", singular — so a
+ // user reaching for it wants a row to name, not the schema's backlog. It
+ // must stay singular however many required properties the doc lacks.
+ diagnostics = [missingDiagnostic('status'), missingDiagnostic('tags')];
+ const provider = makeProvider('inline-add-blank');
+ seedYTextFm(provider, '---\ntitle: Doc\n---\n');
+ await renderPanel(provider);
+
+ await userEvent.click(screen.getByTestId('add-property-trigger'));
+
+ await waitFor(() => expect(addRows()).toHaveLength(1));
+ const row = addRows()[0] as HTMLElement;
+ expect(nameValueOf(row)).toBe('');
+ // A blank row has nothing to fill in yet, so it opens in its name field.
+ expect(document.activeElement).toBe(within(row).getByTestId('add-property-name-input'));
+ });
+
+ test('a present-but-invalid property is not staged', async () => {
+ // Only absent properties are this affordance's business; a wrong value has
+ // a row of its own to correct.
+ diagnostics = [
+ {
+ range: { start: { line: 1, character: 0 }, end: { line: 1, character: 5 } },
+ severity: 'warning',
+ source: 'frontmatter',
+ code: 'enum',
+ message: 'Frontmatter property "status" must be one of: draft',
+ frontmatterScope: 'invalid',
+ },
+ ];
+ const provider = makeProvider('staged-invalid-only');
+ seedYTextFm(provider, '---\nstatus: shipped\n---\n');
+ await renderPanel(provider);
+
+ await userEvent.click(screen.getByTestId('toolbar-add-properties'));
+
+ await waitFor(() => expect(addRows()).toHaveLength(1));
+ expect(nameValueOf(addRows()[0] as HTMLElement)).toBe('');
+ });
+
+ test('dismissing one staged row leaves the rest', async () => {
+ diagnostics = [missingDiagnostic('status'), missingDiagnostic('tags')];
+ const provider = makeProvider('staged-dismiss-one');
+ seedYTextFm(provider, '---\ntitle: Doc\n---\n');
+ await renderPanel(provider);
+ await userEvent.click(screen.getByTestId('toolbar-add-properties'));
+ await waitFor(() => expect(addRows()).toHaveLength(2));
+
+ await userEvent.click(within(rowFor('status')).getByTestId('add-property-cancel'));
+
+ await waitFor(() => expect(addRows()).toHaveLength(1));
+ expect(nameValueOf(rowFor('tags'))).toBe('tags');
+ });
+
+ test('the first staged row starts in its value, not its name', async () => {
+ // "Add it and send me to edit it": the name is already filled in, so the
+ // value is the only thing left to type.
+ diagnostics = [missingDiagnostic('status'), missingDiagnostic('tags')];
+ const provider = makeProvider('staged-focus');
+ seedYTextFm(provider, '---\ntitle: Doc\n---\n');
+ await renderPanel(provider);
+
+ await userEvent.click(screen.getByTestId('toolbar-add-properties'));
+
+ await waitFor(() => expect(addRows()).toHaveLength(2));
+ const first = rowFor('status');
+ const active = document.activeElement;
+ expect(first.contains(active)).toBe(true);
+ expect(active).not.toBe(within(first).getByTestId('add-property-name-input'));
+ });
+
+ test('only the first staged row claims focus', async () => {
+ // `autoFocus` is last-one-wins: without the per-row gate the caret would
+ // land on the bottom row of the batch.
+ diagnostics = [missingDiagnostic('status'), missingDiagnostic('tags')];
+ const provider = makeProvider('staged-focus-single');
+ seedYTextFm(provider, '---\ntitle: Doc\n---\n');
+ await renderPanel(provider);
+
+ await userEvent.click(screen.getByTestId('toolbar-add-properties'));
+
+ await waitFor(() => expect(addRows()).toHaveLength(2));
+ expect(rowFor('tags').contains(document.activeElement)).toBe(false);
+ });
+
+ test('picking a suggestion applies its type, and siblings stop offering it', async () => {
+ // Two mechanisms meet here and are only covered in isolation elsewhere:
+ // `pickAddField` applies name + type + value as one update (so the widget
+ // changes), and `suggestionsFor` withholds a name a sibling row already
+ // claims (so a batch can't point two rows at one property).
+ diagnostics = [missingDiagnostic('status'), missingDiagnostic('tags')];
+ const provider = makeProvider('staged-pick-and-dedup');
+ seedYTextFm(provider, '---\ntitle: Doc\n---\n');
+ await renderPanel(provider);
+ await userEvent.click(screen.getByTestId('toolbar-add-properties'));
+ await waitFor(() => expect(addRows()).toHaveLength(2));
+
+ // Clear the `tags` row's name so its picker opens (an exact-match name
+ // closes the list — there is nothing left to choose).
+ const row = rowFor('tags');
+ const nameInput = within(row).getByTestId('add-property-name-input');
+ await userEvent.clear(nameInput);
+ // The popup portals to document.body, so it is queried at screen level —
+ // only the focused row's list is open at a time.
+ await waitFor(() =>
+ expect(screen.queryAllByTestId('add-property-field-suggestion').length).toBeGreaterThan(0),
+ );
+
+ // `status` is claimed by the sibling staged row, so this row must not offer
+ // it — otherwise a batch could point two rows at one property.
+ const offered = screen
+ .queryAllByTestId('add-property-field-suggestion')
+ .map((el) => el.getAttribute('data-key'));
+ expect(offered).not.toContain('status');
+ expect(offered).toContain('tags');
+
+ // Picking `tags` (declared `array`) swaps the widget to the chip list — the
+ // schema's type rides along with the name, in one update.
+ await userEvent.click(
+ document.querySelector(
+ '[data-testid="add-property-field-suggestion"][data-key="tags"]',
+ ) as HTMLElement,
+ );
+ await waitFor(() =>
+ expect((within(row).getByTestId('add-property-name-input') as HTMLInputElement).value).toBe(
+ 'tags',
+ ),
+ );
+ expect(within(row).getByTestId('list-widget')).toBeTruthy();
+ });
+
+ test('a staged enum field offers its vocabulary instead of free text', async () => {
+ // The row exists because a schema demands the property; handing the user a
+ // free-text box for a fixed vocabulary invites the next violation.
+ lintConfig = configWithSchema(ENUM_SCHEMA);
+ diagnostics = [missingDiagnostic('status')];
+ const provider = makeProvider('staged-enum');
+ seedYTextFm(provider, '---\ntitle: Doc\n---\n');
+ await renderPanel(provider);
+
+ await userEvent.click(screen.getByTestId('toolbar-add-properties'));
+
+ await waitFor(() => expect(addRows()).toHaveLength(1));
+ const row = rowFor('status');
+ expect(within(row).getByTestId('property-enum-select')).toBeTruthy();
+ expect(within(row).queryByTestId('text-widget')).toBeNull();
+ });
+
+ test('a blank row still starts in its name field', async () => {
+ diagnostics = [];
+ const provider = makeProvider('staged-blank-focus');
+ seedYTextFm(provider, '---\ntitle: Doc\n---\n');
+ await renderPanel(provider);
+
+ await userEvent.click(screen.getByTestId('toolbar-add-properties'));
+
+ await waitFor(() => expect(addRows()).toHaveLength(1));
+ const row = addRows()[0] as HTMLElement;
+ expect(document.activeElement).toBe(within(row).getByTestId('add-property-name-input'));
+ });
+
+ test('typing a name in a blank row does not move the caret to the value', async () => {
+ // The focus target describes where a row OPENS. Re-deriving it from the
+ // live draft made the blank row want its name at `''` and its value at
+ // `'a'`, so the first keystroke re-fired the focus effect and every
+ // character after it went into the value widget instead.
+ diagnostics = [];
+ const provider = makeProvider('staged-typing-keeps-focus');
+ seedYTextFm(provider, '---\ntitle: Doc\n---\n');
+ await renderPanel(provider);
+ await userEvent.click(screen.getByTestId('toolbar-add-properties'));
+ await waitFor(() => expect(addRows()).toHaveLength(1));
+
+ const row = addRows()[0] as HTMLElement;
+ const nameInput = within(row).getByTestId<HTMLInputElement>('add-property-name-input');
+ await userEvent.click(nameInput);
+ await userEvent.type(nameInput, 'reviewer');
+
+ expect(nameInput.value).toBe('reviewer');
+ expect(document.activeElement).toBe(nameInput);
+ });
+
+ test('a staged row keeps focus where the user puts it after opening', async () => {
+ diagnostics = [missingDiagnostic('status')];
+ const provider = makeProvider('staged-focus-not-restolen');
+ seedYTextFm(provider, '---\ntitle: Doc\n---\n');
+ await renderPanel(provider);
+ await userEvent.click(screen.getByTestId('toolbar-add-properties'));
+ await waitFor(() => expect(addRows()).toHaveLength(1));
+
+ // The row opened in its value; moving to the name and typing must stick.
+ const nameInput = within(rowFor('status')).getByTestId<HTMLInputElement>(
+ 'add-property-name-input',
+ );
+ await userEvent.click(nameInput);
+ await userEvent.type(nameInput, 'X');
+
+ expect(document.activeElement).toBe(nameInput);
+ });
+
+ test('staged rows carry their own error target', async () => {
+ // One hardcoded id across sibling rows would point every row's
+ // `aria-describedby` at the same node.
+ diagnostics = [missingDiagnostic('status'), missingDiagnostic('tags')];
+ const provider = makeProvider('staged-error-ids');
+ seedYTextFm(provider, '---\ntitle: Doc\n---\n');
+ await renderPanel(provider);
+ await userEvent.click(screen.getByTestId('toolbar-add-properties'));
+ await waitFor(() => expect(addRows()).toHaveLength(2));
+
+ // Enter in the name field commits past the Add button's disabled state, so
+ // both rows raise their own "Value is required".
+ for (const name of ['status', 'tags']) {
+ const nameInput = within(rowFor(name)).getByTestId('add-property-name-input');
+ await userEvent.click(nameInput);
+ await userEvent.keyboard('{Enter}');
+ }
+
+ const errors = await screen.findAllByTestId('add-property-error');
+ expect(errors).toHaveLength(2);
+ const ids = errors.map((el) => el.getAttribute('id'));
+ expect(ids.every((id) => id !== null && id !== '')).toBe(true);
+ expect(new Set(ids).size).toBe(2);
+ // And each row points at its own.
+ for (const name of ['status', 'tags']) {
+ const row = rowFor(name);
+ const describedBy = within(row)
+ .getByTestId('add-property-name-input')
+ .getAttribute('aria-describedby');
+ expect(within(row).getByTestId('add-property-error').getAttribute('id')).toBe(describedBy);
+ }
+ });
+});
diff --git a/packages/app/src/components/PropertyPanel.tsx b/packages/app/src/components/PropertyPanel.tsx
index d5580cca8..649791f36 100644
--- a/packages/app/src/components/PropertyPanel.tsx
+++ b/packages/app/src/components/PropertyPanel.tsx
@@ -32,6 +32,7 @@ import { AlertTriangle, Plus } from 'lucide-react';
import { type ReactNode, useEffect, useRef, useState } from 'react';
import { CommentedDocProvider } from '@/comments/CommentedDocContext';
import { PropertyCommentButton } from '@/comments/PropertyCommentButton';
+import type { AddPropertyFieldSuggestion } from '@/components/AddPropertyNameField';
import { FrontmatterBindingProvider } from '@/components/FrontmatterBindingContext';
import {
type AddDraft,
@@ -51,6 +52,23 @@ import {
} from '@/editor/useFrontmatterDiagnostics';
import { usePublishFrontmatterSelection } from '@/hooks/use-selection-context';
import { enumConstraintsForDoc } from '@/lib/frontmatter-enum-constraints';
+import { schemaFieldsForDoc } from '@/lib/frontmatter-schema-fields';
+
+/**
+ * An add-row in flight. The id keys the row across renders so a sibling
+ * committing or being dismissed doesn't renumber the rest — names can't serve,
+ * since staged rows start out editable and a blank row has none.
+ */
+interface StagedDraft extends AddDraft {
+ id: string;
+ /**
+ * Which control this row wants on mount, decided once when the row is staged.
+ * Deriving it from the live draft instead would re-decide as the user types:
+ * a blank row whose name goes from `''` to `'a'` would flip from wanting the
+ * name to wanting the value, and yank the caret out of the field mid-word.
+ */
+ focusField: 'name' | 'value';
+}
interface PropertyPanelProps {
provider: HocuspocusProvider;
@@ -116,7 +134,17 @@ export function PropertyPanel({ provider, reservedKeys, identitySlot }: Property
// force-expands below (add-property intent) also persist "open"; that's intended.
const [collapsed, setCollapsed] = usePropertiesCollapsed();
const [overrides, setOverrides] = useState<Record<string, FrontmatterType>>({});
- const [adding, setAdding] = useState<AddDraft | null>(null);
+ // A list, not one draft: the toolbar's Add-properties button on a doc missing
+ // several schema-required properties stages a pre-named row for each. Ids are
+ // stable per staged row so React keys and the value-focus target survive a
+ // sibling row committing or being dismissed.
+ const [adding, setAdding] = useState<StagedDraft[]>([]);
+ // Which staged row takes focus on mount — the first of a batch. Read only at
+ // mount (an `autoFocus` attribute and a once-per-row effect), so it can stay
+ // set: a re-render never re-steals the caret from whichever field the user
+ // has since moved to.
+ const [focusRowId, setFocusRowId] = useState<string | null>(null);
+ const blankDraftSeq = useRef(0);
const [renaming, setRenaming] = useState<RenameDraft | null>(null);
const [errors, setErrors] = useState<Record<string, string>>({});
const [resetCounters, setResetCounters] = useState<Record<string, number>>({});
@@ -131,9 +159,15 @@ export function PropertyPanel({ provider, reservedKeys, identitySlot }: Property
// Properties that exist but violate the schema badge this panel's own count.
// The missing ones travel to the toolbar's Add-properties button instead —
// they have no row here to point at, and adding is their fix, not correcting.
- const { invalid: invalidProperties } = partitionFrontmatterProblems(
+ // This panel still reads them: acting on that button lands here, as a staged
+ // row per absent property.
+ const { invalid: invalidProperties, missing: missingProperties } = partitionFrontmatterProblems(
useFrontmatterDiagnostics(provider, lintConfigData?.effective ?? null),
);
+ // What the governing schemas DECLARE, for the name field's type-ahead and for
+ // a staged row's widget type. Same resolved config and same schema selection
+ // as the enum vocabularies above.
+ const schemaFields = schemaFieldsForDoc(lintConfigData?.effective ?? null, docName);
// Publish a highlight inside the property panel into the selection-context
// store (keyed `(docName, 'frontmatter')`) so a property-value selection feeds
@@ -279,80 +313,186 @@ export function PropertyPanel({ provider, reservedKeys, identitySlot }: Property
}
}
- function beginAdd() {
- setAdding({ name: '', type: 'text', value: '', error: null });
+ function defaultValueFor(type: FrontmatterType): FrontmatterValue {
+ return type === 'date' ? new Date().toISOString().slice(0, 10) : DEFAULT_VALUE_FOR_TYPE[type];
+ }
+
+ /** An unnamed row — nothing to fill in yet, so it opens in its name field. */
+ function blankDraft(): StagedDraft {
+ // A fresh id each time, so re-requesting an add remounts the row and its
+ // `autoFocus` fires again rather than leaving a stale row focused.
+ blankDraftSeq.current += 1;
+ return {
+ id: `blank-${blankDraftSeq.current}`,
+ name: '',
+ type: 'text',
+ value: '',
+ error: null,
+ focusField: 'name',
+ };
+ }
+
+ /**
+ * One pre-named row per schema-required property the doc lacks — the schema
+ * already names them, so making the user retype them is the whole complaint.
+ * Empty when nothing is missing or no schema governs the doc.
+ *
+ * Nothing is written here. A staged row is a draft like any other and only
+ * reaches the file once the user supplies a value and commits it, so an
+ * empty placeholder can never land in the doc and quietly satisfy the
+ * `required` check that produced the row.
+ */
+ function stageMissingDrafts(): StagedDraft[] {
+ const staged: StagedDraft[] = [];
+ const seen = new Set<string>();
+ for (const diagnostic of missingProperties) {
+ const name = diagnostic.frontmatterProperty;
+ if (name === undefined || name === '') continue;
+ // Two schemas can each require the same property, and the diagnostics
+ // are per schema.
+ if (seen.has(name)) continue;
+ // The doc may have gained the property since the count was rendered.
+ if (Object.hasOwn(map, name)) continue;
+ // A reserved key is not this panel's to add — a skill's `name` is its
+ // folder identity, renamed by moving the folder, not patched.
+ if (reserved.has(name)) continue;
+ seen.add(name);
+ const id = `staged-${name}`;
+ // Re-requesting an add while a row for this property is already open
+ // keeps that row — rebuilding it would throw away a value the user had
+ // started typing, with nothing on screen to explain where it went.
+ const existing = adding.find((draft) => draft.id === id);
+ if (existing) {
+ staged.push(existing);
+ continue;
+ }
+ const type = schemaFields.get(name)?.type ?? 'text';
+ // Pre-named, so the value is the only thing left to supply. Seeded with
+ // the type's BASE default, not `defaultValueFor` — a staged row is
+ // auto-opened, not chosen, so `defaultValueFor`'s convenience seed for a
+ // date (today) would let one Add click write a date the user never
+ // picked and clear the required warning that produced the row. The base
+ // default is empty for text/date/list, so the commit gate stays shut
+ // until they fill it in. `number`/`boolean` have no empty form — 0 and
+ // an unchecked box are conventional and visibly the value on offer.
+ staged.push({
+ id,
+ name,
+ type,
+ value: DEFAULT_VALUE_FOR_TYPE[type],
+ error: null,
+ focusField: 'value',
+ });
+ }
+ return staged;
+ }
+
+ /** Open the add form on `drafts`, expanding the section if it was collapsed. */
+ function openDrafts(drafts: StagedDraft[]) {
+ setAdding(drafts);
+ setFocusRowId(drafts[0]?.id ?? null);
setCollapsed(false);
}
+ /**
+ * The panel's own inline Add. Singular however many required properties the
+ * doc lacks — its object is one property (the label says so), and a user
+ * reaching for it wants a row to name, not the schema's backlog. Staging that
+ * backlog is the toolbar button's affordance, below.
+ */
+ function beginAddBlank() {
+ openDrafts([blankDraft()]);
+ }
+
+ /** The toolbar's Add-properties button — the batch affordance. */
+ function beginAddMissing() {
+ const staged = stageMissingDrafts();
+ openDrafts(staged.length > 0 ? staged : [blankDraft()]);
+ }
+
// Cross-tree signal from the toolbar's "Add Properties" button.
const { addPropertySignal, clearAddProperty } = useProperties();
const addSignal = addPropertySignal.get(docName) ?? 0;
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `beginAddMissing` closes over live render state (the snapshot map, the diagnostics) and is a new function every render — depending on it would re-stage the rows continuously, discarding whatever the user had typed. The counter is the signal; the effect must fire on it alone.
useEffect(() => {
- if (addSignal > 0) {
- setAdding({ name: '', type: 'text', value: '', error: null });
- setCollapsed(false);
- }
- }, [addSignal, setCollapsed]);
+ if (addSignal > 0) beginAddMissing();
+ }, [addSignal]);
useEffect(() => {
return () => clearAddProperty(docName);
}, [docName, clearAddProperty]);
- function changeAddType(nextType: FrontmatterType) {
- setAdding((prev) => {
- if (!prev) return prev;
- const defaultValue =
- nextType === 'date'
- ? new Date().toISOString().slice(0, 10)
- : DEFAULT_VALUE_FOR_TYPE[nextType];
- return { ...prev, type: nextType, value: defaultValue, error: null };
- });
+ function updateDraft(id: string, patch: (draft: StagedDraft) => StagedDraft) {
+ setAdding((prev) => prev.map((draft) => (draft.id === id ? patch(draft) : draft)));
+ }
+
+ function changeAddType(id: string, nextType: FrontmatterType) {
+ updateDraft(id, (draft) => ({
+ ...draft,
+ type: nextType,
+ value: defaultValueFor(nextType),
+ error: null,
+ }));
+ }
+
+ function changeAddValue(id: string, value: FrontmatterValue) {
+ updateDraft(id, (draft) => ({ ...draft, value }));
}
- function changeAddValue(value: FrontmatterValue) {
- setAdding((prev) => (prev ? { ...prev, value } : prev));
+ function changeAddName(id: string, name: string) {
+ updateDraft(id, (draft) => ({ ...draft, name, error: null }));
}
- function changeAddName(name: string) {
- setAdding((prev) => (prev ? { ...prev, name, error: null } : prev));
+ function pickAddField(id: string, suggestion: AddPropertyFieldSuggestion) {
+ // Name and type in one update — the schema states the type, so picking a
+ // field is the whole answer, not a name the user then types a type for.
+ updateDraft(id, (draft) => ({
+ ...draft,
+ name: suggestion.name,
+ type: suggestion.type,
+ value: defaultValueFor(suggestion.type),
+ error: null,
+ }));
}
- function commitAdd(valueOverride?: FrontmatterValue) {
- if (!adding) return;
+ function commitAdd(id: string, valueOverride?: FrontmatterValue) {
+ const draft = adding.find((entry) => entry.id === id);
+ if (!draft) return;
// Enter-in-value-field carries the freshly-typed value (the draft state
// update from the widget's onCommit lands after this synchronous call).
- const value = valueOverride ?? adding.value;
- const trimmed = adding.name.trim();
+ const value = valueOverride ?? draft.value;
+ const fail = (error: string) => updateDraft(id, (prev) => ({ ...prev, value, error }));
+ const trimmed = draft.name.trim();
if (!trimmed) {
- setAdding({ ...adding, value, error: t`Name is required` });
+ fail(t`Name is required`);
return;
}
// Empty value would be dropped server-side by mergePatch; gate here so the
// user gets an explicit error rather than a silent no-op (the Enter-to-add
// keyboard paths bypass the Add button's disabled state).
if (isFrontmatterValueEmpty(value)) {
- setAdding({ ...adding, value, error: t`Value is required` });
+ fail(t`Value is required`);
return;
}
if (trimmed === 'frontmatter') {
- setAdding({ ...adding, value, error: t`"frontmatter" is a reserved property name` });
+ fail(t`"frontmatter" is a reserved property name`);
return;
}
if (Object.hasOwn(map, trimmed)) {
- setAdding({ ...adding, value, error: t`Property "${trimmed}" already exists` });
+ fail(t`Property "${trimmed}" already exists`);
return;
}
const result = commitPatch({ [trimmed]: value });
if (result.ok) {
- setAdding(null);
+ // Only this row closes — its siblings are still unfilled properties the
+ // doc is missing.
+ setAdding((prev) => prev.filter((entry) => entry.id !== id));
return;
}
- const fieldError = result.fieldErrors?.[trimmed];
- const generic = result.error ?? t`Failed to add property`;
- setAdding({ ...adding, value, error: fieldError ?? generic });
+ fail(result.fieldErrors?.[trimmed] ?? result.error ?? t`Failed to add property`);
}
- function cancelAdd() {
- setAdding(null);
+ function cancelAdd(id: string) {
+ setAdding((prev) => prev.filter((entry) => entry.id !== id));
}
function beginRename(key: string) {
@@ -425,7 +565,7 @@ export function PropertyPanel({ provider, reservedKeys, identitySlot }: Property
// Keep the disclosure alive for its badge whenever one is outstanding.
if (
renderKeys.length === 0 &&
- !adding &&
+ adding.length === 0 &&
!parseError &&
!identitySlot &&
invalidProperties.length === 0
@@ -433,6 +573,29 @@ export function PropertyPanel({ provider, reservedKeys, identitySlot }: Property
return null;
}
+ // Fields the schemas declare that this doc does not already have — the
+ // type-ahead vocabulary for an add-row's name field.
+ const offerableFields: AddPropertyFieldSuggestion[] = [...schemaFields]
+ .filter(([name]) => !Object.hasOwn(map, name) && !reserved.has(name))
+ .map(([name, field]) => ({ name, ...field }));
+
+ /**
+ * The same list minus what a SIBLING row is already staged to add, so a batch
+ * can't point two rows at one property. The row's own name stays offered —
+ * excluding it would empty the list the moment a suggestion was picked.
+ */
+ function suggestionsFor(rowId: string): AddPropertyFieldSuggestion[] {
+ const claimed = new Set(
+ adding
+ .filter((draft) => draft.id !== rowId)
+ .map((draft) => draft.name.trim())
+ .filter((name) => name !== ''),
+ );
+ return claimed.size === 0
+ ? offerableFields
+ : offerableFields.filter((field) => !claimed.has(field.name));
+ }
+
// Flush-left alignment. Sortable rows carry a drag-handle gutter (FrontmatterRow:
// a `w-4` handle + `gap-1` = 1.25rem) that pushes the type-icon column right of
// the document content edge. We pull the whole collapsible content left via
@@ -573,18 +736,31 @@ export function PropertyPanel({ provider, reservedKeys, identitySlot }: Property
onChangeType={() => {}}
/>
) : null}
- {adding ? (
+ {adding.length > 0 ? (
// No drag-handle gutter — cancel the content shift so the add form
// sits flush with the rows (see PROP_CONTENT_SHIFT).
<div className={PROP_GUTTER_COMPENSATE}>
- <AddPropertyRow
- draft={adding}
- onChangeName={changeAddName}
- onChangeType={changeAddType}
- onChangeValue={changeAddValue}
- onCommit={commitAdd}
- onCancel={cancelAdd}
- />
+ {adding.map((draft) => (
+ <AddPropertyRow
+ key={draft.id}
+ rowId={draft.id}
+ draft={draft}
+ // Only the row the batch was opened on takes focus —
+ // `autoFocus` is last-one-wins, so every row claiming it
+ // would land the caret on the bottom one. The target is the
+ // row's own frozen `focusField`, never re-derived from the
+ // live draft.
+ autoFocus={draft.id === focusRowId ? draft.focusField : 'none'}
+ enumConstraint={enumConstraints.get(draft.name.trim())}
+ fieldSuggestions={suggestionsFor(draft.id)}
+ onChangeName={(name) => changeAddName(draft.id, name)}
+ onChangeType={(type) => changeAddType(draft.id, type)}
+ onChangeValue={(value) => changeAddValue(draft.id, value)}
+ onPickField={(suggestion) => pickAddField(draft.id, suggestion)}
+ onCommit={(valueOverride) => commitAdd(draft.id, valueOverride)}
+ onCancel={() => cancelAdd(draft.id)}
+ />
+ ))}
</div>
) : (
// Wrapper mirrors FrontmatterRow's flex layout above: an
@@ -603,7 +779,7 @@ export function PropertyPanel({ provider, reservedKeys, identitySlot }: Property
variant="ghost"
size="sm"
data-testid="add-property-trigger"
- onClick={beginAdd}
+ onClick={beginAddBlank}
// Visible label is just "Add"; the aria-label restores the
// action's object so screen readers don't announce a
// context-free "Add, button".
diff --git a/packages/app/src/components/SkillProperties.tsx b/packages/app/src/components/SkillProperties.tsx
index 31aedfbf1..3fb30681b 100644
--- a/packages/app/src/components/SkillProperties.tsx
+++ b/packages/app/src/components/SkillProperties.tsx
@@ -7,17 +7,9 @@ import { PropertyDisplayRow } from '@/components/PropertyDisplayRow';
import { PropertyPanel } from '@/components/PropertyPanel';
import { Input } from '@/components/ui/input';
import { useSkills } from '@/hooks/use-skills';
+import { SKILL_RESERVED_KEYS } from '@/lib/reserved-property-keys';
import { skillEntryDirs } from '@/lib/skill-scope';
-/**
- * `name` is the skill's folder identity (and the id agents invoke it by), so it
- * is a rename affordance, not a frontmatter property — it is rendered as the
- * first row of the panel with a fixed, non-editable key and hidden from the
- * panel's auto-rendered rows, exactly as a document's filename is not one of
- * its properties.
- */
-const SKILL_RESERVED_KEYS = ['name'] as const;
-
/**
* Skill identity + properties, rendered as the editor's right-hand panel.
*
diff --git a/packages/app/src/lib/frontmatter-schema-fields.test.ts b/packages/app/src/lib/frontmatter-schema-fields.test.ts
new file mode 100644
index 000000000..a74d55aff
--- /dev/null
+++ b/packages/app/src/lib/frontmatter-schema-fields.test.ts
@@ -0,0 +1,269 @@
+import type { LinterConfig } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
+import { schemaFieldsForDoc } from './frontmatter-schema-fields.ts';
+
+function configWith(
+ schemas: {
+ appliesTo?: string | string[];
+ file: string;
+ key?: string;
+ enabled?: boolean;
+ schema?: Record<string, unknown>;
+ }[],
+ enabled = true,
+): LinterConfig {
+ return {
+ enabled: true,
+ plugins: {
+ markdownlint: { enabled: false, rules: {} },
+ frontmatter: { enabled, schemas },
+ },
+ };
+}
+
+const DOC_SCHEMA = {
+ type: 'object',
+ required: ['status'],
+ properties: {
+ status: { type: 'string', description: 'Lifecycle stage' },
+ tags: { type: 'array', items: { type: 'string' } },
+ reviewedAt: { type: 'string', format: 'date' },
+ weight: { type: 'number' },
+ ordinal: { type: 'integer' },
+ draft: { type: 'boolean' },
+ author: { type: 'object' },
+ freeform: {},
+ },
+};
+
+function fieldsFor(schema: Record<string, unknown>, docName = 'docs/guide') {
+ return schemaFieldsForDoc(
+ configWith([{ appliesTo: 'docs/**', file: 'd.json', schema }]),
+ docName,
+ );
+}
+
+/** The fields `schemas` declare for `docs/guide`, all governing it in this order. */
+function fieldsForOrder(schemas: Record<string, unknown>[]) {
+ return schemaFieldsForDoc(
+ configWith(
+ schemas.map((schema, index) => ({
+ appliesTo: 'docs/**',
+ file: `${index}.json`,
+ schema,
+ })),
+ ),
+ 'docs/guide',
+ );
+}
+
+function permutations<T>(items: T[]): T[][] {
+ if (items.length <= 1) return [items];
+ return items.flatMap((item, index) =>
+ permutations([...items.slice(0, index), ...items.slice(index + 1)]).map((rest) => [
+ item,
+ ...rest,
+ ]),
+ );
+}
+
+const WEIGHT_UNTYPED = { type: 'object', properties: { weight: { description: 'How heavy' } } };
+const WEIGHT_NUMBER = { type: 'object', properties: { weight: { type: 'number' } } };
+const WEIGHT_DATE = {
+ type: 'object',
+ properties: { weight: { type: 'string', format: 'date' } },
+};
+const WEIGHT_ARRAY = { type: 'object', properties: { weight: { type: 'array' } } };
+const WEIGHT_REQUIRED_ONLY = { type: 'object', required: ['weight'] };
+
+describe('schemaFieldsForDoc', () => {
+ test('each JSON-Schema type maps to its widget type', () => {
+ const fields = fieldsFor(DOC_SCHEMA);
+ expect(fields.get('status')?.type).toBe('text');
+ expect(fields.get('tags')?.type).toBe('list');
+ expect(fields.get('reviewedAt')?.type).toBe('date');
+ expect(fields.get('weight')?.type).toBe('number');
+ expect(fields.get('ordinal')?.type).toBe('number');
+ expect(fields.get('draft')?.type).toBe('boolean');
+ expect(fields.get('author')?.type).toBe('object');
+ });
+
+ test('an undeclared type falls back to text', () => {
+ expect(fieldsFor(DOC_SCHEMA).get('freeform')?.type).toBe('text');
+ });
+
+ test('a union type falls back to text rather than guessing a branch', () => {
+ const fields = fieldsFor({
+ type: 'object',
+ properties: { either: { type: ['string', 'number'] } },
+ });
+ expect(fields.get('either')?.type).toBe('text');
+ });
+
+ test('an unknown type name falls back to text', () => {
+ const fields = fieldsFor({ type: 'object', properties: { odd: { type: 'null' } } });
+ expect(fields.get('odd')?.type).toBe('text');
+ });
+
+ test('required and description ride along', () => {
+ const fields = fieldsFor(DOC_SCHEMA);
+ expect(fields.get('status')).toEqual({
+ type: 'text',
+ required: true,
+ description: 'Lifecycle stage',
+ });
+ expect(fields.get('tags')?.required).toBe(false);
+ expect(fields.get('tags')?.description).toBeUndefined();
+ });
+
+ test('a field required but never declared is still offered, as text', () => {
+ const fields = fieldsFor({ type: 'object', required: ['ghost'], properties: {} });
+ expect(fields.get('ghost')).toEqual({ type: 'text', required: true });
+ });
+
+ test('conflicting types across two governing schemas degrade to text', () => {
+ const fields = schemaFieldsForDoc(
+ configWith([
+ {
+ appliesTo: 'docs/**',
+ file: 'a.json',
+ schema: { type: 'object', properties: { size: { type: 'number' } } },
+ },
+ {
+ appliesTo: 'docs/**',
+ file: 'b.json',
+ schema: { type: 'object', properties: { size: { type: 'array' } } },
+ },
+ ]),
+ 'docs/guide',
+ );
+ expect(fields.get('size')?.type).toBe('text');
+ });
+
+ test('a conflict stays dropped when a third schema re-declares the first type', () => {
+ // Without the terminal drop set, the third schema would agree with the
+ // `text` fallback and the offered widget would depend on schema order.
+ const fields = schemaFieldsForDoc(
+ configWith([
+ {
+ appliesTo: 'docs/**',
+ file: 'a.json',
+ schema: { type: 'object', properties: { size: { type: 'number' } } },
+ },
+ {
+ appliesTo: 'docs/**',
+ file: 'b.json',
+ schema: { type: 'object', properties: { size: { type: 'array' } } },
+ },
+ {
+ appliesTo: 'docs/**',
+ file: 'c.json',
+ schema: { type: 'object', properties: { size: { type: 'number' } } },
+ },
+ ]),
+ 'docs/guide',
+ );
+ expect(fields.get('size')?.type).toBe('text');
+ });
+
+ test('a schema declaring a property without a type constrains nothing', () => {
+ const expected = { type: 'number', required: false, description: 'How heavy' };
+ expect(fieldsForOrder([WEIGHT_UNTYPED, WEIGHT_NUMBER]).get('weight')).toEqual(expected);
+ expect(fieldsForOrder([WEIGHT_NUMBER, WEIGHT_UNTYPED]).get('weight')).toEqual(expected);
+ });
+
+ test('the merged type is the same under every schema order', () => {
+ const cases = [
+ { schemas: [WEIGHT_UNTYPED, WEIGHT_NUMBER, WEIGHT_NUMBER], type: 'number' },
+ { schemas: [WEIGHT_UNTYPED, WEIGHT_DATE], type: 'date' },
+ { schemas: [WEIGHT_UNTYPED, WEIGHT_UNTYPED], type: 'text' },
+ { schemas: [WEIGHT_REQUIRED_ONLY, WEIGHT_UNTYPED, WEIGHT_NUMBER], type: 'number' },
+ // Two explicit, differing types still have no common widget.
+ { schemas: [WEIGHT_UNTYPED, WEIGHT_NUMBER, WEIGHT_ARRAY], type: 'text' },
+ { schemas: [WEIGHT_NUMBER, WEIGHT_ARRAY, WEIGHT_NUMBER], type: 'text' },
+ ];
+ for (const { schemas, type } of cases) {
+ for (const order of permutations(schemas)) {
+ expect(fieldsForOrder(order).get('weight')?.type).toBe(type);
+ }
+ }
+ });
+
+ test('required unions across schemas regardless of which one declares the field', () => {
+ const fields = schemaFieldsForDoc(
+ configWith([
+ {
+ appliesTo: 'docs/**',
+ file: 'a.json',
+ schema: { type: 'object', properties: { status: { type: 'string' } } },
+ },
+ { appliesTo: 'docs/**', file: 'b.json', schema: { type: 'object', required: ['status'] } },
+ ]),
+ 'docs/guide',
+ );
+ expect(fields.get('status')).toEqual({ type: 'text', required: true });
+ });
+
+ test('the first description wins across schemas', () => {
+ const fields = schemaFieldsForDoc(
+ configWith([
+ {
+ appliesTo: 'docs/**',
+ file: 'a.json',
+ schema: { type: 'object', properties: { status: { description: 'First' } } },
+ },
+ {
+ appliesTo: 'docs/**',
+ file: 'b.json',
+ schema: { type: 'object', properties: { status: { description: 'Second' } } },
+ },
+ ]),
+ 'docs/guide',
+ );
+ expect(fields.get('status')?.description).toBe('First');
+ });
+
+ test('a later schema supplies a description the first one omitted', () => {
+ const fields = schemaFieldsForDoc(
+ configWith([
+ {
+ appliesTo: 'docs/**',
+ file: 'a.json',
+ schema: { type: 'object', properties: { status: { type: 'string' } } },
+ },
+ {
+ appliesTo: 'docs/**',
+ file: 'b.json',
+ schema: { type: 'object', properties: { status: { description: 'Later' } } },
+ },
+ ]),
+ 'docs/guide',
+ );
+ expect(fields.get('status')?.description).toBe('Later');
+ });
+
+ test('a non-matching doc, a disabled plugin, and no doc identity all yield nothing', () => {
+ const config = configWith([{ appliesTo: 'docs/**', file: 'd.json', schema: DOC_SCHEMA }]);
+ expect(schemaFieldsForDoc(config, 'specs/other').size).toBe(0);
+ expect(schemaFieldsForDoc(configWith([], false), 'docs/guide').size).toBe(0);
+ expect(schemaFieldsForDoc(config, undefined).size).toBe(0);
+ expect(schemaFieldsForDoc(config, '').size).toBe(0);
+ expect(schemaFieldsForDoc(null, 'docs/guide').size).toBe(0);
+ });
+
+ test('a toggled-off mapping declares nothing, matching the lint plugin', () => {
+ const fields = schemaFieldsForDoc(
+ configWith([{ appliesTo: 'docs/**', file: 'd.json', enabled: false, schema: DOC_SCHEMA }]),
+ 'docs/guide',
+ );
+ expect(fields.size).toBe(0);
+ });
+
+ test('a content-less mapping declares nothing', () => {
+ const fields = schemaFieldsForDoc(
+ configWith([{ appliesTo: 'docs/**', file: 'missing.json' }]),
+ 'docs/guide',
+ );
+ expect(fields.size).toBe(0);
+ });
+});
diff --git a/packages/app/src/lib/frontmatter-schema-fields.ts b/packages/app/src/lib/frontmatter-schema-fields.ts
new file mode 100644
index 000000000..00b5fcdf0
--- /dev/null
+++ b/packages/app/src/lib/frontmatter-schema-fields.ts
@@ -0,0 +1,170 @@
+/**
+ * Derive the catalogue of fields the schemas governing a doc DECLARE — the
+ * layer above `frontmatter-enum-constraints`, which derives the allowed VALUES
+ * of a field already known. Both read the RESOLVED lint config through
+ * `selectApplicableFrontmatterSchemas`, so neither can disagree with the linter
+ * about which schemas govern a doc.
+ *
+ * Two consumers, both on the add-property path: the field picker offers these
+ * names so a user does not have to open the schema to learn them, and a row
+ * staged for a missing required property takes its widget type from here.
+ *
+ * Presentational only. `required` is unioned across schemas for a hint in the
+ * picker — whether a property is actually missing stays ajv's answer, carried
+ * on the diagnostic as `frontmatterProperty`. Deriving that here instead would
+ * miss `allOf` / `if`-`then` / `$ref` composition, which ajv resolves and a
+ * direct read of `required` does not.
+ *
+ * Merge across schemas mirrors the enum module's conjunction rule: a field
+ * declared with conflicting types by two governing schemas has no single widget
+ * that can satisfy both, so it degrades to `text` rather than picking a side.
+ * Only two EXPLICIT, differing types conflict — a schema that declares a
+ * property without a `type` constrains nothing, so it must not be able to
+ * outvote a sibling that does declare one.
+ */
+
+import {
+ type FrontmatterType,
+ type LinterConfig,
+ selectApplicableFrontmatterSchemas,
+} from '@inkeep/open-knowledge-core';
+
+export interface SchemaField {
+ /** Widget type for the field, defaulting to `text` when undeclared. */
+ type: FrontmatterType;
+ /** Declared `required` by at least one governing schema. */
+ required: boolean;
+ /** The schema's own `description`, shown as secondary text in the picker. */
+ description?: string;
+}
+
+/**
+ * A field mid-merge. `type: null` is "no governing schema has declared one
+ * yet", kept distinct from an explicit `text` so an untyped declaration cannot
+ * masquerade as a constraint a later schema then conflicts with. Resolved to
+ * the panel's `text` fallback once every schema has been folded in.
+ */
+interface DeclaredField {
+ type: FrontmatterType | null;
+ required: boolean;
+ description?: string;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function requiredNames(schema: Record<string, unknown>): string[] {
+ if (!Array.isArray(schema.required)) return [];
+ return schema.required.filter((name): name is string => typeof name === 'string');
+}
+
+/**
+ * JSON-Schema `type` → the panel's widget vocabulary.
+ *
+ * `null` means "no single widget applies": an undeclared type, one OK has no
+ * widget for, or a union (`type: ['string', 'number']`). Callers render those
+ * as `text`, which accepts anything the user types and lets the linter judge
+ * it — the alternative, guessing one branch of a union, produces a widget that
+ * silently cannot express the other.
+ */
+function widgetTypeFor(property: Record<string, unknown>): FrontmatterType | null {
+ const declared = property.type;
+ if (typeof declared !== 'string') return null;
+ switch (declared) {
+ case 'string':
+ // `format: date` is the one format with a dedicated widget; every other
+ // format (email, uri, …) is text with a validator behind it.
+ return property.format === 'date' ? 'date' : 'text';
+ case 'number':
+ case 'integer':
+ return 'number';
+ case 'boolean':
+ return 'boolean';
+ case 'array':
+ return 'list';
+ case 'object':
+ return 'object';
+ default:
+ return null;
+ }
+}
+
+/** The fields declared for `docName` by every schema that governs it. */
+export function schemaFieldsForDoc(
+ config: LinterConfig | null,
+ docName: string | undefined,
+): Map<string, SchemaField> {
+ const slice = config?.plugins.frontmatter;
+ if (!config?.enabled || !slice?.enabled || docName === undefined || docName === '') {
+ return new Map();
+ }
+ const declared = new Map<string, DeclaredField>();
+ const schemas = selectApplicableFrontmatterSchemas(slice.schemas, docName);
+
+ // Unioned up front, not per schema: one schema may declare `status` under
+ // `properties` while a sibling requires it, and the field is required either
+ // way. Folding them in one pass would let declaration order decide.
+ const required = new Set(schemas.flatMap(({ schema }) => requiredNames(schema)));
+
+ // Fields a type conflict already dropped to `text`. Terminal by construction
+ // rather than by `text` happening to absorb every later comparison, so the
+ // offered widget cannot come to depend on schema order.
+ const droppedToText = new Set<string>();
+
+ function declare(name: string, type: FrontmatterType | null, description?: string): void {
+ const existing = declared.get(name);
+ if (existing === undefined) {
+ declared.set(name, {
+ type,
+ required: required.has(name),
+ ...(description === undefined ? {} : { description }),
+ });
+ return;
+ }
+ // The first description wins — schemas are conjoined, not ranked, so
+ // concatenating two would read as one contradictory sentence.
+ const next: DeclaredField = {
+ ...existing,
+ ...(existing.description === undefined && description !== undefined ? { description } : {}),
+ };
+ if (type !== null && !droppedToText.has(name)) {
+ // An unconstrained field takes the first declared type; two explicit,
+ // differing types have no common widget.
+ if (existing.type === null) next.type = type;
+ else if (type !== existing.type) {
+ droppedToText.add(name);
+ next.type = 'text';
+ }
+ }
+ declared.set(name, next);
+ }
+
+ for (const { schema } of schemas) {
+ const properties = isRecord(schema.properties) ? schema.properties : {};
+ for (const [name, rawProperty] of Object.entries(properties)) {
+ if (!isRecord(rawProperty)) continue;
+ const description =
+ typeof rawProperty.description === 'string' && rawProperty.description !== ''
+ ? rawProperty.description
+ : undefined;
+ declare(name, widgetTypeFor(rawProperty), description);
+ }
+ }
+
+ // A schema may require a field it never declares under `properties`. The
+ // picker still has to offer it and a staged row still needs a type, so it
+ // lands unconstrained and resolves to text.
+ for (const name of required) declare(name, null);
+
+ return new Map(
+ [...declared].map(([name, field]) => [
+ name,
+ {
+ type: field.type ?? 'text',
+ required: field.required,
+ ...(field.description === undefined ? {} : { description: field.description }),
+ },
+ ]),
+ );
+}
diff --git a/packages/app/src/lib/reserved-property-keys.ts b/packages/app/src/lib/reserved-property-keys.ts
new file mode 100644
index 000000000..3159b1c8f
--- /dev/null
+++ b/packages/app/src/lib/reserved-property-keys.ts
@@ -0,0 +1,38 @@
+/**
+ * Which frontmatter keys a document's property panel refuses to own, shared by
+ * the panel that reserves them and the toolbar affordance that offers to add
+ * the missing ones. Two copies of the list would drift into a button that
+ * advertises a property the panel then declines to stage.
+ */
+
+import type { LintDiagnostic } from '@inkeep/open-knowledge-core';
+
+/**
+ * A skill's `name` is its folder identity (and the id agents invoke it by), so
+ * it is renamed by moving the folder, never patched as a frontmatter property —
+ * exactly as a document's filename is not one of its properties. The skill panel
+ * renders it as a fixed identity row and keeps it out of its frontmatter rows.
+ */
+export const SKILL_RESERVED_KEYS = ['name'] as const;
+
+/** Ordinary documents own every key, so nothing is held back from them. */
+export const NO_RESERVED_KEYS: readonly string[] = [];
+
+/**
+ * Drop the missing-property diagnostics naming a key reserved for this document.
+ *
+ * A surface that counts or lists them would promise an add the panel will not
+ * perform. The schema violation itself is not lost — it still reports through
+ * the Problems panel like any other diagnostic.
+ */
+export function withoutReservedProperties(
+ diagnostics: readonly LintDiagnostic[],
+ reservedKeys: readonly string[],
+): readonly LintDiagnostic[] {
+ if (reservedKeys.length === 0) return diagnostics;
+ const reserved = new Set(reservedKeys);
+ return diagnostics.filter(
+ (diagnostic) =>
+ diagnostic.frontmatterProperty === undefined || !reserved.has(diagnostic.frontmatterProperty),
+ );
+}
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 29795b38c..c72329f00 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -2311,6 +2311,7 @@
"bUUVED": ["Asset"],
"bV6DJA": ["Who you are, so the agent has your context."],
"bWLmRK": ["Could not fetch branch. Check your connection."],
+ "bYUIzq": ["Schema fields"],
"ba3vIW": [["templateCount", "plural", { "one": ["template"], "other": ["templates"] }]],
"bbJ-VR": ["Zoom Out"],
"bcDHUM": [["descriptorLabel"], " — render error, source editable below"],
@@ -3392,6 +3393,7 @@
],
"sNeKjP": ["Failed to store the token — try again"],
"sOxZaS": ["Failed to load graph"],
+ "sW5OjU": ["required"],
"sZ2IOu": [
"This ",
["targetNoun"],
@@ -3772,6 +3774,7 @@
],
"ygCKqB": ["Stop"],
"yg_6wQ": ["Search failed. Try again."],
+ "yh5-4s": ["Click to add and fill them in"],
"yhI6P0": ["Moved \"", ["0"], "\" to ", ["1"]],
"yhdqox": [
"Installed — ok is available in external terminals. Unchecking removes it; OpenKnowledge's built-in terminal and AI tools keep working."
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 8b21bc43c..88b4ba391 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -2107,6 +2107,10 @@ msgstr "Click <0>+</0> <1/> <2>Create skill</2> <3/> <4>Upload skill</4>."
msgid "Click an agent's avatar in the presence bar to view their session."
msgstr "Click an agent's avatar in the presence bar to view their session."
+#: src/components/AddPropertiesButton.tsx
+msgid "Click to add and fill them in"
+msgstr "Click to add and fill them in"
+
#: src/components/SkillInstallMenu.tsx
msgid "Click to install in {label}"
msgstr "Click to install in {label}"
@@ -6751,7 +6755,7 @@ msgstr "New project"
msgid "New project…"
msgstr "New project…"
-#: src/components/FrontmatterRow.tsx
+#: src/components/AddPropertyNameField.tsx
msgid "New property name"
msgstr "New property name"
@@ -8224,7 +8228,7 @@ msgstr "Properties"
msgid "Property \"{trimmed}\" already exists"
msgstr "Property \"{trimmed}\" already exists"
-#: src/components/FrontmatterRow.tsx
+#: src/components/AddPropertyNameField.tsx
#: src/components/TemplateForm.tsx
msgid "Property name"
msgstr "Property name"
@@ -8801,6 +8805,10 @@ msgstr "Repository name"
msgid "Repository not found. It may have been renamed, deleted, or moved."
msgstr "Repository not found. It may have been renamed, deleted, or moved."
+#: src/components/AddPropertyNameField.tsx
+msgid "required"
+msgstr "required"
+
#: src/components/settings/frontmatter-schema-field-editor.tsx
msgid "Required"
msgstr "Required"
@@ -9157,6 +9165,10 @@ msgstr "Saving"
msgid "schema {deleteTarget}"
msgstr "schema {deleteTarget}"
+#: src/components/AddPropertyNameField.tsx
+msgid "Schema fields"
+msgstr "Schema fields"
+
#: src/components/settings/CustomThemeEditor.tsx
msgid "Scheme copied as base16 YAML"
msgstr "Scheme copied as base16 YAML"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index f3be5b026..b724c0080 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -2311,6 +2311,7 @@
"bUUVED": ["Àśśēţ"],
"bV6DJA": ["Ŵĥō ŷōũ àŕē, śō ţĥē àĝēńţ ĥàś ŷōũŕ ćōńţēxţ."],
"bWLmRK": ["Ćōũĺď ńōţ ƒēţćĥ ƀŕàńćĥ. Ćĥēćķ ŷōũŕ ćōńńēćţĩōń."],
+ "bYUIzq": ["Śćĥēḿà ƒĩēĺďś"],
"ba3vIW": [["templateCount", "plural", { "one": ["ţēḿƥĺàţē"], "other": ["ţēḿƥĺàţēś"] }]],
"bbJ-VR": ["Źōōḿ Ōũţ"],
"bcDHUM": [["descriptorLabel"], " — ŕēńďēŕ ēŕŕōŕ, śōũŕćē ēďĩţàƀĺē ƀēĺōŵ"],
@@ -3392,6 +3393,7 @@
],
"sNeKjP": ["Ƒàĩĺēď ţō śţōŕē ţĥē ţōķēń — ţŕŷ àĝàĩń"],
"sOxZaS": ["Ƒàĩĺēď ţō ĺōàď ĝŕàƥĥ"],
+ "sW5OjU": ["ŕēǫũĩŕēď"],
"sZ2IOu": [
"Ţĥĩś ",
["targetNoun"],
@@ -3772,6 +3774,7 @@
],
"ygCKqB": ["Śţōƥ"],
"yg_6wQ": ["Śēàŕćĥ ƒàĩĺēď. Ţŕŷ àĝàĩń."],
+ "yh5-4s": ["Ćĺĩćķ ţō àďď àńď ƒĩĺĺ ţĥēḿ ĩń"],
"yhI6P0": ["Ḿōvēď \"", ["0"], "\" ţō ", ["1"]],
"yhdqox": [
"Ĩńśţàĺĺēď — ōķ ĩś àvàĩĺàƀĺē ĩń ēxţēŕńàĺ ţēŕḿĩńàĺś. Ũńćĥēćķĩńĝ ŕēḿōvēś ĩţ; ŌƥēńĶńōŵĺēďĝē'ś ƀũĩĺţ-ĩń ţēŕḿĩńàĺ àńď ÀĨ ţōōĺś ķēēƥ ŵōŕķĩńĝ."
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index b725b3812..5c2b7acd8 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -2103,6 +2103,10 @@ msgstr ""
msgid "Click an agent's avatar in the presence bar to view their session."
msgstr ""
+#: src/components/AddPropertiesButton.tsx
+msgid "Click to add and fill them in"
+msgstr ""
+
#: src/components/SkillInstallMenu.tsx
msgid "Click to install in {label}"
msgstr ""
@@ -6747,7 +6751,7 @@ msgstr ""
msgid "New project…"
msgstr ""
-#: src/components/FrontmatterRow.tsx
+#: src/components/AddPropertyNameField.tsx
msgid "New property name"
msgstr ""
@@ -8220,7 +8224,7 @@ msgstr ""
msgid "Property \"{trimmed}\" already exists"
msgstr ""
-#: src/components/FrontmatterRow.tsx
+#: src/components/AddPropertyNameField.tsx
#: src/components/TemplateForm.tsx
msgid "Property name"
msgstr ""
@@ -8797,6 +8801,10 @@ msgstr ""
msgid "Repository not found. It may have been renamed, deleted, or moved."
msgstr ""
+#: src/components/AddPropertyNameField.tsx
+msgid "required"
+msgstr ""
+
#: src/components/settings/frontmatter-schema-field-editor.tsx
msgid "Required"
msgstr ""
@@ -9153,6 +9161,10 @@ msgstr ""
msgid "schema {deleteTarget}"
msgstr ""
+#: src/components/AddPropertyNameField.tsx
+msgid "Schema fields"
+msgstr ""
+
#: src/components/settings/CustomThemeEditor.tsx
msgid "Scheme copied as base16 YAML"
msgstr ""
diff --git a/packages/app/tests/integration/frontmatter-lint-http.test.ts b/packages/app/tests/integration/frontmatter-lint-http.test.ts
index 6d79c7a2b..41c9bdadc 100644
--- a/packages/app/tests/integration/frontmatter-lint-http.test.ts
+++ b/packages/app/tests/integration/frontmatter-lint-http.test.ts
@@ -143,6 +143,25 @@ describe('GET /api/lint — frontmatter diagnostics', () => {
expect(enumViolation?.severity).toBe('warning');
});
+ /**
+ * The absent-property name has to survive `successResponse`'s schema
+ * serialization, or the staged-row affordance an API/MCP consumer builds from
+ * it never fires. Read the RAW wire body rather than `LintDocResultSchema` —
+ * re-parsing with the same schema that serializes the response would mask a
+ * field the server dropped.
+ *
+ */
+ test('a missing-required diagnostic carries frontmatterProperty across the wire', async () => {
+ const res = await fetch(api('/api/lint?doc=docs%2Fguide'));
+ expect(res.status).toBe(200);
+ const raw = (await res.json()) as { diagnostics: Array<Record<string, unknown>> };
+ const required = raw.diagnostics.find((d) => d.code === 'required');
+ expect(required?.frontmatterScope).toBe('missing');
+ // docs/guide.md declares `status` but not `owner`, so `owner` is the absent
+ // required property the diagnostic names.
+ expect(required?.frontmatterProperty).toBe('owner');
+ });
+
test('a doc excluded by the negated glob gets no frontmatter diagnostics', async () => {
const res = await fetch(api('/api/lint?doc=docs%2Findex'));
const body = LintDocResultSchema.parse(await res.json());
diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.ts
index ef630ccba..0ba33b7d8 100644
--- a/packages/core/src/markdown/lint/config-schemas.ts
+++ b/packages/core/src/markdown/lint/config-schemas.ts
@@ -146,6 +146,7 @@ const LintDiagnosticSchema = z.object({
message: z.string(),
fixes: z.array(z.object({ range: LintRangeSchema, newText: z.string() })).optional(),
frontmatterScope: z.enum(['missing', 'invalid']).optional(),
+ frontmatterProperty: z.string().optional(),
});
export const LintDocResultSchema = z.object({
diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.ts
index 3b6c5851f..0d4c9a0df 100644
--- a/packages/core/src/markdown/lint/frontmatter-validate.ts
+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts
@@ -236,12 +236,14 @@ export function validateFrontmatterSource(
let line = 0;
let message: string;
let frontmatterScope: 'missing' | 'invalid' = 'invalid';
+ let frontmatterProperty: string | undefined;
if (keyword === 'required' && error.instancePath === '') {
const missing = String(
(error.params as { missingProperty?: unknown }).missingProperty ?? '',
);
message = `Frontmatter property "${missing}" is required`;
frontmatterScope = 'missing';
+ if (missing !== '') frontmatterProperty = missing;
} else if (error.instancePath === '') {
message = `Frontmatter ${error.message ?? `violates "${keyword}"`}`;
} else {
@@ -265,6 +267,7 @@ export function validateFrontmatterSource(
code: keyword,
message,
frontmatterScope,
+ ...(frontmatterProperty === undefined ? {} : { frontmatterProperty }),
});
}
}
diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.ts
index 7b91a911b..3918e657c 100644
--- a/packages/core/src/markdown/lint/types.ts
+++ b/packages/core/src/markdown/lint/types.ts
@@ -26,6 +26,7 @@ export interface LintDiagnostic {
message: string;
fixes?: LintTextEdit[];
frontmatterScope?: 'missing' | 'invalid';
+ frontmatterProperty?: string;
}
const VALIDATION_SOURCES = [...LINT_PLUGIN_IDS, 'links'] as const;