Skip to content

Commit

Permalink
feat: Add copy to clipboard button to markdown code block #2025 (#2120)
Browse files Browse the repository at this point in the history
Co-authored-by: Martin Turoci <martin.turoci@h2o.ai>
  • Loading branch information
marek-mihok and mturoci authored Sep 6, 2023
1 parent 77e4097 commit 54c0553
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 25 deletions.
1 change: 0 additions & 1 deletion ui/src/copyable_text.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,4 @@ describe('CopyableText.tsx', () => {
rerender(<XCopyableText model={{ ...copyableTextProps, value: 'B' }} />)
expect(getByTestId(name)).toHaveValue('B')
})

})
53 changes: 31 additions & 22 deletions ui/src/copyable_text.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,16 @@ import { clas, cssVar, pc } from './theme'

const
css = stylesheet({
btnMultiline: {
opacity: 0,
transition: 'opacity .5s'
},
btn: {
minWidth: 'initial',
position: 'absolute',
minWidth: 'initial',
width: 24,
height: 24,
right: 0,
transform: 'translate(-4px, 4px)',
outlineWidth: 1,
outlineStyle: 'solid',
outlineColor: cssVar('$text'),
zIndex: 1,
},
copiedBtn: {
Expand Down Expand Up @@ -54,54 +53,64 @@ export interface CopyableText {
height?: S
}

export const XCopyableText = ({ model }: { model: CopyableText }) => {
export const ClipboardCopyButton = ({ value }: { value: S }) => {
const
{ name, multiline, label, value, height } = model,
heightStyle = multiline && height === '1' ? fullHeightStyle : undefined,
ref = React.useRef<Fluent.ITextField>(null),
timeoutRef = React.useRef<U>(),
[copied, setCopied] = React.useState(false),
onClick = async () => {
const el = ref.current
if (!el) return
onClick = React.useCallback(async () => {
try {
if (document.queryCommandSupported('copy')) {
const el = document.createElement('textarea')
el.value = value
document.body.appendChild(el)
el.select()
document.execCommand('copy')
window.getSelection()?.removeAllRanges()
document.body.removeChild(el)
}
} catch (error) {
await window.navigator.clipboard.writeText(value)
}

setCopied(true)
timeoutRef.current = window.setTimeout(() => setCopied(false), 2000)
}
}, [value])

React.useEffect(() => () => window.clearTimeout(timeoutRef.current), [])

return (
<Fluent.PrimaryButton
title='Copy to clipboard'
onClick={onClick}
iconProps={{
iconName: copied ? 'CheckMark' : 'Copy',
styles: { root: { marginTop: -1.35 } } // Nudge up the icon a bit to account for incorrect Fluent crop.
}}
className={clas(css.btn, copied ? css.copiedBtn : '')}
/>
)
}

export const XCopyableText = ({ model }: { model: CopyableText }) => {
const
{ name, multiline, label, value, height } = model,
heightStyle = multiline && height === '1' ? fullHeightStyle : undefined

return (
<Fluent.TextField
data-test={name}
componentRef={ref}
value={value}
multiline={multiline}
onRenderLabel={() =>
<div className={css.labelContainer}>
<Fluent.Label>{label}</Fluent.Label>
<Fluent.PrimaryButton
title='Copy to clipboard'
onClick={onClick}
iconProps={{ iconName: copied ? 'CheckMark' : 'Copy' }}
className={clas(css.btn, copied ? css.copiedBtn : '', multiline ? css.btnMultiline : '')}
/>
<ClipboardCopyButton value={value} />
</div>
}
styles={{
root: {
...heightStyle,
textFieldRoot: { position: 'relative', width: pc(100) },
textFieldMultiline: multiline ? { '&:hover button': { opacity: 1 } } : undefined
textFieldMultiline: multiline ? { '& button': { opacity: 0 }, '&:hover button': { opacity: 1 } } : undefined
},
wrapper: heightStyle,
fieldGroup: heightStyle || { minHeight: height },
Expand Down
4 changes: 3 additions & 1 deletion ui/src/markdown.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@ import { fireEvent, render } from '@testing-library/react'
import React from 'react'
import { Markdown } from './markdown'

const source = 'The quick brown [fox](?fox) jumps over the lazy [dog](dog).'

describe('Markdown.tsx', () => {

// Jest JSDOM does not support event system, so we can only check if the event was dispatched.
it('Dispatches a custom event when link prefixed with "?"', () => {
const dispatchEventMock = jest.fn()
window.dispatchEvent = dispatchEventMock
const { getByText } = render(<Markdown source='The quick brown [fox](?fox) jumps over the lazy [dog](dog).' />)
const { getByText } = render(<Markdown source={source} />)

fireEvent.click(getByText('fox'))
expect(dispatchEventMock).toHaveBeenCalled()
Expand Down
26 changes: 25 additions & 1 deletion ui/src/markdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ import { Model, Rec, S, unpack } from 'h2o-wave'
import hljs from 'highlight.js/lib/core'
import MarkdownIt from 'markdown-it'
import React from 'react'
import ReactDOM from 'react-dom'
import { stylesheet } from 'typestyle'
import { ClipboardCopyButton } from './copyable_text'
import { cards, grid, substitute } from './layout'
import { border, clas, cssVar, padding, pc } from './theme'
import { bond } from './ui'
Expand Down Expand Up @@ -67,6 +69,24 @@ const
},
},
},
codeblock: {
position: 'relative',
$nest: {
'&:hover button': {
opacity: 1,
},
}
},
copyBtnWrapper: {
position: 'absolute',
right: 4,
top: 4,
$nest: {
button: {
opacity: 0,
},
}
},
})
const highlightSyntax = async (str: S, language: S, codeBlockId: S) => {
const codeBlock = document.getElementById(codeBlockId)
Expand All @@ -91,6 +111,10 @@ const highlightSyntax = async (str: S, language: S, codeBlockId: S) => {
: hljs.highlightAuto(str).value

codeBlock.innerHTML = highlightedCode
const btnContainer = document.createElement('div')
btnContainer.classList.add(css.copyBtnWrapper)
ReactDOM.render(<ClipboardCopyButton value={str} />, codeBlock.appendChild(btnContainer))

return highlightedCode
}

Expand All @@ -108,7 +132,7 @@ export const Markdown = ({ source }: { source: S }) => {
setTimeout(async () => prevHighlights.current[+codeBlockId] = await highlightSyntax(str, lang, codeBlockId), 0)

// TODO: Sanitize the HTML.
const ret = `<code id='${codeBlockId}' class="hljs">${prevHighlights.current[codeBlockIdx.current] || str}</code>`
const ret = `<code id='${codeBlockId}' class="hljs ${css.codeblock}">${prevHighlights.current[codeBlockIdx.current] || str}</code>`
codeBlockIdx.current++
return ret
}
Expand Down

0 comments on commit 54c0553

Please sign in to comment.