<template>
	<section>
		<el-icon v-if="copy" class="copy" size="24px" v-copy="copyVal">
			<component :is="'el-icon-copy-document'"/>
		</el-icon>
		<pre><code ref="codeRef" :class="`language-${lang}`"><slot></slot></code></pre>
	</section>
</template>

<script setup>
import {nextTick, ref, useSlots, watch} from "vue"
import hljs from "highlight.js"
import "highlight.js/styles/github.css"

const slots = useSlots()
const codeRef = ref(null)
const props = defineProps({
	lang: {type: String, required: true, default: ""},
	copy: {type: Boolean, default: false},
})
let copyVal = ref("")

watch(() => slots.default?.(), () => {
		highlightCode();
	}
)

const highlightCode = () => {
	nextTick(() => {
		if (codeRef.value) {
			copyVal.value = codeRef.value?.innerText || ""
			codeRef.value.removeAttribute('data-highlighted');
			hljs.highlightElement(codeRef.value);
		}
	})
}
</script>
<style scoped>
.copy {
	float: right;
}
</style>
