SPB Git

Repository Public

editor.ts 39.4 KB 976 lines typescript

1// Éditeur de texte riche maison : commandes sur le DOM par Selection/Range (aucun document.execCommand), modèle normalisé, historique.2import { ZWSP, escapeHtml, urlsToCids } from "../../mail/compose"34export type Mark = "bold" | "italic" | "underline" | "strike" | "code"5export type BlockKind = "p" | "h1" | "h2"6export type Align = "left" | "center" | "right"78const MARK_TAGS: Record<Mark, string[]> = { bold: ["STRONG", "B"], italic: ["EM", "I"], underline: ["U"], strike: ["S", "STRIKE", "DEL"], code: ["CODE"] }9const MARK_TAG: Record<Mark, string> = { bold: "strong", italic: "em", underline: "u", strike: "s", code: "code" }10const INLINE_FORMAT = new Set(["STRONG", "B", "EM", "I", "U", "S", "STRIKE", "DEL", "CODE", "FONT", "SUB", "SUP", "SMALL", "SPAN"])11const LEAF = new Set(["DIV", "P", "H1", "H2", "H3", "H4", "H5", "H6", "LI", "PRE", "TD", "TH"])12const CONTAINER = new Set(["UL", "OL", "BLOCKQUOTE", "TABLE", "THEAD", "TBODY", "TR", "HR"])13const MARKER = "data-cmp-sel"14/** Style d'une citation créée ici : lisible dans les logiciels qui n'ont pas de style par défaut pour <blockquote>. */15export const QUOTE_STYLE = "margin: 0 0 0 0.8ex; border-left: 2px solid #c4c0b4; padding-left: 1ex"1617const isEl = (n: Node | null | undefined): n is Element => !!n && n.nodeType === 118const isText = (n: Node | null | undefined): n is Text => !!n && n.nodeType === 319const isBlock = (n: Node | null | undefined): boolean => isEl(n) && (LEAF.has(n.tagName) || CONTAINER.has(n.tagName))20const isMarker = (n: Node | null | undefined): boolean => isEl(n) && n.hasAttribute(MARKER)21const isList = (n: Node | null | undefined): n is Element => isEl(n) && (n.tagName === "UL" || n.tagName === "OL")22const indexOf = (n: Node): number => Array.prototype.indexOf.call(n.parentNode!.childNodes, n) as number23const uniq = <T>(list: T[]): T[] => list.filter((x, i) => list.indexOf(x) === i)2425function closestIn(root: Element, node: Node | null, test: (el: Element) => boolean): Element | null {26  for (let n: Node | null = node; n && n !== root; n = n.parentNode) if (isEl(n) && test(n)) return n27  return null28}29const blockOf = (root: Element, node: Node | null): Element | null => closestIn(root, node, (el) => LEAF.has(el.tagName))30const markOf = (root: Element, node: Node | null, mark: Mark): Element | null => closestIn(root, node, (el) => MARK_TAGS[mark].includes(el.tagName))3132function rename(el: Element, tag: string, keepAttrs = true): Element {33  if (el.tagName === tag.toUpperCase()) return el34  const next = el.ownerDocument.createElement(tag)35  if (keepAttrs) for (const a of Array.from(el.attributes)) next.setAttribute(a.name, a.value)36  while (el.firstChild) next.appendChild(el.firstChild)37  el.replaceWith(next)38  return next39}40/** Contenu visible d'un élément (les porteurs de largeur nulle et les repères de sélection ne comptent pas). */41function isVisiblyEmpty(el: Element): boolean {42  return (el.textContent ?? "").replace(/[​\s]/g, "") === "" && !el.querySelector("img, hr, table")43}4445// ---------------------------------------------------------------- normalisation du document46/** Regroupe en <div> les suites de nœuds en ligne placées directement dans un conteneur de blocs. */47function wrapInline(container: Element) {48  const doc = container.ownerDocument49  let run: Node[] = []50  const flush = () => {51    if (!run.length) return52    const meaningful = run.some((n) => !(isText(n) && !n.data.trim()))53    if (meaningful) {54      const div = doc.createElement("div")55      run[0].parentNode!.insertBefore(div, run[0])56      for (const n of run) div.appendChild(n)57      // un <br> final ne sert qu'à fermer la ligne : le bloc le fait déjà (sauf s'il est seul)58      if (div.childNodes.length > 1 && isEl(div.lastChild) && div.lastChild.tagName === "BR") div.lastChild.remove()59    }60    run = []61  }62  for (const n of Array.from(container.childNodes)) {63    if (isBlock(n)) flush()64    else {65      run.push(n)66      if (isEl(n) && n.tagName === "BR") flush()67    }68  }69  flush()70}7172function sameAttrs(a: Element, b: Element): boolean {73  if (a.attributes.length !== b.attributes.length) return false74  return Array.from(a.attributes).every((x) => b.getAttribute(x.name) === x.value)75}76/** Rangement après une commande : marques vides retirées, voisines identiques fusionnées, listes contiguës réunies, blocs vides rendus saisissables. */77function tidy(root: Element) {78  const doc = root.ownerDocument79  for (const el of Array.from(root.querySelectorAll("strong, b, em, i, u, s, strike, del, code, a, span, font"))) {80    if (isMarker(el) || el.querySelector("img, br")) continue81    if ((el.textContent ?? "") !== "") continue82    // un repère de sélection resté seul dans une marque en sort ; la marque vide disparaît83    while (el.firstChild) el.before(el.firstChild)84    el.remove()85  }86  for (const el of Array.from(root.querySelectorAll("strong, em, u, s, code, a, ul, ol"))) {87    if (!el.parentNode) continue88    let next = el.nextSibling89    while (isText(next) && next.data === "") next = next.nextSibling90    if (isEl(next) && next.tagName === el.tagName && sameAttrs(el, next) && !isMarker(next)) {91      while (el.lastChild) next.insertBefore(el.lastChild, next.firstChild)92      el.remove()93    }94  }95  for (const el of Array.from(root.querySelectorAll("ul, ol, blockquote"))) if (!el.firstChild) el.remove()96  for (const el of Array.from(root.querySelectorAll("div, p, h1, h2, h3, h4, li"))) {97    if (el.querySelector("br, img, hr, table, ul, ol, div, p") || (el.textContent ?? "") !== "") continue98    el.appendChild(doc.createElement("br"))99  }100  if (!root.firstChild || (root.childNodes.length === 1 && isText(root.firstChild) && root.firstChild.data === "")) root.innerHTML = "<div><br></div>"101}102103/** Met le contenu sous sa forme canonique : balises équivalentes unifiées, texte hors bloc enveloppé, document jamais vide. */104/** Balises équivalentes ramenées à une seule forme (un collage apporte <b>, <i>, <strike>…). */105function unify(root: Element) {106  for (const [from, to] of [["b", "strong"], ["i", "em"], ["strike", "s"], ["del", "s"]] as const) for (const el of Array.from(root.querySelectorAll(from))) rename(el, to)107}108export function normalize(root: Element) {109  unify(root)110  wrapInline(root)111  for (const bq of Array.from(root.querySelectorAll("blockquote"))) if (Array.from(bq.childNodes).some(isBlock)) wrapInline(bq)112  tidy(root)113}114115// ---------------------------------------------------------------- repères de sélection116export interface Ctx {117  root: Element118  doc: Document119  /** début et fin de la sélection, posés dans le document le temps de la commande */120  s: Element121  e: Element122  collapsed: boolean123}124function placeMarkers(root: Element, range: Range): Ctx {125  const doc = root.ownerDocument126  const make = (v: string) => {127    const el = doc.createElement("span")128    el.setAttribute(MARKER, v)129    return el130  }131  const collapsed = range.collapsed132  const s = make("s")133  const e = make("e")134  const end = range.cloneRange()135  end.collapse(false)136  const start = range.cloneRange()137  start.collapse(true)138  // le repère de fin d'abord : celui de début, posé au même point, se place alors devant lui139  end.insertNode(e)140  if (collapsed) e.before(s)141  else start.insertNode(s)142  sink(root, s, true)143  sink(root, e, false)144  if (collapsed) e.before(s)145  return { root, doc, s, e, collapsed }146}147/**148 * Un repère posé entre deux blocs (« tout sélectionner » donne une sélection au niveau de la racine) descend dans le bloc149 * voisin : sinon la normalisation l'envelopperait dans un paragraphe vide de plus.150 */151function sink(root: Element, m: Element, forward: boolean) {152  const sibling = (from: Node, dir: "nextSibling" | "previousSibling"): Element | null => {153    for (let n = from[dir]; n; n = n[dir]) {154      if (isEl(n) && isBlock(n) && n.tagName !== "HR") return n155      if (!isMarker(n) && !(isText(n) && !n.data.trim())) return null156    }157    return null158  }159  for (let guard = 0; guard < 40; guard++) {160    const p = m.parentElement161    if (!p || (p !== root && !CONTAINER.has(p.tagName))) return162    if (Array.from(p.childNodes).some((n) => n !== m && !isMarker(n) && !isBlock(n) && !(isText(n) && !n.data.trim()))) return163    const next = sibling(m, "nextSibling")164    const prev = sibling(m, "previousSibling")165    const target = forward ? (next ?? prev) : (prev ?? next)166    if (!target) return167    if (target === next) target.insertBefore(m, target.firstChild)168    else target.appendChild(m)169  }170}171type Point = { node: Node; offset: number }172/** Premier (ou dernier) point de texte d'un contenu en ligne, sans traverser un bloc ni une image. */173function textEdge(n: Node | null | undefined, first: boolean, deep: boolean): Point | null {174  for (let cur = n; cur; cur = first ? cur.firstChild : cur.lastChild) {175    if (isText(cur)) return { node: cur, offset: first ? 0 : cur.data.length }176    if (!deep || !isEl(cur) || isBlock(cur) || isMarker(cur) || ["IMG", "BR", "HR"].includes(cur.tagName)) return null177  }178  return null179}180/** Retire le repère et rend sa position, de préférence dans le texte voisin (`prefer` : côté regardé d'abord). */181function pointAt(marker: Element, prefer: "before" | "after", deep: boolean): Point {182  const parent = marker.parentNode!183  for (const dir of ["previousSibling", "nextSibling"] as const) for (let n = marker[dir]; isText(n) && n.data === ""; n = marker[dir]) n.remove()184  const i = indexOf(marker)185  marker.remove()186  const before = textEdge(parent.childNodes[i - 1], false, deep)187  const after = textEdge(parent.childNodes[i], true, deep)188  return (prefer === "before" ? (before ?? after) : (after ?? before)) ?? { node: parent, offset: i }189}190function removeMarkers(ctx: Ctx): Range {191  const r = ctx.doc.createRange()192  const collapsed = ctx.s.nextSibling === ctx.e193  if (collapsed) {194    ctx.e.remove()195    const p = pointAt(ctx.s, "before", false)196    r.setStart(p.node, p.offset)197    r.collapse(true)198    return r199  }200  // un repère resté au bord d'une marque en sort : la sélection entoure exactement le texte visé201  const inline = (el: Element | null): el is Element => !!el && el !== ctx.root && !isBlock(el)202  for (let p = ctx.s.parentElement; inline(p) && !ctx.s.nextSibling; p = ctx.s.parentElement) p.after(ctx.s)203  for (let p = ctx.e.parentElement; inline(p) && !ctx.e.previousSibling; p = ctx.e.parentElement) p.before(ctx.e)204  const a = pointAt(ctx.s, "after", true)205  const b = pointAt(ctx.e, "before", true)206  r.setStart(a.node, a.offset)207  r.setEnd(b.node, b.offset)208  return r209}210/** Nœuds situés entre les deux repères, dans l'ordre du document. */211function between(ctx: Ctx): Node[] {212  const out: Node[] = []213  const walker = ctx.doc.createTreeWalker(ctx.root, 0x1 | 0x4)214  walker.currentNode = ctx.s215  for (let n = walker.nextNode(); n && n !== ctx.e; n = walker.nextNode()) out.push(n)216  return out217}218const textsBetween = (ctx: Ctx): Text[] => between(ctx).filter((n): n is Text => isText(n) && n.data !== "")219function selectedBlocks(ctx: Ctx): Element[] {220  const leaves = [ctx.s, ...between(ctx).filter((n) => (isText(n) && n.data !== "") || (isEl(n) && ["BR", "IMG"].includes(n.tagName))), ctx.e]221  return uniq(leaves.map((n) => blockOf(ctx.root, n)).filter((b): b is Element => !!b))222}223224/** Exécute une commande sur la sélection donnée et rend la nouvelle sélection. Le document est d'abord normalisé. */225export function run(root: Element, range: Range, command: (ctx: Ctx) => void): Range {226  // le repère d'abord, la normalisation ensuite : la sélection survit à l'enveloppement du texte hors bloc227  const ctx = placeMarkers(root, range)228  normalize(root)229  command(ctx)230  unify(root)231  tidy(root)232  return removeMarkers(ctx)233}234235// ---------------------------------------------------------------- découpe236/** Scinde `el` juste avant (`after` faux) ou juste après `child`, l'un de ses descendants ; rend la moitié droite. */237function split(el: Element, child: Node, after: boolean): Element {238  let cur: Node = child239  let aft = after240  for (;;) {241    const parent = cur.parentNode as Element242    const clone = parent.cloneNode(false) as Element243    let n: Node | null = aft ? cur.nextSibling : cur244    while (n) {245      const next: Node | null = n.nextSibling246      clone.appendChild(n)247      n = next248    }249    parent.after(clone)250    if (parent === el) return clone251    cur = parent252    aft = true253  }254}255const hollow = (el: Element) => (el.textContent ?? "") === "" && !el.querySelector(`img, br, hr, [${MARKER}]`)256/** Isole `node` hors de son ancêtre `el` (scindé avant et après), puis retire l'enveloppe autour de lui seul. */257function liftOut(node: Node, el: Element) {258  const mid = split(el, node, false)259  const tail = split(mid, node, true)260  if (hollow(el)) el.remove()261  if (hollow(tail)) tail.remove()262  mid.replaceWith(...Array.from(mid.childNodes))263}264265// ---------------------------------------------------------------- marques en ligne266export function toggleMark(mark: Mark): (ctx: Ctx) => void {267  return (ctx) => {268    let texts = textsBetween(ctx)269    let carrier: Text | null = null270    if (!texts.length) {271      // sélection vide : un porteur de largeur nulle reçoit la marque, le texte tapé ensuite en hérite272      carrier = ctx.doc.createTextNode(ZWSP)273      ctx.s.before(carrier)274      texts = [carrier]275    }276    const on = !texts.every((t) => markOf(ctx.root, t, mark))277    for (const t of texts) {278      if (on) {279        if (markOf(ctx.root, t, mark)) continue280        const el = ctx.doc.createElement(MARK_TAG[mark])281        t.before(el)282        el.appendChild(t)283      } else for (let m = markOf(ctx.root, t, mark); m; m = markOf(ctx.root, t, mark)) liftOut(t, m)284    }285    if (carrier) {286      carrier.after(ctx.s)287      ctx.s.after(ctx.e)288    }289  }290}291292export function clearFormatting(ctx: Ctx) {293  for (const t of textsBetween(ctx)) {294    const block = blockOf(ctx.root, t) ?? ctx.root295    for (let m = closestIn(block, t, (el) => INLINE_FORMAT.has(el.tagName) && !isMarker(el)); m; m = closestIn(block, t, (el) => INLINE_FORMAT.has(el.tagName) && !isMarker(el))) liftOut(t, m)296  }297  for (const b of selectedBlocks(ctx)) {298    b.removeAttribute("style")299    b.removeAttribute("align")300    if (/^H\d$/.test(b.tagName)) rename(b, "div")301  }302}303304// ---------------------------------------------------------------- blocs305export function setBlock(kind: BlockKind): (ctx: Ctx) => void {306  return (ctx) => {307    const tag = kind === "p" ? "DIV" : kind.toUpperCase()308    const blocks = selectedBlocks(ctx).filter((b) => !["LI", "TD", "TH", "PRE"].includes(b.tagName))309    const all = blocks.length > 0 && blocks.every((b) => b.tagName === tag)310    for (const b of blocks) rename(b, all ? "div" : tag.toLowerCase())311  }312}313export function setAlign(align: Align): (ctx: Ctx) => void {314  return (ctx) => {315    for (const b of selectedBlocks(ctx)) {316      const el = b as HTMLElement317      el.removeAttribute("align")318      el.style.textAlign = align === "left" ? "" : align319      if (!el.getAttribute("style")) el.removeAttribute("style")320    }321  }322}323324const itemOf = (root: Element, b: Element): Element | null => closestIn(root, b, (el) => el.tagName === "LI")325function selectedItems(ctx: Ctx): Element[] {326  return uniq(selectedBlocks(ctx).filter((b) => b.tagName !== "TD" && b.tagName !== "TH").map((b) => itemOf(ctx.root, b) ?? b))327}328/** Sort un élément de liste d'un niveau ; au premier niveau, il redevient un paragraphe. */329function outdentItem(li: Element) {330  const doc = li.ownerDocument331  const list = li.parentElement332  if (!isList(list)) return333  const outer = list.parentElement334  const rest: Element[] = []335  for (let n = li.nextElementSibling; n; n = n.nextElementSibling) rest.push(n)336  if (outer && outer.tagName === "LI") {337    if (rest.length) {338      const sub = list.cloneNode(false) as Element339      for (const r of rest) sub.appendChild(r)340      li.appendChild(sub)341    }342    outer.after(li)343  } else {344    if (rest.length) {345      const tail = list.cloneNode(false) as Element346      for (const r of rest) tail.appendChild(r)347      list.after(tail)348    }349    const div = doc.createElement("div")350    const nested: Element[] = []351    for (const n of Array.from(li.childNodes)) {352      if (isList(n)) nested.push(n)353      else div.appendChild(n)354    }355    list.after(div)356    let at: Element = div357    for (const n of nested) {358      at.after(n)359      at = n360    }361    li.remove()362  }363  if (!list.firstElementChild) list.remove()364}365function indentItem(li: Element) {366  const prev = li.previousElementSibling367  const list = li.parentElement368  if (!prev || prev.tagName !== "LI" || !isList(list)) return369  let sub = prev.lastElementChild370  if (!isList(sub)) {371    sub = list.cloneNode(false) as Element372    prev.appendChild(sub)373  }374  sub.appendChild(li)375}376export function toggleList(type: "ul" | "ol"): (ctx: Ctx) => void {377  return (ctx) => {378    const items = selectedItems(ctx)379    if (!items.length) return380    const lis = items.filter((b) => b.tagName === "LI")381    if (lis.length === items.length) {382      if (lis.every((li) => li.parentElement?.tagName === type.toUpperCase())) for (const li of [...lis].reverse()) outdentItem(li)383      else for (const list of uniq(lis.map((li) => li.parentElement!))) rename(list, type)384      return385    }386    for (const b of items) {387      if (b.tagName === "LI") continue388      const prev = b.previousElementSibling389      let list: Element390      if (isList(prev) && prev.tagName === type.toUpperCase()) list = prev391      else {392        list = ctx.doc.createElement(type)393        b.before(list)394      }395      const li = ctx.doc.createElement("li")396      while (b.firstChild) li.appendChild(b.firstChild)397      list.appendChild(li)398      b.remove()399    }400  }401}402export function indent(ctx: Ctx) {403  for (const li of selectedItems(ctx).filter((b) => b.tagName === "LI")) indentItem(li)404}405export function outdent(ctx: Ctx) {406  for (const li of selectedItems(ctx).filter((b) => b.tagName === "LI").reverse()) outdentItem(li)407}408409const quoteOf = (root: Element, b: Element): Element | null => closestIn(root, b, (el) => el.tagName === "BLOCKQUOTE")410function childUnder(parent: Element, node: Node): Node {411  let n = node412  while (n.parentNode && n.parentNode !== parent) n = n.parentNode413  return n414}415function unquote(root: Element, b: Element) {416  const bq = quoteOf(root, b)417  if (!bq) return418  liftOut(childUnder(bq, b), bq)419}420export function toggleQuote(ctx: Ctx) {421  const blocks = selectedBlocks(ctx)422  if (!blocks.length) return423  if (blocks.every((b) => quoteOf(ctx.root, b))) {424    for (const b of blocks) if (b.isConnected) unquote(ctx.root, b)425    return426  }427  const tops = uniq(blocks.map((b) => childUnder(ctx.root, b))).filter(isEl)428  let bq: Element | null = null429  let last: Element | null = null430  for (const top of tops) {431    if (!bq || top.previousElementSibling !== last) {432      bq = ctx.doc.createElement("blockquote")433      bq.setAttribute("style", QUOTE_STYLE)434      top.before(bq)435    }436    bq.appendChild(top)437    last = bq438  }439}440441// ---------------------------------------------------------------- liens442export function linkAt(root: Element, range: Range): HTMLAnchorElement | null {443  return (closestIn(root, range.startContainer, (el) => el.tagName === "A") ?? closestIn(root, range.endContainer, (el) => el.tagName === "A")) as HTMLAnchorElement | null444}445/** Pose (ou modifie) un lien. Sélection vide hors d'un lien : le lien est inséré avec `text` (à défaut l'adresse). */446export function setLink(href: string, text?: string): (ctx: Ctx) => void {447  return (ctx) => {448    const texts = textsBetween(ctx)449    const anchor = () => closestIn(ctx.root, ctx.s, (el) => el.tagName === "A")450    if (!texts.length) {451      const cur = anchor()452      if (cur) {453        cur.setAttribute("href", href)454        if (text?.trim()) cur.textContent = text.trim()455        cur.after(ctx.s)456        ctx.s.after(ctx.e)457        return458      }459      const a = ctx.doc.createElement("a")460      a.setAttribute("href", href)461      a.textContent = text?.trim() || href462      ctx.s.before(a)463      return464    }465    for (const t of texts) {466      for (let a = closestIn(ctx.root, t, (el) => el.tagName === "A"); a; a = closestIn(ctx.root, t, (el) => el.tagName === "A")) liftOut(t, a)467      const a = ctx.doc.createElement("a")468      a.setAttribute("href", href)469      t.before(a)470      a.appendChild(t)471    }472  }473}474export function unlink(ctx: Ctx) {475  const texts = textsBetween(ctx)476  if (!texts.length) {477    const a = closestIn(ctx.root, ctx.s, (el) => el.tagName === "A")478    if (a) a.replaceWith(...Array.from(a.childNodes))479    return480  }481  for (const t of texts) for (let a = closestIn(ctx.root, t, (el) => el.tagName === "A"); a; a = closestIn(ctx.root, t, (el) => el.tagName === "A")) liftOut(t, a)482}483484// ---------------------------------------------------------------- insertion485function deleteSelection(ctx: Ctx) {486  if (ctx.collapsed && ctx.s.nextSibling === ctx.e) return487  const first = blockOf(ctx.root, ctx.s)488  const lastBlock = blockOf(ctx.root, ctx.e)489  const r = ctx.doc.createRange()490  r.setStartAfter(ctx.s)491  r.setEndBefore(ctx.e)492  r.deleteContents()493  if (first && lastBlock && first !== lastBlock && lastBlock.isConnected && first.isConnected) {494    // la suppression à cheval sur deux blocs les réunit, comme le ferait la touche Suppr495    let n: Node | null = ctx.e496    while (n) {497      const next: Node | null = n.nextSibling498      first.appendChild(n)499      n = next500    }501    let dead: Element | null = lastBlock502    while (dead && dead !== ctx.root && hollow(dead)) {503      const up: Element | null = dead.parentElement504      dead.remove()505      dead = up506    }507  }508  ctx.s.after(ctx.e)509}510/** Blocs → lignes : pour insérer un contenu structuré là où seul du texte en ligne a sa place (élément de liste, titre). */511function flatten(holder: Element) {512  const doc = holder.ownerDocument513  for (const el of Array.from(holder.querySelectorAll("*")).reverse()) {514    if (!isBlock(el)) continue515    if (el.nextSibling) el.after(doc.createElement("br"))516    el.replaceWith(...Array.from(el.childNodes))517  }518}519function lastLeaf(el: Element): Element {520  let cur = el521  for (;;) {522    const kids = Array.from(cur.children).filter((c) => isBlock(c) && c.tagName !== "HR" && c.tagName !== "TABLE")523    if (LEAF.has(cur.tagName) && !kids.length) return cur524    if (!kids.length) return cur525    cur = kids[kids.length - 1]526  }527}528/** Remplace la sélection par un fragment HTML DÉJÀ assaini ; le curseur se place à sa suite. */529export function insertHtml(html: string): (ctx: Ctx) => void {530  return (ctx) => {531    deleteSelection(ctx)532    const holder = ctx.doc.createElement("div")533    holder.innerHTML = html534    const structured = Array.from(holder.childNodes).some(isBlock)535    const host = blockOf(ctx.root, ctx.s)536    if (!structured || !host || host.tagName !== "DIV" && host.tagName !== "P") {537      if (structured) flatten(holder)538      while (holder.firstChild) ctx.s.before(holder.firstChild)539      return540    }541    wrapInline(holder)542    const right = split(host, ctx.s, false)543    let last: ChildNode | null = null544    while (holder.firstChild) {545      last = holder.firstChild546      right.before(last)547    }548    if (isVisiblyEmpty(host)) host.remove()549    let moved = false550    if (isEl(last)) {551      const leaf = lastLeaf(last)552      if (LEAF.has(leaf.tagName)) {553        if (isEl(leaf.lastChild) && leaf.lastChild.tagName === "BR" && leaf.childNodes.length > 1) leaf.lastChild.remove()554        leaf.appendChild(ctx.s)555        ctx.s.after(ctx.e)556        moved = true557      }558    }559    // la ligne vide où l'on a collé est remplacée par le contenu, pas conservée à sa suite560    if (moved && isVisiblyEmpty(right)) right.remove()561  }562}563/** Texte brut à la place de la sélection : chaque ligne devient un bloc. */564export function insertText(text: string): (ctx: Ctx) => void {565  const lines = text.replace(/\r\n?/g, "\n").split("\n")566  if (lines.length === 1)567    return (ctx) => {568      deleteSelection(ctx)569      if (text) ctx.s.before(ctx.doc.createTextNode(text))570    }571  return insertHtml(lines.map((l) => `<div>${l ? escapeHtml(l).replace(/ {2}/g, " &nbsp;") : "<br>"}</div>`).join(""))572}573export interface InlineImage {574  cid: string575  url: string576  alt: string577  width?: number578}579export function insertImage(img: InlineImage): (ctx: Ctx) => void {580  return (ctx) => {581    deleteSelection(ctx)582    const el = ctx.doc.createElement("img")583    el.setAttribute("data-cid", img.cid)584    el.setAttribute("src", img.url)585    el.setAttribute("alt", img.alt)586    if (img.width) el.setAttribute("width", String(Math.round(img.width)))587    ctx.s.before(el)588  }589}590/** Supprime les `count` caractères qui précèdent le curseur dans son nœud de texte (raccourci d'extrait tapé). */591export function deleteBefore(count: number): (ctx: Ctx) => void {592  return (ctx) => {593    let left = count594    let n: Node | null = ctx.s.previousSibling595    while (left > 0 && isText(n)) {596      const take = Math.min(left, n.data.length)597      n.data = n.data.slice(0, n.data.length - take)598      left -= take599      n = n.previousSibling600    }601  }602}603604// ---------------------------------------------------------------- touches à comportement propre605/** Entrée dans un élément de liste vide ou dans une ligne vide d'une citation : on en sort. Rend faux si le navigateur doit agir. */606export function enterHandled(ctx: Ctx): boolean {607  const block = blockOf(ctx.root, ctx.s)608  if (!block || !ctx.collapsed) return false609  const li = itemOf(ctx.root, block)610  if (li && isVisiblyEmpty(li) && !li.querySelector("ul, ol")) {611    outdentItem(li)612    return true613  }614  if (!li && quoteOf(ctx.root, block) && isVisiblyEmpty(block)) {615    unquote(ctx.root, block)616    return true617  }618  return false619}620/** Retour arrière en tout début de bloc : un élément de liste, une citation ou un titre redevient un paragraphe. */621export function backspaceHandled(ctx: Ctx): boolean {622  const block = blockOf(ctx.root, ctx.s)623  if (!block || !ctx.collapsed) return false624  const r = ctx.doc.createRange()625  r.setStart(block, 0)626  r.setEndBefore(ctx.s)627  if (r.toString().replace(/​/g, "") !== "" || r.cloneContents().querySelector("img, br")) return false628  const li = itemOf(ctx.root, block)629  if (li) {630    // seulement au début de l'élément lui-même (pas d'un paragraphe placé plus bas dans l'élément)631    const lr = ctx.doc.createRange()632    lr.setStart(li, 0)633    lr.setEndBefore(ctx.s)634    if (lr.toString().replace(/​/g, "") !== "") return false635    outdentItem(li)636    return true637  }638  if (/^H\d$/.test(block.tagName)) {639    rename(block, "div")640    return true641  }642  const bq = quoteOf(ctx.root, block)643  if (bq && childUnder(bq, block) === bq.firstElementChild) {644    unquote(ctx.root, block)645    return true646  }647  return false648}649650// ---------------------------------------------------------------- état de la sélection (barre de mise en forme)651export interface FormatState {652  bold: boolean653  italic: boolean654  underline: boolean655  strike: boolean656  code: boolean657  block: BlockKind658  list: "ul" | "ol" | null659  quote: boolean660  link: string | null661  align: Align662}663export const EMPTY_FORMAT: FormatState = { bold: false, italic: false, underline: false, strike: false, code: false, block: "p", list: null, quote: false, link: null, align: "left" }664export function formatState(root: Element, range: Range | null): FormatState {665  if (!range || !root.contains(range.startContainer)) return EMPTY_FORMAT666  let probes: Node[] = []667  if (!range.collapsed) {668    const walker = root.ownerDocument.createTreeWalker(root, 0x4)669    for (let n = walker.nextNode(); n; n = walker.nextNode()) {670      const t = n as Text671      if (!t.data.replace(/​/g, "") || !range.intersectsNode(t)) continue672      if (t === range.endContainer && range.endOffset === 0) continue673      if (t === range.startContainer && range.startOffset >= t.data.length) continue674      probes.push(t)675    }676  }677  if (!probes.length) probes = [range.startContainer]678  const has = (mark: Mark) => probes.every((n) => !!markOf(root, n, mark))679  const start = range.startContainer680  const block = blockOf(root, isEl(start) ? (start.childNodes[range.startOffset] ?? start) : start) ?? blockOf(root, start)681  const li = block ? itemOf(root, block) : null682  const a = linkAt(root, range)683  const el = block as HTMLElement | null684  const align = (el?.style?.textAlign || el?.getAttribute("align") || "left").toLowerCase()685  return {686    bold: has("bold"), italic: has("italic"), underline: has("underline"), strike: has("strike"), code: has("code"),687    block: block?.tagName === "H1" ? "h1" : block?.tagName === "H2" ? "h2" : "p",688    list: li ? (li.parentElement?.tagName === "OL" ? "ol" : "ul") : null,689    quote: !!(block && quoteOf(root, block)),690    link: a ? a.getAttribute("href") : null,691    align: align === "center" || align === "right" ? align : "left",692  }693}694695// ---------------------------------------------------------------- sérialisation696/**697 * HTML du document tel qu'il sera enregistré : sans repères, sans porteurs de largeur nulle, marques vides retirées,698 * images ramenées à `cid:`. Le résultat doit encore passer par l'assainisseur de rédaction avant d'être envoyé.699 */700export function serialize(root: Element): string {701  // copie dans un document inerte : y écrire `src="cid:…"` ne déclenche aucun chargement (la page, elle, tenterait de lire l'image)702  const copy = root.ownerDocument.implementation.createHTMLDocument("").importNode(root, true) as Element703  for (const m of Array.from(copy.querySelectorAll(`[${MARKER}]`))) m.remove()704  const walker = copy.ownerDocument.createTreeWalker(copy, 0x4)705  const texts: Text[] = []706  for (let n = walker.nextNode(); n; n = walker.nextNode()) texts.push(n as Text)707  for (const t of texts) if (t.data.includes(ZWSP)) t.data = t.data.replace(/​/g, "")708  for (const el of Array.from(copy.querySelectorAll("strong, em, u, s, code, a, span"))) if ((el.textContent ?? "") === "" && !el.querySelector("img, br")) el.remove()709  urlsToCids(copy)710  for (const el of Array.from(copy.querySelectorAll("div, p, h1, h2, li"))) if (!el.firstChild) el.appendChild(copy.ownerDocument.createElement("br"))711  const html = copy.innerHTML712  return html === "<div><br></div>" ? "" : html713}714/** Texte du document (lignes séparées), pour les aides à la rédaction. */715export function plainText(root: Element): string {716  const parts: string[] = []717  const visit = (n: Node) => {718    if (isText(n)) parts.push(n.data.replace(/​/g, ""))719    else if (isEl(n)) {720      if (n.tagName === "BR") parts.push("\n")721      for (const c of Array.from(n.childNodes)) visit(c)722      if (LEAF.has(n.tagName) && !/\n$/.test(parts[parts.length - 1] ?? "")) parts.push("\n")723    }724  }725  visit(root)726  return parts.join("").replace(/\n+$/, "")727}728729// ---------------------------------------------------------------- portée de l'assistant d'écriture730/** Ce qui n'a pas été rédigé ici : signature, citation d'une réponse, message transféré. L'assistant n'y touche jamais. */731const NOT_AUTHORED = ".spm-signature, blockquote, .spm-quote-intro, .spm-forward"732export interface AssistScope {733  /** `selection` : le texte sélectionné par la personne ; `authored` : tout ce qu'elle a rédigé (avant la signature et la citation) */734  kind: "selection" | "authored"735  text: string736  /** étendue à remplacer ; null quand rien n'est rédigé */737  range: Range | null738}739function rangeText(range: Range): string {740  const holder = range.startContainer.ownerDocument!.createElement("div")741  holder.appendChild(range.cloneContents())742  for (const m of Array.from(holder.querySelectorAll(`[${MARKER}]`))) m.remove()743  return plainText(holder)744}745const touchesForeign = (root: Element, range: Range): boolean => {746  if (closestIn(root, range.startContainer, (el) => el.matches(NOT_AUTHORED)) || closestIn(root, range.endContainer, (el) => el.matches(NOT_AUTHORED))) return true747  return Array.from(root.querySelectorAll(NOT_AUTHORED)).some((el) => range.intersectsNode(el))748}749/**750 * Portée d'une aide à la rédaction : la sélection si elle est non vide et ne touche ni la signature ni la citation ; sinon les751 * blocs rédigés, du début du document jusqu'au premier bloc étranger (les lignes vides qui le précèdent restent en place).752 */753export function assistScope(root: Element, selection: Range | null): AssistScope {754  if (selection && !selection.collapsed && root.contains(selection.startContainer) && root.contains(selection.endContainer) && !touchesForeign(root, selection)) {755    const text = rangeText(selection)756    if (text.trim()) return { kind: "selection", text, range: selection.cloneRange() }757  }758  const own: Node[] = []759  for (const n of Array.from(root.childNodes)) {760    if (isEl(n) && (n.matches(NOT_AUTHORED) || n.querySelector(NOT_AUTHORED))) break761    own.push(n)762  }763  while (own.length && (isMarker(own[own.length - 1]) || (isEl(own[own.length - 1]) ? isVisiblyEmpty(own[own.length - 1] as Element) : !(own[own.length - 1].textContent ?? "").trim()))) own.pop()764  while (own.length && (isEl(own[0]) ? isVisiblyEmpty(own[0] as Element) : !(own[0].textContent ?? "").trim())) own.shift()765  if (!own.length) return { kind: "authored", text: "", range: null }766  const range = root.ownerDocument.createRange()767  range.setStartBefore(own[0])768  range.setEndAfter(own[own.length - 1])769  // l'étendue est ramenée dans les blocs : la remplacer garde le premier bloc (et sa mise en page) au lieu de vider le document770  const first = own[0]771  const last = own[own.length - 1]772  if (isEl(first) && LEAF.has(first.tagName)) range.setStart(first, 0)773  if (isEl(last) && LEAF.has(last.tagName)) range.setEnd(last, last.childNodes.length)774  return { kind: "authored", text: rangeText(range), range }775}776777// ---------------------------------------------------------------- sélection ⇄ chemin (pour l'historique)778/** Position indépendante du découpage des nœuds de texte : indices d'enfants (texte contigu = un seul) puis décalage. */779export interface PathPoint {780  path: number[]781  offset: number782}783export interface SelectionPath {784  start: PathPoint785  end: PathPoint786}787/** Enfants « logiques » : les nœuds de texte contigus comptent pour un, les vides sont ignorés. */788function logicalIndex(parent: Node, child: Node): { index: number; before: number } {789  let index = -1790  let before = 0791  let prevText = false792  for (const n of Array.from(parent.childNodes)) {793    if (isText(n)) {794      if (n.data === "" && n !== child) continue795      if (!prevText) {796        index++797        before = 0798      }799      if (n === child) return { index, before }800      before += n.data.length801      prevText = true802    } else {803      index++804      prevText = false805      before = 0806      if (n === child) return { index, before: 0 }807    }808  }809  return { index: Math.max(0, index), before: 0 }810}811function toPath(root: Element, node: Node, offset: number): PathPoint {812  let n = node813  let off = offset814  if (isEl(n)) {815    // position entre deux enfants : rapportée au texte voisin si elle tombe dans une suite de texte816    const kids = Array.from(n.childNodes)817    const prev = kids[offset - 1]818    const next = kids[offset]819    if (isText(prev) && (prev.data !== "" || !isText(next))) {820      n = prev821      off = prev.data.length822    } else if (isText(next)) {823      n = next824      off = 0825    } else {826      let count = 0827      let prevText = false828      for (const k of kids.slice(0, offset)) {829        if (isText(k)) {830          if (k.data === "") continue831          if (!prevText) count++832          prevText = true833        } else {834          count++835          prevText = false836        }837      }838      off = count839    }840  }841  const path: number[] = []842  if (isText(n)) {843    const li = logicalIndex(n.parentNode!, n)844    off += li.before845    path.unshift(li.index)846    n = n.parentNode!847  }848  while (n !== root && n.parentNode) {849    path.unshift(logicalIndex(n.parentNode, n).index)850    n = n.parentNode851  }852  return { path, offset: off }853}854export function selectionToPath(root: Element, range: Range): SelectionPath {855  return { start: toPath(root, range.startContainer, range.startOffset), end: toPath(root, range.endContainer, range.endOffset) }856}857function fromPath(root: Element, p: PathPoint): { node: Node; offset: number } {858  let n: Node = root859  for (const i of p.path) {860    const logical: Node[] = []861    let prevText = false862    for (const k of Array.from(n.childNodes)) {863      if (isText(k)) {864        if (k.data === "") continue865        if (!prevText) logical.push(k)866        prevText = true867      } else {868        logical.push(k)869        prevText = false870      }871    }872    const next = logical[i]873    if (!next) return { node: n, offset: n.childNodes.length }874    n = next875  }876  if (isText(n)) {877    // la suite de texte peut être faite de plusieurs nœuds : on avance jusqu'à celui qui contient le décalage878    let left = p.offset879    let t: Text = n880    while (left > t.data.length && isText(t.nextSibling)) {881      left -= t.data.length882      t = t.nextSibling883    }884    return { node: t, offset: Math.min(left, t.data.length) }885  }886  let count = 0887  let prevText = false888  const kids = Array.from(n.childNodes)889  for (let i = 0; i < kids.length; i++) {890    if (count === p.offset) return { node: n, offset: i }891    const k = kids[i]892    if (isText(k)) {893      if (k.data === "") continue894      if (!prevText) count++895      prevText = true896    } else {897      count++898      prevText = false899    }900  }901  return { node: n, offset: kids.length }902}903export function pathToRange(root: Element, sel: SelectionPath): Range {904  const r = root.ownerDocument.createRange()905  const a = fromPath(root, sel.start)906  const b = fromPath(root, sel.end)907  r.setStart(a.node, a.offset)908  r.setEnd(b.node, b.offset)909  return r910}911912// ---------------------------------------------------------------- historique913export interface Snapshot {914  html: string915  sel: SelectionPath | null916}917/** `typing` et `attr` (saisie continue dans le texte, ou dans un champ comme le texte de remplacement d'une image) se regroupent entre eux, jamais l'un avec l'autre. */918export type ChangeKind = "typing" | "attr" | "command" | "paste" | "load"919/** Pile annuler / rétablir tenue par l'éditeur : la frappe continue est regroupée, chaque commande est une étape. */920export class History {921  private stack: Snapshot[] = []922  private index = -1923  private lastKind: ChangeKind | "" = ""924  private lastAt = 0925  constructor(private readonly limit = 200, private readonly typingWindow = 1200) {}926  reset(snap: Snapshot) {927    this.stack = [snap]928    this.index = 0929    this.lastKind = ""930  }931  record(snap: Snapshot, kind: ChangeKind, now = Date.now()) {932    const top = this.stack[this.index]933    if (top && top.html === snap.html) {934      top.sel = snap.sel935      return936    }937    const merge = (kind === "typing" || kind === "attr") && this.lastKind === kind && now - this.lastAt < this.typingWindow && this.index === this.stack.length - 1 && this.index > 0938    if (merge) this.stack[this.index] = snap939    else {940      this.stack.length = this.index + 1941      this.stack.push(snap)942      if (this.stack.length > this.limit) this.stack.shift()943      this.index = this.stack.length - 1944    }945    this.lastKind = kind946    this.lastAt = now947  }948  /** Note la sélection courante sur l'étape du dessus (pour la retrouver en rétablissant). */949  touch(sel: SelectionPath | null) {950    const top = this.stack[this.index]951    if (top && sel) top.sel = sel952  }953  undo(): Snapshot | null {954    if (this.index <= 0) return null955    this.lastKind = ""956    return this.stack[--this.index]957  }958  redo(): Snapshot | null {959    if (this.index >= this.stack.length - 1) return null960    this.lastKind = ""961    return this.stack[++this.index]962  }963  get canUndo() {964    return this.index > 0965  }966  get canRedo() {967    return this.index < this.stack.length - 1968  }969}970971/** Instantané du document vivant (sans repères) et de sa sélection. */972export function snapshot(root: Element, range: Range | null): Snapshot {973  return { html: root.innerHTML, sel: range && root.contains(range.startContainer) && root.contains(range.endContainer) ? selectionToPath(root, range) : null }974}975export type Command = (ctx: Ctx) => void976
Files main
Menu

Theme