generated at
use-KaTeX
scrapbox上で動かすpreactで使えるKaTeXReact Hooks

既知の問題
TypeError: o.body[0] is undefined が発生する
原因はわからん
rendering上は問題なさそうだし、握りつぶしちゃおtakker

dependencies
script.js
import {install} from '../KaTeX-CDN/script.js'; import {useState, useRef, useEffect} from '../preact@10.5.13/hooks.js'; export const useKaTeX = (_formula) => { const ref = useRef(null); const [formula, setFormula] = useState(_formula); const [error, setError] = useState(undefined); useEffect(() => { (async () => { await install(); try { katex.render(formula, ref.current); setError(undefined); } catch (e) { if (e instanceof katex.ParseError) { setError(e.message); } } })(); }, [formula, ref]); return {ref, formula, error, setFormula}; };

test code
js
import('/api/code/programming-notes/use-KaTeX/test1.js');
test1.js
import {html} from '../htm@3.0.4%2Fpreact/script.js'; import {useKaTeX} from './script.js'; import register from '../preact-custom-element@4.2.1/script.js'; const App = ({formula}) => { const {ref, error, setFormula} = useKaTeX(formula); return html` <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.12.0/katex.min.css" /> <style> :host {display: block;max-width: 20vw;} .error {color:#fd7373;} </style> <div class="${error ? 'error' : ''}"> ${error ?? ''}<span class="katex-display" ref="${ref}" /> </div> <input type="text" onInput="${({target}) => setFormula(target.value)}" /> `; }; register(App, 'userscript-katex-test', ['formula'], {shadow: true}); document.getElementById('editor') .insertAdjacentHTML('beforeend', '<userscript-katex-test formula="E=mc^2"></userscript-katex-test>');