Repository Public
1// Construction des réponses et transferts : destinataires, objet, en-têtes de fil, citation. Aucune dépendance au DOM.2import { dedupeAddrs, formatAddress, isValidEmail, parseAddressList, sameEmail, type Addr } from "./address"34export interface SourceEmail {5 from?: Addr[] | null6 to?: Addr[] | null7 cc?: Addr[] | null8 replyTo?: Addr[] | null9 subject?: string | null10 messageId?: string[] | null11 references?: string[] | null12 sentAt?: string | null13 receivedAt?: string | null14}1516export interface ReplyLabels {17 /** « Le {date}, {name} a écrit : » */18 wrote: (date: string, who: string) => string19 forwardedHeader: string20 from: string21 date: string22 subject: string23 to: string24 cc: string25}2627const RE_PREFIX = /^\s*(?:(?:re|rép|rep|réf|aw|sv|antw)\s*(?:\[\d+\])?\s*:\s*)+/i28const FW_PREFIX = /^\s*(?:(?:fwd?|tr|wg|trans|fw)\s*:\s*)+/i2930export function replySubject(subject: string | null | undefined): string {31 const s = (subject ?? "").trim()32 return `Re: ${s.replace(RE_PREFIX, "")}`.trim()33}34export function forwardSubject(subject: string | null | undefined): string {35 const s = (subject ?? "").trim()36 return `Fwd: ${s.replace(FW_PREFIX, "")}`.trim()37}3839/** En-têtes de fil d'une réponse (RFC 5322 §3.6.4) : In-Reply-To = Message-ID d'origine ; References = références d'origine + ce Message-ID. */40export function threadHeaders(src: SourceEmail): { inReplyTo: string[] | null; references: string[] | null } {41 const id = (src.messageId ?? []).filter(Boolean)42 if (!id.length) return { inReplyTo: null, references: null }43 const refs = [...(src.references ?? []), ...id].filter((v, i, a) => v && a.indexOf(v) === i)44 return { inReplyTo: id, references: refs.slice(-30) }45}4647/**48 * Destinataires d'une réponse. `mine` = toutes mes adresses (pour ne pas me répondre à moi-même).49 * Si le message d'origine vient de moi (dossier Envoyés), on répond à ses destinataires.50 */51export function replyRecipients(src: SourceEmail, mine: string[], all: boolean): { to: Addr[]; cc: Addr[] } {52 const isMine = (a: Addr) => mine.some((m) => sameEmail(m, a.email))53 const from = src.from ?? []54 const sentByMe = from.length > 0 && from.every(isMine)55 let to = sentByMe ? [...(src.to ?? [])] : [...(src.replyTo?.length ? src.replyTo : from)]56 let cc: Addr[] = []57 if (all) {58 if (!sentByMe) to = [...to, ...(src.to ?? []).filter((a) => !isMine(a))]59 cc = (src.cc ?? []).filter((a) => !isMine(a))60 }61 to = dedupeAddrs(to)62 if (to.length > 1) to = to.filter((a, i) => i === 0 || !isMine(a))63 cc = dedupeAddrs(cc).filter((a) => !to.some((t) => sameEmail(t.email, a.email)))64 return { to, cc }65}6667// ---------------------------------------------------------------- texte ⇄ HTML6869const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: "\u00a0", eacute: "é", egrave: "è", ecirc: "ê", agrave: "à", acirc: "â", ccedil: "ç", ugrave: "ù", ucirc: "û", ocirc: "ô", icirc: "î", iuml: "ï", euml: "ë", laquo: "«", raquo: "»", hellip: "…", mdash: "—", ndash: "–", rsquo: "’", lsquo: "‘", rdquo: "”", ldquo: "“", euro: "€", copy: "©", reg: "®", trade: "™", deg: "°", middot: "·", bull: "•" }7071export function decodeEntities(s: string): string {72 return s.replace(/&(#x[0-9a-f]+|#\d+|[a-z][a-z0-9]*);/gi, (m, e: string) => {73 if (e[0] === "#") {74 const cp = e[1].toLowerCase() === "x" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10)75 return cp > 0 && cp <= 0x10ffff && !(cp >= 0xd800 && cp <= 0xdfff) ? String.fromCodePoint(cp) : ""76 }77 return ENTITIES[e.toLowerCase()] ?? m78 })79}8081export function escapeHtml(s: string): string {82 return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """)83}8485/** Texte brut → HTML sûr (échappé), retours de ligne conservés. */86export function textToHtml(text: string): string {87 return text88 .split(/\r?\n/)89 .map((l) => (l === "" ? "<br>" : escapeHtml(l).replace(/ {2}/g, " ").replace(/^ /, " ")))90 .map((l) => (l === "<br>" ? "<div><br></div>" : `<div>${l}</div>`))91 .join("")92}9394/** HTML → texte lisible (version text/plain d'un message rédigé en riche). Sans DOM : fonctionne partout. */95export function htmlToText(html: string): string {96 let s = html.replace(/\r\n?/g, "\n")97 s = s.replace(/<!--[\s\S]*?-->/g, "")98 s = s.replace(/<(script|style|head|title)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, "")99 // les blocs cités deviennent des lignes préfixées par « > » ; \u0003 protège leurs retours de ligne jusqu'à la fin100 for (let guard = 0; guard < 50 && /<blockquote\b/i.test(s); guard++) {101 const before = s102 s = s.replace(/<blockquote\b[^>]*>((?:(?!<blockquote\b)[\s\S])*?)<\/blockquote\s*>/gi, (_m, inner: string) => {103 const text = htmlToText(inner)104 return `\u0003${text.split("\n").map((l) => (l ? `> ${l}` : ">")).join("\u0003")}\u0003`105 })106 if (s === before) break107 }108 s = s.replace(/[ \t]*\n[ \t]*/g, " ")109 s = s.replace(/<br\s*\/?>/gi, "\n")110 s = s.replace(/<li\b[^>]*>/gi, "\n• ")111 s = s.replace(/<hr\b[^>]*>/gi, "\n----------\n")112 s = s.replace(/<a\b[^>]*?href\s*=\s*(?:"([^"]*)"|'([^']*)')[^>]*>([\s\S]*?)<\/a\s*>/gi, (_m, h1: string | undefined, h2: string | undefined, inner: string) => {113 const href = decodeEntities(h1 ?? h2 ?? "").trim()114 const text = inner.replace(/<[^>]+>/g, "").trim()115 const bare = href.replace(/^mailto:/i, "")116 if (!href || !/^(https?:|mailto:)/i.test(href)) return text117 return !text || decodeEntities(text) === href || decodeEntities(text) === bare ? bare : `${text} \u0001${bare}\u0002`118 })119 s = s.replace(/<\/(?:p|div|h[1-6]|tr|table|ul|ol|pre|section|article|header|footer)\s*>/gi, "\n")120 s = s.replace(/<(?:p|div|h[1-6]|tr|table|ul|ol|pre|section|article|header|footer)\b[^>]*>/gi, "\n")121 s = s.replace(/<\/t[dh]\s*>/gi, "\t")122 s = s.replace(/<[^>]*>/g, "")123 s = decodeEntities(s).replace(/\u00a0/g, " ").replace(/\u0001/g, "<").replace(/\u0002/g, ">").replace(/[ \t]*\u0003[ \t]*/g, "\n")124 s = s.replace(/[ \t]+\n/g, "\n").replace(/\n[ \t]+(?!•|>)/g, "\n").replace(/\n{3,}/g, "\n\n")125 // « > » restitués par les citations : on garde leur indentation126 return s.replace(/^\n+|\s+$/g, "")127}128129/** Préfixe chaque ligne par « > » (citation en texte brut). */130export function quoteText(text: string): string {131 return text132 .replace(/\r\n?/g, "\n")133 .split("\n")134 .map((l) => (l.startsWith(">") ? `>${l}` : l ? `> ${l}` : ">"))135 .join("\n")136}137138// ---------------------------------------------------------------- citations139140export interface QuotedBody {141 /** HTML à insérer dans l'éditeur ; `originalHtml` doit DÉJÀ être assaini (mode « quote ») */142 html: string143 text: string144}145146export function buildReplyQuote(src: SourceEmail, originalHtml: string | null, originalText: string, dateLabel: string, labels: ReplyLabels): QuotedBody {147 const who = src.from?.[0] ? formatAddress(src.from[0]) : ""148 const intro = labels.wrote(dateLabel, who)149 const inner = originalHtml ?? textToHtml(originalText)150 return {151 html: `<div><br></div><div class="spm-quote-intro">${escapeHtml(intro)}</div><blockquote class="spm-quote" type="cite">${inner}</blockquote><div><br></div>`,152 text: `\n\n${intro}\n${quoteText(originalText)}\n`,153 }154}155156export function buildForwardQuote(src: SourceEmail, originalHtml: string | null, originalText: string, dateLabel: string, labels: ReplyLabels): QuotedBody {157 const list = (l?: Addr[] | null) => (l ?? []).map(formatAddress).join(", ")158 const rows: [string, string][] = [159 [labels.from, list(src.from)],160 [labels.date, dateLabel],161 [labels.subject, src.subject ?? ""],162 [labels.to, list(src.to)],163 ]164 if (src.cc?.length) rows.push([labels.cc, list(src.cc)])165 const inner = originalHtml ?? textToHtml(originalText)166 return {167 html: `<div><br></div><div class="spm-forward"><div>---------- ${escapeHtml(labels.forwardedHeader)} ----------</div>${rows.map(([k, v]) => `<div><b>${escapeHtml(k)}</b> ${escapeHtml(v)}</div>`).join("")}<div><br></div>${inner}</div>`,168 text: `\n\n---------- ${labels.forwardedHeader} ----------\n${rows.map(([k, v]) => `${k} ${v}`).join("\n")}\n\n${originalText}\n`,169 }170}171172/** Balises permises dans un message rédigé ici (assainissement du contenu collé avant l'envoi). */173export const COMPOSE_ALLOWED_TAGS = ["a", "b", "strong", "i", "em", "u", "s", "strike", "p", "div", "span", "br", "ul", "ol", "li", "blockquote", "pre", "code", "h1", "h2", "h3", "h4", "hr", "table", "thead", "tbody", "tr", "td", "th", "font", "sub", "sup", "small"]174export const COMPOSE_ALLOWED_ATTR = ["href", "style", "class", "type", "color", "face", "size", "align", "colspan", "rowspan", "dir", "lang", "title"]175/** La rédaction elle-même admet en plus les images — réduites ensuite aux `cid:` du brouillon (keepKnownImages). */176export const COMPOSE_IMAGE_TAGS = [...COMPOSE_ALLOWED_TAGS, "img"]177export const COMPOSE_IMAGE_ATTR = [...COMPOSE_ALLOWED_ATTR, "src", "alt", "width", "height"]178179/** Enveloppe HTML minimale d'un message sortant. */180export function wrapOutgoingHtml(bodyHtml: string): string {181 return `<!doctype html><html><head><meta charset="utf-8"></head><body><div style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;font-size:15px;line-height:1.5">${bodyHtml}</div></body></html>`182}183184// ================================================================ SP Mail Next — rédaction185// Tout ce qui suit est pur (aucun réseau, aucun état) ; les fonctions qui lisent du HTML reçoivent un analyseur (`parse`).186187export type ParseHtml = (html: string) => Document188189/** Caractère de largeur nulle posé par l'éditeur pour porter une mise en forme sans texte ; jamais envoyé. */190export const ZWSP = "\u200b"191export const stripZwsp = (s: string): string => s.replace(/\u200b/g, "")192193/** Corps d'un message sortant remis à l'API (qui retire <html>/<head>/<body> : seule l'enveloppe de police est gardée). */194export function wrapOutgoingBody(bodyHtml: string): string {195 return `<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; font-size: 15px; line-height: 1.5">${bodyHtml}</div>`196}197198// ---------------------------------------------------------------- images en ligne (cid:)199export const INLINE_IMAGE_TYPES = /^image\/(png|jpeg|gif|webp)$/i200const CID_OK = /^[A-Za-z0-9._@-]{1,100}$/201/** Content-ID d'une image insérée ici (forme acceptée par l'API : lettres, chiffres, « . _ @ - »). */202export function newCid(random: () => string = () => Math.random().toString(36).slice(2, 12)): string {203 return `img-${random()}-${Date.now().toString(36)}@spmail`204}205/** Content-ID normalisé (sans chevrons) ; null s'il ne peut pas voyager tel quel jusqu'à l'API. */206export function cleanCid(raw: string | null | undefined): string | null {207 const c = (raw ?? "").trim().replace(/^<|>$/g, "")208 return CID_OK.test(c) ? c : null209}210/** Content-ID référencés par le HTML (`src="cid:…"`), sans doublon, dans l'ordre. */211export function referencedCids(html: string): string[] {212 const out: string[] = []213 const re = /<img\b[^>]*?\bsrc\s*=\s*(?:"cid:([^"]*)"|'cid:([^']*)')/gi214 for (let m = re.exec(html); m; m = re.exec(html)) {215 const cid = decodeEntities(m[1] ?? m[2] ?? "").trim()216 if (cid && !out.includes(cid)) out.push(cid)217 }218 return out219}220/** Les images en ligne que le texte ne référence plus (citation effacée, image supprimée) ne partent pas. */221export function pruneInline<T extends { inline?: boolean; cid?: string | null }>(attachments: readonly T[], html: string | null): T[] {222 const used = new Set(html === null ? [] : referencedCids(html))223 return attachments.filter((a) => !a.inline || (!!a.cid && used.has(a.cid)))224}225/** Retire toute image dont la source n'est pas un `cid:` connu : jamais d'URL distante, de `data:` ni de `blob:` dans un message rédigé. */226export function keepKnownImages(root: ParentNode, known: ReadonlySet<string>) {227 // ces attributs n'existent que pour les images228 for (const el of Array.from(root.querySelectorAll("[src], [alt], [width], [height]"))) if (el.tagName !== "IMG") for (const a of ["src", "alt", "width", "height"]) el.removeAttribute(a)229 for (const img of Array.from(root.querySelectorAll("img"))) {230 const src = (img.getAttribute("src") ?? "").trim()231 const cid = /^cid:/i.test(src) ? src.slice(4) : null232 if (!cid || !known.has(cid)) {233 img.remove()234 continue235 }236 for (const a of Array.from(img.attributes)) if (!["src", "alt", "width", "height", "style"].includes(a.name)) img.removeAttribute(a.name)237 const w = img.getAttribute("width")238 if (w !== null && !/^\d{1,4}$/.test(w)) img.removeAttribute("width")239 img.removeAttribute("height")240 img.setAttribute("style", "max-width: 100%; height: auto")241 }242}243/**244 * Un contenu collé apporte les couleurs de sa page d'origine (texte noir, fond blanc…) : illisibles dans un thème sombre,245 * et rarement voulues dans un message. Elles sont retirées ; le reste de la mise en forme est gardé.246 */247export function dropColors(root: ParentNode) {248 for (const el of Array.from(root.querySelectorAll("[style], [color], [bgcolor]"))) {249 el.removeAttribute("color")250 el.removeAttribute("bgcolor")251 const style = el.getAttribute("style")252 if (style === null) continue253 const kept = style.split(";").map((d) => d.trim()).filter((d) => d && !/^(?:color|background(?:-color)?|-webkit-text-fill-color|caret-color)\s*:/i.test(d))254 if (kept.length) el.setAttribute("style", kept.join("; "))255 else el.removeAttribute("style")256 }257}258/** Éditeur : `cid:` → adresse `blob:` locale (l'identifiant reste dans `data-cid`). Sans adresse connue, l'image attend, vide. */259export function cidsToUrls(root: ParentNode, urlOf: (cid: string) => string | undefined) {260 for (const img of Array.from(root.querySelectorAll("img"))) {261 const src = img.getAttribute("src") ?? ""262 const cid = img.getAttribute("data-cid") ?? (/^cid:/i.test(src) ? src.slice(4) : null)263 if (!cid) continue264 img.setAttribute("data-cid", cid)265 const url = urlOf(cid)266 if (url) img.setAttribute("src", url)267 else img.removeAttribute("src")268 }269}270/** Sortie de l'éditeur : `data-cid` → `src="cid:…"` ; une image sans identifiant (collée d'ailleurs) est retirée. */271export function urlsToCids(root: ParentNode) {272 for (const img of Array.from(root.querySelectorAll("img"))) {273 const cid = img.getAttribute("data-cid")274 if (!cid) {275 img.remove()276 continue277 }278 img.setAttribute("src", `cid:${cid}`)279 img.removeAttribute("data-cid")280 }281}282283const BLANK_GIF = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"284const b64 = (s: string) => btoa(Array.from(new TextEncoder().encode(s), (b) => String.fromCharCode(b)).join(""))285const unb64 = (s: string) => new TextDecoder().decode(Uint8Array.from(atob(s), (c) => c.charCodeAt(0)))286/**287 * L'assainisseur de citation retire les images `cid:` (il ne garde que les `data:` sûres). Pour citer un message en gardant288 * ses images jointes, chaque `cid:` est d'abord remplacé par un GIF vide d'un pixel dont la fin porte l'identifiant ; après289 * assainissement, `restoreCids` rétablit `src="cid:…"`. Le document analysé est inerte (rien n'est chargé ni exécuté).290 */291export function protectCids(html: string, parse: ParseHtml): string {292 if (!/cid:/i.test(html)) return html293 const doc = parse(html)294 let n = 0295 for (const img of Array.from(doc.querySelectorAll("img"))) {296 const src = (img.getAttribute("src") ?? "").trim()297 const cid = /^cid:/i.test(src) ? cleanCid(src.slice(4)) : null298 if (!cid) continue299 img.setAttribute("src", `data:image/gif;base64,${BLANK_GIF}${b64(cid)}`)300 n++301 }302 return n ? doc.documentElement.outerHTML : html303}304export function restoreCids(html: string, parse: ParseHtml): string {305 if (!html.includes(BLANK_GIF)) return html306 const doc = parse(`<body>${html}</body>`)307 for (const img of Array.from(doc.body.querySelectorAll("img"))) {308 const src = (img.getAttribute("src") ?? "").replace(/\s+/g, "")309 const at = src.indexOf(BLANK_GIF)310 if (at < 0) continue311 let cid: string | null = null312 try {313 cid = cleanCid(unb64(src.slice(at + BLANK_GIF.length)))314 } catch {315 cid = null316 }317 if (cid) img.setAttribute("src", `cid:${cid}`)318 else img.remove()319 }320 return doc.body.innerHTML321}322323/** Dimensions d'une image réduite à `max` pixels de large (jamais agrandie). */324export function fitWidth(width: number, height: number, max: number): { width: number; height: number } {325 if (!(width > 0) || !(height > 0) || width <= max) return { width: Math.round(width), height: Math.round(height) }326 return { width: max, height: Math.max(1, Math.round((height * max) / width)) }327}328export const IMAGE_PRESETS = { small: 320, medium: 640, large: 1280 } as const329export type ImagePreset = keyof typeof IMAGE_PRESETS | "original"330331// ---------------------------------------------------------------- destinataires332/**333 * Saisie ou collage d'une liste : virgules, points-virgules et retours de ligne séparent ; une suite d'adresses nues334 * séparées par des espaces ou des tabulations (colonne de tableur) est aussi comprise.335 */336export function parseRecipients(input: string): { valid: Addr[]; invalid: string[] } {337 const valid: Addr[] = []338 const invalid: string[] = []339 const push = (a: Addr) => {340 if (!valid.some((v) => sameEmail(v.email, a.email))) valid.push(a)341 }342 const parsed = parseAddressList(input.replace(/\r\n?/g, "\n"))343 for (const a of parsed.valid) push(a)344 for (const p of parsed.invalid) {345 const words = p.split(/\s+/).map((w) => w.replace(/^mailto:/i, "").replace(/^<|>$/g, ""))346 if (words.length > 1 && words.every((w) => isValidEmail(w))) for (const w of words) push({ email: w })347 else invalid.push(p)348 }349 return { valid, invalid }350}351const EMAIL_LOOSE = /^[^\s@<>(),;:"\\]+@[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i352353export interface RecipientIssues {354 /** adresses mal formées */355 invalid: string[]356 /** adresses présentes plus d'une fois (tous champs confondus), en minuscules */357 duplicates: string[]358 empty: boolean359}360export function recipientIssues(to: readonly Addr[], cc: readonly Addr[], bcc: readonly Addr[]): RecipientIssues {361 const all = [...to, ...cc, ...bcc]362 const seen = new Set<string>()363 const duplicates = new Set<string>()364 for (const a of all) {365 const k = a.email.trim().toLowerCase()366 if (seen.has(k)) duplicates.add(k)367 seen.add(k)368 }369 return { invalid: all.filter((a) => !(EMAIL_LOOSE.test(a.email) && a.email.length <= 254)).map((a) => a.email), duplicates: [...duplicates], empty: all.length === 0 }370}371/** Destinataires « sensibles » : la liste contient des adresses ou des `@domaine` (même règle que le serveur). */372export function matchSensitive(recipients: readonly string[], list: readonly string[]): string[] {373 const set = new Set(list.map((x) => x.trim().toLowerCase()))374 if (!set.size) return []375 return [...new Set(recipients.map((r) => r.trim().toLowerCase()))].filter((a) => set.has(a) || set.has(`@${a.split("@")[1] ?? ""}`))376}377/** Destinataires hors de mes domaines (ceux de mes propres adresses). */378export function externalRecipients(recipients: readonly string[], ownAddresses: readonly string[]): string[] {379 const domains = new Set(ownAddresses.map((a) => a.split("@")[1]?.toLowerCase()).filter(Boolean))380 if (!domains.size) return []381 return [...new Set(recipients.map((r) => r.trim().toLowerCase()))].filter((a) => !domains.has(a.split("@")[1] ?? ""))382}383384// ---------------------------------------------------------------- pièce jointe annoncée mais absente385// Même liste et mêmes règles que le socle Apple (SPMailCore/Next/NextHelpers.swift, MissingAttachmentDetector).386export const ATTACHMENT_PHRASES = [387 "ci-joint", "ci-jointe", "ci-joints", "ci-jointes", "ci joint", "ci jointe", "ci joints", "ci jointes", "piece jointe", "pieces jointes", "en piece jointe", "en pieces jointes",388 "fichier joint", "fichiers joints", "document joint", "documents joints", "en annexe", "je joins", "je vous joins", "je te joins", "j'ai joint", "nous joignons", "vous trouverez joint",389 "trouverez ci", "en pj", "pj", "p.j.",390 "attached", "attachment", "attachments", "attaching", "enclosed", "enclosing", "i attach", "i have attached", "i've attached", "please find", "see the file",391] as const392const foldText = (s: string) => s.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase().replace(/’/g, "'")393const PHRASE_RE = ATTACHMENT_PHRASES.map((p) => {394 const body = p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/ /g, "\\s+").replace(/'/g, "['’]")395 return { phrase: p as string, re: new RegExp(`(?<![\\p{L}\\p{N}])${body}(?![\\p{L}\\p{N}])`, "u") }396})397/** La partie du texte brut que la personne a tapée : s'arrête à la première citation, à l'en-tête d'une réponse ou au séparateur de signature. */398export function authoredText(text: string): string {399 const out: string[] = []400 const lines = text.replace(/\r\n/g, "\n").split("\n")401 for (let i = 0; i < lines.length; i++) {402 const line = lines[i]403 const tr = line.trim()404 if (line === "-- " || tr === "--" || tr === "—") break405 if (tr.startsWith(">")) continue406 const f = foldText(tr)407 if (["-----original message", "-------- message transfere", "---------- forwarded message", "---------- message transfere", "-----message d'origine", "debut du message transfere", "begin forwarded message"].some((p) => f.startsWith(p))) break408 const joined = i + 1 < lines.length ? `${f} ${foldText(lines[i + 1].trim())}` : f409 if (f.startsWith("on ") && (f.endsWith("wrote:") || (joined.endsWith("wrote:") && f.length > 12))) break410 if (f.startsWith("le ") && (f.endsWith("a ecrit :") || f.endsWith("a ecrit:") || ((joined.endsWith("a ecrit :") || joined.endsWith("a ecrit:")) && f.includes(",")))) break411 if ((f.startsWith("from:") || f.startsWith("de :") || f.startsWith("de:")) && i + 1 < lines.length) {412 const next = lines.slice(i + 1, i + 5).map((l) => foldText(l.trim()))413 if (next.some((n) => ["sent:", "envoye :", "envoye:", "date:", "date :", "to:", "a :"].some((p) => n.startsWith(p)))) break414 }415 out.push(line)416 }417 return out.join("\n")418}419/** Expressions trouvées dans l'objet et dans la partie rédigée (chacune une fois, dans l'ordre de la liste). */420export function attachmentMentions(subject: string, text: string): string[] {421 const hay = `${foldText(subject)}\n${foldText(authoredText(text))}`422 return PHRASE_RE.filter((p) => p.re.test(hay)).map((p) => p.phrase)423}424/** Vrai si le message parle d'une pièce jointe et n'en porte aucune (les images en ligne ne comptent pas). */425export const missingAttachment = (subject: string, text: string, attachmentCount: number): boolean => attachmentCount === 0 && attachmentMentions(subject, text).length > 0426427/** Texte rédigé d'un brouillon HTML : sans la signature (`.spm-signature`), la citation ni le message transféré. */428export function authoredHtmlText(html: string, parse: ParseHtml): string {429 const doc = parse(`<body>${html}</body>`)430 for (const el of Array.from(doc.body.querySelectorAll(".spm-signature, blockquote, .spm-quote-intro, .spm-forward"))) el.remove()431 return htmlToText(doc.body.innerHTML)432}433434// ---------------------------------------------------------------- signatures435export interface SignatureLike {436 id: string437 source?: "user" | "address"438 default_for: readonly string[]439 default_for_replies: readonly string[]440}441/**442 * Signature par défaut d'une adresse : celle (créée par l'utilisateur) qui revendique l'adresse — pour les réponses, celle des443 * réponses d'abord. `null` = aucune ne la revendique : la signature historique de l'adresse (ou de l'identité) s'applique.444 */445export function defaultSignatureId(signatures: readonly SignatureLike[], addressId: string | null | undefined, reply: boolean): string | null {446 if (!addressId) return null447 const own = signatures.filter((s) => s.source !== "address")448 const hit = (reply ? own.find((s) => s.default_for_replies.includes(addressId)) : undefined) ?? own.find((s) => s.default_for.includes(addressId))449 return hit?.id ?? null450}451const squashText = (x: string) => x.replace(/\s+/g, " ").trim()452/**453 * Un brouillon relu du serveur a perdu ses classes : le bloc dont le texte est exactement celui de la signature (hors454 * citation) retrouve la classe `spm-signature`, pour qu'un changement d'expéditeur la remplace au lieu de la doubler.455 */456export function retagSignature(html: string, signatureHtml: string, parse: ParseHtml): string {457 const want = squashText(parse(`<body>${signatureHtml}</body>`).body.textContent ?? "")458 if (!want) return html459 const doc = parse(`<body>${html}</body>`)460 if (doc.body.querySelector(".spm-signature")) return html461 const candidates = Array.from(doc.body.querySelectorAll("div, p")).filter((el) => !el.closest("blockquote") && squashText(el.textContent ?? "") === want)462 // le bloc le plus englobant : la signature elle-même, pas l'une de ses lignes463 const hit = candidates.find((el) => !candidates.some((o) => o !== el && o.contains(el)))464 if (!hit) return html465 hit.classList.add("spm-signature")466 return doc.body.innerHTML467}468469/**470 * La personne a-t-elle touché à la signature ? Vrai si son texte a été réécrit, ou si le bloc a été retiré alors qu'une471 * signature avait été posée : un changement d'expéditeur ne doit alors ni la remplacer ni en ajouter une seconde. Du texte472 * tapé dans le bloc, avant ou après une signature restée intacte, n'est pas une réécriture (le curseur s'y pose quand on473 * clique sous le message) : `swapSignatureHtml` le sort du bloc.474 */475export function signatureEdited(html: string, previousBlock: string, parse: ParseHtml): boolean {476 const prev = squashText(parse(`<body>${previousBlock}</body>`).body.textContent ?? "")477 const own = Array.from(parse(`<body>${html}</body>`).body.querySelectorAll(".spm-signature")).find((el) => !el.closest("blockquote"))478 if (!own) return prev !== ""479 return !squashText(own.textContent ?? "").includes(prev)480}481482/** Un bloc de signature réécrit devient du texte ordinaire de la personne : il ne sera plus jamais remplacé. */483export function demoteSignature(html: string, parse: ParseHtml): string {484 const doc = parse(`<body>${html}</body>`)485 const own = Array.from(doc.body.querySelectorAll(".spm-signature")).filter((el) => !el.closest("blockquote"))486 if (!own.length) return html487 for (const el of own) {488 el.classList.remove("spm-signature")489 if (!el.getAttribute("class")) el.removeAttribute("class")490 }491 return doc.body.innerHTML492}493494// ---------------------------------------------------------------- extraits (« ;raccourci »)495/**496 * La personne vient de taper un séparateur après `;raccourci` : rend le raccourci reconnu et la position de son « ; »497 * dans `before` (le texte qui précède le curseur). Le « ; » doit ouvrir un mot.498 */499export function findSnippetTrigger(before: string, shortcuts: readonly string[]): { shortcut: string; start: number } | null {500 const m = /(?:^|[\s\u00a0(])(;([a-z0-9_-]{1,24}))$/i.exec(before)501 if (!m) return null502 const shortcut = m[2].toLowerCase()503 return shortcuts.some((s) => s.toLowerCase() === shortcut) ? { shortcut, start: before.length - m[1].length } : null504}505506// ---------------------------------------------------------------- enregistrement automatique507export interface AutosaveTimings {508 /** silence exigé avant le premier enregistrement d'un brouillon */509 firstIdle: number510 /** silence exigé avant les suivants (la frappe repousse l'enregistrement) */511 idle: number512 /** écart minimal entre deux enregistrements sur le serveur (chacun remplace le message : nouvel identifiant) */513 minInterval: number514 /** attente maximale depuis la première modification non enregistrée */515 maxWait: number516}517export const AUTOSAVE: AutosaveTimings = { firstIdle: 1500, idle: 3000, minInterval: 30_000, maxWait: 90_000 }518/** Délai avant le prochain enregistrement. `lastSavedAt` null = jamais enregistré sur le serveur. */519export function autosaveDelay(s: { now: number; lastChangeAt: number; firstDirtyAt: number; lastSavedAt: number | null }, cfg: AutosaveTimings = AUTOSAVE): number {520 const idleAt = s.lastChangeAt + (s.lastSavedAt === null ? cfg.firstIdle : cfg.idle)521 const spacedAt = s.lastSavedAt === null ? 0 : s.lastSavedAt + cfg.minInterval522 const capAt = s.firstDirtyAt + cfg.maxWait523 return Math.max(0, Math.max(Math.min(idleAt, capAt), spacedAt) - s.now)524}525export interface Autosaver {526 /** le contenu vient de changer */527 touch(): void528 /** enregistre maintenant s'il y a du nouveau ; attend l'enregistrement en cours */529 flush(): Promise<void>530 /** oublie les modifications en attente (brouillon fermé, envoyé ou abandonné) */531 cancel(): void532 /** un enregistrement a réussi par un autre chemin */533 markSaved(): void534 readonly pending: boolean535 readonly busy: boolean536}537/**538 * Ordonnanceur d'un brouillon : un seul enregistrement à la fois, jamais deux fois le même contenu (`save` n'est appelé539 * que s'il y a eu un `touch` depuis le dernier succès), frappe continue = pas d'enregistrement.540 * `save` rend faux (ou lève) quand il a échoué : la modification reste en attente, sans nouvel essai automatique immédiat.541 */542export function createAutosaver(save: () => Promise<boolean | void>, opts: { timings?: AutosaveTimings; now?: () => number; setTimer?: (fn: () => void, ms: number) => unknown; clearTimer?: (t: unknown) => void } = {}): Autosaver {543 const cfg = opts.timings ?? AUTOSAVE544 const now = opts.now ?? (() => Date.now())545 const setTimer = opts.setTimer ?? ((fn, ms) => setTimeout(fn, ms))546 const clearTimer = opts.clearTimer ?? ((t) => clearTimeout(t as ReturnType<typeof setTimeout>))547 let timer: unknown = null548 let running: Promise<void> | null = null549 let dirty = false550 let firstDirtyAt = 0551 let lastChangeAt = 0552 let lastSavedAt: number | null = null553 const arm = () => {554 if (timer !== null) clearTimer(timer)555 timer = setTimer(() => {556 timer = null557 // un enregistrement est en cours : celui-ci attendra son tour, espacé du précédent558 if (running) return void running.then(() => (dirty && !cancelled && timer === null ? arm() : undefined))559 // un enregistrement a pu aboutir depuis que ce délai a été fixé : l'écart minimal se compte à partir de lui560 if (autosaveDelay({ now: now(), lastChangeAt, firstDirtyAt, lastSavedAt }, cfg) > 0) return arm()561 void run()562 }, autosaveDelay({ now: now(), lastChangeAt, firstDirtyAt, lastSavedAt }, cfg))563 }564 const run = async (): Promise<void> => {565 if (running) await running566 if (!dirty) return567 if (timer !== null) {568 clearTimer(timer)569 timer = null570 }571 dirty = false572 const mine = (async () => {573 let ok = false574 try {575 ok = (await save()) !== false576 } catch {577 ok = false578 }579 if (ok) {580 lastSavedAt = now()581 if (dirty) firstDirtyAt = lastChangeAt582 } else if (!cancelled) dirty = true // échec : en attente, sans nouvel essai automatique (retour du réseau, bouton, prochaine frappe)583 })()584 running = mine585 try {586 await mine587 } finally {588 if (running === mine) running = null589 }590 }591 let cancelled = false592 return {593 touch() {594 cancelled = false595 const t = now()596 if (!dirty) firstDirtyAt = t597 dirty = true598 lastChangeAt = t599 arm()600 },601 flush: run,602 cancel() {603 cancelled = true604 dirty = false605 if (timer !== null) clearTimer(timer)606 timer = null607 },608 markSaved() {609 lastSavedAt = now()610 dirty = false611 if (timer !== null) clearTimer(timer)612 timer = null613 },614 get pending() {615 return dirty616 },617 get busy() {618 return running !== null619 },620 }621}622623// ---------------------------------------------------------------- envoi différé et rappels624export interface TimePreset {625 id: "in1h" | "tonight" | "tomorrowMorning" | "tomorrowAfternoon" | "mondayMorning" | "in1d" | "in3d" | "in1w"626 at: Date627}628const atHour = (d: Date, days: number, hour: number) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + days, hour, 0, 0, 0)629/** Choix rapides de « Envoyer plus tard », dans le fuseau de l'appareil. */630export function sendLaterPresets(now = new Date()): TimePreset[] {631 const out: TimePreset[] = [{ id: "in1h", at: new Date(now.getTime() + 3600_000) }]632 if (now.getHours() < 17) out.push({ id: "tonight", at: atHour(now, 0, 18) })633 out.push({ id: "tomorrowMorning", at: atHour(now, 1, 8) }, { id: "tomorrowAfternoon", at: atHour(now, 1, 13) })634 const toMonday = (8 - now.getDay()) % 7 || 7635 if (toMonday > 1) out.push({ id: "mondayMorning", at: atHour(now, toMonday, 8) })636 return out637}638/** Choix rapides de « me rappeler si personne ne répond ». */639export function remindPresets(now = new Date()): TimePreset[] {640 return [{ id: "in1d", at: atHour(now, 1, 9) }, { id: "in3d", at: atHour(now, 3, 9) }, { id: "in1w", at: atHour(now, 7, 9) }]641}642export const UNDO_CHOICES = [0, 5, 10, 20, 30, 60] as const643