Skip to content

Add React MathType example - #8692

Merged
etrepum merged 10 commits into
meta:mainfrom
culpen90:feature/react-mathtype-example
Aug 31, 2026
Merged

etrepum merged 10 commits into
meta:mainfrom
culpen90:feature/react-mathtype-example

Conversation

@culpen90

@culpen90 culpen90 commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Add a standalone React MathType example under examples/react-mathtype.
  • Store MathType formulas in a custom Lexical node so editor state remains authoritative.
  • Bridge MathType insert/edit callbacks into Lexical updates and document the example setup.

Fixes #7806.

Validation

  • corepack pnpm run typecheck from examples/react-mathtype
  • corepack pnpm run build from examples/react-mathtype
  • corepack pnpm exec prettier --check examples/react-mathtype
  • corepack pnpm exec eslint examples/react-mathtype --no-error-on-unmatched-pattern

@meta-cla

meta-cla Bot commented Jun 13, 2026

Copy link
Copy Markdown

Hi @culpen90!

Thank you for your pull request and welcome to our community.

Action Required

In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

@vercel

vercel Bot commented Jun 13, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lexical Ready Ready Preview Aug 30, 2026 9:48pm
lexical-playground Ready Ready Preview Aug 30, 2026 9:48pm

Request Review

@potatowagon potatowagon 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.

Reviewed by Navi (Tater Thoughts Bobblehead) on behalf of @potatowagon.

Assessment: LGTM (pending CLA)

What this PR does: Adds a standalone examples/react-mathtype/ example showing WIRIS MathType integration with Lexical. Introduces MathTypeNode (DecoratorNode), a React context/provider for integration state, a toolbar plugin, and supporting utilities for MathML encode/decode and DOM import/export.

What I checked:

  1. Code quality & architecture: Well-structured with clear separation of concerns — MathTypeData (pure MathML utilities), MathTypeGlobals (type declarations + window global accessor), MathTypeContext (React state management), MathTypeNode (Lexical node definition), and MathTypePlugin (integration bootstrap). Uses the modern $config() protocol with createState, $getState, $setState, and buildImportMap — follows the latest Lexical patterns from the 0.45.x API.

  2. Correctness:

    • $commitFormula correctly handles both edit (existing nodeKey) and insert (range selection fallback → root append) paths.
    • DOM import uses priority 3 and checks for both .Wirisformula class and data-mathml attribute — good defensive conversion.
    • insertFormula override properly clears temporalImage and pendingNodeKeyRef after commit, preventing stale references.
    • encodeMathML/decodeMathML use WirisPlugin.MathML when available with a manual fallback using Unicode character substitutions — matches WIRIS's established encoding scheme.
  3. Edge cases:

    • parseOptionalNumber guards against NaN, Infinity, and non-positive values.
    • MathTypeFormulaComponent double-click handler is gated on isEditable.
    • Integration cleanup in useEffect properly nulls integrationRef only if it still owns the reference (multi-mount safe).
    • contentEditable={true} on .mathtype-target div is intentional — it's the hidden proxy element that WIRIS requires for its generic integration API.
  4. www compatibility: No concerns — this is a standalone example under examples/, no core library changes, no API surface modifications.

  5. Security: The @wiris/mathtype-generic dependency loads from npm (^8.15.2). The example is self-contained; no new deps added to the core library. The MathML encode/decode uses character substitution (not eval/innerHTML injection).

  6. CI status: Vercel previews pass, CLA is failing (first-time contributor needs to sign). No unit/integration/browser tests triggered since this is example-only.

Minor observations (non-blocking):

  • The declare module '@wiris/mathtype-generic' in vite-env.d.ts is a minimal type stub — fine for an example, but contributors could later add a proper .d.ts if the example grows.
  • No test files included, which is consistent with other standalone examples in the repo.

Verdict: Clean, well-typed MathType example that follows established Lexical patterns. Ready to approve once CLA is signed.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Jun 13, 2026
@meta-cla

meta-cla Bot commented Jun 13, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

@etrepum etrepum left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I'd recommend refactoring this for extensions so it can take advantage of newer features

claude added 2 commits August 30, 2026 18:44
…y bugs

## Description

Applies the review fixes for the `examples/react-mathtype` example added on
this branch. The example currently reopens a formula the user just cancelled
and then inserts it twice, puts an `aria-hidden` element in the tab order, and
fails `pnpm run ci-check` against current `main`.

Bugs

- A cancelled edit reopened the formula it had just dismissed, and then
  inserted it a second time. `editFormula` sets
  `core.editionProperties.temporalImage`, but only a completed insertion
  cleared it, and `GenericIntegration.openNewFormulaEditor()` takes the
  *existing*-formula branch whenever that property is still set. The
  overridden `openNewFormulaEditor` now clears it before delegating, which is
  enough - the vendor implementation restores `dbclick` and `isNewElement`
  itself once it reaches the new-formula branch. Because the override also
  resets `pendingNodeKey`, the reopened formula was committed as a new node
  rather than replacing the original.
- The offscreen MathType edition target is `aria-hidden` but
  `contentEditable`, so it was focusable and sat in the tab order: keyboard
  users landed on an element hidden from assistive technology. It now carries
  `tabIndex={-1}`.
- `createDOM` and `exportDOM` built elements from the `document` global, which
  is the wrong realm for an editor in an iframe and is undefined when
  `$generateHtmlFromNodes` runs headlessly. They use `$getDocument()`, and
  `createImageFromFormula` now takes the owning `Document`, per the Shadow DOM
  and iframe guidance in AGENTS.md.

Lint

- Removes nine hand-written `/* @__PURE__ */` annotations. They were correct
  when this example was written, but meta#9086 has since moved that injection into
  the build and made hand-written annotations an error under
  `@lexical/internal/no-pure-annotation`, which covers `examples/**`. Merging
  main in is what surfaced them.

Cleanup

- The extension no longer overrides `ReactExtension`'s
  `EditorChildrenComponent` to inject a React context. That config is a single
  last-one-wins slot, so taking it silently breaks any other extension in the
  editor that needs it. The bridge state now lives in the extension's own
  `build`, reached with `useExtensionDependency`, and `MathTypeContext.tsx` is
  gone. `nodes` became a thunk so the resulting import cycle cannot hit a
  temporal dead zone.
- Drops the hand-rolled `encodeMathML`/`decodeMathML` fallbacks that mirrored
  WIRIS' own encoding table. `@wiris/mathtype-generic` is imported at module
  scope, so `window.WirisPlugin` is always installed before these run.
- Extracts `isWirisFormulaImage` instead of repeating the predicate in
  `importDOM` and the conversion function, and checks `nodeName` rather than
  `instanceof HTMLImageElement` so it holds for a node from another realm.
- Replaces the inline ref callbacks, which React re-invoked with `null` and
  then the element on every render, with plain ref objects.
- Moves `editor.focus()` into the update's `onUpdate`; `editor.update()` is
  batched, so focusing straight after it ran before reconciliation.
- Sets the version and lexical dependencies to 0.49.0 to match the monorepo
  and every other example (they were 0.45.0), and adds the
  `@rollup/wasm-node` optionalDependency the other examples carry.

## Test plan

### Before

```
$ node_modules/.bin/eslint --no-warn-ignored examples/react-mathtype/
examples/react-mathtype/src/App.tsx
  30:22  error  Remove this /* @__PURE__ */ annotation: the build injects it
  for every module-scope call to defineExtension  @lexical/internal/no-pure-annotation
examples/react-mathtype/src/MathTypeExtension.tsx
  188:34  error  ... defineExtension  @lexical/internal/no-pure-annotation
  191:5   error  ... configExtension  @lexical/internal/no-pure-annotation
examples/react-mathtype/src/MathTypeNode.tsx
  44:21  error  ... createState  @lexical/internal/no-pure-annotation
  48:18  error  ... createState  @lexical/internal/no-pure-annotation
  52:22  error  ... createState  @lexical/internal/no-pure-annotation
  56:20  error  ... createState  @lexical/internal/no-pure-annotation
  60:21  error  ... createState  @lexical/internal/no-pure-annotation
  64:27  error  ... createState  @lexical/internal/no-pure-annotation

✖ 9 problems (9 errors, 0 warnings)
```

The two runtime bugs, driven in Chromium against the production build with
WIRIS' hosted services stubbed. The first result leaves `temporalImage` set
the way a cancelled edit does and then takes the toolbar's insert-formula
route; the second walks the tab order from the editor:

```
{
  "cancelledEditThenInsert": ["opened EXISTING formula editor"],
  "report": {"targetAriaHidden": "true", "targetTabIndex": null},
  "tabReachesHiddenTarget": true
}
```

### After

```
$ node_modules/.bin/eslint --no-warn-ignored examples/react-mathtype/
$ node_modules/.bin/prettier --check examples/react-mathtype/
Checking formatting...
All matched files use Prettier code style!
$ (cd examples/react-mathtype && pnpm run typecheck)
> tsc --noEmit
$ (cd examples/react-mathtype && pnpm run build)
✓ built in 3.28s
```

Same browser checks, same build, no page errors:

```
{
  "cancelledEditThenInsert": ["opened new formula editor"],
  "errors": [],
  "report": {
    "editorText": "Use the MathType toolbar to insert a formula. ",
    "targetAriaHidden": "true",
    "targetTabIndex": "-1"
  },
  "tabReachesHiddenTarget": false
}
```

Not exercised: the MathType toolbar buttons and the formula dialog itself.
Both need WIRIS' hosted services at `www.wiris.net`, which this sandbox cannot
reach; the checks above stub the configuration request, which is enough to
mount the integration but not to render its UI.

Co-Authored-By: Claude Opus 5 <[email protected]>
## Description

Three defects in the MathType bridge, all in the paths where the dialog closes
without a usable formula.

- Accepting an empty formula threw and left the old formula in place.
  `ContentManager.submitAction()` calls `updateFormula(null)` whenever the
  editor is empty - Accept on a blank new formula, or erasing an existing one
  and accepting - and the Accept button is never disabled. That reached
  `Parser.mathmlToImgObject(doc, null, {})`, which does
  `mathml.indexOf('class="')` and threw a TypeError. It also dropped the
  vendor's semantics for that case: `Core.insertFormula` reads empty MathML as
  "remove the formula" via its `if (!mathml)` branch. The override now removes
  the node being edited, and does nothing when the dialog was inserting.
- The editor never got focus back when the dialog was cancelled. Focus was
  only restored on the insert path, but `ModalDialog.cancelAction()` calls
  `IntegrationModel.setActionsOnCancelButtons()`, which calls
  `currentInstance.getSelection()` - and `GenericIntegration.getSelection()`
  focuses `this.target`, the offscreen `aria-hidden` edition target. Typed
  characters went there instead of the editor. `ModalDialog.close()` fires
  `onModalClose` on `Core.globalListeners` for every close path, so the
  integration now subscribes to that and refocuses the editor. `Listeners` has
  `add` but no `remove`, so teardown splices the array it exposes.
- `mathmlToImgObject` was typed as returning `HTMLImageElement`, but it
  returns null when the `showimage` service rejects malformed MathML, and the
  unguarded `createFormulaFromImage(image, ...)` on the next line dereferenced
  it. The declaration hid that from the compiler; it is now
  `HTMLImageElement | null` and the call site leaves the document alone when
  the service rejects the MathML.

Verified against `@wiris/[email protected]` and
`@wiris/[email protected]`: `contentmanager.js:429`,
`core.src.js:368`, `parser.js:54` and `parser.js:100`, `integrationmodel.js:850`,
`modal.js:307` and `modal.js:603`.

## Test plan

Driven in Chromium against the production build with WIRIS' hosted services
stubbed, running each case against the current PR head and then against this
commit.

### Before

Accepting an empty formula, and a MathML the service rejects:

```
{
  "emptyFormulaAccept": "THREW: Cannot read properties of null (reading 'indexOf')",
  "rejectedMathML": "THREW: Cannot read properties of null (reading 'getAttribute')",
  "focusSettled": "mathtype-target"
}
```

End to end - insert a formula, double-click it, then accept with the formula
erased. It throws and the formula is still there:

```
{
  "formulasAfterInsert": 1,
  "formulasAfterEmptyAccept": 1,
  "emptyAcceptThrew": "Cannot read properties of null (reading 'indexOf')"
}
```

### After

```
{
  "emptyFormulaAccept": "ok (no throw)",
  "rejectedMathML": "ok (no throw)",
  "focusSettled": "editor-input",
  "pageErrors": []
}
```

The erased formula is now removed, matching `Core.insertFormula`:

```
{
  "formulasAfterInsert": 1,
  "formulasAfterEmptyAccept": 0,
  "emptyAcceptThrew": null,
  "pageErrors": []
}
```

Also clean:

```
$ node_modules/.bin/eslint --no-warn-ignored examples/react-mathtype/
$ node_modules/.bin/prettier --check examples/react-mathtype/
Checking formatting...
All matched files use Prettier code style!
$ (cd examples/react-mathtype && pnpm run typecheck)
> tsc --noEmit
$ (cd examples/react-mathtype && pnpm run build)
✓ built in 2.11s
```

Not exercised: the real MathType dialog and its toolbar buttons, which need
WIRIS' hosted services at `www.wiris.net`. The runs above stub the
configuration request and drive `insertFormula` and `onModalClose` the way the
dialog does, rather than clicking through it.

Co-Authored-By: Claude Opus 5 <[email protected]>
@etrepum
etrepum added this pull request to the merge queue Aug 31, 2026
Merged via the queue into meta:main with commit 1723cd1 Aug 31, 2026
44 checks passed
@etrepum etrepum mentioned this pull request Aug 31, 2026

This branch was successfully deployed

2 active deployments
Preview – lexical — d49b3339 Deployed Aug 30, 2026 by vercel[bot]
Preview – lexical-playground — d49b3339 Deployed Aug 30, 2026 by vercel[bot]
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 Facebook bot. Authors need to sign the CLA before a PR can be reviewed. extended-tests Run extended e2e tests on a PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: MathType integration

4 participants