Skip to content

Commit

Permalink
fix(math-toolbar): Render portal within shadow DOM
Browse files Browse the repository at this point in the history
  • Loading branch information
Mikey Stengel committed May 7, 2024
1 parent 5af41d1 commit 5b942c1
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions packages/editor/src/math/editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { faQuestionCircle } from '@fortawesome/free-solid-svg-icons'
import { FaIcon } from '@serlo/frontend/src/components/fa-icon'
import { useEditorStrings } from '@serlo/frontend/src/contexts/logged-in-data-context'
import { cn } from '@serlo/frontend/src/helper/cn'
import { useState } from 'react'
import { useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { useHotkeys } from 'react-hotkeys-hook'
import { Key } from 'ts-key-enum'
Expand Down Expand Up @@ -34,6 +34,8 @@ export interface MathEditorProps {
export function MathEditor(props: MathEditorProps) {
const [isHelpOpen, setIsHelpOpen] = useState(false)
const [hasError, setHasError] = useState(false)
// Need to attach a ref to the container to be able to select the shadow DOM
const containerRef = useRef<HTMLDivElement>(null)

const mathStrings = useEditorStrings().plugins.text.math

Expand All @@ -53,10 +55,10 @@ export function MathEditor(props: MathEditorProps) {
const isVisualMode = (visual && !hasError) || false

return (
<>
<div ref={containerRef}>
<MathHelpModal isHelpOpen={isHelpOpen} setIsHelpOpen={setIsHelpOpen} />
{renderChildren()}
</>
</div>
)

function renderChildren() {
Expand Down Expand Up @@ -157,10 +159,12 @@ export function MathEditor(props: MathEditorProps) {
}

function renderControlsPortal(children: JSX.Element) {
return createPortal(
children,
document.querySelector<HTMLDivElement>('.toolbar-controls-target') ??
document.body
)
const root = containerRef.current?.getRootNode()
const target =
(root instanceof ShadowRoot || root instanceof Document
? root.querySelector<HTMLDivElement>('.toolbar-controls-target')
: document.body) ?? document.body

return createPortal(children, target)
}
}

0 comments on commit 5b942c1

Please sign in to comment.