Repository navigation
Add React MathType example - #8692
Conversation
|
Hi @culpen90! Thank you for your pull request and welcome to our community. Action RequiredIn 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. ProcessIn 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 If you have received this in error or have any questions, please contact us at [email protected]. Thanks! |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
potatowagon
left a comment
There was a problem hiding this comment.
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:
-
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), andMathTypePlugin(integration bootstrap). Uses the modern$config()protocol withcreateState,$getState,$setState, andbuildImportMap— follows the latest Lexical patterns from the 0.45.x API. -
Correctness:
$commitFormulacorrectly handles both edit (existing nodeKey) and insert (range selection fallback → root append) paths.- DOM import uses priority 3 and checks for both
.Wirisformulaclass anddata-mathmlattribute — good defensive conversion. insertFormulaoverride properly clearstemporalImageandpendingNodeKeyRefafter commit, preventing stale references.encodeMathML/decodeMathMLuse WirisPlugin.MathML when available with a manual fallback using Unicode character substitutions — matches WIRIS's established encoding scheme.
-
Edge cases:
parseOptionalNumberguards against NaN, Infinity, and non-positive values.MathTypeFormulaComponentdouble-click handler is gated onisEditable.- Integration cleanup in useEffect properly nulls
integrationRefonly if it still owns the reference (multi-mount safe). contentEditable={true}on.mathtype-targetdiv is intentional — it's the hidden proxy element that WIRIS requires for its generic integration API.
-
www compatibility: No concerns — this is a standalone example under
examples/, no core library changes, no API surface modifications. -
Security: The
@wiris/mathtype-genericdependency 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). -
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'invite-env.d.tsis a minimal type stub — fine for an example, but contributors could later add a proper.d.tsif 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.
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
etrepum
left a comment
There was a problem hiding this comment.
I'd recommend refactoring this for extensions so it can take advantage of newer features
…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]>
Summary
examples/react-mathtype.Fixes #7806.
Validation
corepack pnpm run typecheckfromexamples/react-mathtypecorepack pnpm run buildfromexamples/react-mathtypecorepack pnpm exec prettier --check examples/react-mathtypecorepack pnpm exec eslint examples/react-mathtype --no-error-on-unmatched-pattern