Repository Public
1// Éditeur de source léger : <textarea> à chasse fixe, numéros de ligne, retour automatique au choix, tabulation, recherche.2// Aucune dépendance : reste fluide sur un document de 80 Ko (une seule zone de texte native, gouttière en un seul nœud texte).3import { memo, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react"4import { t } from "../../i18n"5import { applyTab, findAll, lineOfOffset, wrappedRows } from "../../templates/variables"6import { Icon, IconButton } from "../kit"78const LINE_H = 209const PAD = 101011export interface CodeEditorProps {12 value: string13 onChange: (value: string) => void14 label: string15 /** langue du contenu pour la vérification orthographique : aucune pour du HTML */16 plain?: boolean17 testId?: string18}1920/** Remplace une portion du texte en gardant l'historique d'annulation du navigateur quand c'est possible. */21function replaceRange(el: HTMLTextAreaElement, start: number, end: number, text: string): boolean {22 el.focus()23 el.setSelectionRange(start, end)24 try {25 if (document.execCommand("insertText", false, text)) return true26 } catch {27 /* non pris en charge : repli ci-dessous */28 }29 el.setRangeText(text, start, end, "end")30 return false31}3233export const CodeEditor = memo(function CodeEditor({ value, onChange, label, plain, testId }: CodeEditorProps) {34 const area = useRef<HTMLTextAreaElement>(null)35 const gutter = useRef<HTMLPreElement>(null)36 const findInput = useRef<HTMLInputElement>(null)37 const id = useId()38 const [wrap, setWrap] = useState(false)39 const [cols, setCols] = useState(80)40 const [finding, setFinding] = useState(false)41 const [needle, setNeedle] = useState("")42 const [hit, setHit] = useState(0)43 const [caret, setCaret] = useState({ line: 1, col: 1 })4445 // largeur utile en colonnes (pour aligner les numéros quand les lignes reviennent à la ligne)46 useLayoutEffect(() => {47 const el = area.current48 if (!el || !wrap) return49 const measure = () => {50 const probe = document.createElement("span")51 probe.style.cssText = "position:absolute;visibility:hidden;white-space:pre;font:inherit"52 probe.textContent = "0".repeat(100)53 el.parentElement?.appendChild(probe)54 const cs = getComputedStyle(el)55 probe.style.font = cs.font56 const ch = probe.getBoundingClientRect().width / 10057 probe.remove()58 if (ch > 0) setCols(Math.max(10, Math.floor((el.clientWidth - 2 * PAD) / ch + 0.01)))59 }60 measure()61 const ro = new ResizeObserver(measure)62 ro.observe(el)63 return () => ro.disconnect()64 }, [wrap])6566 const numbers = useMemo(() => {67 if (!wrap) {68 let n = 169 for (let i = 0; i < value.length; i++) if (value.charCodeAt(i) === 10) n++70 const out = new Array<string>(n)71 for (let i = 0; i < n; i++) out[i] = String(i + 1)72 return { text: out.join("\n"), lines: n }73 }74 const rows = wrappedRows(value, cols)75 return { text: rows.map((r, i) => String(i + 1) + "\n".repeat(r - 1)).join("\n"), lines: rows.length }76 }, [value, wrap, cols])7778 const syncScroll = () => {79 if (gutter.current && area.current) gutter.current.style.transform = `translateY(${-area.current.scrollTop}px)`80 }81 const updateCaret = () => {82 const el = area.current83 if (!el) return84 const pos = el.selectionStart85 const line = lineOfOffset(el.value, pos)86 setCaret({ line: line + 1, col: pos - (el.value.lastIndexOf("\n", pos - 1) + 1) + 1 })87 }8889 // ---- recherche90 const hits = useMemo(() => (finding ? findAll(value, needle) : []), [finding, value, needle])91 const goTo = useCallback(92 (index: number, focusArea = false) => {93 const el = area.current94 if (!el || !hits.length) return95 const i = ((index % hits.length) + hits.length) % hits.length96 setHit(i)97 const start = hits[i]98 el.setSelectionRange(start, start + needle.length)99 if (!wrap) el.scrollTop = Math.max(0, lineOfOffset(el.value, start) * LINE_H - el.clientHeight / 2)100 else {101 const rows = wrappedRows(el.value.slice(0, start), cols)102 el.scrollTop = Math.max(0, rows.reduce((a, b) => a + b, 0) * LINE_H - el.clientHeight / 2)103 }104 syncScroll()105 if (focusArea) el.focus()106 },107 [hits, needle, wrap, cols],108 )109 useEffect(() => {110 if (finding && hits.length) goTo(0)111 else setHit(0)112 // seulement quand la recherche change113 // eslint-disable-next-line react-hooks/exhaustive-deps114 }, [needle, finding])115 const openFind = () => {116 const el = area.current117 const selected = el && el.selectionEnd > el.selectionStart && el.selectionEnd - el.selectionStart < 200 ? el.value.slice(el.selectionStart, el.selectionEnd) : ""118 if (selected && !selected.includes("\n")) setNeedle(selected)119 setFinding(true)120 requestAnimationFrame(() => {121 findInput.current?.focus()122 findInput.current?.select()123 })124 }125 const closeFind = () => {126 setFinding(false)127 area.current?.focus()128 }129130 const onKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {131 const el = e.currentTarget132 if ((e.metaKey || e.ctrlKey) && !e.altKey && e.key.toLowerCase() === "f") {133 e.preventDefault()134 openFind()135 return136 }137 // Échap puis Tab : sortir de l'éditeur au clavier (sinon Tab indente)138 if (e.key === "Escape") {139 el.dataset.tabOut = "1"140 return141 }142 if (e.key === "Tab" && !e.metaKey && !e.ctrlKey && !e.altKey) {143 if (el.dataset.tabOut === "1") {144 delete el.dataset.tabOut145 return146 }147 e.preventDefault()148 const { selectionStart: a, selectionEnd: b } = el149 if (a === b && !e.shiftKey) {150 if (!replaceRange(el, a, b, " ")) onChange(el.value)151 return152 }153 const lineStart = el.value.lastIndexOf("\n", a - 1) + 1154 const anchor = b > a && el.value[b - 1] === "\n" ? b - 1 : b155 let lineEnd = el.value.indexOf("\n", anchor)156 if (lineEnd === -1) lineEnd = el.value.length157 const next = applyTab(el.value, a, b, e.shiftKey)158 const delta = next.text.length - el.value.length159 const replaced = next.text.slice(lineStart, lineEnd + delta)160 if (!replaceRange(el, lineStart, lineEnd, replaced)) onChange(el.value)161 el.setSelectionRange(next.selStart, next.selEnd)162 return163 }164 delete el.dataset.tabOut165 }166167 return (168 <div className={`tpl-code${wrap ? " wrap" : ""}`} data-testid={testId}>169 <div className="tpl-code-bar">170 <IconButton icon="search" label={t("tpl.code.find")} shortcut="Ctrl/⌘+F" pressed={finding} onClick={() => (finding ? closeFind() : openFind())} />171 <IconButton icon="wrap" label={t("tpl.code.wrap")} pressed={wrap} onClick={() => setWrap((w) => !w)} />172 <span className="spacer" />173 <span className="muted small mono" aria-hidden="true">174 {t("tpl.code.position", { line: caret.line, col: caret.col })} · {t("tpl.code.lines", { n: numbers.lines })}175 </span>176 </div>177 {finding ? (178 <div className="tpl-find" role="search" aria-label={t("tpl.code.find")}>179 <input180 ref={findInput}181 className="input"182 type="search"183 value={needle}184 placeholder={t("tpl.code.findPlaceholder")}185 aria-label={t("tpl.code.findPlaceholder")}186 autoComplete="off"187 spellCheck={false}188 onChange={(e) => setNeedle(e.target.value)}189 onKeyDown={(e) => {190 if (e.key === "Enter") {191 e.preventDefault()192 goTo(hit + (e.shiftKey ? -1 : 1))193 } else if (e.key === "Escape") {194 e.preventDefault()195 e.stopPropagation()196 closeFind()197 }198 }}199 />200 <span className="muted small tpl-find-count" role="status" aria-live="polite">201 {needle ? (hits.length ? t("tpl.code.findCount", { i: hit + 1, n: hits.length }) : t("tpl.code.findNone")) : ""}202 </span>203 <IconButton icon="back" className="tpl-up" label={t("tpl.code.findPrev")} disabled={!hits.length} onClick={() => goTo(hit - 1)} />204 <IconButton icon="back" className="tpl-down" label={t("tpl.code.findNext")} disabled={!hits.length} onClick={() => goTo(hit + 1)} />205 <IconButton icon="close" label={t("tpl.code.findClose")} onClick={closeFind} />206 </div>207 ) : null}208 <div className="tpl-code-body">209 <div className="tpl-code-gutter" aria-hidden="true">210 <pre ref={gutter}>{numbers.text}</pre>211 </div>212 <textarea213 ref={area}214 id={id}215 className="tpl-code-area"216 aria-label={label}217 aria-describedby={`${id}-help`}218 value={value}219 spellCheck={plain ? undefined : false}220 autoCapitalize="off"221 autoCorrect="off"222 autoComplete="off"223 wrap={wrap ? "soft" : "off"}224 onChange={(e) => onChange(e.target.value)}225 onScroll={syncScroll}226 onKeyDown={onKeyDown}227 onKeyUp={updateCaret}228 onClick={updateCaret}229 onSelect={updateCaret}230 />231 </div>232 <p className="sr-only" id={`${id}-help`}>233 {t("tpl.code.help")}234 </p>235 </div>236 )237})238