refactor: update ShadowDOM and ArticleLayout components for improved text selection handling

- Replaced the useRef with useState in ShadowDOM to manage shadowRoot more effectively.
- Enhanced text selection listener logic to ensure proper cleanup and functionality.
- Added console logs in ArticleLayout for debugging text selection events.

Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Innei 2025-11-20 22:09:23 +08:00
parent 4e3e1c1513
commit cdea2fa5dd
No known key found for this signature in database
GPG Key ID: 0F62D33977F021F7
2 changed files with 9 additions and 23 deletions

View File

@ -4,16 +4,7 @@ import { getAccentColorValue } from "@follow/shared/settings/constants"
import { hexToHslString } from "@follow/utils"
import { nanoid } from "nanoid"
import type { FC, PropsWithChildren, ReactNode } from "react"
import {
createContext,
createElement,
use,
useCallback,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react"
import { createContext, createElement, use, useLayoutEffect, useMemo, useState } from "react"
import root from "react-shadow"
import { useUISettingKeys } from "~/atoms/settings/ui"
@ -87,15 +78,16 @@ export const ShadowDOM: FC<
injectHostStyles ? cloneStylesElement() : [],
)
const shadowRootRef = useRef<ShadowRoot | null>(null)
const [el, setEl] = useState<{ shadowRoot: ShadowRoot } | null>(null)
useLayoutEffect(() => {
if (!textSelectionEnabled || !shadowRootRef.current || !onTextSelect) return
if (!el) return
const { shadowRoot } = el
const cleanup = addTextSelectionListener(shadowRootRef.current, onTextSelect, onSelectionClear)
if (!textSelectionEnabled || !shadowRoot || !onTextSelect) return
return cleanup
}, [textSelectionEnabled, onTextSelect, onSelectionClear])
return addTextSelectionListener(shadowRoot, onTextSelect, onSelectionClear)
}, [textSelectionEnabled, onTextSelect, onSelectionClear, el])
useLayoutEffect(() => {
if (!injectHostStyles) return
@ -123,14 +115,7 @@ export const ShadowDOM: FC<
return (
// @ts-expect-error
<root.div
{...rest}
ref={useCallback((element) => {
if (element) {
shadowRootRef.current = element.shadowRoot
}
}, [])}
>
<root.div {...rest} ref={setEl}>
<ShadowDOMContext value={true}>
<div
style={useMemo(

View File

@ -143,6 +143,7 @@ export const ArticleLayout: React.FC<EntryLayoutProps> = ({
)}
</ErrorBoundary>
</div>
<TextSelectionToolbar
selection={textSelection}
onRequestClose={handleSelectionClear}