Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(open-knowledge): report frontmatter problems where they can be fixed (PRD-7646 PRD-7645) (#3133)

serafin-garciaa0bac1df8a72
diff --git a/.changeset/frontmatter-problems-badge-not-squiggle.md b/.changeset/frontmatter-problems-badge-not-squiggle.md
new file mode 100644
index 000000000..d3902deb2
--- /dev/null
+++ b/.changeset/frontmatter-problems-badge-not-squiggle.md
@@ -0,0 +1,9 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Frontmatter schema problems no longer underline body text that isn't wrong, and now report next to whatever can actually fix them. When a schema required frontmatter that a document didn't have, the error had no property to attach to, so the red squiggle landed on the document's first line — usually a perfectly correct heading, with no hint that the real problem was a missing frontmatter block.
+
+Required properties the document is missing now show as a warning count on the toolbar's properties button, since adding a property is the fix and there is no row to point at yet. Properties that are present but don't match the schema — a wrong type, a value outside an allowed set — show as a warning count beside the Properties heading, next to the existing property count rather than replacing it. Both carry the specific messages in their tooltip, and the Problems panel continues to carry the full explanation. Clicking a frontmatter row in the Problems panel no longer jumps the cursor to that unrelated first block.
+
+The Problems tab's own count badge picks up the same warning styling, so the three read as one family. Body-anchored rules (hard tabs, heading levels, and the rest of markdownlint) are unchanged and still mark the block they're about.
diff --git a/knip.config.ts b/knip.config.ts
index 13582ee18..f004e6bc3 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -123,7 +123,9 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],
project: 'src/**',
- ignoreDependencies: ['@types/shell-quote'],
+ ignoreDependencies: [
+ '@types/shell-quote',
+ ],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
diff --git a/packages/app/package.json b/packages/app/package.json
index 093fcb858..d54c73780 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -27,7 +27,7 @@
"measure:stress": "bash scripts/measure-stress.sh",
"measure:sweep": "bash scripts/measure-sweep.sh",
"perf:compare": "bash scripts/perf-compare.sh",
- "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts",
+ "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts",
"test:e2e:install-browsers": "playwright install chromium webkit firefox",
"test:visual": "playwright test --config playwright.visual.config.ts",
"test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots",
diff --git a/packages/app/src/components/AddPropertiesButton.dom.test.tsx b/packages/app/src/components/AddPropertiesButton.dom.test.tsx
new file mode 100644
index 000000000..ee263a3d5
--- /dev/null
+++ b/packages/app/src/components/AddPropertiesButton.dom.test.tsx
@@ -0,0 +1,93 @@
+/**
+ * The Add-properties button doubles as the report surface for frontmatter
+ * schema violations, which have no body construct to squiggle. These assert
+ * the badge's observable contract: it appears only when there are problems,
+ * the count reaches assistive tech through the button's accessible name (the
+ * badge itself is decorative), and clicking still opens the add-property form.
+ */
+
+import * as actualLinguiMacro from '@lingui/react/macro';
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+
+vi.doMock('@lingui/react/macro', () => ({
+ ...actualLinguiMacro,
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+/** Badge-relevant props; `onAddProperty` is supplied by the helper. */
+type BadgeProps = { problemCount?: number; problemMessages?: readonly string[] };
+
+async function renderButton(props: BadgeProps = {}) {
+ const { AddPropertiesButton } = await import('./AddPropertiesButton');
+ const onAddProperty = vi.fn();
+ render(
+ <TooltipProvider>
+ <AddPropertiesButton onAddProperty={onAddProperty} {...props} />
+ </TooltipProvider>,
+ );
+ return { onAddProperty };
+}
+
+describe('AddPropertiesButton frontmatter badge', () => {
+ afterEach(() => cleanup());
+
+ test('renders no badge when there are no frontmatter problems', async () => {
+ await renderButton();
+ expect(screen.queryByTestId('add-properties-problem-badge')).toBeNull();
+ });
+
+ test('renders the count when frontmatter problems exist', async () => {
+ await renderButton({ problemCount: 2 });
+ expect(screen.getByTestId('add-properties-problem-badge').textContent).toBe('2');
+ });
+
+ test('carries the count in the accessible name, not only the visual badge', async () => {
+ // The badge is aria-hidden, so the button's own name is the only channel a
+ // screen-reader user has for "this doc is missing a required property".
+ await renderButton({ problemCount: 1 });
+ expect(screen.getByRole('button').getAttribute('aria-label')).toMatch(
+ /1 required property missing/,
+ );
+ expect(screen.getByTestId('add-properties-problem-badge').getAttribute('aria-hidden')).toBe(
+ 'true',
+ );
+ });
+
+ test('caps the badge label so a large count stays legible', async () => {
+ await renderButton({ problemCount: 42 });
+ expect(screen.getByTestId('add-properties-problem-badge').textContent).toBe('9+');
+ // The true count still reaches assistive tech uncapped.
+ expect(screen.getByRole('button').getAttribute('aria-label')).toMatch(
+ /42 required properties missing/,
+ );
+ });
+
+ test('still opens the add-property form when badged', async () => {
+ const { onAddProperty } = await renderButton({ problemCount: 3 });
+ await userEvent.click(screen.getByRole('button'));
+ expect(onAddProperty).toHaveBeenCalledTimes(1);
+ });
+
+ test('lists each missing-property message in the tooltip', async () => {
+ // The badge count says how many; the tooltip says which. Dropping the
+ // per-message list would leave only the summary header, so pin the messages.
+ const user = userEvent.setup();
+ await renderButton({
+ problemCount: 2,
+ problemMessages: [
+ 'Frontmatter property "status" is required',
+ 'Frontmatter property "owner" is required',
+ ],
+ });
+ await user.hover(screen.getByRole('button'));
+ const tooltip = await screen.findByRole('tooltip');
+ expect(tooltip.textContent).toContain('Frontmatter property "status" is required');
+ expect(tooltip.textContent).toContain('Frontmatter property "owner" is required');
+ });
+});
diff --git a/packages/app/src/components/AddPropertiesButton.tsx b/packages/app/src/components/AddPropertiesButton.tsx
index 93ed3de89..7c462470b 100644
--- a/packages/app/src/components/AddPropertiesButton.tsx
+++ b/packages/app/src/components/AddPropertiesButton.tsx
@@ -1,39 +1,97 @@
+import { plural } from '@lingui/core/macro';
import { Trans, useLingui } from '@lingui/react/macro';
import { ListPlus } from 'lucide-react';
+import { Badge, NOTIFICATION_BADGE_MAX } from '@/components/ui/badge';
import { Button } from '@/components/ui/button.tsx';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { cn } from '@/lib/utils';
/**
* Toolbar "Add properties" affordance. PropertyPanel only mounts in WYSIWYG mode
* (gated in EditorActivityPool), so callers hide this in source mode — clicking
* it there would fire a CustomEvent with no listener (an unresponsive-UI no-op).
* Source-mode users edit frontmatter directly in the CodeMirror YAML.
+ *
+ * Doubles as the report surface for the frontmatter properties a schema
+ * requires and the document does NOT have. Those have nothing to mark: no body
+ * anchor (a doc missing its frontmatter entirely has only body text, which is
+ * not itself wrong) and no property row either, since the property is precisely
+ * what is absent — and when the doc has no properties at all `PropertyPanel`
+ * renders nothing. Adding a property is the fix, so this is where they belong.
+ *
+ * Properties that are PRESENT but wrong report on the property panel's own
+ * count instead; they have a row, and adding is not their fix. The badge is a
+ * pointer, not the explanation: the count and messages land in the tooltip, and
+ * the Problems panel carries the full detail.
*/
export function AddPropertiesButton({
onAddProperty,
className,
+ problemCount = 0,
+ problemMessages,
}: {
onAddProperty: () => void;
className?: string;
+ /** Schema-required properties the active doc is missing. 0 renders no badge. */
+ problemCount?: number;
+ /** The missing-property messages, listed in the tooltip under the summary. */
+ problemMessages?: readonly string[];
}) {
const { t } = useLingui();
+ const hasProblems = problemCount > 0;
+ // The accessible name carries the count too — the badge is a visual channel
+ // only, and a screen-reader user gets no signal from it otherwise.
+ const label = hasProblems
+ ? t`Add properties (${plural(problemCount, {
+ one: '# required property missing',
+ other: '# required properties missing',
+ })})`
+ : t`Add properties`;
return (
<Tooltip>
<Button
variant="ghost"
size="icon"
- aria-label={t`Add properties`}
+ aria-label={label}
onClick={onAddProperty}
data-testid="add-properties-button"
- className={className}
+ className={cn('relative', className)}
asChild
>
<TooltipTrigger>
<ListPlus />
+ {hasProblems ? (
+ <Badge
+ variant="notification"
+ // Presentational: the count is already in the button's aria-label,
+ // so announcing it again would double up on every focus.
+ aria-hidden="true"
+ data-testid="add-properties-problem-badge"
+ className="pointer-events-none absolute -top-0.5 -right-0.5 size-3.5 rounded-full p-0 font-sans text-[9px] leading-none tabular-nums"
+ >
+ {problemCount > NOTIFICATION_BADGE_MAX ? `${NOTIFICATION_BADGE_MAX}+` : problemCount}
+ </Badge>
+ ) : null}
</TooltipTrigger>
</Button>
<TooltipContent side="bottom">
- <Trans>Add properties</Trans>
+ {hasProblems ? (
+ <span className="flex flex-col gap-0.5">
+ <span className="font-medium">
+ <Trans>This document is missing required properties</Trans>
+ </span>
+ {/* Index key, not the message: two distinct schema files can both
+ require the same property and emit byte-identical strings. */}
+ {problemMessages?.map((message, index) => (
+ // biome-ignore lint/suspicious/noArrayIndexKey: static within a render
+ <span key={index} className="opacity-90">
+ {message}
+ </span>
+ ))}
+ </span>
+ ) : (
+ <Trans>Add properties</Trans>
+ )}
</TooltipContent>
</Tooltip>
);
diff --git a/packages/app/src/components/DocPanel.tsx b/packages/app/src/components/DocPanel.tsx
index 3d4679228..d9cd467d7 100644
--- a/packages/app/src/components/DocPanel.tsx
+++ b/packages/app/src/components/DocPanel.tsx
@@ -220,7 +220,7 @@ export function DocPanel({
<Icon />
{showBadge && (
<Badge
- variant="destructive"
+ variant="notification"
aria-hidden="true"
className="absolute -right-1.5 -top-1.5 h-4 min-w-4 rounded-full px-1 text-[10px] leading-none"
>
diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsx
index ec2d320b8..6d3a6c46f 100644
--- a/packages/app/src/components/EditorArea.tsx
+++ b/packages/app/src/components/EditorArea.tsx
@@ -41,8 +41,13 @@ import {
useDocumentTransition,
} from '@/editor/DocumentContext';
import { FindReplaceController } from '@/editor/find-replace/FindReplaceController';
+import { useDocLintConfig } from '@/editor/lint-config-client';
import { mountPromiseHasResolved } from '@/editor/mount-promise';
import { syncPromiseHasResolved } from '@/editor/sync-promise';
+import {
+ partitionFrontmatterProblems,
+ useFrontmatterDiagnostics,
+} from '@/editor/useFrontmatterDiagnostics';
import { useDocumentStats } from '@/hooks/use-document-stats';
import { useLifecycleStatus } from '@/hooks/use-lifecycle-status';
import { useSelectionStats } from '@/hooks/use-selection-stats';
@@ -279,6 +284,21 @@ function EditorAreaInner({
);
const syncStatus = useSyncStatus(activeProvider);
const isConnected = syncStatus === 'connected' || syncStatus === 'synced';
+ // Schema-required properties the doc does not have badge the toolbar's
+ // Add-properties button: they have no body construct to mark and no property
+ // row either (being absent is the problem), and on a doc with no properties
+ // at all `PropertyPanel` renders nothing — so the toolbar is the only surface
+ // always there to carry them. Present-but-invalid properties are the panel's.
+ const { data: frontmatterLintConfig } = useDocLintConfig(activeDocName);
+ // Source mode hides the Add-properties button entirely, so the pass has no
+ // consumer there — short-circuit rather than lint on every keystroke for a
+ // badge that cannot render.
+ const { missing: missingProperties } = partitionFrontmatterProblems(
+ useFrontmatterDiagnostics(
+ editorMode === 'source' ? null : activeProvider,
+ frontmatterLintConfig?.effective ?? null,
+ ),
+ );
const lifecycleStatus = useLifecycleStatus(activeDocName);
const isConflict = lifecycleStatus === 'conflict';
// Latches true once any provider has been active this session. It separates a
@@ -1207,6 +1227,8 @@ function EditorAreaInner({
onModeChange={onModeChange}
showAddPropertyButton={!isSourceMode}
onAddProperty={openAddPropertyForm}
+ frontmatterProblemCount={missingProperties.length}
+ frontmatterProblemMessages={missingProperties.map((d) => d.message)}
isPanelCollapsed={isPanelCollapsed}
onTogglePanel={togglePanel}
// When the doc panel is collapsed, the action cluster reaches the
diff --git a/packages/app/src/components/EditorToolbar.tsx b/packages/app/src/components/EditorToolbar.tsx
index aba0a0e94..ca6347e55 100644
--- a/packages/app/src/components/EditorToolbar.tsx
+++ b/packages/app/src/components/EditorToolbar.tsx
@@ -39,6 +39,11 @@ 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[];
isPanelCollapsed: boolean;
onTogglePanel: () => void;
/** Reserve right-side room in the action cluster so it sits left of the
@@ -55,6 +60,8 @@ export function EditorToolbar({
onModeChange,
showAddPropertyButton,
onAddProperty,
+ frontmatterProblemCount = 0,
+ frontmatterProblemMessages,
isPanelCollapsed,
onTogglePanel,
reserveRightGutter = false,
@@ -168,6 +175,8 @@ export function EditorToolbar({
name={activeSkill.name}
showAddPropertyButton={showAddPropertyButton}
onAddProperty={onAddProperty}
+ problemCount={frontmatterProblemCount}
+ problemMessages={frontmatterProblemMessages}
/>
</Suspense>
) : externalSkill ? // Detected-skill edit buffer: reduced mode. Messaging lives in the
@@ -175,7 +184,13 @@ export function EditorToolbar({
null : (
// Non-skill docs only carry add-properties here (no level/install), so
// there's nothing to overflow — the breadcrumb truncates on its own.
- showAddPropertyButton && <AddPropertiesButton onAddProperty={onAddProperty} />
+ showAddPropertyButton && (
+ <AddPropertiesButton
+ onAddProperty={onAddProperty}
+ problemCount={frontmatterProblemCount}
+ problemMessages={frontmatterProblemMessages}
+ />
+ )
)}
<Tooltip>
<Button
diff --git a/packages/app/src/components/ProblemsPanel.dom.test.tsx b/packages/app/src/components/ProblemsPanel.dom.test.tsx
index 981cf0ba9..2780cf341 100644
--- a/packages/app/src/components/ProblemsPanel.dom.test.tsx
+++ b/packages/app/src/components/ProblemsPanel.dom.test.tsx
@@ -526,7 +526,7 @@ describe('ProblemsPanel', () => {
try {
render(<ProblemsPanel docName="notes" diagnostics={[diag({ line: 7, column: 2 })]} />);
fireEvent.click(screen.getByRole('button'));
- expect(received).toEqual({ line: 7, column: 2 });
+ expect(received).toEqual({ line: 7, column: 2, source: 'markdownlint' });
} finally {
window.removeEventListener(LINT_NAV_EVENT, listener);
}
@@ -602,7 +602,7 @@ describe('ProblemsPanel', () => {
// reads as a whole finding out of list context.
expect(occurrences[1]?.getAttribute('aria-label')).toBe('Hard tabs at line 9');
fireEvent.click(occurrences[1] as HTMLElement);
- expect(received).toEqual({ line: 9, column: 1 });
+ expect(received).toEqual({ line: 9, column: 1, source: 'markdownlint' });
} finally {
window.removeEventListener(LINT_NAV_EVENT, listener);
}
@@ -739,7 +739,7 @@ describe('ProblemsPanel', () => {
try {
render(<ProblemsPanel docName="notes" diagnostics={[linkDiag({ line: 5 })]} />);
fireEvent.click(screen.getByRole('button', { name: /does not resolve/ }));
- expect(received).toEqual({ line: 5, column: 1 });
+ expect(received).toEqual({ line: 5, column: 1, source: 'links' });
} finally {
window.removeEventListener(LINT_NAV_EVENT, listener);
}
@@ -752,7 +752,7 @@ describe('ProblemsPanel', () => {
// the next source-mode activation within the TTL replays it.
expect(consumePendingSourceNavigation('notes')).toEqual({
kind: 'lint',
- detail: { line: 7, column: 2 },
+ detail: { line: 7, column: 2, source: 'markdownlint' },
});
});
});
@@ -983,7 +983,7 @@ describe('ProblemsPanel — project scope', () => {
expect(window.location.hash).toBe('#/guides/setup');
expect(consumePendingSourceNavigation('guides/setup')).toEqual({
kind: 'lint',
- detail: { line: 4, column: 2 },
+ detail: { line: 4, column: 2, source: 'markdownlint' },
});
// The in-doc nav event stays quiet on cross-doc clicks — it carries no
// docName and would move the cursor in the doc that is still open.
@@ -1038,7 +1038,7 @@ describe('ProblemsPanel — project scope', () => {
expect(window.location.hash).toBe('#/guides/setup');
expect(consumePendingSourceNavigation('guides/setup')).toEqual({
kind: 'lint',
- detail: { line: 9, column: 1 },
+ detail: { line: 9, column: 1, source: 'frontmatter' },
});
// Cross-doc clicks stay off the in-doc event (it carries no docName).
expect(navEvents).toBe(0);
@@ -1064,11 +1064,11 @@ describe('ProblemsPanel — project scope', () => {
fireEvent.click(screen.getByRole('button', { name: /Hard tabs/ }));
- expect(received).toEqual({ line: 7, column: 2 });
+ expect(received).toEqual({ line: 7, column: 2, source: 'markdownlint' });
expect(window.location.hash).toBe(hashBefore);
expect(consumePendingSourceNavigation('notes')).toEqual({
kind: 'lint',
- detail: { line: 7, column: 2 },
+ detail: { line: 7, column: 2, source: 'markdownlint' },
});
} finally {
window.removeEventListener(LINT_NAV_EVENT, listener);
diff --git a/packages/app/src/components/ProblemsPanel.tsx b/packages/app/src/components/ProblemsPanel.tsx
index 0d94a14a4..eafed55f6 100644
--- a/packages/app/src/components/ProblemsPanel.tsx
+++ b/packages/app/src/components/ProblemsPanel.tsx
@@ -52,6 +52,14 @@ export interface LintNavDetail {
line: number;
/** 1-based column. */
column: number;
+ /**
+ * Producing plugin id. WYSIWYG needs it to decline navigation for
+ * diagnostics that have no body anchor: a `frontmatter` violation reports on
+ * the region's opening fence, which on a doc with no frontmatter is line 1 —
+ * following it would select the first body block, which is not the problem.
+ * Source mode anchors by line and consumes every source alike.
+ */
+ source?: string;
}
export const LINT_NAV_EVENT = 'open-knowledge:lint-nav';
@@ -76,6 +84,7 @@ function lintNavDetailOf(diagnostic: DiagnosticLike): LintNavDetail {
return {
line: diagnostic.range.start.line + 1,
column: diagnostic.range.start.character + 1,
+ source: diagnostic.source,
};
}
diff --git a/packages/app/src/components/PropertyDisclosure.dom.test.tsx b/packages/app/src/components/PropertyDisclosure.dom.test.tsx
new file mode 100644
index 000000000..e694e7101
--- /dev/null
+++ b/packages/app/src/components/PropertyDisclosure.dom.test.tsx
@@ -0,0 +1,113 @@
+/**
+ * The Properties disclosure carries two independent counts: how many properties
+ * the document has, and how many of them violate its schema. These pin that they
+ * stay distinct — a single recolored number would answer the first question
+ * while appearing to answer the second.
+ */
+
+import * as actualLinguiMacro from '@lingui/react/macro';
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+
+vi.doMock('@lingui/react/macro', () => ({
+ ...actualLinguiMacro,
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+async function renderDisclosure(
+ props: { count?: number; problemCount?: number; problemMessages?: readonly string[] } = {},
+) {
+ const { PropertyDisclosure } = await import('./PropertyDisclosure');
+ render(
+ <TooltipProvider>
+ <PropertyDisclosure title="Properties" {...props}>
+ <div>rows</div>
+ </PropertyDisclosure>
+ </TooltipProvider>,
+ );
+}
+
+describe('PropertyDisclosure schema-problem badge', () => {
+ afterEach(() => cleanup());
+
+ test('shows no problem badge when every property is valid', async () => {
+ await renderDisclosure({ count: 4 });
+ expect(screen.queryByTestId('property-problem-badge')).toBeNull();
+ });
+
+ test('shows the problem count beside the property count, not instead of it', async () => {
+ await renderDisclosure({ count: 4, problemCount: 2 });
+ expect(screen.getByTestId('property-problem-badge').textContent).toBe('2');
+ // The property count survives — both numbers are on screen and they differ.
+ expect(screen.getByText('4')).toBeTruthy();
+ });
+
+ test('names the problem count for assistive tech', async () => {
+ await renderDisclosure({ count: 3, problemCount: 1 });
+ // The name lives on the focusable trigger, not the decorative badge inside it.
+ expect(screen.getByTestId('property-problem-badge-trigger').getAttribute('aria-label')).toMatch(
+ /1 property does not match the schema/,
+ );
+ expect(screen.getByTestId('property-problem-badge').getAttribute('aria-hidden')).toBe('true');
+ });
+
+ test('pluralizes the accessible name', async () => {
+ await renderDisclosure({ count: 5, problemCount: 3 });
+ expect(screen.getByTestId('property-problem-badge-trigger').getAttribute('aria-label')).toMatch(
+ /3 properties do not match the schema/,
+ );
+ });
+
+ test('caps the badge label, matching its sibling on the toolbar', async () => {
+ await renderDisclosure({ count: 4, problemCount: 42 });
+ expect(screen.getByTestId('property-problem-badge').textContent).toBe('9+');
+ // The true count still reaches assistive tech uncapped.
+ expect(screen.getByTestId('property-problem-badge-trigger').getAttribute('aria-label')).toMatch(
+ /42 properties do not match the schema/,
+ );
+ });
+
+ test('renders a problem badge even when the property count is hidden', async () => {
+ // `count` renders nothing at 0; the problem badge must not ride on it.
+ await renderDisclosure({ count: 0, problemCount: 1 });
+ expect(screen.getByTestId('property-problem-badge').textContent).toBe('1');
+ });
+
+ test('surfaces the messages on keyboard focus, not just hover', async () => {
+ // The badge used to sit INSIDE the collapsible trigger button, where it
+ // could never take focus (HTML forbids interactive content inside a
+ // button), so the per-message detail was mouse-only.
+ const user = userEvent.setup();
+ await renderDisclosure({
+ count: 4,
+ problemCount: 1,
+ problemMessages: ['status is not one of the allowed values'],
+ });
+ const trigger = screen.getByTestId('property-problem-badge-trigger');
+ await user.tab();
+ await user.tab();
+ expect(document.activeElement).toBe(trigger);
+ const tooltip = await screen.findByRole('tooltip');
+ expect(tooltip.textContent).toContain('status is not one of the allowed values');
+ });
+
+ test('lists each schema-violation message in the badge tooltip', async () => {
+ // The badge number is the pointer; the tooltip carries which properties are
+ // wrong. Dropping the message list would silently reduce it to nothing.
+ const user = userEvent.setup();
+ await renderDisclosure({
+ count: 4,
+ problemCount: 2,
+ problemMessages: ['status is not one of the allowed values', 'owner must be a string'],
+ });
+ await user.hover(screen.getByTestId('property-problem-badge'));
+ const tooltip = await screen.findByRole('tooltip');
+ expect(tooltip.textContent).toContain('status is not one of the allowed values');
+ expect(tooltip.textContent).toContain('owner must be a string');
+ });
+});
diff --git a/packages/app/src/components/PropertyDisclosure.tsx b/packages/app/src/components/PropertyDisclosure.tsx
index 820178c87..3764d8b74 100644
--- a/packages/app/src/components/PropertyDisclosure.tsx
+++ b/packages/app/src/components/PropertyDisclosure.tsx
@@ -1,8 +1,11 @@
+import { plural } from '@lingui/core/macro';
+import { useLingui } from '@lingui/react/macro';
import { ChevronRight } from 'lucide-react';
import { type ReactNode, type Ref, useState } from 'react';
-import { Badge } from '@/components/ui/badge';
+import { Badge, NOTIFICATION_BADGE_MAX } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
/**
@@ -16,6 +19,8 @@ import { cn } from '@/lib/utils';
export function PropertyDisclosure({
title,
count,
+ problemCount,
+ problemMessages,
className,
contentClassName,
testId,
@@ -28,6 +33,16 @@ export function PropertyDisclosure({
/** Optional item count shown as a badge next to the title. Rendered only when
* a positive number — 0 and undefined show nothing. */
count?: number;
+ /**
+ * Properties that are present but violate the document's schema, shown as a
+ * second badge beside the count. Deliberately separate from `count` rather
+ * than recoloring it: the two answer different questions ("how many
+ * properties" vs "how many are wrong"), and a single recolored number would
+ * state the first while implying the second.
+ */
+ problemCount?: number;
+ /** The violation messages, listed in the badge's tooltip. */
+ problemMessages?: readonly string[];
/** Extra container classes (e.g. vertical padding) merged after the base. */
className?: string;
/** Extra classes on the collapsible content box. The editable document panel
@@ -46,6 +61,7 @@ export function PropertyDisclosure({
* can observe text selection within the panel. React 19 ref-as-prop. */
ref?: Ref<HTMLDivElement>;
}) {
+ const { t } = useLingui();
const [internalCollapsed, setInternalCollapsed] = useState(false);
const open = openProp ?? !internalCollapsed;
const setOpen = (next: boolean) => {
@@ -59,24 +75,66 @@ export function PropertyDisclosure({
data-testid={testId}
>
<Collapsible open={open} onOpenChange={setOpen}>
- <CollapsibleTrigger asChild>
- <Button
- type="button"
- variant="ghost"
- className="data-[state=open]:mb-1.5 flex h-auto w-fit items-center gap-1 bg-transparent! tracking-wider px-1 py-0.5 text-sm uppercase font-mono font-medium text-muted-foreground hover:bg-transparent hover:text-foreground space-x-1.5"
- >
- <ChevronRight
- data-expanded={open}
- className="size-3.5 shrink-0 text-muted-foreground transition-transform duration-150 ease-out data-[expanded=true]:rotate-90"
- />
- <span>{title}</span>
- {typeof count === 'number' && count > 0 ? (
- <Badge variant="gray" className="tabular-nums normal-case">
- {count}
- </Badge>
- ) : null}
- </Button>
- </CollapsibleTrigger>
+ {/* The problem badge is a SIBLING of the trigger, not a child of it.
+ Nested inside the button its tooltip would be mouse-only — HTML
+ forbids interactive content inside `button`, so the badge can never
+ take focus and Radix's focus-open never fires. The open-state margin
+ moves here with it so both stay on one baseline. */}
+ <div className={cn('flex w-fit items-center gap-1.5', open && 'mb-1.5')}>
+ <CollapsibleTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ className="flex h-auto w-fit items-center gap-1 bg-transparent! tracking-wider px-1 py-0.5 text-sm uppercase font-mono font-medium text-muted-foreground hover:bg-transparent hover:text-foreground space-x-1.5"
+ >
+ <ChevronRight
+ data-expanded={open}
+ className="size-3.5 shrink-0 text-muted-foreground transition-transform duration-150 ease-out data-[expanded=true]:rotate-90"
+ />
+ <span>{title}</span>
+ {typeof count === 'number' && count > 0 ? (
+ <Badge variant="gray" className="tabular-nums normal-case">
+ {count}
+ </Badge>
+ ) : null}
+ </Button>
+ </CollapsibleTrigger>
+ {typeof problemCount === 'number' && problemCount > 0 ? (
+ <Tooltip>
+ {/* No `asChild`: the trigger renders its own focusable button, so
+ the messages are reachable by keyboard as well as pointer. */}
+ <TooltipTrigger
+ data-testid="property-problem-badge-trigger"
+ aria-label={t`${plural(problemCount, {
+ one: '# property does not match the schema',
+ other: '# properties do not match the schema',
+ })}`}
+ className="rounded-4xl focus-visible:outline-2 focus-visible:outline-ring focus-visible:outline-offset-2"
+ >
+ <Badge
+ variant="notification"
+ data-testid="property-problem-badge"
+ aria-hidden="true"
+ className="tabular-nums normal-case"
+ >
+ {problemCount > NOTIFICATION_BADGE_MAX
+ ? `${NOTIFICATION_BADGE_MAX}+`
+ : problemCount}
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ <span className="flex flex-col gap-0.5">
+ {/* Index key, not the message: two distinct schema files can
+ both constrain the same property and emit identical strings. */}
+ {problemMessages?.map((message, index) => (
+ // biome-ignore lint/suspicious/noArrayIndexKey: static within a render
+ <span key={index}>{message}</span>
+ ))}
+ </span>
+ </TooltipContent>
+ </Tooltip>
+ ) : null}
+ </div>
<CollapsibleContent
className={cn(
'overflow-hidden data-[state=open]:animate-[collapsible-down_150ms_ease-out] data-[state=closed]:animate-[collapsible-up_150ms_ease-in]',
diff --git a/packages/app/src/components/PropertyPanel.block-level-problem.dom.test.tsx b/packages/app/src/components/PropertyPanel.block-level-problem.dom.test.tsx
new file mode 100644
index 000000000..b8dde2a93
--- /dev/null
+++ b/packages/app/src/components/PropertyPanel.block-level-problem.dom.test.tsx
@@ -0,0 +1,79 @@
+/**
+ * A schema can constrain the frontmatter block as a whole — `minProperties`, a
+ * root `anyOf`, `not` — rather than any single property. Those fire against an
+ * empty object, so they name no property row.
+ *
+ * The panel unmounts itself when a document has no properties to show. Since
+ * the body no longer marks frontmatter violations, that unmount would leave a
+ * block-level violation with NO editor surface at all — strictly less visible
+ * than before, when it (wrongly) squiggled the first body block. These pin that
+ * the panel stays mounted to carry its badge whenever one is outstanding.
+ */
+
+import { HocuspocusProvider } from '@hocuspocus/provider';
+import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { TooltipProvider } from '@/components/ui/tooltip';
+
+const blockLevelProblem = {
+ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 1 } },
+ severity: 'warning' as const,
+ source: 'frontmatter' as const,
+ code: 'minProperties',
+ message: 'Frontmatter must NOT have fewer than 1 properties',
+ frontmatterScope: 'invalid' as const,
+};
+
+let diagnostics: unknown[] = [];
+
+vi.doMock('@/editor/useFrontmatterDiagnostics', async () => {
+ const actual = await vi.importActual<typeof import('@/editor/useFrontmatterDiagnostics')>(
+ '@/editor/useFrontmatterDiagnostics',
+ );
+ return { ...actual, useFrontmatterDiagnostics: () => diagnostics };
+});
+
+const providers: HocuspocusProvider[] = [];
+
+function makeProvider(docName: string): HocuspocusProvider {
+ const p = new HocuspocusProvider({ url: 'ws://localhost:1/collab', name: docName });
+ providers.push(p);
+ return p;
+}
+
+async function renderPanel(provider: HocuspocusProvider) {
+ const { PropertyProvider } = await import('./PropertyContext');
+ const { PropertyPanel } = await import('./PropertyPanel');
+ render(
+ <TooltipProvider>
+ <PropertyProvider>
+ <PropertyPanel provider={provider} />
+ </PropertyProvider>
+ </TooltipProvider>,
+ );
+}
+
+afterEach(() => {
+ cleanup();
+ diagnostics = [];
+ for (const p of providers.splice(0)) p.destroy();
+});
+
+describe('PropertyPanel with a block-level frontmatter problem', () => {
+ test('stays mounted for its badge when the document has no properties', async () => {
+ diagnostics = [blockLevelProblem];
+ await renderPanel(makeProvider('block-level-problem'));
+ // Without the guard the panel returns null here and the violation has no
+ // editor surface at all.
+ expect(screen.getByTestId('property-problem-badge')).toBeTruthy();
+ expect(screen.getByTestId('property-problem-badge').textContent).toBe('1');
+ });
+
+ test('still unmounts on a clean document with no properties', async () => {
+ diagnostics = [];
+ await renderPanel(makeProvider('clean-no-properties'));
+ // The guard must not turn into "always render" — an empty panel on every
+ // property-less document would be noise.
+ expect(screen.queryByTestId('property-panel')).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/PropertyPanel.tsx b/packages/app/src/components/PropertyPanel.tsx
index 29146823e..d5580cca8 100644
--- a/packages/app/src/components/PropertyPanel.tsx
+++ b/packages/app/src/components/PropertyPanel.tsx
@@ -45,6 +45,10 @@ import { coerceValue, DEFAULT_VALUE_FOR_TYPE } from '@/components/PropertyWidget
import { usePropertiesCollapsed } from '@/components/properties-collapsed-store';
import { Button } from '@/components/ui/button';
import { useDocLintConfig } from '@/editor/lint-config-client';
+import {
+ partitionFrontmatterProblems,
+ useFrontmatterDiagnostics,
+} from '@/editor/useFrontmatterDiagnostics';
import { usePublishFrontmatterSelection } from '@/hooks/use-selection-context';
import { enumConstraintsForDoc } from '@/lib/frontmatter-enum-constraints';
@@ -124,6 +128,12 @@ export function PropertyPanel({ provider, reservedKeys, identitySlot }: Property
// or a disabled plugin degrades to today's free-text panel.
const { data: lintConfigData } = useDocLintConfig(docName === '' ? null : docName);
const enumConstraints = enumConstraintsForDoc(lintConfigData?.effective ?? null, docName);
+ // 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(
+ useFrontmatterDiagnostics(provider, lintConfigData?.effective ?? null),
+ );
// Publish a highlight inside the property panel into the selection-context
// store (keyed `(docName, 'frontmatter')`) so a property-value selection feeds
@@ -408,7 +418,20 @@ export function PropertyPanel({ provider, reservedKeys, identitySlot }: Property
const dupCount = new Map<string, number>();
for (const k of renderKeys) dupCount.set(k, (dupCount.get(k) ?? 0) + 1);
- if (renderKeys.length === 0 && !adding && !parseError && !identitySlot) return null;
+ // A schema constraint on the frontmatter block as a whole (`minProperties`,
+ // a root `anyOf`, `not`) fires against an empty object, so it has no property
+ // row to attach to — and unmounting here would leave it with no editor
+ // surface at all, since the body no longer marks frontmatter violations.
+ // Keep the disclosure alive for its badge whenever one is outstanding.
+ if (
+ renderKeys.length === 0 &&
+ !adding &&
+ !parseError &&
+ !identitySlot &&
+ invalidProperties.length === 0
+ ) {
+ return null;
+ }
// 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
@@ -435,6 +458,8 @@ export function PropertyPanel({ provider, reservedKeys, identitySlot }: Property
ref={panelRef}
title={<Trans>Properties</Trans>}
count={renderKeys.length}
+ problemCount={invalidProperties.length}
+ problemMessages={invalidProperties.map((d) => d.message)}
testId="property-panel"
className="pt-4"
contentClassName={PROP_CONTENT_SHIFT}
diff --git a/packages/app/src/components/SkillToolbarControls.tsx b/packages/app/src/components/SkillToolbarControls.tsx
index 183b4b03b..7152221f4 100644
--- a/packages/app/src/components/SkillToolbarControls.tsx
+++ b/packages/app/src/components/SkillToolbarControls.tsx
@@ -35,11 +35,17 @@ export function SkillToolbarControls({
name,
showAddPropertyButton,
onAddProperty,
+ problemCount,
+ problemMessages,
}: {
scope: SkillScope;
name: string;
showAddPropertyButton: boolean;
onAddProperty: () => void;
+ /** Schema-required properties the skill doc is missing — badged on the
+ * Add-properties button, the same surface non-skill docs use. */
+ problemCount?: number;
+ problemMessages?: readonly string[];
}) {
const { t } = useLingui();
const scopeLabels = useSkillScopeLabels();
@@ -60,6 +66,8 @@ export function SkillToolbarControls({
{showAddPropertyButton ? (
<AddPropertiesButton
onAddProperty={onAddProperty}
+ problemCount={problemCount}
+ problemMessages={problemMessages}
className="hidden @xl/toolbar:inline-flex"
/>
) : null}
diff --git a/packages/app/src/components/ui/badge.tsx b/packages/app/src/components/ui/badge.tsx
index 38ad81dda..4502668a8 100644
--- a/packages/app/src/components/ui/badge.tsx
+++ b/packages/app/src/components/ui/badge.tsx
@@ -12,6 +12,13 @@ const badgeVariants = cva(
default: 'bg-primary text-primary-foreground [a]:hover:bg-primary/80',
secondary: 'bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80',
warning: 'bg-yellow-500/10 text-yellow-600 [a]:hover:bg-yellow-500/20',
+ // Solid counterpart to `warning`, for a count overlaid on an icon or
+ // button. The tinted `warning` chip reads as part of whatever sits
+ // behind it; an overlay needs its own fill plus a background-colored
+ // ring to separate it from the glyph underneath. Dark text on both amber
+ // shades, never white — white on amber-500 is ~2.1:1, under the WCAG AA
+ // floor for the small count digit; black on it is ~9.8:1.
+ notification: 'bg-amber-500 text-black ring-1 ring-background dark:bg-amber-400',
destructive:
'bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20',
outline: 'border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground',
@@ -47,4 +54,14 @@ function Badge({
);
}
+/**
+ * Cap for a `notification` count rendered as an overlay dot. Past this the
+ * digits stop being legible at that size, and the exact number stops mattering
+ * — the badge is a pointer to a surface that lists them. Shared so sibling
+ * count badges don't drift to different thresholds. Counts over a wider domain
+ * (all diagnostics on a document, not just its frontmatter) reasonably use a
+ * larger cap of their own.
+ */
+export const NOTIFICATION_BADGE_MAX = 9;
+
export { Badge, badgeVariants };
diff --git a/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts b/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts
index 64f27c8b5..99ba2561e 100644
--- a/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts
+++ b/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts
@@ -124,6 +124,51 @@ describe('mapDiagnosticsToBlocks', () => {
const byBlock = mapDiagnosticsToBlocks(fmSource, [diag(2)], md);
expect(byBlock.size).toBe(0);
});
+
+ const fmDiag = (line: number, over: Partial<LintDiagnostic> = {}): LintDiagnostic =>
+ diag(line, {
+ source: 'frontmatter',
+ code: 'required',
+ message: 'Frontmatter property "status" is required',
+ ...over,
+ });
+
+ test('skips a frontmatter violation on a doc with NO frontmatter region', () => {
+ // The validator anchors a missing-`required` violation to the region's
+ // opening fence. With no region there is no fence, so the line lands on
+ // the first line of body text — which is not what is wrong. Marking it
+ // would squiggle a correct heading on exactly the docs where the schema
+ // error matters most.
+ const byBlock = mapDiagnosticsToBlocks(body, [fmDiag(1)], md);
+ expect(byBlock.size).toBe(0);
+ });
+
+ test('skips a frontmatter violation anchored to a key line inside the region', () => {
+ const byBlock = mapDiagnosticsToBlocks(fmSource, [fmDiag(2, { code: 'enum' })], md);
+ expect(byBlock.size).toBe(0);
+ });
+
+ test('skips a frontmatter violation anchored PAST the frontmatter region', () => {
+ // The one case that separates the two guards: `fmSource` has a 3-line
+ // region, so line 4 is body. The line-range guard would let this through;
+ // only the producing-plugin check catches it. Without this, narrowing
+ // `isFrontmatterAnchorless` back to a line check passes the whole suite.
+ const byBlock = mapDiagnosticsToBlocks(fmSource, [fmDiag(4)], md);
+ expect(byBlock.size).toBe(0);
+ });
+
+ test('still marks a markdownlint violation on body line 1 of a doc with no frontmatter', () => {
+ // The frontmatter skip is by producing plugin, not by position — a
+ // body-anchored rule on the same line must keep its decoration.
+ const byBlock = mapDiagnosticsToBlocks(body, [diag(1)], md);
+ expect(byBlock.has(0)).toBe(true);
+ });
+
+ test('drops only the frontmatter diagnostics from a mixed set', () => {
+ const byBlock = mapDiagnosticsToBlocks(body, [fmDiag(1), diag(3)], md);
+ expect([...byBlock.keys()]).toEqual([1]);
+ expect(byBlock.get(1)).toHaveLength(1);
+ });
});
describe('computeSourceBlockSpans', () => {
@@ -264,8 +309,8 @@ describe('Problems-row navigation — scroll suppression', () => {
return mounted;
}
- function clickProblemsRow(line: number): void {
- const detail: LintNavDetail = { line, column: 1 };
+ function clickProblemsRow(line: number, source?: string): void {
+ const detail: LintNavDetail = { line, column: 1, source };
window.dispatchEvent(new CustomEvent<LintNavDetail>(LINT_NAV_EVENT, { detail }));
}
@@ -310,6 +355,18 @@ describe('Problems-row navigation — scroll suppression', () => {
expect($from?.parent.textContent).toBe('First paragraph.');
});
+ test('declines a frontmatter row rather than selecting the first body block', () => {
+ // A missing-frontmatter violation reports on line 1, which on a doc with
+ // no frontmatter is body text. Following it would scroll to and select a
+ // block that has nothing wrong with it; the property panel owns that error.
+ const before = editor?.state.selection.from;
+
+ clickProblemsRow(1, 'frontmatter');
+
+ expect(scrollIntoView).not.toHaveBeenCalled();
+ expect(editor?.state.selection.from).toBe(before);
+ });
+
test('supersedes a position-preserving landing rather than standing down under it', () => {
// The row the user clicked outranks the position a mode-switch toggle was
// preserving. Standing the scroll down while still moving the caret would
diff --git a/packages/app/src/editor/extensions/markdown-lint-decorations.ts b/packages/app/src/editor/extensions/markdown-lint-decorations.ts
index d5c2d429b..9483b3f70 100644
--- a/packages/app/src/editor/extensions/markdown-lint-decorations.ts
+++ b/packages/app/src/editor/extensions/markdown-lint-decorations.ts
@@ -69,10 +69,23 @@ const RECOMPUTE_DEBOUNCE_MS = 400;
/**
* Group diagnostics by the index of the top-level block they fall in.
- * `source` is the full document text (frontmatter included); diagnostics in
- * the FM region are skipped — they have no WYSIWYG anchor (the property panel
- * owns frontmatter) and stay visible in the Problems panel.
+ * `source` is the full document text (frontmatter included); diagnostics with
+ * no body anchor are skipped — they stay visible in the Problems panel.
+ *
+ * Two kinds have no anchor. Anything reported INSIDE the frontmatter region
+ * belongs to the property panel, not the body. And every `frontmatter`-source
+ * diagnostic is anchorless regardless of where its line lands: the validator
+ * anchors a missing-`required` violation to the region's opening fence, which
+ * on a doc with NO frontmatter at all is line 1 — the first line of body text.
+ * Line-based skipping alone therefore paints a squiggle on the one construct
+ * that is definitionally not the problem (there is nothing there to be wrong),
+ * on the docs where the error matters most. `isFrontmatterAnchorless` keys off
+ * the producing plugin instead, which holds for both cases.
*/
+function isFrontmatterAnchorless(diagnostic: LintDiagnostic): boolean {
+ return diagnostic.source === 'frontmatter';
+}
+
export function mapDiagnosticsToBlocks(
source: string,
diagnostics: LintDiagnostic[],
@@ -82,6 +95,7 @@ export function mapDiagnosticsToBlocks(
if (diagnostics.length === 0) return byBlock;
const { spans, fmLineCount } = computeSourceBlockSpans(source, md);
for (const diagnostic of diagnostics) {
+ if (isFrontmatterAnchorless(diagnostic)) continue;
// mdast positions are 1-based; the diagnostic range is 0-based LSP.
const line = diagnostic.range.start.line + 1;
if (fmLineCount > 0 && line <= fmLineCount) continue;
@@ -525,11 +539,15 @@ export const MarkdownLintDecorations = Extension.create<MarkdownLintDecorationsO
*/
function scrollToLintBlock(detail: LintNavDetail): boolean {
if (!view.dom.isConnected || view.dom.offsetParent === null) return false;
+ // Frontmatter diagnostics have no WYSIWYG anchor (property panel
+ // owns that region) — leave the banked source-mode intent alive.
+ // Checked by producing plugin, not by line, for the same reason the
+ // decoration mapping does: on a doc with no frontmatter the
+ // violation's line points into the body.
+ if (detail.source === 'frontmatter') return false;
const source = getSource?.() ?? md.serialize(view.state.doc.toJSON());
const { spans, fmLineCount } = computeSourceBlockSpans(source, md);
if (spans.length !== comparableChildCount(view.state.doc)) return false;
- // Frontmatter diagnostics have no WYSIWYG anchor (property panel
- // owns that region) — leave the banked source-mode intent alive.
if (fmLineCount > 0 && detail.line <= fmLineCount) return false;
const index = blockIndexForLine(spans, detail.line);
if (index === null) return false;
diff --git a/packages/app/src/editor/useFrontmatterDiagnostics.dom.test.tsx b/packages/app/src/editor/useFrontmatterDiagnostics.dom.test.tsx
new file mode 100644
index 000000000..1357ba0b1
--- /dev/null
+++ b/packages/app/src/editor/useFrontmatterDiagnostics.dom.test.tsx
@@ -0,0 +1,135 @@
+/**
+ * Behavioral test for the useFrontmatterDiagnostics effect (the pure
+ * `partitionFrontmatterProblems` split is covered in the sibling unit test).
+ * Uses a real Y.Doc — the hook only touches `provider.document.getText('source')`.
+ *
+ * The effect's job that the pure split can't reach: it must run ONLY the
+ * frontmatter slice (markdownlint suppressed, even when enabled and the body
+ * would trip it), gate on the frontmatter plugin's own enabled flag, and re-run
+ * when the source text changes.
+ */
+
+import type { HocuspocusProvider } from '@hocuspocus/provider';
+import { DEFAULT_LINTER_CONFIG, type LinterConfig } from '@inkeep/open-knowledge-core';
+import { cleanup, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import * as Y from 'yjs';
+import { useFrontmatterDiagnostics } from './useFrontmatterDiagnostics';
+
+function fakeProvider(initial: string): { provider: HocuspocusProvider; doc: Y.Doc } {
+ const doc = new Y.Doc();
+ doc.getText('source').insert(0, initial);
+ return {
+ provider: {
+ document: doc,
+ configuration: { name: 'test-doc' },
+ } as unknown as HocuspocusProvider,
+ doc,
+ };
+}
+
+// Frontmatter schema requires `title`; markdownlint is deliberately ENABLED so
+// the test can prove the hook suppresses it (a hard tab in the body would trip
+// MD010 through the full lint pass, but must never reach this frontmatter-only
+// surface).
+const frontmatterEnabled: LinterConfig = {
+ ...DEFAULT_LINTER_CONFIG,
+ enabled: true,
+ plugins: {
+ markdownlint: { ...DEFAULT_LINTER_CONFIG.plugins.markdownlint, enabled: true },
+ frontmatter: {
+ ...DEFAULT_LINTER_CONFIG.plugins.frontmatter,
+ enabled: true,
+ schemas: [{ file: 'test.json', schema: { type: 'object', required: ['title'] } }],
+ },
+ },
+};
+
+const frontmatterDisabled: LinterConfig = {
+ ...frontmatterEnabled,
+ plugins: {
+ ...frontmatterEnabled.plugins,
+ frontmatter: { ...frontmatterEnabled.plugins.frontmatter, enabled: false },
+ },
+};
+
+// Missing the required `title`, plus a body hard tab (MD010) that markdownlint
+// would flag if it ran.
+const MISSING_TITLE_WITH_TAB = '---\nx: 1\n---\n\n\ttabbed line\n';
+
+afterEach(() => cleanup());
+
+describe('useFrontmatterDiagnostics', () => {
+ test('returns [] when the provider is null', () => {
+ const { result } = renderHook(() => useFrontmatterDiagnostics(null, frontmatterEnabled));
+ expect(result.current).toEqual([]);
+ });
+
+ test('returns [] when linting is disabled', () => {
+ const { provider } = fakeProvider(MISSING_TITLE_WITH_TAB);
+ const { result } = renderHook(() =>
+ useFrontmatterDiagnostics(provider, { ...frontmatterEnabled, enabled: false }),
+ );
+ expect(result.current).toEqual([]);
+ });
+
+ test('returns [] when the frontmatter plugin is disabled', () => {
+ // The plugin-specific gate, distinct from the top-level `enabled`: linting
+ // is on and markdownlint is enabled, but with frontmatter off this surface
+ // contributes nothing.
+ const { provider } = fakeProvider(MISSING_TITLE_WITH_TAB);
+ const { result } = renderHook(() => useFrontmatterDiagnostics(provider, frontmatterDisabled));
+ expect(result.current).toEqual([]);
+ });
+
+ test('reports the frontmatter violation and suppresses markdownlint', async () => {
+ const { provider } = fakeProvider(MISSING_TITLE_WITH_TAB);
+ const { result } = renderHook(() => useFrontmatterDiagnostics(provider, frontmatterEnabled));
+ // The missing-`title` diagnostic lands a tick after mount.
+ await waitFor(() =>
+ expect(result.current.some((d) => d.source === 'frontmatter' && d.code === 'required')).toBe(
+ true,
+ ),
+ );
+ // The body hard tab would trip MD010 — the whole point of the frontmatter
+ // pass is that markdownlint never runs, so it must not appear here.
+ expect(result.current.every((d) => d.source === 'frontmatter')).toBe(true);
+ expect(result.current.some((d) => d.code === 'MD010')).toBe(false);
+ });
+
+ test('re-lints (debounced) when the source text changes', async () => {
+ const { provider, doc } = fakeProvider('---\ntitle: ok\n---\n\nbody\n');
+ const { result } = renderHook(() => useFrontmatterDiagnostics(provider, frontmatterEnabled));
+ // Conformant to start — the required property is present.
+ await waitFor(() => expect(result.current).toEqual([]));
+
+ const ytext = doc.getText('source');
+ ytext.delete(0, ytext.length);
+ ytext.insert(0, '---\nx: 1\n---\n\nbody\n');
+ await waitFor(() =>
+ expect(result.current.some((d) => d.source === 'frontmatter' && d.code === 'required')).toBe(
+ true,
+ ),
+ );
+ });
+
+ test('unobserves the source text on unmount', async () => {
+ // The effect observes one handler on mount and must remove that same one on
+ // unmount, or every viewed doc leaks a live Yjs observer (silent in prod).
+ const { provider, doc } = fakeProvider(MISSING_TITLE_WITH_TAB);
+ const ytext = doc.getText('source');
+ const observeSpy = vi.spyOn(ytext, 'observe');
+ const unobserveSpy = vi.spyOn(ytext, 'unobserve');
+ const { result, unmount } = renderHook(() =>
+ useFrontmatterDiagnostics(provider, frontmatterEnabled),
+ );
+ await waitFor(() => expect(result.current.some((d) => d.code === 'required')).toBe(true));
+ expect(observeSpy).toHaveBeenCalledTimes(1);
+ const handler = observeSpy.mock.calls[0]?.[0];
+ expect(handler).toBeDefined();
+
+ unmount();
+ // Symmetric teardown: unobserve is called with the exact handler observe got.
+ expect(unobserveSpy).toHaveBeenCalledWith(handler);
+ });
+});
diff --git a/packages/app/src/editor/useFrontmatterDiagnostics.test.ts b/packages/app/src/editor/useFrontmatterDiagnostics.test.ts
new file mode 100644
index 000000000..864012612
--- /dev/null
+++ b/packages/app/src/editor/useFrontmatterDiagnostics.test.ts
@@ -0,0 +1,88 @@
+/**
+ * The missing/invalid split decides which affordance reports a frontmatter
+ * problem, so it has to hold for the cases the validator can actually produce —
+ * including the one `code === 'required'` alone gets wrong.
+ */
+
+import type { LintDiagnostic } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
+import { partitionFrontmatterProblems } from './useFrontmatterDiagnostics.ts';
+
+function diag(over: Partial<LintDiagnostic>): LintDiagnostic {
+ return {
+ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 1 } },
+ severity: 'warning',
+ source: 'frontmatter',
+ code: 'required',
+ message: 'Frontmatter property "status" is required',
+ ...over,
+ };
+}
+
+describe('partitionFrontmatterProblems', () => {
+ test('routes an absent top-level property to missing', () => {
+ const { missing, invalid } = partitionFrontmatterProblems([
+ diag({ frontmatterScope: 'missing' }),
+ ]);
+ expect(missing).toHaveLength(1);
+ expect(invalid).toHaveLength(0);
+ });
+
+ test('routes a present-but-wrong property to invalid', () => {
+ const { missing, invalid } = partitionFrontmatterProblems([
+ diag({ code: 'enum', frontmatterScope: 'invalid' }),
+ ]);
+ expect(missing).toHaveLength(0);
+ expect(invalid).toHaveLength(1);
+ });
+
+ test('a nested `required` is invalid, not missing', () => {
+ // The property exists; a key INSIDE it is absent. Routing this to the
+ // Add-properties button would tell the user to add something already there.
+ const { missing, invalid } = partitionFrontmatterProblems([
+ diag({
+ code: 'required',
+ frontmatterScope: 'invalid',
+ message: 'Frontmatter property "author.email" is required',
+ }),
+ ]);
+ expect(missing).toHaveLength(0);
+ expect(invalid).toHaveLength(1);
+ });
+
+ test('splits a mixed set and preserves order within each bucket', () => {
+ const { missing, invalid } = partitionFrontmatterProblems([
+ diag({ frontmatterScope: 'missing', message: 'a' }),
+ diag({ frontmatterScope: 'invalid', message: 'b' }),
+ diag({ frontmatterScope: 'missing', message: 'c' }),
+ ]);
+ expect(missing.map((d) => d.message)).toEqual(['a', 'c']);
+ expect(invalid.map((d) => d.message)).toEqual(['b']);
+ });
+
+ test('a diagnostic with no scope falls to invalid', () => {
+ // Predates the field. Invalid keeps it on the panel rather than inviting an
+ // add for a property that may already exist.
+ const { missing, invalid } = partitionFrontmatterProblems([diag({})]);
+ expect(missing).toHaveLength(0);
+ expect(invalid).toHaveLength(1);
+ });
+
+ test('a non-frontmatter diagnostic is excluded from both buckets', () => {
+ // A markdownlint (or any future third-plugin) diagnostic carries no
+ // frontmatterScope; without a source guard it would fall to `invalid` and
+ // inflate the "N do not match the schema" count. The badge is a frontmatter
+ // count, so non-frontmatter sources belong in neither bucket.
+ const { missing, invalid } = partitionFrontmatterProblems([
+ diag({ source: 'markdownlint', code: 'MD010', message: 'Hard tabs' }),
+ ]);
+ expect(missing).toHaveLength(0);
+ expect(invalid).toHaveLength(0);
+ });
+
+ test('an empty set yields two empty buckets', () => {
+ const { missing, invalid } = partitionFrontmatterProblems([]);
+ expect(missing).toEqual([]);
+ expect(invalid).toEqual([]);
+ });
+});
diff --git a/packages/app/src/editor/useFrontmatterDiagnostics.ts b/packages/app/src/editor/useFrontmatterDiagnostics.ts
new file mode 100644
index 000000000..0e481aa9c
--- /dev/null
+++ b/packages/app/src/editor/useFrontmatterDiagnostics.ts
@@ -0,0 +1,93 @@
+/**
+ * Live frontmatter-schema diagnostics for the active document — the toolbar
+ * badge's data source.
+ *
+ * Frontmatter violations have no body anchor (the WYSIWYG decoration pass
+ * skips them by producing plugin), so the editor needs a surface of its own to
+ * report them: the badge on the Add-properties button. This hook feeds it.
+ *
+ * It runs the SAME `lintDocument` entry point the Problems panel does, with
+ * every other plugin forced off, rather than reaching for the frontmatter
+ * validator directly. Going through the public seam is what keeps the badge
+ * count and the panel's frontmatter rows from ever disagreeing — a
+ * hand-rolled second call path would drift the moment plugin dispatch,
+ * `appliesTo` matching, or schema selection changed on one side only.
+ *
+ * A second pass rather than a shared one: the toolbar and the doc panel are
+ * siblings with no data channel between them, and the panel's diagnostics come
+ * bundled with link findings and validation-store bookkeeping that the toolbar
+ * has no use for. Disabling the other plugins reduces this pass to a single
+ * synchronous ajv validation over the frontmatter object, which is cheap
+ * enough that a second pass costs less than lifting the panel's state — but it
+ * is the same `useDocDiagnostics` effect, not a copy of it.
+ */
+
+import type { HocuspocusProvider } from '@hocuspocus/provider';
+import { LINT_PLUGINS, type LintDiagnostic, type LinterConfig } from '@inkeep/open-knowledge-core';
+import { useDocDiagnostics } from './useDocDiagnostics.ts';
+
+/**
+ * Split frontmatter problems by the affordance that can act on them.
+ *
+ * `missing` names a property the document does not have, so there is no row to
+ * mark — it reports on the Add-properties button. `invalid` is a property that
+ * exists and is wrong, which the property panel can point at, so it reports on
+ * the panel's own count. The validator supplies the distinction
+ * (`frontmatterScope`); a diagnostic without it predates the field and is
+ * treated as invalid, which keeps it on the panel rather than inviting the user
+ * to add something twice.
+ *
+ * Only `frontmatter`-source diagnostics count. `frontmatterOnly` already keeps
+ * the hook's pass to that source today, but the registry is append-designed
+ * (`LINT_PLUGIN_IDS`): a future plugin would carry no `frontmatterScope` and
+ * silently swell the `invalid` count. Guarding on source here means the two
+ * badge counts stay frontmatter-only regardless of what else the pass produces.
+ */
+export function partitionFrontmatterProblems(diagnostics: readonly LintDiagnostic[]): {
+ missing: LintDiagnostic[];
+ invalid: LintDiagnostic[];
+} {
+ const missing: LintDiagnostic[] = [];
+ const invalid: LintDiagnostic[] = [];
+ for (const diagnostic of diagnostics) {
+ if (diagnostic.source !== 'frontmatter') continue;
+ if (diagnostic.frontmatterScope === 'missing') missing.push(diagnostic);
+ else invalid.push(diagnostic);
+ }
+ return { missing, invalid };
+}
+
+/**
+ * `config` with every plugin but frontmatter disabled. Derived from the plugin
+ * registry rather than naming markdownlint: the registry is append-designed, so
+ * a hardcoded list would silently start running a third plugin's pass here —
+ * the same growth `partitionFrontmatterProblems` guards its output against.
+ */
+function frontmatterOnly(config: LinterConfig): LinterConfig {
+ const plugins = { ...config.plugins };
+ for (const { id } of LINT_PLUGINS) {
+ if (id === 'frontmatter') continue;
+ plugins[id] = { ...plugins[id], enabled: false };
+ }
+ return { ...config, plugins };
+}
+
+/**
+ * Live `frontmatter`-source diagnostics for `provider`'s doc under `config`.
+ * Returns `[]` when either is null, when linting is off, or when the
+ * frontmatter plugin is disabled.
+ *
+ * Delegates to `useDocDiagnostics` with a frontmatter-only config rather than
+ * repeating its effect: the debounce, the config-hash key, the observe/
+ * unobserve pair, and the cancel-on-teardown guard are all subtleties that
+ * would have to stay in lockstep across two copies, and a divergence would be
+ * silent. Handing it a `null` config when the plugin is off short-circuits
+ * before the async pass instead of relying on `lintDocument` to return empty.
+ */
+export function useFrontmatterDiagnostics(
+ provider: HocuspocusProvider | null,
+ config: LinterConfig | null,
+): LintDiagnostic[] {
+ const active = config?.enabled === true && config.plugins.frontmatter.enabled;
+ return useDocDiagnostics(provider, active && config ? frontmatterOnly(config) : null);
+}
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 713ff18a1..fc1892dcf 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -225,6 +225,18 @@
"3Ib6FN": ["Move down"],
"3J7d2N": ["Big section heading."],
"3JYy1p": ["Branch ", ["0"], " no longer exists. Cloned to default branch."],
+ "3KOHFt": [
+ "Add properties (",
+ [
+ "problemCount",
+ "plural",
+ {
+ "one": ["#", " required property missing"],
+ "other": ["#", " required properties missing"]
+ }
+ ],
+ ")"
+ ],
"3LbBJn": ["Attach images"],
"3MnvrL": ["Showing top ", ["0"], " matches — keep typing to narrow"],
"3Mwaly": ["Could not initialize ", ["0"], "."],
@@ -696,6 +708,7 @@
"AwLCZA": [
"The endpoint answered, but not with an OpenAI-compatible embeddings response. Check the base URL."
],
+ "AwrGuz": ["This document is missing required properties"],
"B11p-O": ["Edit markdown link"],
"B2DrPb": ["Auto-save"],
"B2Srgd": [["packName"], " skill installed."],
@@ -1342,6 +1355,16 @@
"M5_9s2": ["Sending report"],
"M5mfAe": ["Add tag"],
"M6mvVi": ["Copy relative path"],
+ "M6vuZU": [
+ [
+ "problemCount",
+ "plural",
+ {
+ "one": ["#", " property does not match the schema"],
+ "other": ["#", " properties do not match the schema"]
+ }
+ ]
+ ],
"M7SqjM": ["Reopen"],
"M92_0q": ["Close comment"],
"M9597s": ["Preparing share URL..."],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 386512ee6..d8bf2dc2e 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -641,6 +641,10 @@ msgstr "{percent}% used ({left}% left)"
msgid "{phase} — {pct}%"
msgstr "{phase} — {pct}%"
+#: src/components/PropertyDisclosure.tsx
+msgid "{problemCount, plural, one {# property does not match the schema} other {# properties do not match the schema}}"
+msgstr "{problemCount, plural, one {# property does not match the schema} other {# properties do not match the schema}}"
+
#: src/editor/extensions/JsxComponentView.tsx
msgid "{propPanelDescriptorLabel} Properties"
msgstr "{propPanelDescriptorLabel} Properties"
@@ -1127,6 +1131,10 @@ msgstr "Add pattern"
msgid "Add properties"
msgstr "Add properties"
+#: src/components/AddPropertiesButton.tsx
+msgid "Add properties ({problemCount, plural, one {# required property missing} other {# required properties missing}})"
+msgstr "Add properties ({problemCount, plural, one {# required property missing} other {# required properties missing}})"
+
#: src/components/PropertyPanel.tsx
#: src/components/TemplateForm.tsx
msgid "Add property"
@@ -10904,6 +10912,10 @@ msgstr "This doc isn't on GitHub yet. The link won't work until it's pushed."
msgid "This document is already active in the editor. Use Open to collapse the graph."
msgstr "This document is already active in the editor. Use Open to collapse the graph."
+#: src/components/AddPropertiesButton.tsx
+msgid "This document is missing required properties"
+msgstr "This document is missing required properties"
+
#: src/components/settings/SearchSection.tsx
msgid "This endpoint ignored the vector size you configured. Remove <0>search.semantic.dimensions</0> to use the model's own size."
msgstr "This endpoint ignored the vector size you configured. Remove <0>search.semantic.dimensions</0> to use the model's own size."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 71fa077b0..ac3230d65 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -225,6 +225,18 @@
"3Ib6FN": ["Ḿōvē ďōŵń"],
"3J7d2N": ["ßĩĝ śēćţĩōń ĥēàďĩńĝ."],
"3JYy1p": ["ßŕàńćĥ ", ["0"], " ńō ĺōńĝēŕ ēxĩśţś. Ćĺōńēď ţō ďēƒàũĺţ ƀŕàńćĥ."],
+ "3KOHFt": [
+ "Àďď ƥŕōƥēŕţĩēś (",
+ [
+ "problemCount",
+ "plural",
+ {
+ "one": ["#", " ŕēǫũĩŕēď ƥŕōƥēŕţŷ ḿĩśśĩńĝ"],
+ "other": ["#", " ŕēǫũĩŕēď ƥŕōƥēŕţĩēś ḿĩśśĩńĝ"]
+ }
+ ],
+ ")"
+ ],
"3LbBJn": ["Àţţàćĥ ĩḿàĝēś"],
"3MnvrL": ["Śĥōŵĩńĝ ţōƥ ", ["0"], " ḿàţćĥēś — ķēēƥ ţŷƥĩńĝ ţō ńàŕŕōŵ"],
"3Mwaly": ["Ćōũĺď ńōţ ĩńĩţĩàĺĩźē ", ["0"], "."],
@@ -696,6 +708,7 @@
"AwLCZA": [
"Ţĥē ēńďƥōĩńţ àńśŵēŕēď, ƀũţ ńōţ ŵĩţĥ àń ŌƥēńÀĨ-ćōḿƥàţĩƀĺē ēḿƀēďďĩńĝś ŕēśƥōńśē. Ćĥēćķ ţĥē ƀàśē ŨŔĹ."
],
+ "AwrGuz": ["Ţĥĩś ďōćũḿēńţ ĩś ḿĩśśĩńĝ ŕēǫũĩŕēď ƥŕōƥēŕţĩēś"],
"B11p-O": ["Ēďĩţ ḿàŕķďōŵń ĺĩńķ"],
"B2DrPb": ["Àũţō-śàvē"],
"B2Srgd": [["packName"], " śķĩĺĺ ĩńśţàĺĺēď."],
@@ -1342,6 +1355,16 @@
"M5_9s2": ["Śēńďĩńĝ ŕēƥōŕţ"],
"M5mfAe": ["Àďď ţàĝ"],
"M6mvVi": ["Ćōƥŷ ŕēĺàţĩvē ƥàţĥ"],
+ "M6vuZU": [
+ [
+ "problemCount",
+ "plural",
+ {
+ "one": ["#", " ƥŕōƥēŕţŷ ďōēś ńōţ ḿàţćĥ ţĥē śćĥēḿà"],
+ "other": ["#", " ƥŕōƥēŕţĩēś ďō ńōţ ḿàţćĥ ţĥē śćĥēḿà"]
+ }
+ ]
+ ],
"M7SqjM": ["Ŕēōƥēń"],
"M92_0q": ["Ćĺōśē ćōḿḿēńţ"],
"M9597s": ["Ƥŕēƥàŕĩńĝ śĥàŕē ŨŔĹ..."],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index ca7eab1bc..d7750eb5a 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -641,6 +641,10 @@ msgstr ""
msgid "{phase} — {pct}%"
msgstr ""
+#: src/components/PropertyDisclosure.tsx
+msgid "{problemCount, plural, one {# property does not match the schema} other {# properties do not match the schema}}"
+msgstr ""
+
#: src/editor/extensions/JsxComponentView.tsx
msgid "{propPanelDescriptorLabel} Properties"
msgstr ""
@@ -1123,6 +1127,10 @@ msgstr ""
msgid "Add properties"
msgstr ""
+#: src/components/AddPropertiesButton.tsx
+msgid "Add properties ({problemCount, plural, one {# required property missing} other {# required properties missing}})"
+msgstr ""
+
#: src/components/PropertyPanel.tsx
#: src/components/TemplateForm.tsx
msgid "Add property"
@@ -10900,6 +10908,10 @@ msgstr ""
msgid "This document is already active in the editor. Use Open to collapse the graph."
msgstr ""
+#: src/components/AddPropertiesButton.tsx
+msgid "This document is missing required properties"
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "This endpoint ignored the vector size you configured. Remove <0>search.semantic.dimensions</0> to use the model's own size."
msgstr ""
diff --git a/packages/app/tests/stress/frontmatter-schema-badge.e2e.ts b/packages/app/tests/stress/frontmatter-schema-badge.e2e.ts
new file mode 100644
index 000000000..24d0e84b6
--- /dev/null
+++ b/packages/app/tests/stress/frontmatter-schema-badge.e2e.ts
@@ -0,0 +1,252 @@
+/**
+ * Playwright E2E for how frontmatter-schema violations report in WYSIWYG.
+ *
+ * A frontmatter violation has no body construct to mark. The validator anchors
+ * a missing-`required` error to the frontmatter region's opening fence, so on a
+ * document with no frontmatter at all it lands on line 1 — the first line of
+ * body text, which is not what is wrong. These tests pin the two halves of the
+ * resulting contract: the body stays unmarked, and the error reports on the
+ * toolbar's Add-properties button instead (the only affordance still present
+ * when a doc has zero properties and `PropertyPanel` renders nothing).
+ *
+ * Every fixture carries a markdownlint violation alongside the frontmatter one.
+ * That is deliberate: "the frontmatter error marked nothing" asserted against a
+ * body with no violations at all would also pass if the decoration pass never
+ * ran (or the schema never loaded). Pinning the body to exactly ONE marked
+ * block — the markdownlint one — makes the pass prove it ran before it proves
+ * what it declined to mark.
+ *
+ * The last test pins decoration stability across a block-move round trip by
+ * following which block index carries the mark, which is the observable a
+ * "the squiggly vanished" report comes down to.
+ *
+ * Requires: Playwright browsers installed. Dev server started by
+ * playwright.config.ts webServer on VITE_PORT (or default 5173).
+ */
+
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { Page } from '@playwright/test';
+import {
+ type ApiHelpers,
+ expect,
+ filterCriticalErrors,
+ type LogEntry,
+ test,
+ waitForActiveProviderSynced as waitForProvider,
+} from './_helpers';
+
+/** The hard tab trips markdownlint MD010 — a genuinely body-anchored rule. */
+const TAB_LINE = '\tindented with a hard tab';
+/** No frontmatter at all → the schema's `required` fires with nothing to anchor to. */
+const NO_FRONTMATTER_BODY = `# Heading\n\nfirst paragraph\n\n${TAB_LINE}\n`;
+/** Both required properties present; `status` is not in the schema's enum. */
+const INVALID_ENUM_BODY = `---\nstatus: shipped\nowner: sam\n---\n\n# Heading\n\nfirst paragraph\n\n${TAB_LINE}\n`;
+/** One property present but wrong, one required property absent — one of each. */
+const MIXED_BODY = `---\nstatus: shipped\n---\n\n# Heading\n\nfirst paragraph\n\n${TAB_LINE}\n`;
+/** Same shape, schema-conformant. */
+const CONFORMANT_BODY = `---\nstatus: draft\nowner: sam\n---\n\n# Heading\n\nfirst paragraph\n\n${TAB_LINE}\n`;
+
+const errors: LogEntry[] = [];
+let testDocName = '';
+
+const addPropertiesButton = (page: Page) => page.getByTestId('add-properties-button');
+/** Missing required properties — reported on the toolbar's Add-properties button. */
+const missingBadge = (page: Page) => page.getByTestId('add-properties-problem-badge');
+/** Present-but-invalid properties — reported on the Properties disclosure count. */
+const invalidBadge = (page: Page) => page.getByTestId('property-problem-badge');
+const decoratedBlocks = (page: Page) =>
+ page.locator('.ProseMirror:not(.composer-prosemirror) > .ok-lint-block');
+
+/**
+ * Index of the marked top-level block among the editor's children, or -1 when
+ * nothing is marked. A positional read (rather than a count) is what makes the
+ * move round trip observable: the mark has to leave one index and arrive at
+ * another for the assertions to advance.
+ */
+const markedBlockIndex = (page: Page) =>
+ page.evaluate(() => {
+ const editor = document.querySelector('.ProseMirror:not(.composer-prosemirror)');
+ if (!editor) return -1;
+ return Array.from(editor.children).findIndex((child) =>
+ child.classList.contains('ok-lint-block'),
+ );
+ });
+
+/** Seed the doc and wait for the body to arrive (lint settles under each assertion). */
+async function seed(page: Page, api: ApiHelpers, markdown: string) {
+ await api.replaceDoc(testDocName, markdown);
+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)')).toContainText('hard tab', {
+ timeout: 15_000,
+ });
+}
+
+test.beforeEach(async ({ page, api, workerServer }) => {
+ mkdirSync(join(workerServer.contentDir, '.ok', 'schemas'), { recursive: true });
+ writeFileSync(
+ join(workerServer.contentDir, '.ok', 'schemas', 'doc.schema.json'),
+ JSON.stringify({
+ type: 'object',
+ required: ['status', 'owner'],
+ properties: { status: { enum: ['draft', 'review', 'published'] } },
+ }),
+ 'utf-8',
+ );
+ writeFileSync(
+ join(workerServer.contentDir, '.ok', 'config.yml'),
+ [
+ 'contentRules:',
+ ' markdownlint:',
+ ' enabled: true',
+ ' frontmatter:',
+ ' enabled: true',
+ ' schemas:',
+ ' - file: .ok/schemas/doc.schema.json',
+ '',
+ ].join('\n'),
+ 'utf-8',
+ );
+ errors.length = 0;
+ page.on('pageerror', (err) => errors.push({ type: 'uncaught', text: err.message }));
+ page.on('console', (msg) => {
+ if (msg.type() === 'error') {
+ const loc = msg.location();
+ errors.push({ type: 'error', text: msg.text(), url: loc.url, line: loc.lineNumber });
+ }
+ });
+
+ testDocName = `fmbadge-${randomUUID().slice(0, 8)}`;
+ await api.createPage(`${testDocName}.md`);
+ await page.goto(`/#/${testDocName}`);
+ await waitForProvider(page);
+ await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)');
+});
+
+test.afterEach(() => {
+ expect(filterCriticalErrors(errors), 'Expected zero critical console errors').toEqual([]);
+});
+
+test.afterAll(({ workerServer }) => {
+ // Restore the default (both plugins off) so any e2e sharing this worker isn't
+ // left with the linter silently enabled.
+ writeFileSync(join(workerServer.contentDir, '.ok', 'config.yml'), '', 'utf-8');
+});
+
+test.describe('frontmatter schema violations in WYSIWYG', () => {
+ test('a doc missing required frontmatter marks the tab block only, never the heading', async ({
+ page,
+ api,
+ }) => {
+ await seed(page, api, NO_FRONTMATTER_BODY);
+ // The badge witnesses the schema loaded and the violation is live.
+ await expect(missingBadge(page)).toBeVisible();
+ // Exactly one mark, and it is markdownlint's — the frontmatter violation's
+ // line-1 anchor used to add a second one on the heading.
+ await expect(decoratedBlocks(page)).toHaveCount(1);
+ await expect(decoratedBlocks(page).first()).toContainText('hard tab');
+ });
+
+ test('missing properties report on the Add-properties button', async ({ page, api }) => {
+ await seed(page, api, NO_FRONTMATTER_BODY);
+ // Both `status` and `owner` are absent.
+ await expect(missingBadge(page)).toHaveText('2');
+ // The count reaches assistive tech through the button's own name — the
+ // badge is aria-hidden.
+ await expect(addPropertiesButton(page)).toHaveAttribute(
+ 'aria-label',
+ /2 required properties missing/,
+ );
+ // With no frontmatter there are no properties, so the panel — and its own
+ // badge — do not render at all.
+ await expect(invalidBadge(page)).toHaveCount(0);
+ });
+
+ test('a present-but-invalid property reports on the Properties count, not the button', async ({
+ page,
+ api,
+ }) => {
+ await seed(page, api, INVALID_ENUM_BODY);
+ // `status: shipped` exists and is wrong — adding a property is not its fix.
+ await expect(invalidBadge(page)).toHaveText('1');
+ // The accessible name sits on the focusable tooltip trigger; the badge
+ // inside it is aria-hidden decoration.
+ await expect(page.getByTestId('property-problem-badge-trigger')).toHaveAttribute(
+ 'aria-label',
+ /1 property does not match the schema/,
+ );
+ await expect(missingBadge(page)).toHaveCount(0);
+ // And the body is still left alone.
+ await expect(decoratedBlocks(page)).toHaveCount(1);
+ await expect(decoratedBlocks(page).first()).toContainText('hard tab');
+ });
+
+ test('one of each lands on its own affordance', async ({ page, api }) => {
+ // `status: shipped` is present and wrong; `owner` is absent. This is the
+ // case a single shared badge would collapse into one indistinct number.
+ await seed(page, api, MIXED_BODY);
+ await expect(invalidBadge(page)).toHaveText('1');
+ await expect(missingBadge(page)).toHaveText('1');
+ });
+
+ test('both badges clear once the frontmatter satisfies the schema', async ({ page, api }) => {
+ // Start violating so the clear is a transition rather than an initial
+ // state a never-loaded schema would also produce.
+ await seed(page, api, MIXED_BODY);
+ await expect(invalidBadge(page)).toBeVisible();
+ await expect(missingBadge(page)).toBeVisible();
+
+ await api.replaceDoc(testDocName, CONFORMANT_BODY);
+ await expect(invalidBadge(page)).toHaveCount(0);
+ await expect(missingBadge(page)).toHaveCount(0);
+ await expect(addPropertiesButton(page)).toHaveAttribute('aria-label', 'Add properties');
+ // The body rule is untouched by the frontmatter fix.
+ await expect(decoratedBlocks(page)).toHaveCount(1);
+ });
+});
+
+test.describe('body-anchored decorations survive block reordering', () => {
+ test('the mark follows its block up and back down again', async ({ page, api }) => {
+ await seed(page, api, NO_FRONTMATTER_BODY);
+ // blocks: 0 heading, 1 paragraph, 2 tab block (+ trailing empty paragraph)
+ await expect.poll(() => markedBlockIndex(page), { timeout: 15_000 }).toBe(2);
+
+ // Drive the block-mover through a synthetic keydown rather than
+ // page.keyboard: Cmd+Shift+Arrow is claimed by the OS/browser on some
+ // platforms, and the harness needs the shortcut to reach ProseMirror.
+ const moveMarkedBlock = (direction: 'up' | 'down') =>
+ page.evaluate((dir) => {
+ const editor = window.__activeEditor;
+ if (!editor) throw new Error('no active editor');
+ let target = -1;
+ editor.state.doc.forEach((node, offset) => {
+ if (node.textContent.includes('hard tab')) target = offset;
+ });
+ if (target < 0) throw new Error('marked block not found');
+ editor.commands.focus();
+ editor.commands.setTextSelection(target + 1);
+ // The binding is `Mod-Shift-Arrow*`, and ProseMirror resolves `Mod` to
+ // Meta on macOS but Ctrl everywhere else. A hardcoded `metaKey` matches
+ // nothing on the Linux CI runner — the block simply never moves and the
+ // assertion reads as a decoration bug rather than a wrong keystroke.
+ const isMac = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);
+ editor.view.dom.dispatchEvent(
+ new KeyboardEvent('keydown', {
+ key: dir === 'up' ? 'ArrowUp' : 'ArrowDown',
+ metaKey: isMac,
+ ctrlKey: !isMac,
+ shiftKey: true,
+ bubbles: true,
+ }),
+ );
+ }, direction);
+
+ await moveMarkedBlock('up');
+ await expect.poll(() => markedBlockIndex(page), { timeout: 15_000 }).toBe(1);
+
+ await moveMarkedBlock('down');
+ await expect.poll(() => markedBlockIndex(page), { timeout: 15_000 }).toBe(2);
+ await expect(decoratedBlocks(page)).toHaveCount(1);
+ await expect(decoratedBlocks(page).first()).toContainText('hard tab');
+ });
+});
diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.ts
index d7a845280..dfd95ef49 100644
--- a/packages/core/src/bridge/bind-frontmatter-doc.ts
+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts
@@ -1,3 +1,4 @@
+
import type * as Y from 'yjs';
import type { Err, Ok, Result } from '../config/result.ts';
import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';
diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.ts
index 005627195..8bfdb40cd 100644
--- a/packages/core/src/bridge/bridge-invariant.ts
+++ b/packages/core/src/bridge/bridge-invariant.ts
@@ -1,3 +1,4 @@
+
import { fnv1aDigest } from './hash-util.ts';
export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index f4cc8a286..2a597ec3d 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,3 +1,4 @@
+
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index 8890f6739..c18c086d5 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,3 +1,4 @@
+
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
const LEADING_BOUNDARY_RE = /^(?:\r?\n)+/;
diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.ts
index 9d9c244b0..463e89595 100644
--- a/packages/core/src/bridge/growth-detect.ts
+++ b/packages/core/src/bridge/growth-detect.ts
@@ -1,3 +1,4 @@
+
const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;
export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;
diff --git a/packages/core/src/bridge/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.ts
index c43fdd7e7..0939885bb 100644
--- a/packages/core/src/bridge/intraline-predicate.ts
+++ b/packages/core/src/bridge/intraline-predicate.ts
@@ -1,3 +1,4 @@
+
export function rawLineCounts(doc: string): Map<string, number> {
const counts = new Map<string, number>();
for (const line of doc.split('\n')) {
diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.ts
index 251560a35..c0dc65705 100644
--- a/packages/core/src/bridge/merge-three-way.ts
+++ b/packages/core/src/bridge/merge-three-way.ts
@@ -65,6 +65,7 @@ export function tryLineLevelCombine(
return { clean: true, merged };
}
+
export type BridgeMergeContentLossSide = 'user' | 'agent';
export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';
diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.ts
index da41900cd..d35f6b455 100644
--- a/packages/core/src/bridge/normalize.ts
+++ b/packages/core/src/bridge/normalize.ts
@@ -1,3 +1,4 @@
+
const COMMONMARK_ESCAPE_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~])/g;
const TABLE_ALIGN_ROW_RE = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/;
diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.ts
index 754dc5cc2..0be5203e4 100644
--- a/packages/core/src/bridge/pm-structural-equivalence.ts
+++ b/packages/core/src/bridge/pm-structural-equivalence.ts
@@ -32,6 +32,7 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };
const BR_LITERAL_RE = /^<br\s*\/?>$/i;
+
interface DegradeEntry {
readonly label: string;
readonly severity: ToleranceClassSeverity;
@@ -127,6 +128,7 @@ export interface ComparePmStructuralOptions {
ignoreAttrs?: (attrKey: string) => boolean;
}
+
/** Rebuild a node with `fn` applied to each child; identity when childless.
* Shared by the degrade canonicalizers so none re-implements the walk. */
function mapChildren(
@@ -248,6 +250,7 @@ function applyDegrades(tree: PmStructuralNode): {
return { normalized: current, fired };
}
+
export function comparePmStructural(
expected: PmStructuralNode,
actual: PmStructuralNode,
diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.ts
index af20de1e2..dca644141 100644
--- a/packages/core/src/bridge/subsequence.ts
+++ b/packages/core/src/bridge/subsequence.ts
@@ -1,3 +1,4 @@
+
/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):
* insertions in `haystack` are free; any dropped or substituted `needle` byte
* fails. */
diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.ts
index 83d47404a..a363dfd54 100644
--- a/packages/core/src/markdown/callout-transformer.ts
+++ b/packages/core/src/markdown/callout-transformer.ts
@@ -1,3 +1,4 @@
+
import type { Blockquote, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.ts
index 9807a7e82..4499dbc92 100644
--- a/packages/core/src/markdown/code-fence.ts
+++ b/packages/core/src/markdown/code-fence.ts
@@ -1,3 +1,4 @@
+
export function selectFenceChar(info: string): '`' | '~' {
return info.includes('`') ? '~' : '`';
}
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index 7415c474a..34704165b 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.ts
index ece5c02a1..b6299a948 100644
--- a/packages/core/src/markdown/dedent-block-jsx-close.ts
+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts
@@ -1,3 +1,4 @@
+
import { findFencedRegions, isInsideFence } from './fence-regions.ts';
const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;
diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.ts
index 54774764a..acd398aa6 100644
--- a/packages/core/src/markdown/details-accordion-promoter.ts
+++ b/packages/core/src/markdown/details-accordion-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.ts
index 43ecdc709..ba9b56384 100644
--- a/packages/core/src/markdown/div-align-promoter.ts
+++ b/packages/core/src/markdown/div-align-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.ts
index 6d3f3643e..4513da9bb 100644
--- a/packages/core/src/markdown/fence-regions.ts
+++ b/packages/core/src/markdown/fence-regions.ts
@@ -1,3 +1,4 @@
+
const FENCE_RE = /^(`{3,}|~{3,})/gm;
export function findFencedRegions(src: string): Array<[number, number]> {
diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.ts
index 00f5771ee..6931623c7 100644
--- a/packages/core/src/markdown/fixtures/index.ts
+++ b/packages/core/src/markdown/fixtures/index.ts
@@ -1,3 +1,4 @@
+
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -8,6 +9,7 @@ function fixturePath(...segments: string[]): string {
return resolve(FIXTURES_DIR, ...segments);
}
+
interface GfmExample {
section: string;
markdown: string;
@@ -17,6 +19,7 @@ export function loadGfmExamples(): GfmExample[] {
return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];
}
+
interface MdxCrashEntry {
id: string;
input: string;
@@ -68,6 +71,7 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {
) as LargeEmbedFixture[];
}
+
export function loadPrd6955Before(): string {
return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');
}
@@ -76,6 +80,7 @@ export function loadPrd6955CorruptedTriplicated(): string {
return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');
}
+
export interface NgPinnedCase {
id: string;
name: string;
@@ -92,6 +97,7 @@ export function loadNgPinnedCases(): NgPinnedCase[] {
) as NgPinnedCase[];
}
+
export function loadLargeRealistic(): string {
return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');
}
diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.ts
index 8b1eb8519..daa3ef82b 100644
--- a/packages/core/src/markdown/fixtures/perf/generate.ts
+++ b/packages/core/src/markdown/fixtures/perf/generate.ts
@@ -1,3 +1,4 @@
+
import { writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -10,6 +11,7 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;
const SEED = 0xf1de1117;
+
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
@@ -36,6 +38,7 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {
return items[items.length - 1][0];
}
+
const WORDS = [
'lorem',
'ipsum',
@@ -153,6 +156,7 @@ function mdxBlock(rand: () => number): string {
return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;
}
+
type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';
const MIX: readonly [BlockKind, number][] = [
@@ -191,6 +195,7 @@ function generateDocument(blockCount: number, seed: number): string {
return `${blocks.join('\n\n')}\n`;
}
+
function main(): void {
for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {
const doc = generateDocument(count, SEED);
diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.ts
index 420dc0fe5..32c055c5b 100644
--- a/packages/core/src/markdown/guard-flanking-matrix.ts
+++ b/packages/core/src/markdown/guard-flanking-matrix.ts
@@ -7,6 +7,7 @@ import {
import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';
import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';
+
export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;
export type FlankClass = 'whitespace' | 'punctuation' | 'other';
diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.ts
index 2653473da..283913255 100644
--- a/packages/core/src/markdown/handler-shadow-audit.ts
+++ b/packages/core/src/markdown/handler-shadow-audit.ts
@@ -1,3 +1,4 @@
+
export interface HandlerShadowWitness {
input: string;
expect: 'byte' | 'byte-and-reparse-type';
diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.ts
index da0a81d23..5d1000cc4 100644
--- a/packages/core/src/markdown/highlight-promoter.ts
+++ b/packages/core/src/markdown/highlight-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.ts
index 787315157..9681c0056 100644
--- a/packages/core/src/markdown/html-to-mdast.ts
+++ b/packages/core/src/markdown/html-to-mdast.ts
@@ -1,3 +1,4 @@
+
import type { Element as HastElement, Root as HastRoot } from 'hast';
import type { List, Nodes as MdastNodes, Root as MdastRoot } from 'mdast';
import rehypeParse from 'rehype-parse';
@@ -128,7 +129,8 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRo
throw new HtmlPayloadTooLargeError(html.length, maxBytes);
}
- const processor = unified().use(rehypeParse, { fragment: true });
+ const processor = unified()
+ .use(rehypeParse, { fragment: true });
for (const plugin of cleanupPlugins) {
processor.use(plugin);
diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.ts
index 706fa9afb..994eb6917 100644
--- a/packages/core/src/markdown/image-promoter.ts
+++ b/packages/core/src/markdown/image-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Image, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.ts
index f49f4b64e..25bc43422 100644
--- a/packages/core/src/markdown/index.ts
+++ b/packages/core/src/markdown/index.ts
@@ -1,3 +1,4 @@
+
import {
type FromProseMirrorOptions,
fromPmMark,
@@ -205,6 +206,7 @@ export class MarkdownManager {
}
}
+
const registry = createRegistry();
function destructureAttrs(
@@ -253,6 +255,7 @@ function destructureAttrs(
return result;
}
+
function hasDirtyDescendant(node: PmNode): boolean {
let found = false;
node.descendants((child) => {
@@ -272,6 +275,7 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChec
return freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;
}
+
function isEmptyMdastParagraph(node: MdastNodes): boolean {
if (node.type !== 'paragraph') return false;
const children = node.children ?? [];
@@ -340,6 +344,7 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {
return out;
}
+
import {
AUDIO_EXTENSIONS,
FILE_ATTACHMENT_EXTENSIONS,
@@ -592,6 +597,7 @@ function buildMdastToPmHandlers(
}));
}
+
if (m.emphasis) {
handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({
sourceDelimiter: node.data?.sourceDelimiter ?? '*',
@@ -672,6 +678,7 @@ function buildMdastToPmHandlers(
}));
}
+
if (m.link) {
const sourceLiteralMark = m.sourceLiteral;
handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {
@@ -950,6 +957,7 @@ function buildMdastToPmHandlers(
};
}
+
const blockUnknownHandler = (node: {
type: string;
position?: { start: { offset: number }; end: { offset: number } };
@@ -1075,6 +1083,7 @@ function buildMdastToPmHandlers(
return handlers as RemarkProseMirrorOptions['handlers'];
}
+
function buildPmToMdastHandlers(
schema: Schema,
freshness: FreshnessCheckerHolder,
diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.ts
index fa0be9e86..b79e9aef7 100644
--- a/packages/core/src/markdown/lint/applies-to.ts
+++ b/packages/core/src/markdown/lint/applies-to.ts
@@ -1,3 +1,4 @@
+
import picomatch from 'picomatch';
import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';
diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.ts
index 312c9c74b..94b34dee1 100644
--- a/packages/core/src/markdown/lint/config-files.ts
+++ b/packages/core/src/markdown/lint/config-files.ts
@@ -1,3 +1,4 @@
+
const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set([
'.markdownlint.json',
'.markdownlint.jsonc',
diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.ts
index c94bfce20..f1262c7c9 100644
--- a/packages/core/src/markdown/lint/config-schemas.ts
+++ b/packages/core/src/markdown/lint/config-schemas.ts
@@ -38,6 +38,7 @@ const fullPluginShape = Object.fromEntries(
LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),
) as z.ZodRawShape;
+
export const LinterConfigSchema = z.object({
enabled: z.boolean(),
plugins: z.object(fullPluginShape),
@@ -145,6 +146,7 @@ const LintDiagnosticSchema = z.object({
code: z.string(),
message: z.string(),
fixes: z.array(z.object({ range: LintRangeSchema, newText: z.string() })).optional(),
+ frontmatterScope: z.enum(['missing', 'invalid']).optional(),
});
export const LintDocResultSchema = z.object({
diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.ts
index d48eea5e4..a51f2ffb0 100644
--- a/packages/core/src/markdown/lint/default-config.ts
+++ b/packages/core/src/markdown/lint/default-config.ts
@@ -6,6 +6,7 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSetting
MD013: false,
};
+
export function resolveMarkdownlintConfig(
rules: Record<string, MarkdownlintRuleSetting> | undefined,
): Configuration {
diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
index ef478e268..9c9542661 100644
--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
@@ -1,3 +1,4 @@
+
import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';
export interface FrontmatterFieldConstraint {
diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.ts
index 3871ccada..d4f3c1164 100644
--- a/packages/core/src/markdown/lint/frontmatter-validate.ts
+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts
@@ -1,3 +1,4 @@
+
import Ajv, { type ValidateFunction } from 'ajv';
import Ajv2019 from 'ajv/dist/2019.js';
import Ajv2020 from 'ajv/dist/2020.js';
@@ -235,11 +236,13 @@ export function validateFrontmatterSource(
const keyword = error.keyword;
let line = 0;
let message: string;
+ let frontmatterScope: 'missing' | 'invalid' = 'invalid';
if (keyword === 'required' && error.instancePath === '') {
const missing = String(
(error.params as { missingProperty?: unknown }).missingProperty ?? '',
);
message = `Frontmatter property "${missing}" is required`;
+ frontmatterScope = 'missing';
} else if (error.instancePath === '') {
message = `Frontmatter ${error.message ?? `violates "${keyword}"`}`;
} else {
@@ -262,6 +265,7 @@ export function validateFrontmatterSource(
source: 'frontmatter',
code: keyword,
message,
+ frontmatterScope,
});
}
}
diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.ts
index 00d08265a..48d260ed6 100644
--- a/packages/core/src/markdown/lint/index.ts
+++ b/packages/core/src/markdown/lint/index.ts
@@ -1,3 +1,4 @@
+
import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';
import type { LintDiagnostic } from './types.ts';
diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.ts
index 5e832aa19..be5871ed9 100644
--- a/packages/core/src/markdown/lint/plugins.ts
+++ b/packages/core/src/markdown/lint/plugins.ts
@@ -1,3 +1,4 @@
+
import { z } from 'zod';
import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';
import {
@@ -13,6 +14,7 @@ import {
type MarkdownlintSlice,
} from './types.ts';
+
const MarkdownlintRuleSettingSchema = z.union([
z.boolean(),
z.enum(MARKDOWNLINT_RULE_SEVERITIES),
diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.ts
index da6c477e9..e23681598 100644
--- a/packages/core/src/markdown/lint/types.ts
+++ b/packages/core/src/markdown/lint/types.ts
@@ -1,3 +1,4 @@
+
export const LINT_PLUGIN_IDS = ['markdownlint', 'frontmatter'] as const;
export type LintPluginId = (typeof LINT_PLUGIN_IDS)[number];
@@ -25,6 +26,7 @@ export interface LintDiagnostic {
code: string;
message: string;
fixes?: LintTextEdit[];
+ frontmatterScope?: 'missing' | 'invalid';
}
const VALIDATION_SOURCES = [...LINT_PLUGIN_IDS, 'links'] as const;
@@ -69,6 +71,7 @@ export interface FrontmatterSlice {
schemas: ResolvedFrontmatterSchemaEntry[];
}
+
interface RuleOptionSpecBase {
key: string;
description: string;
diff --git a/packages/core/src/markdown/lint/validation-counts.ts b/packages/core/src/markdown/lint/validation-counts.ts
index 98238656e..437cc539a 100644
--- a/packages/core/src/markdown/lint/validation-counts.ts
+++ b/packages/core/src/markdown/lint/validation-counts.ts
@@ -1,3 +1,4 @@
+
export interface ValidationSourceCounts {
errorCount: number;
warningCount: number;
diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.ts
index a5b511f25..bd79424c7 100644
--- a/packages/core/src/markdown/math-promoter.ts
+++ b/packages/core/src/markdown/math-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Code, Root } from 'mdast';
import type { Math as MdastMath } from 'mdast-util-math';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.ts
index ed89371d0..00fbc0035 100644
--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts
+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, ElementContent, Properties } from 'hast';
import type { FootnoteDefinition, FootnoteReference } from 'mdast';
import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.ts
index 8ce2b2492..df788a80d 100644
--- a/packages/core/src/markdown/mdast-to-html.ts
+++ b/packages/core/src/markdown/mdast-to-html.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root as HastRoot, Text as HastText } from 'hast';
import type { Root as MdastRoot, Text as MdastText } from 'mdast';
import type { Handler } from 'mdast-util-to-hast';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index bfd7e3109..fa3cfcd86 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.ts
index 1a897fca8..17ed2b829 100644
--- a/packages/core/src/markdown/mermaid-promoter.ts
+++ b/packages/core/src/markdown/mermaid-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Code, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.ts
index 9864b3b60..7e4a9a48b 100644
--- a/packages/core/src/markdown/parse-with-fallback.ts
+++ b/packages/core/src/markdown/parse-with-fallback.ts
@@ -168,6 +168,7 @@ export function parseRecursive(
}
}
+
interface VFilePlace {
offset?: number;
start?: { offset?: number };
@@ -186,6 +187,7 @@ function extractErrorOffset(err: unknown): number | undefined {
return undefined;
}
+
interface Region {
start: number;
end: number;
@@ -209,6 +211,7 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {
return null;
}
+
export interface TagEvent {
kind: 'open' | 'close' | 'self-close';
name: string;
@@ -355,6 +358,7 @@ function findFallbackRegion(src: string, errorOffset: number): Region {
return { start: blockStart, end: blockEnd };
}
+
interface SourceBlock {
src: string;
start: number;
@@ -452,6 +456,7 @@ function tryPerBlockFallback(
};
}
+
function wholeDocRawText(source: string): JSONContent {
return {
type: 'doc',
diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.ts
index e6ab4fd57..43d420187 100644
--- a/packages/core/src/markdown/parser-drop-closure.ts
+++ b/packages/core/src/markdown/parser-drop-closure.ts
@@ -1,3 +1,4 @@
+
export type DroppedTokenAdjudication =
| {
kind: 'format-dof-axis';
diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.ts
index 4426ab46e..c21e1fdf1 100644
--- a/packages/core/src/markdown/pipeline.ts
+++ b/packages/core/src/markdown/pipeline.ts
@@ -1,3 +1,4 @@
+
import {
type FromProseMirrorOptions,
fromProseMirror,
diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.ts
index 91cdf658f..ccf06e94d 100644
--- a/packages/core/src/markdown/position-aware-join.ts
+++ b/packages/core/src/markdown/position-aware-join.ts
@@ -1,3 +1,4 @@
+
import type { Join } from 'mdast-util-to-markdown';
import type { Position } from 'unist';
import { isBlankLineParagraph } from './zero-emission-blocks.ts';
diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.ts
index 0f399d34c..e5b4c9eba 100644
--- a/packages/core/src/markdown/position-slice.ts
+++ b/packages/core/src/markdown/position-slice.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Root } from 'mdast';
import { visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
@@ -476,7 +477,8 @@ export function applyPositionSliceToNode(
const first = source[startOff];
if (first !== '[' && first !== '<' && !node.title) {
node.data.sourceStyle = 'gfm-autolink';
- } else if (first === '[') {
+ }
+ else if (first === '[') {
const slice = source.slice(startOff, endOff);
const closeBracketIdx = slice.lastIndexOf('](');
if (closeBracketIdx !== -1) {
diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
index db10fa54b..ca225ce9b 100644
--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, Root, Text } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
index 34068d103..3a2524a9a 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
index 93151d43b..2279a0189 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
index 188f02d83..a0f467c42 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
index 4ba2c3418..4e8542a21 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
index 1a74b1272..a3c96b24a 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
index de35e7b79..e95cf43d6 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
index b4be1b2ea..ffdb4d5b5 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
index 3c8d88b7c..e2a96d1a7 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.ts
index cf2c9da8e..0389575ac 100644
--- a/packages/core/src/markdown/resolve-image-url.ts
+++ b/packages/core/src/markdown/resolve-image-url.ts
@@ -1,3 +1,4 @@
+
import { isRelativeUrl } from './safe-url.ts';
function isDevDiagnosticContext(): boolean {
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 4d3250d3a..8be632ba4 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,3 +1,4 @@
+
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
index 0dd54070e..96304e7a5 100644
--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts
+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
@@ -1,3 +1,4 @@
+
import type { JSONContent } from '@tiptap/core';
import type { Nodes } from 'mdast';
import { expect } from 'vitest';
diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.ts
index 46cc6a074..542204403 100644
--- a/packages/core/src/markdown/serialize-helpers.ts
+++ b/packages/core/src/markdown/serialize-helpers.ts
@@ -1,3 +1,4 @@
+
import type { Node as PmNode } from '@tiptap/pm/model';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { PropDef, SerializeContext } from '../registry/types.ts';
diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.ts
index b012a5aff..8c08b7a04 100644
--- a/packages/core/src/markdown/single-dollar-math-promoter.ts
+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts
@@ -1,3 +1,4 @@
+
import type { PhrasingContent, Root, Text } from 'mdast';
import type { InlineMath } from 'mdast-util-math';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.ts
index a41534404..20ce25dbe 100644
--- a/packages/core/src/markdown/to-markdown-handlers.ts
+++ b/packages/core/src/markdown/to-markdown-handlers.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parents } from 'mdast';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { Handle, Info, State } from 'mdast-util-to-markdown';
diff --git a/packages/core/src/markdown/underline-promoter.ts b/packages/core/src/markdown/underline-promoter.ts
index 0f1b0f27d..6e6d73400 100644
--- a/packages/core/src/markdown/underline-promoter.ts
+++ b/packages/core/src/markdown/underline-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.ts
index 1a082bda7..932d7d2a8 100644
--- a/packages/core/src/markdown/unknown-mdast-guard.ts
+++ b/packages/core/src/markdown/unknown-mdast-guard.ts
@@ -1,3 +1,4 @@
+
import type { Root as MdastRoot } from 'mdast';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.ts
index d578476a7..ac9f5239b 100644
--- a/packages/core/src/markdown/whitespace-char-ref.ts
+++ b/packages/core/src/markdown/whitespace-char-ref.ts
@@ -1,3 +1,4 @@
+
const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([
[0x20, ' '],
[0x09, '\t'],
diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.ts
index 6dad26200..afd9936fe 100644
--- a/packages/core/src/markdown/wiki-link-micromark.ts
+++ b/packages/core/src/markdown/wiki-link-micromark.ts
@@ -17,6 +17,7 @@ declare module 'micromark-util-types' {
}
}
+
const CODE_BANG = 33; // !
const CODE_LBRACKET = 91; // [
const CODE_RBRACKET = 93; // ]
@@ -260,6 +261,7 @@ export function wikiLinkSyntax(): Extension {
};
}
+
function enterWikiLink(this: CompileContext, token: Token) {
this.enter(
{
@@ -385,6 +387,7 @@ export const wikiLinkToMarkdown: {
unsafe: [{ character: '[', inConstruct: ['phrasing'] }],
};
+
const MICROMARK_EXT = wikiLinkSyntax();
export function remarkWikiLink(this: Processor) {