Repository Public
1// Variables {{nom}} d'un modèle : extraction, insertion au curseur, valeurs d'aperçu, repères de longueur et de poids.2// Logique pure, alignée sur le serveur (server/src/templates-ai.ts) : nom = ^[a-z][a-z0-9_]{0,39}$.34export const VARIABLE_NAME = /^[a-z][a-z0-9_]{0,39}$/5const VAR = /\{\{\s*([a-z][a-z0-9_]{0,39})\s*\}\}/g67export interface TemplateVariable {8 name: string9 description: string10 example: string11 required: boolean12}1314/** Noms des variables présentes dans les textes donnés, sans doublon, triés (comme le serveur). */15export function extractVariables(...texts: string[]): string[] {16 const found = new Set<string>()17 for (const t of texts) for (const m of t.matchAll(VAR)) found.add(m[1])18 return [...found].sort()19}2021/** Nombre d'occurrences de chaque variable. */22export function countVariables(...texts: string[]): Map<string, number> {23 const counts = new Map<string, number>()24 for (const t of texts) for (const m of t.matchAll(VAR)) counts.set(m[1], (counts.get(m[1]) ?? 0) + 1)25 return counts26}2728/** Insère `{{nom}}` à la place de la sélection ; rend le nouveau texte et la position du curseur (après l'insertion). */29export function insertVariable(text: string, name: string, selStart: number, selEnd = selStart): { text: string; caret: number } {30 if (!VARIABLE_NAME.test(name)) return { text, caret: selEnd }31 const a = Math.max(0, Math.min(selStart, selEnd, text.length))32 const b = Math.max(a, Math.min(Math.max(selStart, selEnd), text.length))33 const token = `{{${name}}}`34 return { text: text.slice(0, a) + token + text.slice(b), caret: a + token.length }35}3637/** Remplace les variables d'un texte simple (objet, aperçu) ; une variable sans valeur reste visible telle quelle. */38export function fillText(text: string, values: Readonly<Record<string, string>>): string {39 return text.replace(VAR, (raw, name: string) => (name in values ? values[name] : raw))40}4142/** Valeurs de départ de l'aperçu : l'exemple de chaque variable. */43export function exampleValues(variables: readonly TemplateVariable[]): Record<string, string> {44 const out: Record<string, string> = {}45 for (const v of variables) out[v.name] = v.example46 return out47}4849/** Variables obligatoires sans valeur (ni saisie, ni exemple). */50export function missingRequired(variables: readonly TemplateVariable[], values: Readonly<Record<string, string>>): string[] {51 return variables.filter((v) => v.required && !(values[v.name] ?? "").trim()).map((v) => v.name)52}5354/**55 * Garde les valeurs saisies quand la liste des variables change (réalignement par le serveur) : une variable nouvelle56 * prend son exemple, une variable disparue est oubliée.57 */58export function reconcileValues(variables: readonly TemplateVariable[], previous: Readonly<Record<string, string>>): Record<string, string> {59 const out: Record<string, string> = {}60 for (const v of variables) out[v.name] = v.name in previous ? previous[v.name] : v.example61 return out62}6364/** Fusionne les variables déclarées avec celles réellement utilisées (descriptions et exemples conservés). */65export function alignVariables(declared: readonly TemplateVariable[], ...texts: string[]): TemplateVariable[] {66 const by = new Map(declared.map((v) => [v.name, v]))67 return extractVariables(...texts).map((name) => by.get(name) ?? { name, description: "", example: "", required: false })68}6970// ---------------------------------------------------------------- longueurs (objet, texte d'aperçu)71export const SUBJECT_SOFT_LIMIT = 6072export const PREHEADER_SOFT_LIMIT = 11073export const PREHEADER_MIN = 407475export type LengthHint = "empty" | "short" | "ok" | "long"76/** Longueur en caractères visibles (un émoji compte pour un). */77export function visibleLength(s: string): number {78 return Array.from(s).length79}80export function subjectHint(rendered: string): LengthHint {81 const n = visibleLength(rendered.trim())82 return n === 0 ? "empty" : n > SUBJECT_SOFT_LIMIT ? "long" : "ok"83}84export function preheaderHint(rendered: string): LengthHint {85 const n = visibleLength(rendered.trim())86 return n === 0 ? "empty" : n < PREHEADER_MIN ? "short" : n > PREHEADER_SOFT_LIMIT ? "long" : "ok"87}88/** Coupe comme le ferait une liste de messages : au plus `max` caractères, points de suspension compris. */89export function truncateVisible(s: string, max: number): string {90 const chars = Array.from(s)91 return chars.length <= max ? s : `${chars.slice(0, Math.max(0, max - 1)).join("").trimEnd()}…`92}9394// ---------------------------------------------------------------- poids95/** Gmail tronque un message dont le HTML dépasse environ 102 Ko (« Message tronqué »). */96export const CLIP_BYTES = 102 * 102497export const CLIP_WARN_BYTES = 100 * 100098export const MAX_TEMPLATE_BYTES = 400 * 102499100export function byteLength(s: string): number {101 let n = 0102 for (let i = 0; i < s.length; i++) {103 const c = s.charCodeAt(i)104 if (c < 0x80) n += 1105 else if (c < 0x800) n += 2106 else if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {107 n += 4108 i++109 } else n += 3110 }111 return n112}113export type SizeLevel = "ok" | "near" | "clipped" | "over"114/** ok : à l'aise ; near : au-delà de 80 Ko ; clipped : Gmail tronquera ; over : refusé par le serveur. */115export function sizeLevel(bytes: number): SizeLevel {116 if (bytes > MAX_TEMPLATE_BYTES) return "over"117 if (bytes >= CLIP_WARN_BYTES) return "clipped"118 if (bytes >= 80 * 1000) return "near"119 return "ok"120}121export function formatBytes(bytes: number, lang: "fr" | "en"): string {122 const unit = lang === "fr" ? ["o", "Ko", "Mo"] : ["B", "KB", "MB"]123 const sep = lang === "fr" ? " " : " "124 if (bytes < 1000) return `${bytes}${sep}${unit[0]}`125 const kb = bytes / 1024126 if (kb < 1000) return `${kb < 10 ? kb.toFixed(1) : Math.round(kb)}${sep}${unit[1]}`.replace(".", lang === "fr" ? "," : ".")127 return `${(kb / 1024).toFixed(1)}${sep}${unit[2]}`.replace(".", lang === "fr" ? "," : ".")128}129130/** Nom de fichier sûr pour l'export. */131export function exportFileName(name: string, ext = "html"): string {132 const base = name133 .normalize("NFKD")134 .replace(/[̀-ͯ]/g, "")135 .replace(/[^a-zA-Z0-9]+/g, "-")136 .replace(/^-+|-+$/g, "")137 .toLowerCase()138 .slice(0, 60)139 return `${base || "modele"}.${ext}`140}141142// ---------------------------------------------------------------- dates relatives143/** « il y a 3 h », « hier », « 12 mars » — pour les cartes de la bibliothèque. */144export function relativeDate(iso: string, lang: "fr" | "en", now = Date.now()): string {145 const then = new Date(iso).getTime()146 if (Number.isNaN(then)) return ""147 const sec = Math.round((now - then) / 1000)148 const locale = lang === "fr" ? "fr-CA" : "en-CA"149 if (sec < 45) return lang === "fr" ? "à l'instant" : "just now"150 const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto", style: "short" })151 if (sec < 3600) return rtf.format(-Math.max(1, Math.round(sec / 60)), "minute")152 if (sec < 86400) return rtf.format(-Math.round(sec / 3600), "hour")153 if (sec < 7 * 86400) return rtf.format(-Math.round(sec / 86400), "day")154 const d = new Date(then)155 return d.toLocaleDateString(locale, d.getFullYear() === new Date(now).getFullYear() ? { day: "numeric", month: "short" } : { day: "numeric", month: "short", year: "numeric" })156}157158// ---------------------------------------------------------------- éditeur de source159/** Indice de ligne (à partir de 0) d'une position dans le texte. */160export function lineOfOffset(text: string, offset: number): number {161 let line = 0162 const end = Math.min(offset, text.length)163 for (let i = 0; i < end; i++) if (text.charCodeAt(i) === 10) line++164 return line165}166167/** Positions de toutes les occurrences (insensible à la casse), plafonnées pour rester rapide sur un gros document. */168export function findAll(text: string, needle: string, cap = 5000): number[] {169 const out: number[] = []170 if (!needle) return out171 const hay = text.toLowerCase()172 const n = needle.toLowerCase()173 for (let i = hay.indexOf(n); i !== -1 && out.length < cap; i = hay.indexOf(n, i + Math.max(1, n.length))) out.push(i)174 return out175}176177/**178 * Lignes d'écran occupées par chaque ligne logique quand le retour automatique est actif, pour une police à chasse fixe,179 * `cols` colonnes et des tabulations de `tab` colonnes (le texte est coupé n'importe où : line-break: anywhere).180 */181export function wrappedRows(text: string, cols: number, tab = 2): number[] {182 const rows: number[] = []183 const width = Math.max(1, Math.floor(cols))184 let col = 0185 for (let i = 0; i <= text.length; i++) {186 const c = i < text.length ? text.charCodeAt(i) : 10187 if (c === 10) {188 rows.push(Math.max(1, Math.ceil(col / width)))189 col = 0190 } else if (c === 9) col += tab - (col % tab)191 else if (c >= 0xdc00 && c <= 0xdfff) continue192 else col += 1193 }194 return rows195}196197/** Tabulation dans la source : indente (ou désindente) les lignes sélectionnées, ou insère deux espaces au curseur. */198export function applyTab(text: string, selStart: number, selEnd: number, outdent: boolean, unit = " "): { text: string; selStart: number; selEnd: number } {199 if (selStart === selEnd && !outdent) return { text: text.slice(0, selStart) + unit + text.slice(selEnd), selStart: selStart + unit.length, selEnd: selStart + unit.length }200 const lineStart = text.lastIndexOf("\n", selStart - 1) + 1201 const endAnchor = selEnd > selStart && text[selEnd - 1] === "\n" ? selEnd - 1 : selEnd202 let lineEnd = text.indexOf("\n", endAnchor)203 if (lineEnd === -1) lineEnd = text.length204 const lines = text.slice(lineStart, lineEnd).split("\n")205 let firstDelta = 0206 let total = 0207 const next = lines.map((l, i) => {208 if (!outdent) {209 if (i === 0) firstDelta = unit.length210 total += unit.length211 return unit + l212 }213 const cut = l.startsWith(unit) ? unit.length : l.startsWith("\t") ? 1 : l.startsWith(" ") ? 1 : 0214 if (i === 0) firstDelta = -Math.min(cut, selStart - lineStart)215 total -= cut216 return l.slice(cut)217 })218 return { text: text.slice(0, lineStart) + next.join("\n") + text.slice(lineEnd), selStart: Math.max(lineStart, selStart + firstDelta), selEnd: Math.max(lineStart, selEnd + total) }219}220