Repository Public
1// Zone de texte riche : contentEditable piloté par beforeinput / Selection / Range, barre de mise en forme accessible, historique maison.2import { forwardRef, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState, type ReactNode } from "react"3import { createPortal } from "react-dom"4import { t, type MsgKey } from "../../i18n"5import { IMAGE_PRESETS, cidsToUrls, dropColors, findSnippetTrigger, type ImagePreset } from "../../mail/compose"6import { safeLinkHref } from "../../mail/links"7import { sanitizeEmailHtml } from "../../mail/sanitize"8import { sanitizeComposerHtml } from "../../state/composer"9import { Dialog, Field, Icon, type IconName } from "../kit"10import {11 EMPTY_FORMAT, History, assistScope, backspaceHandled, clearFormatting, deleteBefore, enterHandled, formatState, indent, insertHtml, insertImage, insertText, linkAt, normalize, outdent, pathToRange, plainText, run, serialize, setBlock,12 setLink, snapshot, toggleList, toggleMark, toggleQuote, unlink, type ChangeKind, type Command, type FormatState, type InlineImage,13} from "./editor"14import { CmpIcon, type CmpIconName } from "./icons"1516export interface RichEditorHandle {17 /** recopie tout de suite le contenu dans `onChange` (avant un enregistrement ou un envoi) */18 flush(): void19 insertHtml(html: string): void20 insertText(text: string): void21 insertImage(img: InlineImage): void22 getText(): string23 /** portée d'une aide à la rédaction (sélection, sinon texte rédigé hors signature et citation) et de quoi la remplacer */24 assist(): AssistHandle25 focus(): void26}27export interface AssistHandle {28 kind: "selection" | "authored"29 text: string30 /** remplace la portée par du texte brut (jamais interprété comme du balisage) ; une étape d'historique */31 replace(text: string): void32}33export interface SnippetLike {34 shortcut: string | null35 html: string36 subject?: string | null37}38export interface RichEditorProps {39 /** identifiant du document : le contenu n'est rechargé que si lui ou `rev` change (zone non contrôlée) */40 docKey: string41 rev: number42 html: string43 onChange: (html: string) => void44 label: string45 /** Content-ID des images en ligne permises et leur adresse d'affichage ; absent = aucune image */46 images?: { cids: ReadonlySet<string>; urlOf: (cid: string) => string | undefined; rev: number; onPick: () => void; onFiles: (files: File[]) => void; onPreset?: (cid: string, preset: ImagePreset) => void }47 /** fichiers collés qui ne sont pas des images */48 onFiles?: (files: File[]) => void49 snippets?: readonly SnippetLike[]50 onSnippet?: (s: SnippetLike) => void51 /** boutons ajoutés à la fin de la barre (extraits, modèles) */52 tools?: { id: string; icon: IconName; label: string; onClick: () => void }[]53 compact?: boolean54 placeholder?: string55}5657const MAC = typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform)58const MOD = MAC ? "⌘" : "Ctrl+"59const SHIFT = MAC ? "⇧" : "Shift+"60const ALT = MAC ? "⌥" : "Alt+"6162type ToolId = "bold" | "italic" | "underline" | "strike" | "h1" | "h2" | "ul" | "ol" | "outdent" | "indent" | "quote" | "code" | "link" | "image" | "clear" | "undo" | "redo"63interface Tool {64 id: ToolId | string65 icon: CmpIconName | { kit: IconName }66 label: string67 keys?: string68 pressed?: boolean69 disabled?: boolean70 run: () => void71 /** séparateur devant ce bouton */72 group?: boolean73}7475// ---------------------------------------------------------------- dialogue de lien76function LinkDialog({ initial, text, editing, onSubmit, onRemove, onClose }: { initial: string; text: string | null; editing: boolean; onSubmit: (href: string, text: string) => void; onRemove: () => void; onClose: () => void }) {77 const [url, setUrl] = useState(initial)78 const [label, setLabel] = useState(text ?? "")79 const [bad, setBad] = useState(false)80 const submit = () => {81 const raw = url.trim()82 const href = safeLinkHref(/^[a-z][a-z0-9+.-]*:/i.test(raw) ? raw : /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(raw) ? `mailto:${raw}` : `https://${raw}`)83 if (!raw || !href || /^https?:\/\/[^./]*$/i.test(href)) return setBad(true)84 onSubmit(href, label)85 onClose()86 }87 return createPortal(88 <Dialog89 title={editing ? t("cmp.link.edit") : t("compose.link")}90 onClose={onClose}91 footer={92 <>93 {editing ? (94 <button95 type="button"96 className="btn danger"97 onClick={() => {98 onRemove()99 onClose()100 }}101 >102 {t("cmp.link.remove")}103 </button>104 ) : null}105 <span className="spacer" />106 <button type="button" className="btn" onClick={onClose}>107 {t("common.cancel")}108 </button>109 <button type="button" className="btn primary" onClick={submit}>110 {editing ? t("cmp.link.apply") : t("compose.insertLink")}111 </button>112 </>113 }114 >115 <form116 className="stack"117 onSubmit={(e) => {118 e.preventDefault()119 submit()120 }}121 >122 <Field label={t("compose.linkUrl")} id="cmp-link-url" hint={bad ? undefined : t("cmp.link.hint")}>123 <input124 id="cmp-link-url"125 className="input"126 data-autofocus127 value={url}128 inputMode="url"129 autoComplete="off"130 spellCheck={false}131 aria-invalid={bad}132 aria-describedby={bad ? "cmp-link-error" : undefined}133 onChange={(e) => {134 setUrl(e.target.value)135 setBad(false)136 }}137 />138 </Field>139 {bad ? (140 <p id="cmp-link-error" className="small cmp-field-error" role="alert">141 {t("cmp.link.invalid")}142 </p>143 ) : null}144 {text !== null ? (145 <Field label={t("cmp.link.text")} id="cmp-link-text">146 <input id="cmp-link-text" className="input" value={label} onChange={(e) => setLabel(e.target.value)} />147 </Field>148 ) : null}149 </form>150 </Dialog>,151 document.body,152 )153}154155// ---------------------------------------------------------------- barre de mise en forme (un seul arrêt de tabulation, flèches entre les boutons)156function Toolbar({ tools, label, onLeave }: { tools: Tool[]; label: string; onLeave: () => void }) {157 const [current, setCurrent] = useState(0)158 const ref = useRef<HTMLDivElement>(null)159 const index = Math.min(current, tools.length - 1)160 const move = (to: number) => {161 const n = (to + tools.length) % tools.length162 setCurrent(n)163 ref.current?.querySelectorAll<HTMLButtonElement>("button")[n]?.focus()164 }165 return (166 <div167 ref={ref}168 className="editor-tools cmp-toolbar"169 role="toolbar"170 aria-label={label}171 aria-orientation="horizontal"172 onKeyDown={(e) => {173 if (e.key === "ArrowRight") move(index + 1)174 else if (e.key === "ArrowLeft") move(index - 1)175 else if (e.key === "Home") move(0)176 else if (e.key === "End") move(tools.length - 1)177 else if (e.key === "Escape") {178 e.stopPropagation()179 onLeave()180 } else return181 e.preventDefault()182 }}183 >184 {tools.map((tool, i) => (185 <button186 key={tool.id}187 type="button"188 className={`tool cmp-tool${tool.group ? " cmp-tool-group" : ""}`}189 data-tool={tool.id}190 tabIndex={i === index ? 0 : -1}191 aria-label={tool.label}192 aria-pressed={tool.pressed}193 aria-disabled={tool.disabled || undefined}194 title={tool.keys ? `${tool.label} (${tool.keys})` : tool.label}195 // la sélection du texte ne doit pas se perdre au clic196 onMouseDown={(e) => e.preventDefault()}197 onFocus={() => setCurrent(i)}198 onClick={() => {199 if (!tool.disabled) tool.run()200 }}201 >202 {typeof tool.icon === "string" ? <CmpIcon name={tool.icon} /> : <Icon name={tool.icon.kit} />}203 </button>204 ))}205 </div>206 )207}208209// ---------------------------------------------------------------- réglages d'une image en ligne210function ImageTools({ img, onPreset, onAlt, onRemove, onClose }: { img: HTMLImageElement; onPreset: (p: ImagePreset) => void; onAlt: (alt: string) => void; onRemove: () => void; onClose: () => void }) {211 const [alt, setAlt] = useState(img.getAttribute("alt") ?? "")212 const width = Number(img.getAttribute("width")) || 0213 const natural = img.naturalWidth || 0214 const presets: ImagePreset[] = ["small", "medium", "large", "original"]215 const active = presets.find((p) => (p === "original" ? !width || width === natural : width === Math.min(IMAGE_PRESETS[p], natural || IMAGE_PRESETS[p])))216 return (217 <div218 className="cmp-image-tools"219 role="group"220 aria-label={t("cmp.image.tools")}221 onKeyDown={(e) => {222 if (e.key === "Escape") {223 e.stopPropagation()224 onClose()225 }226 }}227 >228 <div className="cmp-image-sizes" role="radiogroup" aria-label={t("cmp.image.size")}>229 {presets.map((p) => (230 <button key={p} type="button" role="radio" aria-checked={active === p} className="cmp-chip-btn" onClick={() => onPreset(p)}>231 {t(`cmp.image.size.${p}` as MsgKey)}232 </button>233 ))}234 </div>235 <label className="cmp-image-alt">236 <span className="small">{t("cmp.image.alt")}</span>237 <input238 className="input"239 value={alt}240 maxLength={300}241 placeholder={t("cmp.image.altHint")}242 onChange={(e) => {243 setAlt(e.target.value)244 onAlt(e.target.value)245 }}246 />247 </label>248 <div className="row">249 <button type="button" className="btn small danger" onClick={onRemove}>250 {t("cmp.image.remove")}251 </button>252 <span className="spacer" />253 <button type="button" className="btn small" onClick={onClose}>254 {t("common.close")}255 </button>256 </div>257 </div>258 )259}260261/** HTML collé ou déposé : réduit à la liste blanche de la rédaction (aucune image, aucun contenu actif), couleurs d'origine retirées. */262function pastedHtml(raw: string): string {263 const doc = new DOMParser().parseFromString(`<body>${sanitizeComposerHtml(sanitizeEmailHtml(raw, { mode: "quote" }).body)}</body>`, "text/html")264 dropColors(doc.body)265 return doc.body.innerHTML266}267268/** Le curseur est-il dans une liste, une citation (ou un titre) ? Seuls ces cas ont une touche Entrée / Retour arrière à nous. */269function inStructure(root: Element, node: Node, headings: boolean): boolean {270 for (let n: Node | null = node; n && n !== root; n = n.parentNode) {271 const tag = (n as Element).tagName272 if (tag === "LI" || tag === "BLOCKQUOTE" || (headings && /^H[1-6]$/.test(tag ?? ""))) return true273 }274 return false275}276277// ---------------------------------------------------------------- éditeur278export const RichEditor = forwardRef<RichEditorHandle, RichEditorProps>(function RichEditor(props, ref) {279 const { docKey, rev, html, label, images, tools: extraTools, compact } = props280 const rootRef = useRef<HTMLDivElement>(null)281 const history = useRef(new History())282 const composing = useRef(false)283 const lastRange = useRef<Range | null>(null)284 const plainPaste = useRef(false)285 const pending = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)286 const emitted = useRef("")287 const live = useRef(props)288 live.current = props289 const [fmt, setFmt] = useState<FormatState>(EMPTY_FORMAT)290 const [stack, setStack] = useState({ undo: false, redo: false })291 const [link, setLink_] = useState<{ range: Range; href: string; text: string | null; editing: boolean } | null>(null)292 const [picked, setPicked] = useState<HTMLImageElement | null>(null)293 const [empty, setEmpty] = useState(true)294 const [, bump] = useState(0)295296 const currentRange = useCallback((): Range => {297 const root = rootRef.current!298 const sel = window.getSelection()299 if (sel && sel.rangeCount && root.contains(sel.anchorNode) && root.contains(sel.focusNode)) return sel.getRangeAt(0)300 const saved = lastRange.current301 if (saved && root.contains(saved.startContainer) && root.contains(saved.endContainer)) return saved302 const r = document.createRange()303 r.selectNodeContents(root.firstElementChild ?? root)304 r.collapse(true)305 return r306 }, [])307 const select = useCallback((range: Range) => {308 const sel = window.getSelection()309 if (!sel) return310 sel.removeAllRanges()311 sel.addRange(range)312 lastRange.current = range.cloneRange()313 }, [])314 const refresh = useCallback(() => {315 const root = rootRef.current316 if (!root) return317 const sel = window.getSelection()318 const inside = !!sel && sel.rangeCount > 0 && root.contains(sel.anchorNode)319 if (inside) lastRange.current = sel!.getRangeAt(0).cloneRange()320 setFmt(formatState(root, inside ? sel!.getRangeAt(0) : lastRange.current))321 setStack({ undo: history.current.canUndo, redo: history.current.canRedo })322 setEmpty((root.textContent ?? "").replace(//g, "") === "" && !root.querySelector("img, li, blockquote, hr, table"))323 }, [])324 const emitNow = useCallback(() => {325 clearTimeout(pending.current)326 pending.current = undefined327 if (!rootRef.current) return328 // rien n'est signalé tant que le contenu est celui chargé (ou déjà transmis) : ouvrir un brouillon ne le modifie pas329 const out = serialize(rootRef.current)330 if (out === emitted.current) return331 emitted.current = out332 live.current.onChange(out)333 }, [])334 const changed = useCallback(335 (kind: ChangeKind) => {336 const root = rootRef.current337 if (!root) return338 const sel = window.getSelection()339 history.current.record(snapshot(root, sel && sel.rangeCount && root.contains(sel.anchorNode) ? sel.getRangeAt(0) : null), kind)340 // pendant la frappe, le brouillon suit à intervalle régulier (et non à la première pause) : l'enregistrement341 // automatique voit ainsi que l'on écrit encore342 if (kind === "typing" || kind === "attr") pending.current ??= setTimeout(emitNow, 250)343 else {344 clearTimeout(pending.current)345 pending.current = setTimeout(emitNow, 0)346 }347 refresh()348 },349 [emitNow, refresh],350 )351 /** Exécute une commande sur la sélection (rétablie dans la zone si le focus était ailleurs), puis note l'étape. */352 const exec = useCallback(353 (command: Command, kind: ChangeKind = "command") => {354 const root = rootRef.current355 if (!root) return356 const range = currentRange()357 root.focus({ preventScroll: true })358 select(run(root, range, command))359 changed(kind)360 },361 [changed, currentRange, select],362 )363 const restore = useCallback(364 (snap: { html: string; sel: Parameters<typeof pathToRange>[1] | null } | null) => {365 const root = rootRef.current366 if (!snap || !root) return367 root.innerHTML = snap.html368 root.focus({ preventScroll: true })369 if (snap.sel) {370 try {371 select(pathToRange(root, snap.sel))372 } catch {373 /* sélection introuvable : le curseur reste où le navigateur le pose */374 }375 }376 setPicked(null)377 clearTimeout(pending.current)378 pending.current = setTimeout(emitNow, 0)379 refresh()380 },381 [emitNow, refresh, select],382 )383 const undo = useCallback(() => restore(history.current.undo()), [restore])384 const redo = useCallback(() => restore(history.current.redo()), [restore])385386 // contenu non contrôlé : rechargé seulement quand le document est remplacé par programme387 useLayoutEffect(() => {388 const root = rootRef.current389 if (!root) return390 // le HTML est d'abord monté dans un document inerte : les images y reçoivent leur adresse d'affichage avant d'entrer dans la page391 // (un `src="cid:…"` posé directement dans la page y serait chargé, et refusé par la politique de sécurité du contenu)392 const inert = new DOMParser().parseFromString(`<body>${sanitizeComposerHtml(html, images?.cids)}</body>`, "text/html")393 if (images) cidsToUrls(inert.body, images.urlOf)394 root.replaceChildren(...Array.from(inert.body.childNodes).map((n) => document.adoptNode(n)))395 normalize(root)396 history.current.reset(snapshot(root, null))397 emitted.current = serialize(root)398 lastRange.current = null399 setPicked(null)400 refresh()401 // eslint-disable-next-line react-hooks/exhaustive-deps402 }, [docKey, rev])403 // une image dont l'adresse vient d'être connue (téléversement, brouillon relu) s'affiche sans recharger le document404 useEffect(() => {405 const root = rootRef.current406 if (!root || !images) return407 for (const img of Array.from(root.querySelectorAll<HTMLImageElement>("img[data-cid]"))) {408 if (img.getAttribute("src")) continue409 const url = images.urlOf(img.getAttribute("data-cid") ?? "")410 if (url) img.setAttribute("src", url)411 }412 // eslint-disable-next-line react-hooks/exhaustive-deps413 }, [images?.rev])414 useEffect(() => () => clearTimeout(pending.current), [])415416 const openLink = useCallback(() => {417 const root = rootRef.current418 if (!root) return419 const range = currentRange().cloneRange()420 const a = linkAt(root, range)421 setLink_({ range, href: a?.getAttribute("href") ?? "https://", text: range.collapsed && !a ? "" : null, editing: !!a })422 }, [currentRange])423424 /** `;raccourci` devant le curseur : remplacé par l'extrait. Rend vrai si une expansion a eu lieu. */425 const expandSnippet = useCallback((): boolean => {426 const root = rootRef.current427 const list = live.current.snippets428 const sel = window.getSelection()429 if (!root || !list?.length || !sel || !sel.isCollapsed || !sel.rangeCount || !root.contains(sel.anchorNode)) return false430 const caret = sel.getRangeAt(0)431 const node = caret.startContainer432 if (node.nodeType !== 3) return false433 const before = (node as Text).data.slice(0, caret.startOffset)434 const hit = findSnippetTrigger(before, list.map((s) => s.shortcut).filter((s): s is string => !!s))435 if (!hit) return false436 const snip = list.find((s) => s.shortcut?.toLowerCase() === hit.shortcut)437 if (!snip) return false438 exec((ctx) => {439 deleteBefore(before.length - hit.start)(ctx)440 insertHtml(sanitizeComposerHtml(snip.html))(ctx)441 })442 live.current.onSnippet?.(snip)443 return true444 }, [exec])445446 // événements natifs : `beforeinput` porte le type de saisie (React n'en expose qu'une imitation)447 useEffect(() => {448 const root = rootRef.current449 if (!root) return450 const onBeforeInput = (e: InputEvent) => {451 // composition (accents morts, saisie CJK) : le navigateur garde la main, rien n'est intercepté452 if (composing.current || e.isComposing) return453 const stop = (fn: () => void) => {454 e.preventDefault()455 fn()456 }457 switch (e.inputType) {458 case "formatBold":459 return stop(() => exec(toggleMark("bold")))460 case "formatItalic":461 return stop(() => exec(toggleMark("italic")))462 case "formatUnderline":463 return stop(() => exec(toggleMark("underline")))464 case "formatStrikeThrough":465 return stop(() => exec(toggleMark("strike")))466 case "formatIndent":467 return stop(() => exec(indent))468 case "formatOutdent":469 return stop(() => exec(outdent))470 case "insertOrderedList":471 return stop(() => exec(toggleList("ol")))472 case "insertUnorderedList":473 return stop(() => exec(toggleList("ul")))474 case "formatRemove":475 return stop(() => exec(clearFormatting))476 case "historyUndo":477 return stop(undo)478 case "historyRedo":479 return stop(redo)480 case "insertText":481 if (e.data === " " && expandSnippet()) e.preventDefault()482 return483 case "insertParagraph": {484 if (expandSnippet()) return e.preventDefault()485 let handled = false486 const range = currentRange()487 if (!range.collapsed || !inStructure(root, range.startContainer, false)) return488 const next = run(root, range, (ctx) => void (handled = enterHandled(ctx)))489 select(next)490 if (handled) {491 e.preventDefault()492 changed("command")493 }494 return495 }496 case "deleteContentBackward": {497 const range = currentRange()498 if (!range.collapsed || range.startOffset !== 0 || !inStructure(root, range.startContainer, true)) return499 let handled = false500 const next = run(root, range, (ctx) => void (handled = backspaceHandled(ctx)))501 select(next)502 if (handled) {503 e.preventDefault()504 changed("command")505 }506 return507 }508 default:509 return510 }511 }512 const onInput = () => {513 if (!composing.current) changed("typing")514 }515 const onCompositionStart = () => {516 composing.current = true517 }518 const onCompositionEnd = () => {519 composing.current = false520 changed("typing")521 }522 root.addEventListener("beforeinput", onBeforeInput)523 root.addEventListener("input", onInput)524 root.addEventListener("compositionstart", onCompositionStart)525 root.addEventListener("compositionend", onCompositionEnd)526 const onSelection = () => {527 if (root.contains(document.getSelection()?.anchorNode ?? null)) refresh()528 }529 document.addEventListener("selectionchange", onSelection)530 return () => {531 root.removeEventListener("beforeinput", onBeforeInput)532 root.removeEventListener("input", onInput)533 root.removeEventListener("compositionstart", onCompositionStart)534 root.removeEventListener("compositionend", onCompositionEnd)535 document.removeEventListener("selectionchange", onSelection)536 }537 }, [changed, currentRange, exec, expandSnippet, redo, refresh, select, undo])538539 useImperativeHandle(540 ref,541 () => ({542 flush: emitNow,543 insertHtml: (h) => exec(insertHtml(h), "paste"),544 insertText: (text) => exec(insertText(text), "paste"),545 insertImage: (img) => exec(insertImage(img), "paste"),546 getText: () => (rootRef.current ? plainText(rootRef.current) : ""),547 assist: () => {548 const root = rootRef.current549 if (!root) return { kind: "authored", text: "", replace: () => {} }550 const sel = window.getSelection()551 const live = sel && sel.rangeCount && root.contains(sel.anchorNode) && root.contains(sel.focusNode) ? sel.getRangeAt(0) : lastRange.current552 const scope = assistScope(root, live && root.contains(live.startContainer) ? live : null)553 return {554 kind: scope.kind,555 text: scope.text,556 replace: (text) => {557 const range = scope.range && root.contains(scope.range.startContainer) && root.contains(scope.range.endContainer) ? scope.range : null558 const at = range ?? document.createRange()559 if (!range) {560 at.selectNodeContents(root.firstElementChild ?? root)561 at.collapse(true)562 }563 select(at)564 exec(insertText(text), "paste")565 },566 }567 },568 focus: () => {569 const root = rootRef.current570 if (!root) return571 root.focus({ preventScroll: true })572 select(currentRange())573 },574 }),575 [currentRange, emitNow, exec, select],576 )577578 const onKeyDown = (e: React.KeyboardEvent) => {579 if (e.nativeEvent.isComposing || composing.current) return580 const mod = e.metaKey || e.ctrlKey581 const key = e.key.toLowerCase()582 const done = (fn: () => void) => {583 e.preventDefault()584 fn()585 }586 if (e.altKey && e.key === "F10") return done(() => rootRef.current?.parentElement?.querySelector<HTMLElement>('.cmp-toolbar button[tabindex="0"]')?.focus())587 if (e.key === "Tab" && !mod && !e.altKey) {588 if (!e.shiftKey && expandSnippet()) return e.preventDefault()589 // dans une liste, Tab change de niveau ; ailleurs il garde son rôle (quitter la zone)590 if (fmt.list) return done(() => exec(e.shiftKey ? outdent : indent))591 return592 }593 if (!mod) return594 if (key === "v" && e.shiftKey) {595 // « coller sans mise en forme » : l'événement de collage qui suit prendra le texte brut596 plainPaste.current = true597 setTimeout(() => (plainPaste.current = false), 800)598 return599 }600 if (e.altKey && (e.code === "Digit1" || e.code === "Digit2")) return done(() => exec(setBlock(e.code === "Digit1" ? "h1" : "h2")))601 if (e.altKey && e.code === "Digit0") return done(() => exec(setBlock("p")))602 if (e.altKey) return603 if (key === "z") return done(e.shiftKey ? redo : undo)604 if (key === "y" && !e.shiftKey) return done(redo)605 if (key === "b" && !e.shiftKey) return done(() => exec(toggleMark("bold")))606 if (key === "i" && !e.shiftKey) return done(() => exec(toggleMark("italic")))607 if (key === "u" && !e.shiftKey) return done(() => exec(toggleMark("underline")))608 if (key === "x" && e.shiftKey) return done(() => exec(toggleMark("strike")))609 if (key === "e" && !e.shiftKey) return done(() => exec(toggleMark("code")))610 if (key === "k" && !e.shiftKey) {611 // ⌘K ouvre la palette ailleurs ; dans le texte, c'est « lien »612 e.stopPropagation()613 e.nativeEvent.stopImmediatePropagation()614 return done(openLink)615 }616 if (e.shiftKey && e.code === "Digit7") return done(() => exec(toggleList("ol")))617 if (e.shiftKey && e.code === "Digit8") return done(() => exec(toggleList("ul")))618 if (e.shiftKey && e.code === "Digit9") return done(() => exec(toggleQuote))619 if (e.code === "BracketRight") return done(() => exec(indent))620 if (e.code === "BracketLeft") return done(() => exec(outdent))621 if (e.code === "Backslash") return done(() => exec(clearFormatting))622 }623624 const onPaste = (e: React.ClipboardEvent) => {625 const data = e.clipboardData626 const files = Array.from(data.files)627 if (files.length) {628 e.preventDefault()629 const pics = images ? files.filter((f) => /^image\/(png|jpeg|gif|webp)$/i.test(f.type)) : []630 const rest = files.filter((f) => !pics.includes(f))631 if (pics.length) images!.onFiles(pics)632 if (rest.length) props.onFiles?.(rest)633 return634 }635 const rich = plainPaste.current ? "" : data.getData("text/html")636 plainPaste.current = false637 e.preventDefault()638 if (rich) {639 // le HTML collé est réduit à la liste blanche de la rédaction avant d'entrer dans la page (aucune image distante)640 const clean = pastedHtml(rich)641 if (clean.trim()) return exec(insertHtml(clean), "paste")642 }643 const text = data.getData("text/plain")644 if (text) exec(insertText(text), "paste")645 }646 const onDrop = (e: React.DragEvent) => {647 // les fichiers sont pris par la fenêtre de rédaction ; tout autre contenu déposé est assaini comme un collage648 if (e.dataTransfer.types.includes("Files")) return649 e.preventDefault()650 const root = rootRef.current!651 const doc = document as Document & { caretRangeFromPoint?: (x: number, y: number) => Range | null; caretPositionFromPoint?: (x: number, y: number) => { offsetNode: Node; offset: number } | null }652 let at: Range | null = doc.caretRangeFromPoint?.(e.clientX, e.clientY) ?? null653 if (!at && doc.caretPositionFromPoint) {654 const p = doc.caretPositionFromPoint(e.clientX, e.clientY)655 if (p) {656 at = document.createRange()657 at.setStart(p.offsetNode, p.offset)658 at.collapse(true)659 }660 }661 if (at && root.contains(at.startContainer)) select(at)662 const rich = e.dataTransfer.getData("text/html")663 const clean = rich ? pastedHtml(rich) : ""664 if (clean.trim()) exec(insertHtml(clean), "paste")665 else {666 const text = e.dataTransfer.getData("text/plain")667 if (text) exec(insertText(text), "paste")668 }669 }670671 const mark = (id: "bold" | "italic" | "underline" | "strike" | "code") => () => exec(toggleMark(id))672 const tools: Tool[] = [673 { id: "bold", icon: "bold", label: t("compose.bold"), keys: `${MOD}B`, pressed: fmt.bold, run: mark("bold") },674 { id: "italic", icon: "italic", label: t("compose.italic"), keys: `${MOD}I`, pressed: fmt.italic, run: mark("italic") },675 { id: "underline", icon: "underline", label: t("compose.underline"), keys: `${MOD}U`, pressed: fmt.underline, run: mark("underline") },676 { id: "strike", icon: "strike", label: t("cmp.fmt.strike"), keys: `${MOD}${SHIFT}X`, pressed: fmt.strike, run: mark("strike") },677 ...(compact678 ? []679 : ([680 { id: "h1", icon: "h1", label: t("cmp.fmt.h1"), keys: `${MOD}${ALT}1`, pressed: fmt.block === "h1", run: () => exec(setBlock("h1")), group: true },681 { id: "h2", icon: "h2", label: t("cmp.fmt.h2"), keys: `${MOD}${ALT}2`, pressed: fmt.block === "h2", run: () => exec(setBlock("h2")) },682 ] satisfies Tool[])),683 { id: "ul", icon: { kit: "list" }, label: t("compose.bullets"), keys: `${MOD}${SHIFT}8`, pressed: fmt.list === "ul", run: () => exec(toggleList("ul")), group: true },684 { id: "ol", icon: "ol", label: t("compose.numbers"), keys: `${MOD}${SHIFT}7`, pressed: fmt.list === "ol", run: () => exec(toggleList("ol")) },685 ...(compact686 ? []687 : ([688 { id: "outdent", icon: "outdent", label: t("cmp.fmt.outdent"), keys: `${MOD}[`, disabled: !fmt.list, run: () => exec(outdent) },689 { id: "indent", icon: "indent", label: t("cmp.fmt.indent"), keys: `${MOD}]`, disabled: !fmt.list, run: () => exec(indent) },690 ] satisfies Tool[])),691 { id: "quote", icon: "quote", label: t("compose.quote"), keys: `${MOD}${SHIFT}9`, pressed: fmt.quote, run: () => exec(toggleQuote), group: true },692 { id: "code", icon: { kit: "code" }, label: t("cmp.fmt.code"), keys: `${MOD}E`, pressed: fmt.code, run: mark("code") },693 { id: "link", icon: "link", label: fmt.link ? t("cmp.link.edit") : t("compose.link"), keys: `${MOD}K`, pressed: !!fmt.link, run: openLink },694 ...(images ? ([{ id: "image", icon: { kit: "image" }, label: t("cmp.image.insert"), run: images.onPick }] satisfies Tool[]) : []),695 { id: "clear", icon: "clear", label: t("compose.clear"), keys: `${MOD}\\`, run: () => exec(clearFormatting), group: true },696 { id: "undo", icon: "undo", label: t("cmp.fmt.undo"), keys: `${MOD}Z`, disabled: !stack.undo, run: undo },697 { id: "redo", icon: "redo", label: t("cmp.fmt.redo"), keys: `${MOD}${SHIFT}Z`, disabled: !stack.redo, run: redo },698 ...(extraTools ?? []).map((x, i): Tool => ({ id: x.id, icon: { kit: x.icon }, label: x.label, run: x.onClick, group: i === 0 })),699 ]700701 let imageTools: ReactNode = null702 if (picked && picked.isConnected) {703 imageTools = (704 <ImageTools705 key={picked.getAttribute("data-cid") ?? "img"}706 img={picked}707 onClose={() => setPicked(null)}708 onAlt={(alt) => {709 picked.setAttribute("alt", alt)710 changed("attr")711 }}712 onPreset={(p) => {713 const natural = picked.naturalWidth || 0714 if (p === "original") picked.removeAttribute("width")715 else picked.setAttribute("width", String(natural ? Math.min(IMAGE_PRESETS[p], natural) : IMAGE_PRESETS[p]))716 changed("command")717 images?.onPreset?.(picked.getAttribute("data-cid") ?? "", p)718 bump((n) => n + 1)719 }}720 onRemove={() => {721 picked.remove()722 setPicked(null)723 if (rootRef.current) normalize(rootRef.current)724 changed("command")725 }}726 />727 )728 }729730 return (731 <div className={`cmp-rich${compact ? " cmp-rich-compact" : ""}`}>732 <Toolbar tools={tools} label={t("compose.formatting")} onLeave={() => rootRef.current?.focus()} />733 <div className="cmp-editor-wrap">734 <div735 ref={rootRef}736 className={`editor cmp-editor${empty && props.placeholder ? " cmp-editor-empty" : ""}`}737 contentEditable738 suppressContentEditableWarning739 role="textbox"740 aria-multiline="true"741 aria-label={label}742 data-placeholder={props.placeholder}743 spellCheck744 onKeyDown={onKeyDown}745 onPaste={onPaste}746 onDrop={onDrop}747 // le déplacement de texte à la souris insérerait du contenu non assaini : il est désactivé (couper-coller reste possible)748 onDragStart={(e) => e.preventDefault()}749 onBlur={emitNow}750 onClick={(e) => {751 const el = e.target as HTMLElement752 if (el.tagName === "IMG" && images) setPicked(el as HTMLImageElement)753 else if (picked) setPicked(null)754 // clic dans le vide sous le texte : le navigateur poserait le curseur à la fin du dernier bloc — la signature.755 // On écrit au-dessus d'elle, pas dedans.756 const root = rootRef.current757 const last = root?.lastElementChild758 if (root && el === root && last?.classList.contains("spm-signature") && e.clientY > last.getBoundingClientRect().bottom) {759 let before = last.previousElementSibling760 if (!before || before.tagName === "BLOCKQUOTE" || before.classList.contains("spm-signature")) {761 before = document.createElement("div")762 before.appendChild(document.createElement("br"))763 last.before(before)764 }765 // message encore vide : on commence par sa première ligne, pas par la dernière ligne blanche766 const blank = (n: Element | null): n is Element => !!n && (n.tagName === "DIV" || n.tagName === "P") && (n.textContent ?? "").replace(/\u200b/g, "") === "" && !n.querySelector("img")767 while (blank(before) && blank(before.previousElementSibling)) before = before.previousElementSibling768 const r = document.createRange()769 r.selectNodeContents(before)770 r.collapse(false)771 // un <br> final ne se dépasse pas : le curseur se place devant lui772 if (before.lastChild?.nodeName === "BR") r.setEndBefore(before.lastChild), r.collapse(false)773 select(r)774 }775 }}776 />777 {imageTools}778 </div>779 {link ? (780 <LinkDialog781 initial={link.href}782 text={link.text}783 editing={link.editing}784 onClose={() => setLink_(null)}785 onRemove={() => {786 setTimeout(() => {787 select(link.range)788 exec(unlink)789 }, 0)790 }}791 onSubmit={(href, text) => {792 // le dialogue rend le focus à la zone ; la sélection d'origine est rétablie avant de poser le lien793 setTimeout(() => {794 select(link.range)795 exec(setLink(href, text))796 }, 0)797 }}798 />799 ) : null}800 </div>801 )802})803