import { isPageTranslated } from 'common/sentry' export type NodeLike = { prototype: { removeChild(child: Node): unknown insertBefore(newNode: Node, referenceNode: Node | null): unknown } } interface InstallOptions { nodeConstructor?: NodeLike isTranslated?: () => boolean } let isInstalled = false /** * Google Translate replaces text nodes with `` wrappers. React still holds the original * text node, so a later `removeChild` / `insertBefore` against it throws a `NotFoundError` and * takes down the whole page (facebook/react#11538). * * Narrow on purpose: it only steps in when the page is translated AND the node is not where the * caller expects it. Every other call, including the same failure on an untranslated page, * goes to the native method untouched so real bugs still surface. * * - `removeChild`: the node is already gone from `this`, so skip. * - `insertBefore`: the reference node is gone, so append instead of dropping the new node. */ export function installTranslationDomGuard({ nodeConstructor = typeof Node === 'undefined' ? undefined : Node, isTranslated = isPageTranslated, }: InstallOptions = {}) { if (!nodeConstructor || isInstalled) return isInstalled = true const nativeRemoveChild = nodeConstructor.prototype.removeChild const nativeInsertBefore = nodeConstructor.prototype.insertBefore nodeConstructor.prototype.removeChild = function removeChild(this: Node, child: Node) { if (child && child.parentNode !== this && isTranslated()) return child return nativeRemoveChild.call(this, child) } nodeConstructor.prototype.insertBefore = function insertBefore( this: Node, newNode: Node, referenceNode: Node | null ) { if (referenceNode && referenceNode.parentNode !== this && isTranslated()) { return nativeInsertBefore.call(this, newNode, null) } return nativeInsertBefore.call(this, newNode, referenceNode) } } export function resetTranslationDomGuardForTests() { isInstalled = false }