FMHYedit/.vitepress/markdown/base64.ts

30 lines
1.2 KiB
TypeScript
Raw Normal View History

2024-07-10 04:05:54 +00:00
import type { MarkdownRenderer } from 'vitepress'
2023-11-12 16:42:57 +00:00
// FIXME: tasky: possibly write less horror jank?
export function base64DecodePlugin(md: MarkdownRenderer) {
2024-01-25 16:32:45 +00:00
const decode = (str: string): string =>
Buffer.from(str, 'base64').toString('binary')
2023-11-12 16:42:57 +00:00
// Save the original rule for backticks
const defaultRender =
md.renderer.rules.code_inline ||
2024-07-10 04:05:54 +00:00
function (tokens, idx, options, _env, self) {
2024-01-25 16:32:45 +00:00
return self.renderToken(tokens, idx, options)
}
2023-11-12 16:42:57 +00:00
md.renderer.rules.code_inline = function (tokens, idx, options, env, self) {
// @ts-expect-error shut the fuck up already I HATE THIS
2024-01-25 16:32:45 +00:00
if (
!env.frontmatter.title ||
(env.frontmatter.title && !env.frontmatter.title === 'base64')
) {
return defaultRender(tokens, idx, options, env, self)
2023-11-12 16:42:57 +00:00
}
2024-01-25 16:32:45 +00:00
const token = tokens[idx]
const content = token.content
2023-11-12 16:42:57 +00:00
return `<button class='base64' onclick="(function(btn){ const codeEl = btn.querySelector('code'); navigator.clipboard.writeText('${decode(
2024-01-25 16:32:45 +00:00
content
)}').then(() => { const originalText = codeEl.textContent; codeEl.textContent = 'Copied'; setTimeout(() => codeEl.textContent = originalText, 3000); }).catch(console.error); })(this)"><code>${content}</code></button>`
}
2023-11-12 16:42:57 +00:00
}