@haklex/rich-compose

中文文档
0.66.0发布于 2026/11/15MITTypeScriptES Module构建来源已验证近 30 天下载 1.3万

Compose primitives for haklex rich content renderers — Gundam-style assembly of Lexical nodes, sync/lazy renderers, and Provider stacks.

原始使用文档
文档目录21 节
  1. Why
  2. Installation
  3. Peer Dependencies
  4. Quick start
  5. Read-only renderer
  6. Editor
  7. Optional renderer virtualization
  8. Three consumer modes
  9. Mode A — defaults
  10. Mode B — custom renderer (tree-shake the default)
  11. Mode C — wrap the default
  12. Module shapes
  13. Dedup rules
  14. Lazy modules
  15. Platform-agnostic rendering
  16. Module catalog
  17. Sub-path exports
  18. CSS strategy
  19. Why not auto-injected via import side effects
  20. Part of Haklex
  21. License

@haklex/rich-compose

Compose primitives for haklex rich content — Gundam-style assembly of Lexical nodes, sync/lazy renderers, edit-side decorators, and Provider stacks. Powers both composeRenderer (read-only) and composeEditor (editable).

Why

The legacy @haklex/rich-kit-shiro/renderer (now removed) shipped every default renderer eagerly: overriding CodeBlock or LinkCard left the original shiki and LinkCardRenderer chains in the bundle. rich-compose solves three problems at once:

  1. Subtractable — drop a module by not importing it.
  2. Replaceable — swap a default renderer with no leftover bytes.
  3. Extensible — add new renderer slots (sync or lazy) without touching the package.

Tree-shake is enforced by physical subpath isolation (./modules/<name>/node separates Klasses from heavy renderer code; ./modules/<name> vs ./modules/<name>/edit separates static-only from editor-only chains) plus ESM-only emit.

Installation

pnpm add @haklex/rich-compose

Peer Dependencies

PackageVersion
react / react-dom>=19
lexical / @lexical/react^0.45.0
@haklex/rich-editorworkspace

Per-module upstream packages (@haklex/rich-ext-*, @haklex/rich-renderer-*) are optional peers — install only those you compose.

Quick start

Read-only renderer

import { composeRenderer } from '@haklex/rich-compose/core';
import { allRendererModules } from '@haklex/rich-compose/renderer';

const RichContent = composeRenderer({ modules: allRendererModules });

// Render
<RichContent value={editorState} theme="light" variant="article" />;

Or cherry-pick:

import { composeRenderer } from '@haklex/rich-compose/core';
import { embedModule } from '@haklex/rich-compose/modules/embed';
import { codeBlockModule } from '@haklex/rich-compose/modules/code-block';

const RichContent = composeRenderer({ modules: [embedModule, codeBlockModule] });

Editor

import { composeEditor } from '@haklex/rich-compose';
import { allEditorModules } from '@haklex/rich-compose/editor';

const RichEditor = composeEditor({ modules: allEditorModules });

// Use like @haklex/rich-editor's RichEditor — accepts the same props plus children for plugins.
<RichEditor initialValue={state} onChange={setState} variant="article" />;

Both helpers return memoized React components. composeEditor internally wires composeRenderer for nested editor states.

Optional renderer virtualization

Rendering remains complete by default. Enable the recycler with props:

const scrollRef = useRef<HTMLDivElement>(null);
const virtualization = useMemo(() => ({ scrollContainer: scrollRef, preserveCapacity: 32 }), []);

<ScrollArea scrollRef={scrollRef}>
  <RichContent value={editorState} virtualization={virtualization} />
</ScrollArea>;

The viewport must have a bounded height. scrollContainer accepts its DOM element, a ref, or a getter; it must contain the rendered content. Without it, the recycler finds the nearest scrolling ancestor, then uses the window.

Alternatively, install the implementation as a compose module:

import { rendererVirtualizationModule } from '@haklex/rich-compose/virtualization';

const RichContent = composeRenderer({
  modules: [...allRendererModules, rendererVirtualizationModule({ preserveCapacity: 32 })],
});

An explicit virtualization={false} overrides an installed module. The module supplies a rendering surface; it does not turn on a second full-document renderer. Nested renderers keep their ordinary surface unless explicitly enabled.

The editor and renderer share typed recycling pools, measured margin collapse, and the keep-mounted manager. Up to 32 offscreen mounts are retained by default; LRU eviction saves details/dynamic state before reusing an instance. Set preserveCapacity: 0 for immediate state restoration. Dynamic components need getState/setState to survive eviction; custom components can use useEditorBlock().nodeState() and retain().

Heading anchors and footnote numbering are prepared from the complete document, while React trees are created only for rendered windows. Opt-in virtual SSR emits a bounded initial window; default SSR stays complete. Float images and the flowing text through their clearing block remain one native flow unit, as does the note lead paragraph with its next block. A very large flow unit or single table is not virtualized internally. Initial parsing and document replacement still scale with document size. Changing the document, variant, or recycler options rebuilds the transient view cache. Native selection/copy across unmounted content and browser find-in-page remain limited to mounted windows.

The demo's 20,000 Complex Nodes preset supports both Edit and Render. Both use the UI ScrollArea viewport explicitly, with a fixed inspector beside it. Rendering and editing share the same article width and horizontal spacing.

Three consumer modes

Mode A — defaults

Import the module sugar. Klass + renderer + (optional) lazy/SSR fallback are wired automatically.

import { embedModule } from '@haklex/rich-compose/modules/embed';
import { embedEditModule } from '@haklex/rich-compose/modules/embed/edit';

Mode B — custom renderer (tree-shake the default)

Import the Klass from /node; supply your own renderer.

import { GalleryNode } from '@haklex/rich-compose/modules/gallery/node';

const myGalleryModule: RichRendererModule = {
  name: 'gallery',
  nodes: [GalleryNode],
  renderers: { Gallery: MyGalleryRenderer },
};

For renderer-only modules (no custom Klass), construct with matching name:

const myLinkCardModule: RichRendererModule = {
  name: 'link-card',
  renderers: { LinkCard: MyLinkCardRenderer },
};

Mode C — wrap the default

Pull the default renderer from /renderer and wrap.

import { LinkCardRenderer } from '@haklex/rich-compose/modules/link-card/renderer';

const wrappedModule: RichRendererModule = {
  name: 'link-card',
  renderers: {
    LinkCard: (props) => (
      <div className="extra-wrap">
        <LinkCardRenderer {...props} />
      </div>
    ),
  },
};

Module shapes

RichRendererModule (read-only) and RichEditorModule (editor superset).

interface RichRendererModule {
  name: string; // dedup key
  nodes?: Klass<LexicalNode>[]; // base Klasses
  renderers?: Partial<RendererConfig>; // sync renderer map
  Provider?: ComponentType<{ children: ReactNode }>; // shared provider
  lazyRenderers?: Partial<{
    [K in RendererKey]: () => Promise<{ default: NonNullable<RendererConfig[K]> }>;
  }>;
  ssrFallback?: Partial<Record<RendererKey, ReactNode>>;
}

interface RichEditorModule extends RichRendererModule {
  editNodes?: Klass<LexicalNode>[]; // edit-side subclasses (override base by getType)
  editRenderers?: Partial<RendererConfig>; // override renderers in editor mode
  EditorProvider?: ComponentType<{ children: ReactNode }>; // editor-only provider
  plugins?: ReactNode; // module-owned editor plugins
  nestedEditorPlugins?: ReactNode; // plugins mounted inside LexicalNestedComposer surfaces
  actions?: ReactNode; // module-owned action UI
}

composeRenderer consumes RichRendererModule[]; composeEditor consumes RichEditorModule[]. Each editor module spreads its renderer-only counterpart, so allEditorModules is a strict superset of allRendererModules.

Dedup rules

modules:
  reference seen   → skip silently
  same name        → warn (dev), replace previous module entirely
  else             → append

nodes:
  reference seen          → skip
  subclass override       → edit Klass replaces base Klass (same getType, A extends B)
  unrelated collision     → throw at compose time
                            (would break instanceof across module boundaries)

Lazy modules

code-block and mermaid ship lazy by default with deterministic ssrFallbacks. whiteboard's Klass code-splits internally via its own decorate().

To override a lazy renderer (e.g., pre-tokenized code block for SSR), pass overrides:

composeRenderer({
  modules: allRendererModules,
  overrides: { CodeBlock: PreTokenizedCodeBlock },
});

The lazy chunk is still emitted but never fetched at runtime.

Platform-agnostic rendering

RichRenderer (and composeRenderer) emit DOM by default, but every DOM touchpoint is injectable so the same tree walk can target another React renderer (React Native, ink, a test harness):

HookCovers
builtinNodeOverrides[type]Element nodes (paragraph, heading, list, …) and decorator nodes (image, mermaid, …)
builtinNodeOverrides.textText leaves — receives the serialized text node (text, format, style)
blockAnchor(el, blockId, key)Root-level block wrapper carrying $.blockId; defaults to a data-block-id div
asHost container — any ElementType; non-string hosts receive only style and children

A decorator override receives the default decoration as its single child and may drop it:

<RichRenderer
  as={View}
  blockAnchor={(el, blockId, key) => (
    <View key={key} nativeID={blockId}>
      {el}
    </View>
  )}
  builtinNodeOverrides={{
    text: (node, key) => (
      <Text key={key} style={textStyle(node.format)}>
        {node.text}
      </Text>
    ),
    paragraph: (_node, key, children) => <Text key={key}>{children}</Text>,
    mermaid: (node, key) => <NativeMermaid key={key} diagram={node.diagram} />,
  }}
  value={state}
/>

Decorator slots (rendererConfig / module renderers) accept any React component, so Image, CodeBlock, LinkCard etc. can be replaced the same way.

Module catalog

ModuleBase KlassEdit KlassModeSource
alertbuiltin—syncrich-renderer-alert
bannerbuiltin—syncrich-renderer-banner
chartChartNodeChartEditNodesyncrich-ext-chart
chatChatNodeChatEditNodesyncrich-ext-chat
code-blockbuiltin—lazy + ssr fallbackrich-renderer-codeblock
code-snippetCodeSnippetNodeCodeSnippetEditNodesyncrich-ext-code-snippet
embedEmbedNodeEmbedEditNodesync (via node decorate)rich-ext-embed
whiteboardWhiteboardNodeWhiteboardEditNodevia node decoraterich-ext-whiteboard
galleryGalleryNodeGalleryEditNodesyncrich-ext-gallery
imagebuiltin—syncrich-renderer-image
katex—builtinedit-only (no static renderer)rich-renderer-katex
link-cardbuiltin—syncrich-renderer-linkcard
mentionbuiltin—syncrich-renderer-mention
mermaidbuiltin—lazy + ssr fallbackrich-renderer-mermaid
nested-docNestedDocNodeNestedDocEditNoderecursive (via composeRenderer)rich-ext-nested-doc
pollPollNodePollEditNodesyncrich-ext-poll
rubybuiltin—syncrich-renderer-ruby
videobuiltin—syncrich-renderer-video

katex ships only an edit module — KaTeX rendering for the read-only side is wired by the host renderer via decorate().

Sub-path exports

PathDescription
@haklex/rich-composecompatibility barrel: core helpers plus aggregate conveniences
@haklex/rich-compose/corerenderer composition core: composeRenderer, RichRenderer, renderer types
@haklex/rich-compose/rendereraggregate barrel — every renderer module + allRendererModules
@haklex/rich-compose/editoraggregate barrel — every editor module + allEditorModules
@haklex/rich-compose/modules/<name>renderer-side module barrel
@haklex/rich-compose/modules/<name>/editeditor-side module (extends the renderer module)
@haklex/rich-compose/modules/<name>/nodeKlass(es) only (when applicable)
@haklex/rich-compose/modules/<name>/rendererdefault renderer only
@haklex/rich-compose/style.cssall-in-one CSS bundle — prose body + tokens + every module
@haklex/rich-compose/style/foundation.cssprose body + theme tokens + variant classes (no modules)
@haklex/rich-compose/style/table.cssbuilt-in table renderer
@haklex/rich-compose/style/<name>.cssper-module CSS (alert, banner, image, video, …)

Aggregate barrels are convenient defaults; the fine-grained /modules/<name> and /modules/<name>/edit subpaths stay available for dynamic-import and selective inclusion.

CSS strategy

Two consumer patterns:

All-in-one (default). One import covers everything rich-compose can render:

import '@haklex/rich-compose/style.css';

Fine-grained (advanced). Use this when you've overridden one or more default renderers and want to drop their CSS from your bundle. Import foundation.css plus the modules you keep — never reach into rich-renderer-* or rich-ext-* packages directly:

import '@haklex/rich-compose/style/foundation.css';
import '@haklex/rich-compose/style/alert.css';
import '@haklex/rich-compose/style/image.css';
import '@haklex/rich-compose/style/ruby.css';
// …only modules whose default renderer you kept

Module subpaths mirror the JS module subpaths (modules/<name> ↔ style/<name>.css).

Why not auto-injected via import side effects

Earlier versions tried to side-effect-import each module's CSS from inside modules/<name>/index.ts. Combined with sideEffects: ["**/*.css"] (which marks .mjs files as side-effect-free) and bundler optimizations such as Next.js optimizePackageImports, those bare CSS imports were tree-shaken away — modules rendered but their styling was missing. The explicit subpath model above eliminates that footgun: the consumer states which CSS they want, and the bundler honors it deterministically.

Part of Haklex

This package is part of the Haklex rich editor ecosystem.

License

MIT

版本与发布记录

@haklex/rich-compose 共发布 127 个版本,首次发布于 2026/05/08;过去 12 个月发布了 127 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.66.0latest2026/11/151 天前
0.65.72026/11/143 天前
0.65.62026/11/124 天前
0.65.52026/11/124 天前
0.65.42026/11/124 天前
0.65.32026/11/124 天前

关于 @haklex/rich-compose 的常见问题

@haklex/rich-compose 是什么?

Compose primitives for haklex rich content renderers — Gundam-style assembly of Lexical nodes, sync/lazy renderers, and Provider stacks.

如何安装 @haklex/rich-compose?

在项目目录运行 npm install @haklex/rich-compose,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=19)、lexical(^0.53.0)、react-dom(>=19)、lucide-react(^1.0.0)、@lexical/react(^0.53.0)、@haklex/rich-editor(^0.66.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@haklex/rich-compose 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@haklex/rich-compose 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@haklex/rich-compose 可以商用吗?

@haklex/rich-compose 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@haklex/rich-compose 的下载量有多少?

根据 npm 官方下载统计,@haklex/rich-compose 在 2026/10/17 – 2026/11/15 这 30 天内被下载 13,085 次,日均约 436 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@haklex/rich-compose 还在维护吗?

最新版本 0.66.0 发布于 2026/11/15(1 天前);至今共发布 127 个版本,其中过去 12 个月发布了 127 个;首次发布于 2026/05/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。