|
| 1 | +import { qsAll } from './helpers' |
| 2 | +import { showToast } from './toast' |
| 3 | + |
| 4 | +/** |
| 5 | + * Initializes copy markdown links. |
| 6 | + */ |
| 7 | + |
| 8 | +window.addEventListener('exdoc:loaded', initialize) |
| 9 | + |
| 10 | +function initialize () { |
| 11 | + if (!('clipboard' in navigator)) return |
| 12 | + |
| 13 | + qsAll('a.copy-markdown').forEach(link => { |
| 14 | + link.addEventListener('click', handleCopyMarkdownClick) |
| 15 | + }) |
| 16 | +} |
| 17 | + |
| 18 | +/** |
| 19 | + * Handles clicks on copy markdown links. |
| 20 | + * |
| 21 | + * If Ctrl/Cmd is held, allows normal link behavior. |
| 22 | + * Otherwise, attempts to fetch and copy the markdown to clipboard. |
| 23 | + * |
| 24 | + * @param {MouseEvent} event |
| 25 | + */ |
| 26 | +function handleCopyMarkdownClick (event) { |
| 27 | + if (event.ctrlKey || event.metaKey) { |
| 28 | + return |
| 29 | + } |
| 30 | + |
| 31 | + event.preventDefault() |
| 32 | + const link = event.currentTarget |
| 33 | + const markdownUrl = link.href |
| 34 | + |
| 35 | + // Use ClipboardItem with a promise for Safari compatibility as it |
| 36 | + // requires the clipboard API to be called synchronously during user gesture |
| 37 | + const clipboardItem = new ClipboardItem({ |
| 38 | + 'text/plain': fetch(markdownUrl) |
| 39 | + .then(response => { |
| 40 | + if (!response.ok) { |
| 41 | + throw new Error('Failed to fetch markdown') |
| 42 | + } |
| 43 | + return response.text() |
| 44 | + }) |
| 45 | + .then(markdown => { |
| 46 | + return new Blob([markdown], { type: 'text/plain' }) |
| 47 | + }) |
| 48 | + }) |
| 49 | + |
| 50 | + navigator.clipboard.write([clipboardItem]) |
| 51 | + .then(() => { |
| 52 | + showToast('Page copied as Markdown to clipboard') |
| 53 | + }) |
| 54 | + .catch((error) => { |
| 55 | + console.log('Copying Markdown failed:', error) |
| 56 | + |
| 57 | + const shouldOpen = window.confirm( |
| 58 | + 'Could not copy to clipboard. Do you want to open the Markdown page instead?' |
| 59 | + ) |
| 60 | + if (shouldOpen) { |
| 61 | + window.location.href = markdownUrl |
| 62 | + } |
| 63 | + }) |
| 64 | +} |
0 commit comments