Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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-stable-host-blocks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@frontlit/text-editor": patch
---

`ContentRenderer` keeps host-rendered blocks mounted across re-renders, so a block with its own state (a quiz's answers and result, a playing video) no longer resets when the page around it re-renders. Host blocks also get the same vertical spacing as the library's blocks, so two of them in a row no longer touch. Small block buttons in the editor (such as the Video block's "Use") no longer wrap.
5 changes: 5 additions & 0 deletions packages/text-editor/src/prose.css
Original file line number Diff line number Diff line change
Expand Up @@ -860,6 +860,11 @@
margin: 1rem 0;
}

/* Blocks the host renders get the same spacing as the library's own. */
.tiptap-renderer .te-host-block {
margin: 1rem 0;
}

.te-media__caption {
margin-top: 0.5rem;
color: var(--muted-foreground);
Expand Down
2 changes: 1 addition & 1 deletion packages/text-editor/src/ui/block-frame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import type { PickMedia } from "./media-picker";
export const inputClass =
"h-7 min-w-0 rounded border border-input bg-card px-2 text-xs text-foreground placeholder:text-muted-foreground";
export const smallButton =
"inline-flex h-7 items-center gap-1 rounded px-2 text-xs text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-40";
"inline-flex h-7 shrink-0 items-center gap-1 whitespace-nowrap rounded px-2 text-xs text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-40";

export const paragraph = (text = ""): JSONContent =>
text
Expand Down
49 changes: 42 additions & 7 deletions packages/text-editor/src/ui/renderer.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import React from "react";
import { renderToReactElement } from "@tiptap/static-renderer";
import {
applyStaticEditorOptionsToExtensions,
domOutputSpecToReactElement,
renderToElement,
TiptapStaticRenderer,
} from "@tiptap/static-renderer";
import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
import { extractTextFromNode } from "../extract-text-from-node";
import emptyDoc from "../empty-doc";
Expand Down Expand Up @@ -69,6 +74,30 @@ const extensionsFor = (profile: Profile) => {
return extensions;
};

const DEFINED_TYPES = {
doc: ({ children }: { children?: React.ReactNode }) => <>{children}</>,
text: ({ node }: { node: { text?: string } }) => node.text ?? "",
};

/**
* Tiptap's React renderer mounts each node mapping as a component. Our
* mappings (and Tiptap's own `doc` one) are new functions on every render, so
* React would unmount and remount the whole page each time the host
* re-renders: a quiz would lose its answers and a video would reload. Calling
* the mappings as plain functions instead leaves only stable element types
* (`p`, `figure`, the host's block components) in the tree.
*/
function renderMappingsInline(options: Parameters<typeof TiptapStaticRenderer>[1]) {
let key = 0;
return TiptapStaticRenderer(({ component, props }: any) => {
const output = component(props) as React.ReactNode;
const k = key++;
if (React.isValidElement(output)) return React.cloneElement(output, { key: k });
if (Array.isArray(output)) return <React.Fragment key={k}>{output}</React.Fragment>;
return output;
}, options);
}

/** Built-in renderers for library blocks the profile holds. */
export function libraryRenderers(profile: Profile, resolveMedia?: ResolveMedia) {
const all: Record<string, unknown> = {
Expand Down Expand Up @@ -114,20 +143,26 @@ export function ContentRenderer({
headingIds.set(node, headings[headingIndex++].id);
});
}
// Host blocks sit in a wrapper that gives them the library blocks' spacing.
const hosted = Object.fromEntries(
Object.entries(blocks ?? {}).map(([name, Component]) => [
name,
({ node, children }: { node: ProseMirrorNode; children?: React.ReactNode }) => (
<Component node={node} attrs={node.attrs} resolveMedia={resolveMedia}>
{children}
</Component>
<div className="te-host-block" data-block={name}>
<Component node={node} attrs={node.attrs} resolveMedia={resolveMedia}>
{children}
</Component>
</div>
),
]),
);

const rendered = renderToReactElement({
extensions,
content: renderContent,
const rendered = renderToElement({
renderer: renderMappingsInline as any,
domOutputSpecToElement: domOutputSpecToReactElement,
mapDefinedTypes: DEFINED_TYPES as any,
extensions: applyStaticEditorOptionsToExtensions(extensions, undefined),
content: renderContent as any,
options: {
nodeMapping: {
paragraph: ({ children }) => {
Expand Down
66 changes: 66 additions & 0 deletions packages/text-editor/src/ui/ui.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -454,3 +454,69 @@ describe("table bar", () => {
expect(single.find((action) => action.id === "deleteColumn")?.disabled).toBe(true);
});
});

describe("renderer stability", () => {
// React keeps a component mounted only while its element type and key
// stay the same at the same place. Compare two renders of the same json.
type Shape = { type: unknown; key: unknown; children: Shape[] };
const shape = (node: unknown): Shape[] => {
if (Array.isArray(node)) return node.flatMap(shape);
if (!React.isValidElement(node)) return [];
const props = node.props as { children?: unknown };
return [{ type: node.type, key: node.key, children: shape(props.children) }];
};
const same = (a: Shape[], b: Shape[]): boolean =>
a.length === b.length &&
a.every(
(item, i) =>
item.type === b[i].type &&
item.key === b[i].key &&
same(item.children, b[i].children),
);
const Counter = ({ children }: { children?: React.ReactNode }) =>
React.createElement("section", null, children);
const content = doc(
{ type: "paragraph", content: [{ type: "text", text: "Intro" }] },
{ type: "callout", attrs: { type: "tip" }, content: [{ type: "paragraph" }] },
{ type: "video", attrs: { provider: "youtube", videoId: "dQw4w9WgXcQ" } },
{
type: "bulletList",
content: [{ type: "listItem", content: [{ type: "paragraph" }] }],
},
);
const element = (resolveMedia: () => undefined) =>
(ContentRenderer as (props: object) => React.ReactNode)({
profile: lesson,
json: content,
blocks: { callout: Counter },
resolveMedia,
});

it("keeps every element type and key across renders, so host blocks keep their state", () => {
const first = shape(element(() => undefined));
const second = shape(element(() => undefined));
expect(first.length).toBeGreaterThan(0);
expect(same(first, second)).toBe(true);
const types = (items: Shape[]): unknown[] =>
items.flatMap((item) => [item.type, ...types(item.children)]);
expect(types(first)).toContain(Counter);
});

it("still renders changed content", () => {
const changed = renderToStaticMarkup(
React.createElement(ContentRenderer, {
profile: lesson,
json: doc({
type: "paragraph",
content: [{ type: "text", text: "Changed" }],
}) as never,
}),
);
expect(changed).toContain("Changed");
});

it("spaces host blocks like the library's blocks", () => {
const html = render(content, { blocks: { callout: Counter } });
expect(html).toContain('<div class="te-host-block" data-block="callout"><section>');
});
});
Loading