<template>
	<div
		class="tui-markdown-view selectable break-all line-numbers"
		v-html="markdownHTML"
		:data-max-height="maxHeight"
	></div>
</template>
<script lang="ts" setup>
import Prism from "prismjs";
import Markdown from "../../utils/Markdown";

defineOptions({
	name: "MarkdownView"
});

const props = withDefaults(defineProps<{
	code?: string;
	content?: string;
	showCodeBorder?: boolean;
	maxHeight?: string;
}>(), {
	content: "",
	showCodeBorder: true,
	maxHeight: "400px"
});
const { content } = toRefs(props);
const markdownHTML = ref("");

const buildMarkdown = () => {
	if (props.code) {
		const codeRaw = props.code ?? "";
		const sepIndex = codeRaw.indexOf(":");
		const lang = sepIndex < 0 ? "" : codeRaw.slice(0, sepIndex).trim();
		const codeText = sepIndex < 0 ? codeRaw : codeRaw.slice(sepIndex + 1);
		const langTag = lang ? lang : "";

		return `\`\`\`${langTag}\n${codeText}\n\`\`\``;
	}
	return content.value;
};

const doRender = async () => {
	const markdownText = buildMarkdown();
	markdownHTML.value = await Markdown.getInstance().toHTML(markdownText);
	await nextTick();
	Prism.highlightAll();
};

watch(() => [props.code, props.content], doRender);
onMounted(doRender);
</script>
<style lang="less" scoped>
.tui-markdown-view {
	width: 100%;
	overflow: auto;
}
</style>
