<script setup>
import {onMounted, ref} from "vue";

const props = defineProps(["v-word"])
const textRef = ref()
const textValue = ref("")

onMounted(() => {
	let word = props.vWord
	if (word == null) {
		word = ""
	} else {
		word = word.replace(/\)/g, "\\)")
		word = word.replace(/\(/g, "\\(")
		word = word.replace(/\+/g, "\\+")
		word = word.replace(/\^/g, "\\^")
		word = word.replace(/\$/g, "\\$")
		word = word.replace(/\?/g, "\\?")
		word = word.replace(/\*/g, "\\*")
		word = word.replace(/\[/g, "\\[")
		word = word.replace(/{/g, "\\{")
		word = word.replace(/\./g, "\\.")
	}

	let text = textRef.value.textContent
	if (typeof text !== "string") {
		return
	}
	if (word.length > 0) {
		let m = []  // replacement => tmp
		let tmpIndex = 0
		text = text.replaceAll(new RegExp("(" + word + ")", "ig"), function (replacement) {
			tmpIndex++
			let s = "<span style=\"border: 1px #ccc dashed; color: #ef4d58\">" + encodeHTML(replacement) + "</span>"
			let tmpKey = "$TMP__KEY__" + tmpIndex.toString() + "$"
			m.push([tmpKey, s])
			return tmpKey
		})
		text = encodeHTML(text)

		m.forEach(function (r) {
			text = text.replace(r[0], r[1])
		})

	} else {
		text = encodeHTML(text)
	}

	textValue.value = text
})

const encodeHTML = function (s) {
	s = s.replace(/&/g, "&amp;")
	s = s.replace(/</g, "&lt;")
	s = s.replace(/>/g, "&gt;")
	s = s.replace(/"/g, "&quot;")
	return s
}
</script>

<template>
	<span>
		<span style="display: none" ref="textRef">
			<slot></slot>
		</span>
		<span v-html="textValue"></span>
	</span>
</template>

<style scoped>

</style>