Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
6ee634c
refactor(text-editor): build default and docs setups from block profiles
s3rot0n1n Nov 20, 2026
12922a5
feat(text-editor): pluggable blocks with a block library, insert menu…
s3rot0n1n Nov 20, 2026
4baf462
fix(text-editor): place the insert menu at the caret on scrolled pages
s3rot0n1n Nov 20, 2026
121ad02
docs(text-editor): document pluggable blocks and add a changeset
s3rot0n1n Nov 20, 2026
c361761
fix(text-editor): multi-word / filter, cursor in the first field afte…
s3rot0n1n Nov 20, 2026
dc15218
fix(text-editor): render the editor after mount so hydration matches
s3rot0n1n Nov 20, 2026
353a686
docs(docs): document pluggable blocks on the text editor page
s3rot0n1n Nov 20, 2026
3fc63fa
fix(text-editor): stop deep documents from overflowing the availabili…
s3rot0n1n Nov 20, 2026
d7ba500
feat(examples): add a text-editor blocks example with real MediaLit u…
s3rot0n1n Nov 20, 2026
067d92a
fix(text-editor): keep the / menu inside the viewport
s3rot0n1n Nov 20, 2026
aef00c6
fix(text-editor): make blocks usable from the keyboard and with scree…
s3rot0n1n Nov 20, 2026
09174b4
fix(text-editor): make the / menu's keyboard highlight visible and st…
s3rot0n1n Nov 20, 2026
1be0e41
feat(text-editor): sectioned / menu with descriptions and key hints
s3rot0n1n Nov 20, 2026
f07ca8a
docs(text-editor): require WCAG 2.2 AA in the package's agent guide
s3rot0n1n Nov 20, 2026
907bdb2
fix(text-editor): stop styling embeds as black video frames
s3rot0n1n Nov 20, 2026
7455b64
feat(text-editor): Button, WebPreview and H5P blocks, success callout…
s3rot0n1n Nov 20, 2026
e1c468b
docs(text-editor): rewrite the README for newcomers
s3rot0n1n Nov 20, 2026
86b89d4
feat(text-editor): make the content format agent-friendly
s3rot0n1n Nov 20, 2026
110aa29
feat(api): refuse publishing half-filled blocks in articles and produ…
s3rot0n1n Nov 20, 2026
5ec9ba4
build(docker): build JavaScript natively, only the runtime image per …
s3rot0n1n Nov 20, 2026
56d8a09
feat(text-editor): table bar to insert and delete rows and columns
s3rot0n1n Nov 20, 2026
95d2cf6
fix(text-editor): / menu picks label matches first and inserts put th…
s3rot0n1n Nov 20, 2026
a39499c
fix(text-editor): drag handle shows in editors with padded content
s3rot0n1n Nov 20, 2026
41b25a8
fix(text-editor): links end where they end
s3rot0n1n Nov 20, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/text-editor-pluggable-blocks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@frontlit/text-editor": minor
---

Add pluggable blocks. `defineProfile` builds the schema, Markdown parser and serializer, validator (with availability checks), renderer and a format reference from one list of blocks; the new server-safe `@frontlit/text-editor/blocks` entry exports it with a block library (Image, Video, Audio, PDF, File, Embed, Callout, Tabs, Accordion, Steps). The editor gains a `/` insert menu, drag handles, block settings popovers, a media picker and an `unavailable` prop; `TextRenderer` accepts profile objects, host block components and `resolveMedia`. The default and documentation setups are rebuilt on profiles with unchanged Markdown output. Blocks work from the keyboard (Ctrl/⌘+Shift+↑/↓ moves a block, Alt+F10 reaches its controls, Escape returns) and with screen readers: the editing area is a labelled textbox (new `ariaLabel` prop) and the `/` menu is announced through `aria-activedescendant`. The `/` menu shows blocks in sections (Text, Media, Layout, or a block's own `insert.group`) with a description under each, and lists its keys in a footer. New library blocks: Button, WebPreview and H5P (allowed hosts only), plus a `success` callout type and Warning / Tip / Success / Danger callout presets in the `/` menu; all are in the documentation profile, so the API and MCP accept them. `contentFormat()`, `describeContentFormat()` and `schema/content.v1.json` describe the format for AI agents. Attributes can be `requiredToPublish`, and `incompleteBlocks(profile, content)` reports blocks saved without them (publish blockers, never save errors); the format reference now lists Markdown-only props (`docs.props`), child tags and the accepted literal syntax.
9 changes: 7 additions & 2 deletions apps/api/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
# Multi-arch:
# docker buildx build --platform linux/amd64,linux/arm64 \
# -f apps/api/Dockerfile -t codelit/frontlit:k3s --push .
FROM oven/bun:1.4.1-alpine AS base
# Install and build run on the build machine's own platform ($BUILDPLATFORM):
# the output is JavaScript, and emulating arm64 on an x86 builder (or the
# reverse) is several times slower. Production dependencies, which may carry
# native binaries, are installed for the target platform (prod-deps).
FROM --platform=$BUILDPLATFORM oven/bun:1.4.1-alpine AS base
FROM oven/bun:1.4.1-alpine AS target-base

FROM base AS deps
RUN apk add --no-cache libc6-compat
Expand All @@ -26,7 +31,7 @@ RUN bun run --filter @frontlit/text-editor build
RUN bun run --filter @frontlit/page-builder build:schema
RUN bun run --filter @frontlit/api build

FROM base AS prod-deps
FROM target-base AS prod-deps
WORKDIR /app

COPY package.json bun.lock ./
Expand Down
7 changes: 7 additions & 0 deletions apps/api/src/documentation/authoring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,13 @@ import {
serializeDocsMarkdown,
hashDocsContent,
extractDocsHeadings,
incompleteDocsBlocks,
type DocsDiagnostic,
} from "@frontlit/text-editor/docs";
import {
normalizeDocumentationContent,
validateDocumentationFeaturedImage,
requireCompleteMarkdownBlocks,
} from "./content-validation";
import { normalizeFeaturedImage } from "../documents/queries";
import { slugify, uniqueSlug } from "../utils/slug";
Expand Down Expand Up @@ -128,6 +130,7 @@ function parseInput(raw: unknown, create = false) {
const { content, frontmatter } = parseDocsMarkdown(patch.markdown, {
frontmatter: patch.markdown.trimStart().startsWith("---"),
});
requireCompleteMarkdownBlocks(content);
const fields: Record<string, string> = {
title: "title",
description: "excerpt",
Expand Down Expand Up @@ -212,6 +215,10 @@ export async function draftReport(
);
if (!draft.draftTitle.trim())
add("MISSING_TITLE", "A title is required before publication.", "title");
// Blocks the editor saved before they were filled in (a Button without its
// link) render nothing; they may stay in the draft but not go live.
for (const item of incompleteDocsBlocks(draft.draftContent))
diagnostics.push({ ...item, documentId: options.documentId });
const sections =
options.sections ??
(await (options.executor ?? db).query.docSections.findMany({
Expand Down
14 changes: 14 additions & 0 deletions apps/api/src/documentation/content-validation.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
DocsContentError,
diagnostic,
incompleteDocsBlocks,
isSafeDocsUrl,
requireDocsContent,
serializeDocsMarkdown,
Expand Down Expand Up @@ -29,6 +30,19 @@ export function normalizeDocumentationContent(input: unknown): TextEditorContent
return content as TextEditorContentRow;
}

/**
* Markdown sent through the API or MCP arrives whole (it isn't an editor
* draft being typed), so a block missing a required prop, such as a Button
* without its link, is refused instead of saved as an invisible block.
*/
export function requireCompleteMarkdownBlocks(content: unknown) {
const missing = incompleteDocsBlocks(content);
if (missing.length)
throw new DocsContentError(
missing.map((item) => ({ ...item, severity: "error", blocksSave: true })),
);
}

export function validateDocumentationFeaturedImage(
image: Record<string, unknown> | null | undefined,
) {
Expand Down
71 changes: 71 additions & 0 deletions apps/api/src/documents/markdown-body.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,4 +195,75 @@ describe("Markdown bodies for articles and product updates", () => {
"Markdown",
);
});

it("refuses agent Markdown with a block missing a required prop", async () => {
const result = await callTool("create_article", teamId, {
title: "CTA",
markdown: 'Intro.\n\n<Button label="Start" />\n',
});
expect(result.isError).toBe(true);
expect(
documentationValidationErrorSchema.parse(result.structuredContent),
).toMatchObject({
code: "INCOMPLETE_BLOCK",
diagnostics: [
{
code: "INCOMPLETE_BLOCK",
message: "<Button> needs href before it can be published.",
blocksSave: true,
},
],
});
});

it("reports and refuses publishing a half-filled block saved as JSON", async () => {
const half = {
type: "doc",
content: [{ type: "button", attrs: { label: "Start", href: null } }],
};
const created = await callTool("create_article", teamId, {
title: "CTA",
content: half,
});
expect(created.isError).toBeFalsy();
expect(created.structuredContent).toMatchObject({
publishable: false,
diagnostics: [
{ code: "INCOMPLETE_BLOCK", fieldPath: "content.content[0].attrs.href" },
],
});
const { documentId } = created.structuredContent;

const refused = await callTool("publish_article", teamId, { documentId });
expect(refused.isError).toBe(true);
expect(
documentationValidationErrorSchema.parse(refused.structuredContent),
).toMatchObject({ code: "INCOMPLETE_BLOCK" });
expect((await getDocumentByDocumentId("blog", documentId))?.publishedAt).toBeNull();

const fixed = await callTool("update_article", teamId, {
documentId,
markdown: '<Button label="Start" href="/start" />\n',
});
expect(fixed.structuredContent).toMatchObject({
publishable: true,
diagnostics: [],
});
const published = await callTool("publish_article", teamId, { documentId });
expect(published.isError).toBeFalsy();
});

it("describes every block, its props and examples in the markdown field", () => {
const field = tools.get("create_article")!.config.inputSchema.markdown;
const text: string = field.description;
for (const needle of [
"- Button:",
"href: URL",
"- Tab (inside <Tabs>)",
"items?: string[]",
"register_media",
"https://frontlit.app/schema/content.v1.json",
])
expect(text).toContain(needle);
});
});
21 changes: 19 additions & 2 deletions apps/api/src/documents/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ import {
import {
DocsContentError,
diagnostic,
incompleteDocsBlocks,
parseDocsMarkdown,
} from "@frontlit/text-editor/docs";
import { requireCompleteMarkdownBlocks } from "../documentation/content-validation";
import { and, count, desc, eq, ilike, isNotNull, ne, sql } from "drizzle-orm";
import { db } from "../db/client";
import { documents, type DocumentKind, type TextEditorContentRow } from "../db/schema";
Expand Down Expand Up @@ -48,8 +50,21 @@ function documentBody(input: {
fieldPath: "markdown",
}),
]);
return parseDocsMarkdown(input.markdown, { frontmatter: false })
.content as TextEditorContentRow;
const { content } = parseDocsMarkdown(input.markdown, { frontmatter: false });
requireCompleteMarkdownBlocks(content);
return content as TextEditorContentRow;
}

/**
* Whether an article's or product update's draft can be published, and why
* not: blocks the editor saved half-filled (a Button without its link)
* render nothing, so they block publishing. Docs carry their own, fuller
* report (`draftReport`).
*/
export function withPublishReport<T extends Record<string, unknown>>(row: T) {
if (row.kind === "doc" || "publishable" in row) return row;
const diagnostics = incompleteDocsBlocks(row.draftContent);
return { ...row, publishable: diagnostics.length === 0, diagnostics };
}

export function normalizeFeaturedImage(input: unknown): Record<string, unknown> | null {
Expand Down Expand Up @@ -453,6 +468,8 @@ export async function publishDocument(
}
const existing = await getDocumentByDocumentId(kind, documentId);
if (!existing || existing.teamId !== teamId) return null;
const blockers = incompleteDocsBlocks(existing.draftContent);
if (blockers.length) throw new DocsContentError(blockers);
const [doc] = await db
.update(documents)
.set({
Expand Down
3 changes: 2 additions & 1 deletion apps/api/src/documents/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
listDocuments,
publishDocument,
updateDocument,
withPublishReport,
} from "./queries";
import { omitInternal, serializeDates } from "../utils/public";
import {
Expand All @@ -32,7 +33,7 @@ import {
function toPublicDocument<T extends Record<string, unknown>>(doc: T) {
return serializeDates(
omitInternal(
{ ...doc, status: deriveDocumentStatus(doc as any) },
{ ...withPublishReport(doc), status: deriveDocumentStatus(doc as any) },
"teamId",
"kind",
"authorAccountId",
Expand Down
38 changes: 28 additions & 10 deletions apps/api/src/mcp/tools/documents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,11 @@ import {
listDocuments,
publishDocument,
updateDocument,
withPublishReport,
} from "../../documents/queries";
import { AUTH_ERROR, INTERNAL_ERROR, NOT_FOUND, jsonResult } from "./responses";
import { getTeamId } from "./auth";
import { DocsContentError } from "@frontlit/text-editor/docs";
import { DocsContentError, describeContentFormat } from "@frontlit/text-editor/docs";
import { documentationErrorBody } from "../../documentation/content-validation";
import { omitInternal, serializeDates } from "../../utils/public";
import {
Expand All @@ -45,7 +46,7 @@ const DOCUMENTATION_ONLY_KEYS = [
] as const;

function toPublicDocument<T extends Record<string, unknown>>(doc: T) {
const row = { ...doc };
const row = withPublishReport({ ...doc });
if (row.kind !== "doc")
for (const key of DOCUMENTATION_ONLY_KEYS)
delete (row as Record<string, unknown>)[key];
Expand All @@ -65,6 +66,16 @@ function toPublicDocument<T extends Record<string, unknown>>(doc: T) {
* the tools/output schema; `metaSchema` documents type-specific metadata for
* MCP clients. The database kind stays internal.
*/

/** The `markdown` field of every create/update tool: the format, generated
* from the documentation profile so new blocks need no tool edits. */
const markdownField = z
.string()
.optional()
.describe(
`Body as Markdown, converted to TipTap JSON. Send markdown or content, never both. Invalid Markdown returns diagnostics with line numbers.\n${describeContentFormat()}`,
);

export function registerDocumentTools(
server: McpToolRegistrar,
kind: DocumentKind,
Expand All @@ -90,6 +101,14 @@ export function registerDocumentTools(
createdAt: z.string().nullable(),
updatedAt: z.string().nullable(),
index: documentationIndexSchema.nullable().optional(),
publishable: z
.boolean()
.optional()
.describe("False when publish_* would be refused; see diagnostics."),
diagnostics: z
.array(z.any())
.optional()
.describe("What blocks publishing, e.g. a Button without its link."),
});
const itemSchema = kind === "doc" ? documentationSchema : documentSchema;
const outputSchema =
Expand All @@ -100,12 +119,7 @@ export function registerDocumentTools(
content: textEditorContentSchema
.optional()
.describe("Body as TipTap JSON. Send content or markdown, never both."),
markdown: z
.string()
.optional()
.describe(
"Body as Markdown (CommonMark/GFM, plus the Callout, Tabs, Steps, Cards, Accordion, CodeGroup and TypeTable blocks), converted to TipTap JSON. Images need https URLs. Send markdown or content, never both.",
),
markdown: markdownField,
};
const handleError = (error: unknown) =>
error instanceof DocsContentError
Expand All @@ -121,7 +135,7 @@ export function registerDocumentTools(
: `Creates a new ${humanLabel} (draft only) for the current team. Pass the body as Markdown (\`markdown\`) or TipTap JSON (\`content\`), or omit both for an empty draft. Invalid Markdown returns structured diagnostics with line numbers.`,
inputSchema:
kind === "doc"
? createDocumentationBodySchema.shape
? { ...createDocumentationBodySchema.shape, markdown: markdownField }
: {
title: z.string().min(1),
...bodyFields,
Expand Down Expand Up @@ -214,7 +228,11 @@ export function registerDocumentTools(
description: `Updates a ${humanLabel}'s draft title, body (Markdown via \`markdown\`, or TipTap JSON via \`content\`, never both), excerpt, featured image, and/or type-specific metadata. Writes only the draft state — call publish_${label} to make changes live.`,
inputSchema:
kind === "doc"
? { documentId: z.string(), ...updateDocumentationBodySchema.shape }
? {
documentId: z.string(),
...updateDocumentationBodySchema.shape,
markdown: markdownField,
}
: {
documentId: z.string(),
title: z.string().optional(),
Expand Down
65 changes: 65 additions & 0 deletions apps/docs/content/docs/components/text-editor.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,70 @@ import { Editor, ImagePickerContextProvider } from "@frontlit/text-editor";
paragraphs, and links. Without one it falls back to plain semantic HTML tags. It is structurally typed against
that small theme shape instead of importing `@frontlit/page-builder`, so this package stays usable on its own.

## Pluggable blocks

Type `/` in the editor to insert a block; the menu filters as you type. Hover a block to drag it by its
handle, and open a block's settings from the gear on its bar. From the keyboard, Ctrl/⌘+Shift+↑/↓ moves the
block at the cursor, Alt+F10 jumps to its controls and Escape returns to its text. In a table, a bar
above it inserts and deletes rows and columns; Alt+F10 reaches it too.

A **profile** lists what a document can hold: base nodes and marks, blocks and size limits. One profile
builds the editor, the renderer, a Markdown parser and serializer, a validator and a format reference.
`profile` also accepts `"default"` and `"documentation"`.

```ts
// Server-safe: no React. Use it in your API to validate writes.
import {
defineProfile,
image,
video,
audio,
embed,
callout,
parseMarkdown,
validateContent,
} from "@frontlit/text-editor/blocks";

export const lessonProfile = defineProfile({
base: { exclude: ["table"], headings: { levels: [2, 3, 4] } },
blocks: [image({ hosts: ["images.unsplash.com"], media: true }), video(), audio(), embed(), callout()],
});

const content = parseMarkdown(lessonProfile, markdown); // throws ContentError with diagnostics
const result = validateContent(lessonProfile, next, {
previous: stored,
unavailable: { embed: "plan_required" },
});
```

The block library (off unless listed) has Image, Video, Audio, PDF, File, Embed, Callout, Tabs, Accordion,
Steps, Button, Web preview and H5P. Media blocks store a media ID; the package never fetches media. Supply a
picker in the editor and URLs in the renderer:

```tsx
import { Editor, MediaPickerContextProvider, TextRenderer } from "@frontlit/text-editor";

<MediaPickerContextProvider pickMedia={async ({ kind }) => openMediaLibrary(kind)}>
<Editor
profile={lessonProfile}
unavailable={{ embed: "Upgrade to add embeds" }}
onChange={save}
/>
</MediaPickerContextProvider>;

<TextRenderer profile={lessonProfile} json={content} resolveMedia={(id) => mediaUrls[id]} />;
```

`unavailable` greys a block out in the menus with its reason; `validateContent` refuses only an increase
in its count over the stored version, so existing ones keep working. Embeds run only in a sandboxed
`srcdoc` frame without `allow-same-origin`; H5P loads only from allowed hosts (`h5p({ hosts })`, default
h5p.org and \*.h5p.com).

For AI agents, `contentFormat()` and `describeContentFormat()` (from `@frontlit/text-editor/docs`) describe
the Markdown that the FrontLit API and MCP accept: every block with its props and an example. The same
reference is published at `https://frontlit.app/schema/content.v1.json`. See the package README for writing your own blocks
(`BlockSchema` and `BlockUi`) and host renderers (`TextRenderer blocks={{ quiz: LearnerQuiz }}`).

## What's inside

- `Editor` — the WYSIWYG editing surface (toolbar, bubble menu, tables, code blocks with syntax highlighting,
Expand All @@ -130,3 +194,4 @@ that small theme shape instead of importing `@frontlit/page-builder`, so this pa
- `emptyDoc`, `createExtensions`, `createId`, `extractHeadings`, `extractTextFromNode` — lower-level building
blocks, exported for advanced use.
- `ImagePickerContextProvider` — optional hook so a host can supply its own image-upload UI.
- `defineProfile`, the block library and `MediaPickerContextProvider` — see [Pluggable blocks](#pluggable-blocks).
Loading
Loading