UNPKG

@novacbn/svelte-codejar

Version:

Svelte Binding for the embeddable code editor CodeJar

56 lines (55 loc) 2.01 kB
import { CodeJar } from "codejar"; import { withLineNumbers as _withLineNumbers } from "codejar/linenumbers"; export function codejar(element, options) { let { highlight, onUpdate, syntax, value, withLineNumbers, ...extendedOptions } = options; let jar = CodeJar(element, wrapHighlight(highlight), extendedOptions); function destroy() { jar.destroy(); const wrap = element.parentElement; if (wrap && wrap.classList.contains("codejar-wrap")) { const parent = wrap.parentElement; element.style.padding = ""; parent.appendChild(element); wrap.remove(); } } function onInput(event) { if (onUpdate) onUpdate(jar.toString()); } function wrapHighlight(highlight) { const _highlight = highlight ? (element) => { var _a; element.innerHTML = highlight((_a = element.textContent) !== null && _a !== void 0 ? _a : "", syntax); } : (element) => void 0; return withLineNumbers ? _withLineNumbers(_highlight) : _highlight; } element.addEventListener("input", onInput); return { destroy() { destroy(); element.removeEventListener("input", onInput); }, update(newOptions) { ({ highlight, onUpdate, syntax, value, withLineNumbers, ...extendedOptions } = newOptions); if (options.highlight !== highlight || options.withLineNumbers !== withLineNumbers) { destroy(); jar = CodeJar(element, wrapHighlight(highlight), options); } else jar.updateOptions(extendedOptions); if (value !== jar.toString()) jar.updateCode(value); options = { highlight, value, withLineNumbers, ...extendedOptions }; }, }; }