Skip to content

feat(lab): add imperative ref API to RichTextEditor - #4417

Merged
potatowagon merged 6 commits into
meta:mainfrom
potatowagon:navi/feat/richtext-ref-api
Jul 29, 2026
Merged

potatowagon merged 6 commits into
meta:mainfrom
potatowagon:navi/feat/richtext-ref-api

Conversation

@potatowagon

@potatowagon potatowagon commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

What

Adds an imperative ref API to the experimental RichTextEditor (@astryxdesign/lab) via a new RichTextEditorRef handle:

  • focus() — move focus into the editable surface
  • clear() — empty the content (reset to a single empty paragraph)
  • getEditorState() — read the current EditorState
  • getEditor() — access the underlying LexicalEditor for advanced use

Why

Today the only way to imperatively drive the editor (focus it, clear it, read its state, reach the Lexical instance) is to write a custom plugin that calls useLexicalComposerContext() and pass it via the plugins slot. That's boilerplate for common operations. This exposes a first-class ref, matching the ergonomics consumers expect from other Astryx inputs.

One of the general-purpose gaps identified for EPS RichTextArea → Astryx RichTextEditor parity (EPS ships focus/clear/getEditorState/getEditor on its ref). Low-risk and additive.

How

The LexicalEditor instance only exists inside the LexicalComposer, so the handle can't be wired from the outer component directly. A small internal EditorRefBridge plugin (rendered inside the composer) reads the editor via useLexicalComposerContext() and connects it to the outer ref with useImperativeHandle — the same pattern as the existing AutoFocusOnMount plugin.

  • Component wrapped in forwardRef<RichTextEditorRef, RichTextEditorProps>.
  • clear() uses editor.update(() => $getRoot().clear()).

Docs / exports / tests (SYNC contract)

  • Exported RichTextEditorRef from RichTextEditor/index.ts and the @astryxdesign/lab barrel.
  • Updated the component JSDoc example to show ref usage; added a doc.mjs best-practice note.
  • Added 6 unit tests (handle shape after mount, focus wiring, getEditorState, getEditor, clear).

Testing

  • pnpm -F @astryxdesign/lab typecheck — clean
  • eslint on changed files — clean
  • vitest run RichTextEditor.test.tsx — 21/21 passing (incl. 6 new)

human test

Screen.Recording.2026-07-27.at.4.47.35.PM.mov

Notes

  • The focus() test asserts the call is wired + the root element is reachable rather than jsdom document.activeElement, because jsdom does not reliably reflect programmatic contenteditable focus (same limitation the existing autofocus path has).
  • Independent of feat(lab): expose transformers prop on RichTextEditor #4416 (transformers) — different surface, no file overlap; both branch off main.

@vercel

vercel Bot commented Jul 27, 2026

Copy link
Copy Markdown

Deployment failed with the following error:

You don't have permission to create a Preview Deployment for this Vercel project: astryx.

View Documentation: https://vercel.com/docs/accounts/team-members-and-roles

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 27, 2026
@github-actions github-actions Bot added community Authored by a community contributor (not on the eng/design team) needs:code-review High-risk change (new package/component/API) — needs human code review before merge labels Jul 27, 2026
@github-actions

github-actions Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

PR Analysis Report

No new or modified components detected.

Bundle Size Summary

Package Size (ESM) Size (CJS) Gzipped
@astryxdesign/core N/A 4.7KB 0B

Accessibility Audit

Status: No accessibility violations detected.


Generated by PR Enrichment workflow | View full report

@nynexman4464 nynexman4464 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve with nits. forwardRef correct, handle memoized on [editor], type exported from component index + lab barrel. Good coverage + story.

  • Resolve or acknowledge before landing: clear() calls $getRoot().clear(), leaving zero children, but docs say "single empty paragraph." Use $getRoot().clear(); $getRoot().append($createParagraphNode()) + assert getChildrenSize() === 1.
  • clear()/focus() aren't gated on isReadOnly/isDisabled.
  • No test asserts clear() fires onChange.

— Reviewed with Navi on behalf of Alex Rock

@github-actions github-actions Bot removed the needs:code-review High-risk change (new package/component/API) — needs human code review before merge label Jul 27, 2026
@potatowagon

Copy link
Copy Markdown
Contributor Author

Thanks for the review! All three nits addressed in 05f3e57:

  1. clear() now leaves a single empty paragraph. Changed to $getRoot().clear(); $getRoot().append($createParagraphNode()), matching the documented behaviour. Added a test asserting getChildrenSize() === 1 after clear.
  2. clear()/focus() are gated on editability. Both no-op when isReadOnly or isDisabled (bridge now takes an editable prop). Added read-only + disabled no-op tests.
  3. Added a test asserting clear() fires onChange.

Also synced the JSDoc + doc.mjs per the file's SYNC block. pnpm test (24 passing), typecheck, and lint all green.

@potatowagon
potatowagon force-pushed the navi/feat/richtext-ref-api branch 3 times, most recently from 0c69f8b to 7a2ffc0 Compare July 29, 2026 02:42
Exposes a `RichTextEditorRef` via `forwardRef` with focus(), clear(),
getEditorState(), and getEditor() — so callers can drive the editor without
wiring a custom plugin.

The Lexical editor instance only exists inside the LexicalComposer, so the
handle is wired by a small internal EditorRefBridge plugin that reads the
editor via useLexicalComposerContext() and connects it to the outer ref with
useImperativeHandle (same pattern as the existing AutoFocusOnMount plugin).

- New RichTextEditorRef type, exported from index.ts + lab barrel
- Updated JSDoc example + doc.mjs best-practice note
- Added 6 unit tests (handle shape, focus, getEditorState, getEditor, clear)
Interactive story demonstrating the new ref handle — buttons wired to focus(),
clear(), getEditorState() (prints text content), and getEditor(). Gives
reviewers a live demo of the imperative API.
- clear() now resets to a single empty paragraph (root.clear() + append
  $createParagraphNode()) instead of leaving a childless root, matching the
  documented single empty paragraph behaviour
- focus() and clear() are gated on editability — no-op when isReadOnly or
  isDisabled, so the imperative handle cannot mutate/focus a locked editor
- add tests: clear() leaves getChildrenSize() === 1, clear() fires onChange,
  clear()/focus() are no-ops when read-only/disabled
- sync JSDoc + doc.mjs with the read-only gating and single-paragraph reset
The @astryxdesign `source` resolve rule cascades into how those packages
resolve their own imports, so @astryxdesign/lab resolved `import 'lexical'`
with the `source` condition — pulling lexical's raw `src/*.ts` (which Next's
Babel can't compile: `declare` class fields), failing the build-sandbox job.

Add a higher-precedence webpack rule that forces lexical + @lexical/* to their
default (built dist) conditions regardless of importer. Add next.test.mjs
regression test asserting the rule shape, precedence, and non-overlap with the
@astryxdesign source rule.
The previous approach (a webpack module.rule keyed on the lexical resource) did
NOT work: a rule's resolve.conditionNames govern how the MATCHED module resolves
its own imports, so when @astryxdesign/lab imports 'lexical' the resolution runs
in lab's context (source condition) and picks lexical's raw-TS source export —
the rule keyed on the lexical resource never gets a chance to override it.
Verified in Next's bundled webpack: lexical still resolved to src/*.ts.

Restore the global 'source' condition (so @astryxdesign builds from source as
on main) and pin lexical + every @lexical/* package — including every exports
subpath — to its prebuilt dist via exact-match resolve.alias entries, resolved
through Node's own resolver (ignores the webpack-only 'source' convention and
honors exports-map renames like ReactProviderExtension -> LexicalReactProvider
Extension). Aliases win over condition resolution regardless of issuer.

Verified end-to-end: RichTextEditor's full lexical import graph (56 modules)
resolves entirely to dist with no build errors. Rewrote next.test.mjs (7 tests).
@potatowagon

Copy link
Copy Markdown
Contributor Author

Update on the build-sandbox failure (commit 329324a):

My first attempt (a webpack module.rule keyed on the lexical resource) did not actually work — I reproduced the build in Next's bundled webpack and confirmed lexical still resolved to raw src/*.ts. Root cause: a rule's resolve.conditionNames govern how the matched module resolves its own imports, so when @astryxdesign/lab imports lexical the resolution runs in lab's context (the global source condition) and picks lexical's raw-TS source export. A rule keyed on the lexical resource never gets a chance to override that.

Actual fix: keep the global source condition (so @astryxdesign/* still builds from source, same as main), and pin lexical + every installed @lexical/* package — including every exports subpath — to its prebuilt dist file via exact-match resolve.alias entries. Aliases are resolved through Node's own resolver (which ignores the webpack-only source convention and honors exports-map renames like ./ReactProviderExtension → dist/LexicalReactProviderExtension.mjs), and win over export-condition resolution regardless of which package issued the import.

Verified end-to-end in Next's actual bundled webpack: the RichTextEditor's full lexical import graph (56 modules) resolves entirely to dist with no build errors. Added a 7-test next.test.mjs regression guard. Also restored the @potatowagon credit line the changeset lost in a rebase.

The imperative clear() used $getRoot/$createParagraphNode imported from the
top-level 'lexical' package. In the sandbox's Next build a top-level 'lexical'
value import forces Babel to transpile lexical's raw src/*.ts (which uses
'declare' class fields) and fails build-sandbox. Same class of issue fixed for
the char counter in the sibling maxLength PR.

Reset via editor.setEditorState(editor.parseEditorState(EMPTY_STATE)) instead —
both are editor-instance methods, so no top-level 'lexical' value import is
needed. Still resets to a single empty paragraph and notifies update listeners
(onChange fires). Only the erased 'import type' from 'lexical' remains.

Reverts the earlier withAstryx/next.js changes (and their test + changeset):
that build-config approach was wrong — the sibling PR proves the scoped-rule
next.js on main builds lexical fine once the component avoids the bare-lexical
value import. next.js is restored to the baseline.
@potatowagon

Copy link
Copy Markdown
Contributor Author

Correction + real fix (commit fb041dd):

My earlier withAstryx/next.js changes were the wrong approach — I've fully reverted them (and their test + changeset); next.js is back to the baseline. Comparing against the passing sibling PR #4502 (feat(lab): add maxLength character counter) made the real cause obvious: it fixes the identical build-sandbox failure in the component, not in the build config.

Root cause: the imperative clear() used $getRoot / $createParagraphNode imported from the top-level lexical package — a runtime value import. When the sandbox's Next build resolves @astryxdesign/lab's built dist, a top-level lexical value import forces Babel to transpile lexical's raw src/*.ts (which uses declare class fields) and fails. @lexical/* subpath value imports are fine — only the bare lexical value import leaks.

Fix: clear() now resets via editor.setEditorState(editor.parseEditorState(EMPTY_STATE)) — both editor-instance methods, so no top-level lexical value import is needed. It still resets to a single empty paragraph and fires onChange. Only the compile-time-erased import type { … } from 'lexical' remains.

Verified: built @astryxdesign/lab dist has zero bare-lexical value imports (only @lexical/* subpaths); all 31 RichTextEditor tests pass; lab typecheck + lint clean.

@potatowagon
potatowagon merged commit 68f5654 into meta:main Jul 29, 2026
17 of 18 checks passed
potatowagon added a commit to potatowagon/astryx that referenced this pull request Jul 30, 2026
Adds `getMarkdown()` to the RichTextEditorRef handle. Serializes the current
content to a Markdown string via $convertToMarkdownString, run inside a read
context.

Honors the same `transformers` the editor is configured with (the prop added
in meta#4416), so custom transformers round-trip to Markdown — mirroring the
Lexical playground, where one transformer array feeds shortcut typing, import,
and export. The bridge now receives the memoized transformers array.

`@lexical/markdown` is a subpackage (built dist), so this adds no top-level
`lexical` value import — keeping the sandbox build safe.

- Extended RichTextEditorRef + EditorRefBridge
- Updated doc.mjs ref best-practice note
- Added getMarkdown() button to the ImperativeRef storybook story
- Added 3 unit tests (plain text, heading with default transformers, and
  custom empty-transformers set proving the prop is honored)

Depends on the merged ref API (meta#4417) and transformers prop (meta#4416).
potatowagon added a commit that referenced this pull request Jul 30, 2026
* feat(lab): add getMarkdown() to RichTextEditor imperative ref

Adds `getMarkdown()` to the RichTextEditorRef handle. Serializes the current
content to a Markdown string via $convertToMarkdownString, run inside a read
context.

Honors the same `transformers` the editor is configured with (the prop added
in #4416), so custom transformers round-trip to Markdown — mirroring the
Lexical playground, where one transformer array feeds shortcut typing, import,
and export. The bridge now receives the memoized transformers array.

`@lexical/markdown` is a subpackage (built dist), so this adds no top-level
`lexical` value import — keeping the sandbox build safe.

- Extended RichTextEditorRef + EditorRefBridge
- Updated doc.mjs ref best-practice note
- Added getMarkdown() button to the ImperativeRef storybook story
- Added 3 unit tests (plain text, heading with default transformers, and
  custom empty-transformers set proving the prop is honored)

Depends on the merged ref API (#4417) and transformers prop (#4416).

* chore: re-trigger CI/Vercel deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot. community Authored by a community contributor (not on the eng/design team)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants