Repository navigation
refactor: remove unsafe type assertions from emoji, selection, and sound utilities - #98879
Conversation
Codecov Report✅ Changes either increased or maintained existing code coverage, great job!
|
|
@ikevin127 Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button] |
|
|
||
| // cspell:ignore mtext | ||
|
|
||
| // Selection scraping only exists in the web implementation; the native variant always returns an empty string. |
There was a problem hiding this comment.
❌ CONSISTENCY-16 (docs)
This comment joins two independent clauses with a semicolon. Per the plain comment style guideline, prefer two separate sentences over a semicolon so the comment reads more naturally.
Split it into two sentences:
// Selection scraping only exists in the web implementation. The native variant always returns an empty string.Reviewed at: c87258e | Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.
There was a problem hiding this comment.
Addressed in bce709d. The comment now uses two sentences instead of joining the clauses with a semicolon.
Reviewer Checklist
Screenshots/VideosAndroid: HybridApp 🔊screen-20260912-150000-1789250374652.mp4MacOS: Chrome / SafariScreen.Recording.2026-09-12.at.14.44.15.mov |
| @@ -12,6 +12,63 @@ import type GetCurrentSelection from './types'; | |||
| const markdownElements = new Set(['h1', 'strong', 'em', 'del', 'blockquote', 'q', 'code', 'pre', 'a', 'br', 'li', 'ul', 'ol', 'b', 'i', 's', 'mention-user']); | |||
| const tagAttribute = 'data-testid'; | |||
|
|
|||
There was a problem hiding this comment.
🟠 SelectionScraper/index.ts — roughly 60 lines of dom-serializer-internals machinery were added to preserve two invalid-HTML outputs, in order to delete 4 assertions.
The core refactor is right: replaceNodes used to return {...dom, ...} as Element & DataNode, a plain object spread that was not a real domhandler node and whose parent / prev / next still pointed into the original untransformed tree. Replacing that with real cloneNode() instances plus installTransformedChildren is a genuine improvement, and it is what removes the assertions.
But that fix also silently corrected a serialization bug, so the PR adds two shims to put the bug back.
I reproduced this with the repo's own htmlparser2 and dom-serializer:
1) coherent parse -> render : <svg><foreignObject><div></div></foreignObject></svg>
2) foreignobject name BEFORE : foreignobject
foreignobject name AFTER : foreignObject
3) old spread-style render : <svg><foreignObject><div/></foreignObject></svg>
And for the editor-collapse case the PR's own test pins:
coherent (span parented to mtext) : <math><mtext><span></span></mtext></math>
stale parent (removed <div>) : <math><mtext><span/></mtext></math>
What is happening: dom-serializer decides HTML vs foreign (SVG/MathML) mode by reading elem.parent.name, and it mutates elem.name in place during render (foreignobject becomes foreignObject). Under the old code the children's parent pointed at the original, never-renamed node, so the integration-point lookup missed and the children serialized in XML mode. With a coherent tree the lookup hits and they serialize as HTML, which is correct.
installForeignObjectRenderCompatibility recreates the miss by cloning the foreignObject and re-parenting its children onto an unattached lowercase copy. installEditorCollapseRenderCompatibility does the same for children hoisted out of a collapsed editor div.
Two problems with paying that cost:
-
The preserved output is not valid HTML, and it reaches the clipboard.
useCopySelectionHelper.ts:19callsClipboard.setHtml(selection, clipboardText), so this string is what lands in the user's clipboard astext/html.<div/>is not self-closing in HTML; every HTML parser treats it as an unclosed<div>. Paste a selection containing an SVGforeignObjectinto Gmail, Word, or Notion and the unclosed div can swallow the content that follows it. The new testpreserves pinned SVG foreignObject serializationasserts that exact string, so the defect is now pinned by a green test. -
The shims depend on dom-serializer internals that are not public API: that it mutates
elem.namein place, and the exact contents of its privateforeignModeIntegrationPointsset. Nothing here would fail loudly if a patch bump changed either. The comments explain the mechanism carefully but never say the behavior being preserved is wrong.
Recommendation: delete both shims and let the coherent tree produce the correct output. That removes about 60 lines, removes the dom-serializer coupling, and still removes all 4 assertions. The two test expectations become <div></div> and <span></span>, and the PR description gains one line saying SVG foreignObject and MathML integration-point children now serialize as well-formed HTML.
If you would rather keep it strictly behavior-preserving, that is defensible for a refactor, but then the comments need to say so plainly:
/**
* Reproduces a known-incorrect serialization: children of SVG `foreignObject` are emitted in XML
* mode (`<div/>`) rather than HTML mode. This is invalid HTML that reaches the clipboard via
* `Clipboard.setHtml`. Preserved deliberately to keep this PR behavior-neutral. See <issue link>.
*/Right now a future reader has no way to tell this is bug-compatibility rather than a requirement.
There was a problem hiding this comment.
Addressed in bce709d. I removed both compatibility shims and kept the transformed domhandler tree coherent. SVG foreignObject and MathML integration-point children now serialize with paired HTML tags. The tests now assert the corrected clipboard output.
| declare module '*.mp3' { | ||
| const value: number; | ||
| export default value; | ||
| } | ||
|
|
There was a problem hiding this comment.
🟡 src/types/global.d.ts:15 — the *.mp3 declaration is a global claim that is only true for Metro.
Metro resolves asset imports to a numeric registry ID, so number is right on native. Web bundlers resolve them to a URL string. The neighbouring declarations avoid this: *.png and *.jpg both use ImageSourcePropType, which is honest on both platforms.
Today only src/libs/Sound/index.native.ts imports an .mp3, and the web sound path builds string URLs by hand (index.ts:53), so nothing is broken. But this is a global declaration, and the first web-side import x from './foo.mp3' will be typed number while holding a string, with no error anywhere.
AudioSource is string | number | null | {...} (expo-audio/build/Audio.types.d.ts:16), so the honest declaration costs nothing and needs no other change:
declare module '*.mp3' {
// Metro resolves assets to a numeric registry ID; web bundlers resolve them to a URL string.
const value: number | string;
export default value;
}Worth naming what this change actually is: the hand-written module declaration is the type claim that replaced require(...) as AudioSource. Nothing verifies it. That is the same shape as the overload trick from #98759, though far more defensible here since it matches four existing declarations in the same file.
Making it honest for both bundlers is the difference between a convention and a cast in disguise.
There was a problem hiding this comment.
Addressed in bce709d. The *.mp3 declaration now uses number | string, which covers Metro asset IDs and web URLs. The native sound map still narrows each entry to the scalar variants accepted by AudioSource.
| const documentCloneSpy = jest.spyOn(Document.prototype, 'cloneNode'); | ||
| selectFixture('<math><mtext><div>first</div><span>middle</span><p>last</p></mtext></math>'); | ||
|
|
||
| expect(SelectionScraper.getCurrentSelection()).toBe('<math><mtext><div>first</div><span>middle</span><p>last</p></mtext></math>'); | ||
|
|
||
| const firstCloneResult = documentCloneSpy.mock.results.at(0); |
There was a problem hiding this comment.
🟡 tests/unit/SelectionScraperTest.ts:52-64 — the MathML test asserts on implementation internals.
const documentCloneSpy = jest.spyOn(Document.prototype, 'cloneNode');
...
const firstCloneResult = documentCloneSpy.mock.results.at(0);This reaches into the transformed document by grabbing the return value of the first Document.prototype.cloneNode call. It encodes how many times the implementation clones and in what order. Reorder parsedDom.cloneNode() and domRepresentation.cloneNode(true) in getCurrentSelection, and this test fails without any behavior changing.
Since the other three tests already assert on rendered output, this one is the odd one out.
The parent/prev/next wiring it checks is worth testing, but it belongs on installTransformedChildren directly. Export it and test it as a pure function, and the spy disappears.
Separately, line 1:
import type * as SelectionScraperModule from '@libs/SelectionScraper/index.native';
...
jest.requireActual<typeof SelectionScraperModule>('@libs/SelectionScraper/index.ts').default;This types the web module using the native module's type. They happen to match today, and index.native.ts is a four-line stub returning ''. If the web module ever gains an export, the test's type silently lies. src/libs/SelectionScraper/types.ts already exports GetCurrentSelection, so use that:
jest.requireActual<{default: {getCurrentSelection: GetCurrentSelection}}>('@libs/SelectionScraper/index.ts').default;There was a problem hiding this comment.
Addressed in bce709d. The test no longer spies on Document.prototype.cloneNode. It tests installTransformedChildren directly and derives the web module type from the actual web implementation, so export-shape changes remain type-checked.
| const transformedParent = parent; | ||
| transformedParent.children = children; | ||
|
|
||
| for (const [index, child] of children.entries()) { | ||
| child.parent = transformedParent; | ||
| child.prev = index > 0 ? (children.at(index - 1) ?? null) : null; |
There was a problem hiding this comment.
🟢 installTransformedChildren has a no-op alias and a dead fallback.
const transformedParent = parent;
transformedParent.children = children;
...
child.prev = index > 0 ? (children.at(index - 1) ?? null) : null;transformedParent is the same object as parent, so the alias only obscures that the function mutates its argument. And for index > 0, children.at(index - 1) is always defined, so ?? null never fires.
Same phantom-fallback pattern that got fixed in #98846 by destructuring with a default.
const installTransformedChildren = (parent: ParentNode, children: ChildNode[]) => {
parent.children = children;
for (const [index, child] of children.entries()) {
child.parent = parent;
child.prev = children[index - 1] ?? null;
child.next = children[index + 1] ?? null;
}
};There was a problem hiding this comment.
Addressed in bce709d. I removed the transformedParent alias and now update parent.children directly. The sibling assignments use indexed neighbors with ?? null, so the dead conditional fallback is gone.
|
@KJ21-ENG Dropped (4) code review comments that should be addressed before approval. |
|
PR doesn’t need product input as a refactor PR. Unassigning and unsubscribing myself. |
|
Addressed all four review findings in bce709d. Ready for another look. |
|
@KJ21-ENG LGTM, but PR is in draft mode so I can't approve. |
|
@ikevin127 Could you please take a look at this when you get a chance? Thanks! |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@ikevin127 Ah my bad! It looks like some generated GitHub Actions files were unintentionally included while I was testing locally (they were for my fork, I messed up heads) . I’ve removed them, confirmed the PR contains only the intended changes. |
|
FYI, failing Jest tests are unrelated to this PR. They are still on the latest |
Both Done BTW |
| @@ -0,0 +1,80 @@ | |||
| import type * as SelectionScraperModule from '@libs/SelectionScraper/index.native'; | |||
There was a problem hiding this comment.
🟡 tests/unit/SelectionScraperTest.ts:1 - The native-type-for-web-module problem is back
This is the exact defect from the first pass, which he fixed in bce709d and has now reverted:
-import type * as SelectionScraperWebModule from '@libs/SelectionScraper/index';
+import type * as SelectionScraperModule from '@libs/SelectionScraper/index.native';The requireActual call still loads @libs/SelectionScraper/index.ts, so the web module is once again typed with the native module's type.
It compiles today only because moving the helper out made the two surfaces identical again, which is precisely what makes it fragile: the next export added to index.ts puts the test's type silently out of sync with what it loads, and index.native.ts is a four-line stub returning ''.
There was no reason to revert it, probably AI mishap. I confirmed TS resolves @libs/SelectionScraper/index to the web file (no moduleSuffixes in tsconfig.json or in the inherited expo/tsconfig.base), and ESLint was green on the previous form.\
One-line fix, back to what he already had:
import type * as SelectionScraperWebModule from '@libs/SelectionScraper/index';
...
const {default: SelectionScraper} = jest.requireActual<typeof SelectionScraperWebModule>('@libs/SelectionScraper/index.ts');|
🟡 The The rewrite replaced it rather than adding to it. The body now runs Explanation, Fixed Issues, Count change, QA Steps, Offline tests, with no Worth restoring before merge so the section order matches the template and the ticked box is true. |
|
|
||
| installTransformedChildren(parent, children); | ||
|
|
||
| expect(parent.children).toBe(children); |
There was a problem hiding this comment.
🟢 tests/unit/SelectionScraperTest.ts:54 - expect(parent.children).toBe(children) still asserts array identity. Carried over from the last pass. It pins that the helper assigns the caller's array rather than copying it, so a defensive copy would fail the test with every DOM relationship still correct.
toEqual is the assertion that matches the intent. The nine toBe calls below it are correct, those really are node identity checks.
| @@ -6,12 +11,12 @@ import {createAudioPlayer, setAudioModeAsync} from 'expo-audio'; | |||
| import {getIsMuted, SOUNDS, withMinimalExecutionTime} from './BaseSound'; | |||
|
|
|||
| // Sound assets must be required at compile time | |||
There was a problem hiding this comment.
🟢 src/libs/Sound/index.native.ts:13 - comment is still stale. "Sound assets must be required at compile time" predates the switch to static imports.
|
@KJ21-ENG Completed PR Reviewer Checklist, tests well. Dropped (4) more comments above after the final-pass review, these should be addressed before we merge - including the unrelated failing jest unit test. Tag me once done 🙌 |
|
@ikevin127 Addressed the four comments in 95407e7:
Also merged latest main |
ikevin127
left a comment
There was a problem hiding this comment.
🟢 LGTM - Thanks for addressing all comments 🙌
blimpich
left a comment
There was a problem hiding this comment.
Looks good. Nice job @KJ21-ENG and @ikevin127 👍
|
✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release. |
|
🚧 blimpich has triggered a test Expensify/App build. You can view the workflow run here. |
|
🧪🧪 Use the links below to test this adhoc build on Android, iOS, and Web. Happy testing! 🧪🧪
|
|
🚀 Deployed to staging by https://github.com/blimpich in version: 9.4.80-0 🚀
|
|
🤖 No help site changes are required. No draft PR was created. This PR is an internal type-safety refactor. It removes unsafe type assertions and adds a DOM-linking helper plus unit tests. It does not add, rename, or remove any feature, setting, tab, or button, so nothing in How I checkedFiles changed (all
Articles I checked for staleness:
Neither article documents emoji search internals, clipboard serialization, or sound asset loading, which is all this PR touches. Since no help site PR exists, there is nothing to review or mark |
|
Nah, I checked #98879’s diff and the attached logs. This points to #100800: browser Back restores the Insights route without params, and cc: @blimpich @ikevin127 |
|
Agreed |
|
🚀 Deployed to production by https://github.com/luacmartins in version: 9.4.80-0 🚀
Bundle Size Analysis (Sentry): |
Explanation of Change
Removes 12 unsafe type assertions from emoji search, formatted selection copying, and native sound loading.
The change keeps the existing emoji and native sound type contracts. It also keeps transformed DOM parent and sibling links coherent before serialization. SVG
foreignObjectand MathML integration-point children now serialize with paired HTML tags. That is an intentional correction to malformed serialized output, not a claim that every previous byte of output is unchanged.Fixed Issues
$ #94739
PROPOSAL: #94739 (comment)
Tests
Repeatable development test steps are below. The attached September 12 Chrome recording is partial evidence, not a completed retest of the latest main merge.
smileandthumbs up. Select a skin-tone variant and verify the selected emoji appears correctly in the composer.Offline tests
QA Steps
Repeat Tests steps 1–4 on staging for the applicable web and native platforms. Compare any formatting or search failure against current main before attributing it to this PR.
PR Author Checklist
### Fixed Issuessection aboveTestssectionOffline stepssectionQA stepssectionAvatar, I verified the components usingAvatarare working as expected)StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))npm run compress-svg)Avataris modified, I verified thatAvataris working as expected in all cases)Designlabel and/or tagged@Expensify/designso the design team can review the changes.mainbranch was merged into this PR after a review, I tested again and verified the outcome was still expected according to theTeststeps.Screenshots/Videos
Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari
September 12 Chrome recording, before the latest main merge. It shows emoji selection and formatted copy/paste online and offline. Online smile search returned no results, and formatted paste lost bold formatting and changed line breaks; these observations have not been established as PR regressions. SVG/MathML fixtures and native sound behavior are not demonstrated in this recording.
17.Kush.J.you._2026-09-12_13-40-52.mp4