Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(theme-classic): toggle code wrap button #7036

Merged
merged 13 commits into from
Apr 22, 2022
Merged
10 changes: 10 additions & 0 deletions packages/docusaurus-theme-classic/src/theme-classic.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,11 +136,21 @@ declare module '@theme/CodeBlock' {
declare module '@theme/CodeBlock/CopyButton' {
export interface Props {
readonly code: string;
readonly className?: string;
}

export default function CopyButton(props: Props): JSX.Element;
}

declare module '@theme/CodeBlock/WordWrapButton' {
export interface Props {
readonly codeBlockRef: React.RefObject<HTMLPreElement>;
readonly className?: string;
}

export default function WordWrapButton(props: Props): JSX.Element;
}

declare module '@theme/DocCard' {
import type {PropSidebarItem} from '@docusaurus/plugin-content-docs';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import type {Props} from '@theme/CodeBlock/CopyButton';

import styles from './styles.module.css';

export default function CopyButton({code}: Props): JSX.Element {
export default function CopyButton({code, className}: Props): JSX.Element {
const [isCopied, setIsCopied] = useState(false);
const copyTimeout = useRef<number | undefined>(undefined);
const handleCopyCode = useCallback(() => {
Expand Down Expand Up @@ -48,8 +48,9 @@ export default function CopyButton({code}: Props): JSX.Element {
description: 'The copy button label on code blocks',
})}
className={clsx(
styles.copyButton,
'clean-btn',
className,
styles.copyButton,
isCopied && styles.copyButtonCopied,
)}
onClick={handleCopyCode}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,10 @@
* LICENSE file in the root directory of this source tree.
*/

.copyButton {
display: flex;
background: inherit;
border: 1px solid var(--ifm-color-emphasis-300);
border-radius: var(--ifm-global-radius);
padding: 0.4rem;
position: absolute;
right: calc(var(--ifm-pre-padding) / 2);
top: calc(var(--ifm-pre-padding) / 2);
transition: opacity 200ms ease-in-out;
opacity: 0;
}

.copyButton:focus-visible,
.copyButton:hover,
:global(.theme-code-block:hover) .copyButtonCopied {
opacity: 1 !important;
}

:global(.theme-code-block:hover) .copyButton:not(.copyButtonCopied) {
opacity: 0.4;
}

.copyButtonIcons {
position: relative;
width: 1.125rem;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import React, {useCallback, useState, useEffect} from 'react';
import clsx from 'clsx';
import {translate} from '@docusaurus/Translate';
import type {Props} from '@theme/CodeBlock/WordWrapButton';

import styles from './styles.module.css';

export default function WordWrapButton({
codeBlockRef,
className,
}: Props): JSX.Element | null {
const [isEnabled, setIsEnabled] = useState(false);
const [isCodeScrollable, setIsCodeScrollable] = useState<boolean>(false);
Josh-Cena marked this conversation as resolved.
Show resolved Hide resolved
const toggleWordWrapCode = useCallback(() => {
setIsEnabled((value) => !value);

const codeElement = codeBlockRef.current!.querySelector('code');
codeElement?.classList.toggle(styles.codeWithWordWrap!);
}, [codeBlockRef]);
const updateCodeIsScrollable = useCallback(() => {
const {scrollWidth, clientWidth} = codeBlockRef.current!;
setIsCodeScrollable(scrollWidth > clientWidth);
}, [codeBlockRef]);
const title = translate({
id: 'theme.CodeBlock.wordWrapToggle',
message: 'Toggle word wrap',
description:
'The title attribute for toggle word wrapping button of code block lines',
});

useEffect(() => {
updateCodeIsScrollable();

window.addEventListener('resize', updateCodeIsScrollable);

return () => {
window.removeEventListener('resize', updateCodeIsScrollable);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

if (!isCodeScrollable) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Little issue:

  • mobile
  • enable word wrap
  • resize

Now isCodeScrollable = false and the button disappears => no way to turn word wrap off

image

return null;
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

all this code is quite technical and shouldn't be there

The button should preferably always render a button, and users swizzling it should be able to change its display/icon without having to manage this technical code.

I don't think the button should either handle a ref of parent code block. It's the parent that should decide if the toggle button should be displayed, not the button itself.

I'd suggest moving this complexity to a custom hook in theme-common, and using the hook inside <CodeBlock> instead <WordWrapButton>


return (
<button
type="button"
onClick={toggleWordWrapCode}
className={clsx(
'clean-btn',
className,
styles.wordWrapButton,
isEnabled && styles.wordWrapButtonEnabled,
)}
aria-label={title}
title={title}>
<svg
className={styles.wordWrapButtonIcon}
viewBox="0 0 24 24"
aria-hidden="true">
<path
fill="currentColor"
d="M4 19h6v-2H4v2zM20 5H4v2h16V5zm-3 6H4v2h13.25c1.1 0 2 .9 2 2s-.9 2-2 2H15v-2l-3 3l3 3v-2h2c2.21 0 4-1.79 4-4s-1.79-4-4-4z"
/>
</svg>
</button>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

.wordWrapButton {
right: calc(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like the button to not decide where it will be rendered: that's the responsibility of the parent

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like it either, I was thinking of grouping these buttons into one new div container, but it's not that easy because we would have to somehow get background of the current Prism color theme (need it for button background, not its container). Therefore inherit value won't work here, so maybe we dynamically set two new CSS vars, like as --prism-background and --prism-color? Will that be acceptable solution?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe this works? usePrismTheme().plain.backgroundColor

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean, in the case of button container, we need to set the style attribute for each button inside to set the proper background. I think it's kind of redundant overhead, which we can avoid by dynamically creating two CSS vars that also can re-use in other places where the style attribute is currently used.

image

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lex111 FWIW, Prism also inlines their styles, so it won't be too harmful

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just wouldn't want to overuse it, especially if there's a pretty appropriate alternative solution. Beside that, using inline styles would require creating one specific prop style for each button component, which can also be avoided.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this rule still necessary?

Looks to me it's not useful anymore => removing it and things keep working?

var(--ifm-pre-padding) + var(--docusaurus-code-button-size)
) !important;
}

.wordWrapButtonIcon {
width: 1.2rem;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe we want to use the same size for all buttongroup icons? and introduce anv env variable to customize?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't work that way, the proportions of both icons are different, so if we use the same sizing for them, the wordWrap button will look smaller than the copyButton icon:

image

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can keep it this way for now, but I guess the wordWrap svg could also be cropped somehow to take full space

height: 1.2rem;
}

.wordWrapButtonEnabled .wordWrapButtonIcon {
Josh-Cena marked this conversation as resolved.
Show resolved Hide resolved
color: var(--ifm-color-primary);
}

.codeWithWordWrap {
lex111 marked this conversation as resolved.
Show resolved Hide resolved
white-space: pre-wrap;
}
16 changes: 12 additions & 4 deletions packages/docusaurus-theme-classic/src/theme/CodeBlock/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import React, {isValidElement, useEffect, useState} from 'react';
import React, {isValidElement, useEffect, useState, useRef} from 'react';
import clsx from 'clsx';
import Highlight, {defaultProps, type Language} from 'prism-react-renderer';
import {
Expand All @@ -17,6 +17,7 @@ import {
usePrismTheme,
} from '@docusaurus/theme-common';
import CopyButton from '@theme/CodeBlock/CopyButton';
import WordWrapButton from '@theme/CodeBlock/WordWrapButton';
import type {Props} from '@theme/CodeBlock';

import styles from './styles.module.css';
Expand All @@ -29,6 +30,7 @@ export default function CodeBlock({
language: languageProp,
}: Props): JSX.Element {
const {prism} = useThemeConfig();
const codeBlockRef = useRef<HTMLPreElement>(null);

const [mounted, setMounted] = useState(false);
// The Prism theme on SSR is always the default theme but the site theme
Expand Down Expand Up @@ -115,8 +117,9 @@ export default function CodeBlock({
<pre
/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */
tabIndex={0}
className={clsx(className, styles.codeBlock, 'thin-scrollbar')}>
<code className={styles.codeBlockLines}>
className={clsx(className, styles.codeBlock, 'thin-scrollbar')}
ref={codeBlockRef}>
<code className={clsx(styles.codeBlockLines)}>
{tokens.map((line, i) => {
if (line.length === 1 && line[0]!.content === '\n') {
line[0]!.content = '';
Expand All @@ -140,7 +143,12 @@ export default function CodeBlock({
</code>
</pre>

<CopyButton code={code} />
<WordWrapButton
className={styles.codeButton}
codeBlockRef={codeBlockRef}
/>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What I have in mind:

Suggested change
<WordWrapButton
className={styles.codeButton}
codeBlockRef={codeBlockRef}
/>
{(wordWrap.enabled || wordWrap.codeScrollable) && (
<WordWrapButton
className={styles.codeButton}
onClick={() => wordWrap.toggle()}
/>
)}


<CopyButton className={styles.codeButton} code={code} />
</div>
</div>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,29 @@
white-space: pre-wrap;
}
}

.codeButton {
--docusaurus-code-button-size: 2rem;
position: absolute;
right: calc(var(--ifm-pre-padding) / 2);
top: calc(var(--ifm-pre-padding) / 2);
width: var(--docusaurus-code-button-size);
height: var(--docusaurus-code-button-size);
display: flex;
justify-content: center;
align-items: center;
background: inherit;
border: 1px solid var(--ifm-color-emphasis-300);
border-radius: var(--ifm-global-radius);
transition: opacity 200ms ease-in-out;
opacity: 0;
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should try to separate this CSS in 2 parts:

  • the "inner" of a code button (can be extracted and moved to a separate CodeButton component)
  • the rules that are responsible to position the button inside the parent component


.codeButton:focus-visible,
.codeButton:hover {
opacity: 1 !important;
}

:global(.theme-code-block:hover) .codeButton {
opacity: 0.4;
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"theme.CodeBlock.copied": "تم النسخ",
"theme.CodeBlock.copy": "نسخ",
"theme.CodeBlock.copyButtonAriaLabel": "نسخ الرمز إلى الحافظة",
"theme.CodeBlock.wordWrapToggle": "Toggle word wrap",
"theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel": "Toggle the collapsible sidebar category '{label}'",
"theme.ErrorPageContent.title": "This page crashed.",
"theme.ErrorPageContent.tryAgain": "Try again",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
"theme.CodeBlock.copy___DESCRIPTION": "The copy button label on code blocks",
"theme.CodeBlock.copyButtonAriaLabel": "Copy code to clipboard",
"theme.CodeBlock.copyButtonAriaLabel___DESCRIPTION": "The ARIA label for copy code blocks button",
"theme.CodeBlock.wordWrapToggle": "Toggle word wrap",
"theme.CodeBlock.wordWrapToggle___DESCRIPTION": "The title attribute for toggle word wrapping button of code block lines",
"theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel": "Toggle the collapsible sidebar category '{label}'",
"theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel___DESCRIPTION": "The ARIA label to toggle the collapsible sidebar category",
"theme.ErrorPageContent.title": "This page crashed.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"theme.CodeBlock.copied": "কপিড",
"theme.CodeBlock.copy": "কপি",
"theme.CodeBlock.copyButtonAriaLabel": "ক্লিপবোর্ডে কোড কপি করুন",
"theme.CodeBlock.wordWrapToggle": "Toggle word wrap",
"theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel": "Toggle the collapsible sidebar category '{label}'",
"theme.ErrorPageContent.title": "This page crashed.",
"theme.ErrorPageContent.tryAgain": "Try again",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"theme.CodeBlock.copied": "Zkopírováno",
"theme.CodeBlock.copy": "Zkopírovat",
"theme.CodeBlock.copyButtonAriaLabel": "Zkopírovat kód do schránky",
"theme.CodeBlock.wordWrapToggle": "Toggle word wrap",
"theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel": "Toggle the collapsible sidebar category '{label}'",
"theme.ErrorPageContent.title": "This page crashed.",
"theme.ErrorPageContent.tryAgain": "Try again",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"theme.CodeBlock.copied": "Kopieret",
"theme.CodeBlock.copy": "Kopier",
"theme.CodeBlock.copyButtonAriaLabel": "Kopier kode til udklipsholder",
"theme.CodeBlock.wordWrapToggle": "Toggle word wrap",
"theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel": "Toggle the collapsible sidebar category '{label}'",
"theme.ErrorPageContent.title": "This page crashed.",
"theme.ErrorPageContent.tryAgain": "Try again",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"theme.CodeBlock.copied": "Kopiert",
"theme.CodeBlock.copy": "Kopieren",
"theme.CodeBlock.copyButtonAriaLabel": "In die Zwischenablage kopieren",
"theme.CodeBlock.wordWrapToggle": "Toggle word wrap",
"theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel": "Umschalten der Seitenleiste mit einklappbarer Kategorie '{label}'",
"theme.ErrorPageContent.title": "Die Seite ist abgestürzt.",
"theme.ErrorPageContent.tryAgain": "Nochmal versuchen",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"theme.CodeBlock.copied": "Copiado",
"theme.CodeBlock.copy": "Copiar",
"theme.CodeBlock.copyButtonAriaLabel": "Copiar código al portapapeles",
"theme.CodeBlock.wordWrapToggle": "Toggle word wrap",
"theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel": "Toggle the collapsible sidebar category '{label}'",
"theme.ErrorPageContent.title": "This page crashed.",
"theme.ErrorPageContent.tryAgain": "Try again",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"theme.CodeBlock.copied": "کپی شد",
"theme.CodeBlock.copy": "کپی",
"theme.CodeBlock.copyButtonAriaLabel": "کپی به کلیپ بورد",
"theme.CodeBlock.wordWrapToggle": "Toggle word wrap",
"theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel": "Toggle the collapsible sidebar category '{label}'",
"theme.ErrorPageContent.title": "This page crashed.",
"theme.ErrorPageContent.tryAgain": "Try again",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"theme.CodeBlock.copied": "Kinopya",
"theme.CodeBlock.copy": "Kopyahin",
"theme.CodeBlock.copyButtonAriaLabel": "Kopyahin ang code sa clipboard",
"theme.CodeBlock.wordWrapToggle": "Toggle word wrap",
"theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel": "Toggle the collapsible sidebar category '{label}'",
"theme.ErrorPageContent.title": "This page crashed.",
"theme.ErrorPageContent.tryAgain": "Try again",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"theme.CodeBlock.copied": "Copié",
"theme.CodeBlock.copy": "Copier",
"theme.CodeBlock.copyButtonAriaLabel": "Copier le code",
"theme.CodeBlock.wordWrapToggle": "Toggle word wrap",
lex111 marked this conversation as resolved.
Show resolved Hide resolved
"theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel": "Toggle the collapsible sidebar category '{label}'",
"theme.ErrorPageContent.title": "Cette page a planté.",
"theme.ErrorPageContent.tryAgain": "Réessayer",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"theme.CodeBlock.copied": "הועתק",
"theme.CodeBlock.copy": "העתק",
"theme.CodeBlock.copyButtonAriaLabel": "העתק קוד ללוח העריכה",
"theme.CodeBlock.wordWrapToggle": "Toggle word wrap",
"theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel": "Toggle the collapsible sidebar category '{label}'",
"theme.ErrorPageContent.title": "This page crashed.",
"theme.ErrorPageContent.tryAgain": "Try again",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"theme.CodeBlock.copied": "कॉपीड",
"theme.CodeBlock.copy": "कॉपी",
"theme.CodeBlock.copyButtonAriaLabel": "क्लिपबोर्ड पर कोड कॉपी करें",
"theme.CodeBlock.wordWrapToggle": "Toggle word wrap",
"theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel": "Toggle the collapsible sidebar category '{label}'",
"theme.ErrorPageContent.title": "This page crashed.",
"theme.ErrorPageContent.tryAgain": "Try again",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"theme.CodeBlock.copied": "Copiato",
"theme.CodeBlock.copy": "Copia",
"theme.CodeBlock.copyButtonAriaLabel": "Copia il codice negli appunti",
"theme.CodeBlock.wordWrapToggle": "Toggle word wrap",
"theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel": "Attiva/disattiva la categoria '{label}' della barra laterale collassabile",
"theme.ErrorPageContent.title": "Questa pagina è andata in crash.",
"theme.ErrorPageContent.tryAgain": "Prova di nuovo",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"theme.CodeBlock.copied": "コピーしました",
"theme.CodeBlock.copy": "コピー",
"theme.CodeBlock.copyButtonAriaLabel": "クリップボードにコードをコピー",
"theme.CodeBlock.wordWrapToggle": "Toggle word wrap",
"theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel": "Toggle the collapsible sidebar category '{label}'",
"theme.ErrorPageContent.title": "This page crashed.",
"theme.ErrorPageContent.tryAgain": "Try again",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"theme.CodeBlock.copied": "복사했습니다",
"theme.CodeBlock.copy": "복사",
"theme.CodeBlock.copyButtonAriaLabel": "클립보드에 코드 복사",
"theme.CodeBlock.wordWrapToggle": "Toggle word wrap",
"theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel": "접을 수 있는 사이드바 분류 '{label}' 접기(펼치기)",
"theme.ErrorPageContent.title": "페이지에 오류가 발생하였습니다.",
"theme.ErrorPageContent.tryAgain": "다시 시도해 보세요",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"theme.CodeBlock.copied": "Skopiowano!",
"theme.CodeBlock.copy": "Kopiuj",
"theme.CodeBlock.copyButtonAriaLabel": "Kopiuj do schowka",
"theme.CodeBlock.wordWrapToggle": "Toggle word wrap",
"theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel": "Toggle the collapsible sidebar category '{label}'",
"theme.ErrorPageContent.title": "This page crashed.",
"theme.ErrorPageContent.tryAgain": "Try again",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"theme.CodeBlock.copied": "Copiado",
"theme.CodeBlock.copy": "Copiar",
"theme.CodeBlock.copyButtonAriaLabel": "Copiar código para a área de transferência",
"theme.CodeBlock.wordWrapToggle": "Toggle word wrap",
"theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel": "Toggle the collapsible sidebar category '{label}'",
"theme.ErrorPageContent.title": "This page crashed.",
"theme.ErrorPageContent.tryAgain": "Try again",
Expand Down
Loading