{#- Based on https://www.roboleary.net/2022/01/13/copy-code-to-clipboard-blog.html -#}

<script type="text/javascript">
	document.addEventListener("DOMContentLoaded", function () {
		let blocks = document.querySelectorAll("pre[class^='language-']");

		blocks.forEach((block) => {
			if (navigator.clipboard) {
				// Code block header title
				let title = document.createElement("span");
				let lang = block.getAttribute("data-lang");
				title.innerHTML = lang;

				// Copy button icon
				let icon = document.createElement("i");
				icon.classList.add("icon");

				// Copy button label (for screen readers)
				let label = document.createElement("span");
				label.classList.add("hidden");
				label.innerHTML = "{{ macros_translate::translate(key='copy_code', default='Copy code', language_strings=language_strings) }}";

				// Copy button
				let button = document.createElement("button");
				button.appendChild(icon);
				button.appendChild(label);

				// Code block header
				let header = document.createElement("div");
				header.classList.add("header");
				header.appendChild(button);
				header.appendChild(title);

				// Container that holds header and the code block itself
				let container = document.createElement("div");
				container.classList.add("pre-container");
				container.appendChild(header);

				// Move code block into the container
				block.parentNode.insertBefore(container, block);
				container.appendChild(block);

				button.addEventListener("click", async () => {
					await copyCode(block, header);
				});
			}
		});

		async function copyCode(block, header) {
			let code = block.querySelector("code");
			let text = code.innerText;

			await navigator.clipboard.writeText(text);

			header.classList.add("active");

			setTimeout(() => {
				header.classList.remove("active");
			}, 800);
		}
	});
</script>
