yggdrasil/libs/yggdrasil-core/src/post-content.ts
xfy ac1f92d816 refactor(core): 迁移 post-content 到 yggdrasil-core,删除 public/js
逐行 TypeScript 化(逻辑不变),改走 window.__initPostContent 全局入口。
post-content.js 已迁移进 libs/yggdrasil-core/,public/js/ 目录随之删除。
2026-06-26 13:57:48 +08:00

49 lines
1.4 KiB
TypeScript

/**
* 代码块 copy 按钮。
*
* 为 pre>code 注入一个 .copy-code 按钮,点击复制代码文本并回显 copied!。
* 2 秒后还原文案。样式见 input.css 的 .copy-code 规则(全局 Tailwind 构建)。
*/
function initCopyButtons(root: Element): void {
const blocks = root.querySelectorAll('pre > code');
blocks.forEach((code) => {
const pre = code.parentElement;
if (!pre) return;
if (pre.querySelector('.copy-code')) return;
const btn = document.createElement('button');
btn.className = 'copy-code';
btn.textContent = 'copy';
btn.setAttribute('aria-label', 'Copy code');
const codeText = code.textContent || '';
btn.addEventListener('click', () => {
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(codeText);
} else {
const ta = document.createElement('textarea');
ta.value = codeText;
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
document.body.removeChild(ta);
}
btn.textContent = 'copied!';
setTimeout(() => {
btn.textContent = 'copy';
}, 2000);
});
pre.appendChild(btn);
});
}
export function initPostContent(selector: string): void {
const root = document.querySelector(selector);
if (!root) return;
initCopyButtons(root);
}