Files
chatgpt-web/src/lib/Code.svelte

61 lines
1.9 KiB
Svelte
Raw Normal View History

2023-03-06 14:15:52 +01:00
<script lang="ts">
2024-06-28 17:43:45 +09:00
import { HighlightAuto } from 'svelte-highlight'
2023-03-06 14:15:52 +01:00
// Import both dark and light styles
import { github, githubDark } from 'svelte-highlight/styles/index'
// Style depends on system theme
2023-03-20 15:35:07 +01:00
const style = window.matchMedia('(prefers-color-scheme: dark)').matches ? githubDark : github
2023-03-12 16:22:43 +08:00
// Copy function for the code block
2023-03-20 15:35:07 +01:00
import copy from 'copy-to-clipboard'
2023-03-12 16:22:43 +08:00
2024-04-23 09:10:57 +09:00
import 'katex/contrib/mhchem'
2024-06-21 02:55:19 +09:00
import renderMathInElement from 'katex/contrib/auto-render'
2024-04-23 09:10:57 +09:00
2023-03-20 15:35:07 +01:00
export const type: 'code' = 'code'
export const raw: string = ''
export const codeBlockStyle: 'indented' | undefined = undefined
export let text: string
2023-03-06 14:15:52 +01:00
2025-07-05 22:32:51 +09:00
let renderedMath: string | undefined
2023-03-12 16:22:43 +08:00
2023-03-13 09:13:32 +01:00
// For copying code - reference: https://vyacheslavbasharov.com/blog/adding-click-to-copy-code-markdown-blog
const copyFunction = (event) => {
2023-03-13 09:13:32 +01:00
// Get the button the user clicked on
2023-03-20 15:35:07 +01:00
const clickedElement = event.target as HTMLButtonElement
2023-03-13 09:13:32 +01:00
// Get the next element
2023-03-20 15:47:11 +01:00
const nextElement = clickedElement.nextElementSibling as HTMLElement
2023-03-13 09:13:32 +01:00
// Modify the appearance of the button
2023-03-20 15:35:07 +01:00
const originalButtonContent = clickedElement.innerHTML
clickedElement.classList.add('is-success')
clickedElement.innerHTML = 'Copied!'
2023-03-13 09:13:32 +01:00
// Retrieve the code in the code block
2023-03-20 15:35:07 +01:00
const codeBlock = (nextElement.querySelector('pre > code') as HTMLPreElement).innerText
copy(codeBlock)
2023-03-13 09:13:32 +01:00
// Restored the button after copying the text in 1 second.
setTimeout(() => {
2023-03-20 15:35:07 +01:00
clickedElement.innerHTML = originalButtonContent
clickedElement.classList.remove('is-success')
clickedElement.blur()
}, 1000)
}
2023-03-06 14:15:52 +01:00
</script>
<svelte:head>
{@html style}
</svelte:head>
2024-06-21 02:55:19 +09:00
{#if renderedMath}
2024-04-23 09:10:57 +09:00
{@html renderedMath}
{:else}
<div class="code-block is-relative">
<button class="button is-light is-outlined is-small p-2" on:click={copyFunction}>Copy</button>
2024-06-28 17:43:45 +09:00
<HighlightAuto code={text} />
2024-04-23 09:10:57 +09:00
</div>
2024-06-28 17:37:38 +09:00
{/if}