From 86ea3947ca6fdf61f603de92f2151f30a0fbfed2 Mon Sep 17 00:00:00 2001 From: ozakione <29860391+OzakIOne@users.noreply.github.com> Date: Thu, 28 Sep 2023 18:03:42 +0200 Subject: [PATCH] refactor: sync wrap states in localstorage --- .../src/theme/CodeBlock/Content/String.tsx | 1 + .../src/hooks/useCodeWordWrap.ts | 38 ++++++++++--------- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/packages/docusaurus-theme-classic/src/theme/CodeBlock/Content/String.tsx b/packages/docusaurus-theme-classic/src/theme/CodeBlock/Content/String.tsx index 6a051802e2ef..122b14489dd0 100644 --- a/packages/docusaurus-theme-classic/src/theme/CodeBlock/Content/String.tsx +++ b/packages/docusaurus-theme-classic/src/theme/CodeBlock/Content/String.tsx @@ -85,6 +85,7 @@ export default function CodeBlockString({ ref={wordWrap.codeBlockRef} className={clsx(className, styles.codeBlock, 'thin-scrollbar')}> { + const newValue = value === 'true' ? 'false' : 'true'; + storageSlot.set(newValue); + }, [value, storageSlot]); + + return [value === 'true', toggle] as const; +} + export function useCodeWordWrap(): { readonly codeBlockRef: RefObject; readonly isEnabled: boolean; readonly isCodeScrollable: boolean; readonly toggle: () => void; + readonly codeStyle: CSSProperties; } { - const [value, storageSlot] = useStorageSlot('docusaurus.code.wordWrap'); + const [isEnabled, toggleWrap] = useCodeWrapState(); const [isCodeScrollable, setIsCodeScrollable] = useState(false); const codeBlockRef = useRef(null); + const codeStyle: CSSProperties = isEnabled + ? {whiteSpace: 'pre-wrap', overflowWrap: 'anywhere'} + : {}; const toggle = useCallback(() => { - const codeElement = codeBlockRef.current!.querySelector('code')!; - - if (value === 'true') { - codeElement.removeAttribute('style'); - } else { - codeElement.style.whiteSpace = 'pre-wrap'; - // When code wrap is enabled, we want to avoid a scrollbar in any case - // Ensure that very very long words/strings/tokens still wrap - codeElement.style.overflowWrap = 'anywhere'; - } - - storageSlot.set(value === 'true' ? 'false' : 'true'); - }, [codeBlockRef, value, storageSlot]); + toggleWrap(); + }, [toggleWrap]); const updateCodeIsScrollable = useCallback(() => { const {scrollWidth, clientWidth} = codeBlockRef.current!; @@ -90,7 +94,7 @@ export function useCodeWordWrap(): { useEffect(() => { updateCodeIsScrollable(); - }, [value, updateCodeIsScrollable]); + }, [isEnabled, updateCodeIsScrollable]); useEffect(() => { window.addEventListener('resize', updateCodeIsScrollable, { @@ -102,5 +106,5 @@ export function useCodeWordWrap(): { }; }, [updateCodeIsScrollable]); - return {codeBlockRef, isEnabled: value === 'true', isCodeScrollable, toggle}; + return {codeBlockRef, isEnabled, isCodeScrollable, toggle, codeStyle}; }