Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(markdown): apply div/center alignment wrappers like GitHub (#2995)
Abraham429657f4a084
diff --git a/.changeset/div-align-render.md b/.changeset/div-align-render.mdnew file mode 100644index 000000000..416bfd2d3--- /dev/null+++ b/.changeset/div-align-render.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": minor+---++GitHub-style `<div align="center">` wrappers now render the way GitHub shows them: the tag lines disappear and everything between them — headings, text, badge images — actually centers (left/right/justify work too). The content inside stays fully editable, and the `<div align>` markdown is preserved byte-for-byte on disk. Divs with other attributes keep their literal rendering.diff --git a/packages/app/src/editor/components/AlignBlock.tsx b/packages/app/src/editor/components/AlignBlock.tsxnew file mode 100644index 000000000..dfd4c93ed--- /dev/null+++ b/packages/app/src/editor/components/AlignBlock.tsx@@ -0,0 +1,32 @@+/**+ * AlignBlock — DIY renderer for the `HtmlAlignBlock` canonical descriptor+ * (`<div align="…">` GitHub-README wrapper, promoted by+ * `div-align-promoter.ts`). Children are ordinary PM-managed blocks; the+ * wrapper only contributes text alignment, so images/badges (inline+ * content) and headings center the way GitHub renders them.+ */++import { cn } from '@/lib/utils';++const ALIGN_CLASS: Record<string, string> = {+ center: 'text-center',+ left: 'text-left',+ right: 'text-right',+ justify: 'text-justify',+};++interface AlignBlockProps {+ align?: string;+ children?: React.ReactNode;+}++export function AlignBlock(props: AlignBlockProps) {+ return (+ <div+ data-component-type="align-block"+ className={cn('prose-no-margin', ALIGN_CLASS[props.align ?? ''] ?? null)}+ >+ {props.children}+ </div>+ );+}diff --git a/packages/app/src/editor/components/componentMap.tsx b/packages/app/src/editor/components/componentMap.tsxindex db8dbf6bf..e2a23e254 100644--- a/packages/app/src/editor/components/componentMap.tsx+++ b/packages/app/src/editor/components/componentMap.tsx@@ -42,6 +42,7 @@* '*' maps to UnregisteredBadgeRender for the wildcard fallback.*/import { Accordion } from './Accordion.tsx';+import { AlignBlock } from './AlignBlock.tsx';import { Audio } from './Audio.tsx';import { Callout } from './Callout.tsx';import { Embed } from './Embed.tsx';@@ -85,6 +86,10 @@ export const componentMap: Record<string, React.ComponentType<any>> = {// Renders via a cross-origin iframe with `referrerPolicy="no-referrer"`.Embed,Accordion,+ // `HtmlAlignBlock` — canonical renderer for promoted `<div align>` wrappers+ // (GitHub-README centered headers). Children stay ordinary editable+ // blocks; the wrapper only applies text alignment.+ HtmlAlignBlock: AlignBlock,Tabs,Tab,Math: MathView,diff --git a/packages/app/src/editor/slash-command/component-items.test.ts b/packages/app/src/editor/slash-command/component-items.test.tsindex aa7f1305f..bc700587e 100644--- a/packages/app/src/editor/slash-command/component-items.test.ts+++ b/packages/app/src/editor/slash-command/component-items.test.ts@@ -49,6 +49,7 @@ describe('getComponentItems (slash menu)', () => {expect(labels).toEqual(['Accordion',+ 'Align block','Audio','Callout','Embed',@@ -253,11 +254,11 @@ describe('agent-surface ↔ slash-menu filter parity', () => {}});- test('broad set minus agent set === fence-kind names (today: just MermaidFence)', () => {+ test('broad set minus agent set === fence- and html-kind names', () => {const broad = broadCanonicalSet();const agent = agentCanonicalSet();const divergence = new Set([...broad].filter((name) => !agent.has(name)));- expect(divergence).toEqual(new Set(['MermaidFence']));+ expect(divergence).toEqual(new Set(['MermaidFence', 'HtmlAlignBlock']));});test('broad set minus slash-menu set === SLASH_HIDDEN_CANONICALS exactly', () => {diff --git a/packages/app/src/globals.css b/packages/app/src/globals.cssindex f553b4933..9af915bd7 100644--- a/packages/app/src/globals.css+++ b/packages/app/src/globals.css@@ -1907,6 +1907,14 @@outline-offset: 2px;}+/* `<div align>` compat wrapper (HtmlAlignBlock / div-align-promoter):+ images inside the aligned block flow inline like GitHub renders them —+ the OK default `display: block` image would ignore the wrapper's+ text-align and pin badges/heroes to the left edge. */+.ProseMirror [data-component-type="align-block"] img {+ display: inline-block;+}+/* Wiki-link chip icon — the `<img>` inside `[data-wiki-link-icon]`. LivesAFTER `.ProseMirror img` so source order matches the descending-specificity ratchet (biome's noDescendingSpecificity). Overridesdiff --git a/packages/core/schema-snapshot.json b/packages/core/schema-snapshot.jsonindex b47cb1828..4d2c978da 100644--- a/packages/core/schema-snapshot.json+++ b/packages/core/schema-snapshot.json@@ -899,6 +899,11 @@"version": null,"hasOptions": false},+ {+ "name": "div-align-promoter",+ "version": null,+ "hasOptions": false+ },{"name": "image-promoter","version": null,diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.tsnew file mode 100644index 000000000..43ecdc709--- /dev/null+++ b/packages/core/src/markdown/div-align-promoter.ts@@ -0,0 +1,106 @@+import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';+import type { MdxJsxFlowElement } from 'mdast-util-mdx';+import { visit } from 'unist-util-visit';++const OPENER_RE = /^<(div|center)(\s[^>]*?)?\s*>$/i;++const ALIGN_VALUES = new Set(['center', 'left', 'right', 'justify']);++function extractAlign(rawAttrs: string | undefined): string | null {+ if (!rawAttrs) return null;+ const m = rawAttrs.match(/\balign\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>]+))/i);+ if (!m) return null;+ const align = (m[1] ?? m[2] ?? m[3] ?? '').toLowerCase();+ return ALIGN_VALUES.has(align) ? align : null;+}++function isTextOnlyParagraph(node: Nodes): node is Paragraph {+ if (node.type !== 'paragraph') return false;+ const children = (node as Paragraph).children;+ return children.length === 1 && children[0].type === 'text';+}++function textValue(paragraph: Paragraph): string {+ return (paragraph.children[0] as Text).value ?? '';+}++interface OpenerInfo {+ tag: 'div' | 'center';+ align: string | null;+ sourceAttrs: string;+}++function openerInfo(node: Nodes): OpenerInfo | null {+ if (!isTextOnlyParagraph(node)) return null;+ const m = textValue(node).trim().match(OPENER_RE);+ if (!m) return null;+ const tag = m[1].toLowerCase() as 'div' | 'center';+ const sourceAttrs = m[2] ?? '';+ const align = extractAlign(sourceAttrs) ?? (tag === 'center' ? 'center' : null);+ return { tag, align, sourceAttrs };+}++function findCloserIdx(children: Nodes[], startIdx: number, tag: string): number | null {+ const closerRe = new RegExp(String.raw`^\s*</${tag}>\s*$`, 'i');+ for (let j = startIdx + 1; j < children.length; j++) {+ const candidate = children[j];+ if (!isTextOnlyParagraph(candidate)) continue;+ const value = textValue(candidate);+ if (closerRe.test(value)) return j;+ const trimmed = value.trimStart().toLowerCase();+ if (+ trimmed.startsWith('<div') ||+ trimmed.startsWith('<center') ||+ trimmed.includes(`</${tag}>`)+ ) {+ return null;+ }+ }+ return null;+}++function promoteInParent(parent: Parent): void {+ const children = parent.children as Nodes[];+ let i = 0;+ while (i < children.length) {+ const info = openerInfo(children[i]);+ if (info !== null) {+ const closerIdx = findCloserIdx(children, i, info.tag);+ if (closerIdx !== null) {+ const opener = children[i];+ const closer = children[closerIdx];+ const body = children.slice(i + 1, closerIdx) as MdxJsxFlowElement['children'];+ const openerPos = opener.position;+ const closerPos = closer.position;+ const replacement: MdxJsxFlowElement = {+ type: 'mdxJsxFlowElement',+ name: 'HtmlAlignBlock',+ attributes: [+ ...(info.align !== null+ ? [{ type: 'mdxJsxAttribute' as const, name: 'align', value: info.align }]+ : []),+ { type: 'mdxJsxAttribute' as const, name: 'tag', value: info.tag },+ { type: 'mdxJsxAttribute' as const, name: 'sourceAttrs', value: info.sourceAttrs },+ ],+ children: body,+ position:+ openerPos && closerPos ? { start: openerPos.start, end: closerPos.end } : undefined,+ };+ (children as unknown[]).splice(i, closerIdx - i + 1, replacement);+ i++;+ continue;+ }+ }+ i++;+ }+}++export function divAlignPromoterPlugin() {+ return (tree: Root) => {+ visit(tree, (node) => {+ if ('children' in node && Array.isArray((node as Parent).children)) {+ promoteInParent(node as Parent);+ }+ });+ };+}diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.tsindex 7f2d5adca..21bc33473 100644--- a/packages/core/src/markdown/pipeline.ts+++ b/packages/core/src/markdown/pipeline.ts@@ -22,6 +22,7 @@ import { calloutTransformerPlugin, REMARK_GITHUB_ALERTS_OPTIONS } from './callouimport { commentPromoterPlugin } from './comment-promoter.ts';import { dedentBlockJsxClose } from './dedent-block-jsx-close.ts';import { detailsAccordionPromoterPlugin } from './details-accordion-promoter.ts';+import { divAlignPromoterPlugin } from './div-align-promoter.ts';import { encodeEntityRefs, restoreEntityRefsPlugin } from './entity-ref-guard.ts';import { highlightPromoterPlugin } from './highlight-promoter.ts';import { imagePromoterPlugin } from './image-promoter.ts';@@ -84,6 +85,7 @@ export const ACTIVE_MDAST_PLUGINS = [{ name: 'restore-entity-refs', plugin: restoreEntityRefsPlugin },{ name: 'restore-backslash-escapes', plugin: restoreBackslashEscapesPlugin },{ name: 'details-accordion-promoter', plugin: detailsAccordionPromoterPlugin },+ { name: 'div-align-promoter', plugin: divAlignPromoterPlugin },{ name: 'image-promoter', plugin: imagePromoterPlugin },{ name: 'indented-code-promoter', plugin: indentedCodePromoterPlugin },{ name: 'math-promoter', plugin: mathPromoterPlugin },diff --git a/packages/core/src/registry/built-ins.ts b/packages/core/src/registry/built-ins.tsindex d134d9528..fdab80971 100644--- a/packages/core/src/registry/built-ins.ts+++ b/packages/core/src/registry/built-ins.ts@@ -779,6 +779,38 @@ const htmlDetailsAccordionProps: PropDef[] = [accordionProps[5],];+// HtmlAlignBlock exposes the one attribute the `<div align>` authoring form+// encodes; the enum mirrors the promoter's validated value set.+const htmlAlignBlockProps: PropDef[] = [+ {+ name: 'align',+ type: 'enum',+ enumValues: ['center', 'left', 'right', 'justify'],+ required: false,+ defaultValue: 'center',+ description: 'Block alignment from the `<div align>` attribute.',+ },+ {+ // 'div' | 'center' — which HTML wrapper authored this block.+ name: 'tag',+ type: 'string',+ required: false,+ defaultValue: 'div',+ hidden: true,+ description: 'Source wrapper tag (div or center).',+ },+ {+ // Raw attribute bytes from the opener tag (leading whitespace included)+ // so a dirty-path rebuild re-emits non-align attributes untouched.+ name: 'sourceAttrs',+ type: 'string',+ required: false,+ defaultValue: '',+ hidden: true,+ description: 'Raw opener-tag attribute bytes preserved for round-trip.',+ },+];+// WikiEmbed* compats expose only what `![[file.ext|alias]]` can encode — a// single editable string slot. Stored target / anchor stay on the prop bag// alongside `alias` so `serialize` can rebuild byte-identical source bytes,@@ -1694,6 +1726,55 @@ export const builtInComponents: JsxComponentMeta[] = [};},},+ {+ // Canonical (not compat) on the MermaidFence precedent: the HTML+ // `<div align>` wrapper IS the authoring form — there is no MDX JSX+ // counterpart to render through, so a compat row would dangle T7's+ // rendersAs-resolves-to-canonical invariant.+ name: 'HtmlAlignBlock',+ surface: 'canonical',+ hasChildren: true,+ props: htmlAlignBlockProps,+ icon: 'AlignCenter',+ category: 'content',+ displayName: 'Align block',+ description:+ 'GitHub-style `<div align>` wrapper. Children render as normal blocks with the alignment applied; the `<div align>` syntax is preserved on round-trip.',+ searchTerms: ['align', 'center', 'centered', 'div'],+ serialize: (node, ctx) => {+ const p = node.attrs.props as+ | { align?: string; tag?: string; sourceAttrs?: string }+ | undefined;+ const tag = p?.tag === 'center' ? 'center' : 'div';+ const align = typeof p?.align === 'string' && p.align ? p.align : null;+ // Start from the preserved raw attr bytes (non-align attributes ride+ // along untouched), then reconcile the live `align` prop into them —+ // a PropPanel alignment edit must reach disk, not lose to the stale+ // captured bytes. `<center>` implies center; it only carries an+ // explicit align attr when the user picks a different alignment.+ let attrs = typeof p?.sourceAttrs === 'string' ? p.sourceAttrs : '';+ const alignAttrRe = /(\balign\s*=\s*)(?:"[^"]*"|'[^']*'|[^\s"'<>]+)/i;+ if (align !== null && (tag === 'div' || align !== 'center')) {+ attrs = alignAttrRe.test(attrs)+ ? attrs.replace(alignAttrRe, `$1"${escapeHtmlAttr(align)}"`)+ : `${attrs} align="${escapeHtmlAttr(align)}"`;+ } else if (align === null || (tag === 'center' && align === 'center')) {+ attrs = attrs.replace(new RegExp(`\\s*${alignAttrRe.source}`, 'i'), '');+ }+ return {+ type: 'mdxJsxFlowElement' as const,+ name: 'HtmlAlignBlock',+ attributes: [],+ children: ctx.all(node) as never,+ data: {+ htmlBoundary: {+ opener: `<${tag}${attrs}>`,+ closer: `</${tag}>`,+ },+ },+ };+ },+ },// Math compat descriptors — pair with the Math canonical above.// Mermaid has no compat row: the fence IS the canonical form (the// canonical descriptor is named `MermaidFence` and serializes todiff --git a/packages/core/src/registry/canonical-compat.test.ts b/packages/core/src/registry/canonical-compat.test.tsindex 76585c872..73966c7d5 100644--- a/packages/core/src/registry/canonical-compat.test.ts+++ b/packages/core/src/registry/canonical-compat.test.ts@@ -28,8 +28,8 @@ describe('canonical/compat split — registry shape', () => {}});- test('exactly 14 canonical descriptors (5-pack + Math + MermaidFence + Pdf + File + Tabs + Tab + Embed + Mirror + MirrorSource)', () => {- expect(canonicalDescriptors.length).toBe(14);+ test('exactly 15 canonical descriptors (5-pack + Math + MermaidFence + Pdf + File + Tabs + Tab + Embed + Mirror + MirrorSource + HtmlAlignBlock)', () => {+ expect(canonicalDescriptors.length).toBe(15);// Media canonicals with a matching HTML primitive are lowercase// (img/video/audio). Non-native canonicals stay capitalized// (Callout, Accordion, Math, MermaidFence, Pdf, File, Tabs, Tab,@@ -44,6 +44,7 @@ describe('canonical/compat split — registry shape', () => {'Callout','Embed','File',+ 'HtmlAlignBlock','Math','MermaidFence','Mirror',diff --git a/packages/core/src/registry/projection.test.ts b/packages/core/src/registry/projection.test.tsindex 57946c910..0ce0298b5 100644--- a/packages/core/src/registry/projection.test.ts+++ b/packages/core/src/registry/projection.test.ts@@ -24,9 +24,9 @@ const PARSE_EXTENSIONS = [mdx()];const PARSE_MDAST_EXTENSIONS = [mdxFromMarkdown()];describe('getCanonicalDescriptors (broad filter)', () => {- test('returns 14 canonicals (matches built-ins snapshot)', () => {+ test('returns 15 canonicals (matches built-ins snapshot)', () => {const canonicals = getCanonicalDescriptors();- expect(canonicals.length).toBe(14);+ expect(canonicals.length).toBe(15);});test('excludes compat surfaces', () => {@@ -48,7 +48,7 @@ describe('getCanonicalDescriptors (broad filter)', () => {});describe('getAgentCanonicalDescriptors (JSX-only agent surface)', () => {- test('returns 13 canonicals — broad set minus fence-kind', () => {+ test('returns 13 canonicals — broad set minus fence- and html-kind', () => {expect(getAgentCanonicalDescriptors().length).toBe(13);});@@ -64,11 +64,11 @@ describe('getAgentCanonicalDescriptors (JSX-only agent surface)', () => {}});- test('broad set minus agent set equals exactly the fence-kind names', () => {+ test('broad set minus agent set equals exactly the fence- and html-kind names', () => {const broad = new Set(getCanonicalDescriptors().map((d) => d.name));const agent = new Set(getAgentCanonicalDescriptors().map((d) => d.name));const divergence = new Set([...broad].filter((name) => !agent.has(name)));- expect(divergence).toEqual(new Set(['MermaidFence']));+ expect(divergence).toEqual(new Set(['MermaidFence', 'HtmlAlignBlock']));});});@@ -79,7 +79,7 @@ describe('projectLite — 4 fields per entry', () => {expect(lite.id).toBe(d.name);expect(lite.displayName.length).toBeGreaterThan(0);expect(lite.description.length).toBeGreaterThan(0);- expect(['jsx-block', 'jsx-void', 'fence']).toContain(lite.kind);+ expect(['jsx-block', 'jsx-void', 'fence', 'html']).toContain(lite.kind);}});diff --git a/packages/core/src/registry/projection.ts b/packages/core/src/registry/projection.tsindex b0e298e0b..13e6fe087 100644--- a/packages/core/src/registry/projection.ts+++ b/packages/core/src/registry/projection.ts@@ -41,7 +41,7 @@ const TO_MARKDOWN_MDX_EXT = mdxToMarkdown();* - `jsx-void` — self-closing JSX with no body (`<img src="" />`).* - `fence` — fenced code block (`MermaidFence`, the one fence-kind canonical).*/-export type ComponentKind = 'jsx-block' | 'jsx-void' | 'fence';+export type ComponentKind = 'jsx-block' | 'jsx-void' | 'fence' | 'html';/** Lite per-entry shape — what the write-tool-description inventory carries. */export interface ComponentEntryLite {@@ -97,7 +97,10 @@ export function getCanonicalDescriptors(): JsxComponentMeta[] {* stays in the registry because it's load-bearing for the parse pipeline.*/export function getAgentCanonicalDescriptors(): JsxComponentMeta[] {- return getCanonicalDescriptors().filter((d) => resolveKind(d) !== 'fence');+ return getCanonicalDescriptors().filter((d) => {+ const kind = resolveKind(d);+ return kind !== 'fence' && kind !== 'html';+ });}/**@@ -113,6 +116,11 @@ export function getAgentCanonicalDescriptors(): JsxComponentMeta[] {*/function resolveKind(descriptor: JsxComponentMeta): ComponentKind {if (descriptor.name === 'MermaidFence') return 'fence';+ // html-kind: the authoring form is raw HTML (`<div align>` / `<center>`),+ // so advertising a `<HtmlAlignBlock>` JSX form to agents would teach them+ // markup that renders in OK but nowhere else (same exclusion rationale as+ // fence-kind).+ if (descriptor.name === 'HtmlAlignBlock') return 'html';if (descriptor.hasChildren) return 'jsx-block';return 'jsx-void';}diff --git a/packages/core/src/registry/registry.test.ts b/packages/core/src/registry/registry.test.tsindex f763a72e0..707aee8a4 100644--- a/packages/core/src/registry/registry.test.ts+++ b/packages/core/src/registry/registry.test.ts@@ -4,9 +4,11 @@ import { builtInComponents, createRegistry, wildcardMeta } from './index.ts';import type { JsxComponentMeta } from './types.ts';describe('createRegistry', () => {- test('returns the 14 canonical + 9 compat descriptors + wildcard', () => {- // 14 canonicals (Callout, Image, Video, Audio, Accordion, Math,- // MermaidFence, Pdf, File, Tabs, Tab, Embed, Mirror, MirrorSource)+ test('returns the 15 canonical + 9 compat descriptors + wildcard', () => {+ // 15 canonicals (Callout, Image, Video, Audio, Accordion, Math,+ // MermaidFence, Pdf, File, Tabs, Tab, Embed, Mirror, MirrorSource,+ // HtmlAlignBlock — the `<div align>` HTML form is canonical, per the+ // MermaidFence fence-only precedent)// + 9 compats (GFMCallout, CommonMarkImage, HtmlDetailsAccordion,// WikiEmbedImage, WikiEmbedVideo, WikiEmbedAudio, WikiEmbedFile,// DollarMath, MathFence) + '*' wildcard.@@ -22,7 +24,7 @@ describe('createRegistry', () => {// through to the wildcard.const registry = createRegistry();const entries = [...registry.entries()];- expect(entries.length).toBe(24);+ expect(entries.length).toBe(25);});test('get returns registered component by name', () => {@@ -116,11 +118,11 @@ describe('createRegistry', () => {});describe('builtInComponents manifest', () => {- test('contains 14 canonical + 9 compat entries (5-pack + Math + MermaidFence + Pdf + File + Tabs + Tab + Embed + Mirror + MirrorSource canonicals; source-form preservation + math syntax + wiki-embed compats; Mermaid is fence-only)', () => {- expect(builtInComponents.length).toBe(23);+ test('contains 15 canonical + 9 compat entries (5-pack + Math + MermaidFence + Pdf + File + Tabs + Tab + Embed + Mirror + MirrorSource canonicals; source-form preservation + math syntax + wiki-embed compats; Mermaid is fence-only)', () => {+ expect(builtInComponents.length).toBe(24);const canonical = builtInComponents.filter((m) => m.surface === 'canonical');const compat = builtInComponents.filter((m) => m.surface === 'compat');- expect(canonical.length).toBe(14);+ expect(canonical.length).toBe(15);expect(compat.length).toBe(9);});