Files
Atay-Makhzan/web_src/js/markup/codecopy.ts
T

26 lines
999 B
TypeScript
Raw Normal View History

import {svg} from '../svg.ts';
2026-02-11 11:22:33 +08:00
import {createElementFromAttrs, queryElems} from '../utils/dom.ts';
2026-02-08 12:21:11 +08:00
export function makeCodeCopyButton(attrs: Record<string, string> = {}): HTMLButtonElement {
2026-02-11 11:22:33 +08:00
const btn = createElementFromAttrs<HTMLButtonElement>('button', {
class: 'ui compact icon button code-copy auto-hide-control',
...attrs,
});
btn.innerHTML = svg('octicon-copy');
return btn;
}
export function initMarkupCodeCopy(elMarkup: HTMLElement): void {
2025-04-05 11:56:48 +08:00
// .markup .code-block code
queryElems(elMarkup, '.code-block code', (el) => {
if (!el.textContent) return;
// remove final trailing newline introduced during HTML rendering
2026-02-11 11:22:33 +08:00
const btn = makeCodeCopyButton({
'data-clipboard-text': el.textContent.replace(/\r?\n$/, ''),
});
// we only want to use `.code-block-container` if it exists, no matter `.code-block` exists or not.
2026-02-11 11:22:33 +08:00
const btnContainer = el.closest('.code-block-container') ?? el.closest('.code-block')!;
btnContainer.append(btn);
2025-04-05 11:56:48 +08:00
});
}