Elffuss BraidHub

utopia-ia/elffuss-code public

main · 12.9 KiBRawPermalink
1// Decoraciones de las extensiones (setDecorations) pintadas en el editor de
2// Code. Las opciones de cada tipo NUNCA pasan tal cual: se reconstruyen con
3// una lista blanca de valores (colores, longitudes, listas cerradas) y se
4// convierten en reglas CSS nuestras, `.monaco-editor .x2d-N`, dentro de
5// <style id="x2-deco">. Fuera: fontFamily, cualquier url(), CSS libre, y el
6// atajo `border` que no se deje partir en sus tres piezas. El texto antes y
7// después (contentText) va como texto inyectado de Monaco, no como CSS, y los
8// mensajes al pasar el ratón como markdown canónico (sanitize.js). Los
9// iconos de margen no se pintan en esta versión.
10//
11// Las decoraciones son del documento activo: al cambiar de pestaña se
12// borran, y la extensión las vuelve a poner (como en VS Code, al cambiar el
13// editor activo).
14import { canonicalMarkdown, markdownFromText } from './sanitize.js';
15
16const NAMED = new Set(('aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse '
17 + 'chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkgrey darkkhaki darkmagenta darkolivegreen '
18 + 'darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkslategrey darkturquoise darkviolet deeppink deepskyblue dimgray '
19 + 'dimgrey dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow grey honeydew hotpink indianred '
20 + 'indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightgrey '
21 + 'lightpink lightsalmon lightseagreen lightskyblue lightslategray lightslategrey lightsteelblue lightyellow lime limegreen linen magenta maroon '
22 + 'mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue '
23 + 'mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred '
24 + 'papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna '
25 + 'silver skyblue slateblue slategray slategrey snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow '
26 + 'yellowgreen transparent currentcolor').split(' '));
27const LENGTH = /^-?\d{1,4}(\.\d{1,3})?(px|em|ch|%)?$/;
28const LISTS = {
29 borderStyle: new Set(['none', 'hidden', 'dotted', 'dashed', 'solid', 'double', 'groove', 'ridge', 'inset', 'outset']),
30 fontStyle: new Set(['normal', 'italic', 'oblique']),
31 fontWeight: new Set(['normal', 'bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '700', '800', '900']),
32 cursor: new Set(['default', 'pointer', 'text', 'crosshair', 'help', 'move', 'not-allowed', 'wait', 'progress', 'zoom-in', 'zoom-out', 'grab', 'grabbing',
33 'col-resize', 'row-resize', 'ew-resize', 'ns-resize', 'context-menu', 'cell', 'copy', 'alias', 'none']),
34};
35const DECO_LINE = new Set(['none', 'underline', 'overline', 'line-through']);
36const DECO_STYLE = new Set(['solid', 'double', 'dotted', 'dashed', 'wavy']);
37const BORDER_WIDTH = new Set(['thin', 'medium', 'thick']);
38// rgb()/hsl() solo con números: con comas o con espacios (y «/ alfa»)
39const N = '-?\\d{1,3}(?:\\.\\d{1,3})?(?:%|deg)?';
40const FN_COMMAS = new RegExp(`^(?:rgb|hsl)a?\\(\\s*${N}\\s*,\\s*${N}\\s*,\\s*${N}\\s*(?:,\\s*${N}\\s*)?\\)$`);
41const FN_SPACES = new RegExp(`^(?:rgb|hsl)a?\\(\\s*${N}\\s+${N}\\s+${N}\\s*(?:\\/\\s*${N}\\s*)?\\)$`);
42
43export function color(v) {
44 if (v && typeof v === 'object' && typeof v.themeColor === 'string') return /^[A-Za-z0-9.]{1,100}$/.test(v.themeColor) ? `var(--vscode-${v.themeColor.replace(/\./g, '-')})` : null;
45 if (typeof v !== 'string') return null;
46 const s = v.trim().toLowerCase();
47 if (/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(s)) return s;
48 if (NAMED.has(s)) return s;
49 if (FN_COMMAS.test(s) || FN_SPACES.test(s)) return s;
50 return null;
51}
52export const length = v => (typeof v === 'number' && Number.isFinite(v) ? (LENGTH.test(String(v)) ? v + 'px' : null) : typeof v === 'string' && LENGTH.test(v.trim()) ? v.trim() : null);
53const lengths = (v, max = 4) => {
54 if (typeof v !== 'string' && typeof v !== 'number') return null;
55 const parts = String(v).trim().split(/\s+/);
56 if (!parts.length || parts.length > max) return null;
57 const ok = parts.map(p => length(p));
58 return ok.every(Boolean) ? ok.join(' ') : null;
59};
60const listed = (k, v) => (typeof v === 'string' && LISTS[k].has(v.trim().toLowerCase()) ? v.trim().toLowerCase() : typeof v === 'number' && k === 'fontWeight' && LISTS.fontWeight.has(String(v)) ? String(v) : null);
61const opacity = v => { const s = String(v ?? '').trim(); return /^(0(\.\d{1,3})?|1(\.0{1,3})?|\.\d{1,3})$/.test(s) ? s : null; };
62export function textDecoration(v) {
63 if (typeof v !== 'string') return null;
64 const toks = v.trim().toLowerCase().split(/\s+/);
65 if (!toks.length || toks.length > 4) return null;
66 const out = [];
67 for (const t of toks) {
68 if (DECO_LINE.has(t) || DECO_STYLE.has(t)) out.push(t);
69 else if (color(t)) out.push(color(t));
70 else if (length(t)) out.push(length(t));
71 else return null;
72 }
73 return out.join(' ');
74}
75// `border` / `outline`: solo si se parte en anchura, estilo y color válidos
76export function borderShorthand(v) {
77 if (typeof v !== 'string') return null;
78 const toks = v.trim().toLowerCase().split(/\s+/);
79 if (!toks.length || toks.length > 3) return null;
80 const out = [];
81 for (const t of toks) {
82 if (LISTS.borderStyle.has(t) || BORDER_WIDTH.has(t)) out.push(t);
83 else if (length(t)) out.push(length(t));
84 else if (color(t)) out.push(color(t));
85 else return null;
86 }
87 return out.join(' ');
88}
89
90// opciones de un tipo (o de una variante clara/oscura) → declaraciones CSS
91const CSS = {
92 block: [
93 ['backgroundColor', 'background-color', color], ['outline', 'outline', borderShorthand], ['outlineColor', 'outline-color', color],
94 ['outlineStyle', 'outline-style', v => listed('borderStyle', v)], ['outlineWidth', 'outline-width', length], ['border', 'border', borderShorthand],
95 ['borderColor', 'border-color', color], ['borderRadius', 'border-radius', v => lengths(v)], ['borderSpacing', 'border-spacing', v => lengths(v, 2)],
96 ['borderStyle', 'border-style', v => listed('borderStyle', v)], ['borderWidth', 'border-width', v => lengths(v)],
97 ],
98 inline: [
99 ['color', 'color', color], ['fontStyle', 'font-style', v => listed('fontStyle', v)], ['fontWeight', 'font-weight', v => listed('fontWeight', v)],
100 ['textDecoration', 'text-decoration', textDecoration], ['cursor', 'cursor', v => listed('cursor', v)], ['opacity', 'opacity', opacity],
101 ['letterSpacing', 'letter-spacing', length],
102 ],
103 content: [
104 ['color', 'color', color], ['backgroundColor', 'background-color', color], ['border', 'border', borderShorthand], ['borderColor', 'border-color', color],
105 ['fontStyle', 'font-style', v => listed('fontStyle', v)], ['fontWeight', 'font-weight', v => listed('fontWeight', v)],
106 ['textDecoration', 'text-decoration', textDecoration], ['margin', 'margin', v => lengths(v)], ['width', 'width', length], ['height', 'height', length],
107 ['opacity', 'opacity', opacity],
108 ],
109};
110export function declarations(o, group) {
111 if (!o || typeof o !== 'object') return '';
112 const out = [];
113 for (const [k, prop, fn] of CSS[group]) {
114 if (o[k] === undefined || o[k] === null) continue;
115 const v = fn(o[k]);
116 if (v) out.push(`${prop}: ${v};`);
117 }
118 return out.join(' ');
119}
120const contentText = c => (c && typeof c.contentText === 'string' ? c.contentText.replace(/[\r\n]+/g, ' ').slice(0, 200) : null);
121const LANES = new Set([1, 2, 4, 7]);
122const STICK = new Set([0, 1, 2, 3]);
123
124export class Decorations {
125 constructor({ monaco, editor, docs }) {
126 this.monaco = monaco;
127 this.editor = editor;
128 this.docs = docs;
129 this.types = new Map(); // key → { cls, ...options normalizadas }
130 this.collections = new Map(); // key → colección del documento activo
131 this.css = new Map(); // texto CSS → nombre de clase (para no repetir reglas)
132 this.n = 0;
133 this.style = null;
134 this.rules = [];
135 this.sub = editor.onDidChangeModel(() => this.clear());
136 }
137
138 sheet() {
139 if (!this.style || !this.style.isConnected) {
140 this.style = document.createElement('style');
141 this.style.id = 'x2-deco';
142 document.head.appendChild(this.style);
143 }
144 return this.style;
145 }
146 // una clase para estas declaraciones (con sus variantes clara y oscura)
147 classFor(base, light, dark) {
148 if (!base && !light && !dark) return null;
149 const sig = base + '|' + light + '|' + dark;
150 if (this.css.has(sig)) return this.css.get(sig);
151 const cls = 'x2d-' + (++this.n);
152 if (base) this.rules.push(`.monaco-editor .${cls} { ${base} }`);
153 if (light) this.rules.push(`.monaco-editor.vs .${cls}, .monaco-editor.hc-light .${cls} { ${light} }`);
154 if (dark) this.rules.push(`.monaco-editor.vs-dark .${cls}, .monaco-editor.hc-black .${cls} { ${dark} }`);
155 this.sheet().textContent = this.rules.join('\n');
156 this.css.set(sig, cls);
157 return cls;
158 }
159 contentClass(c, light, dark) {
160 return this.classFor(declarations(c, 'content'), declarations(light, 'content'), declarations(dark, 'content'));
161 }
162
163 type(key, o) {
164 if (typeof key !== 'string' || !o || typeof o !== 'object') return;
165 const light = o.light && typeof o.light === 'object' ? o.light : null;
166 const dark = o.dark && typeof o.dark === 'object' ? o.dark : null;
167 const t = {
168 className: this.classFor(declarations(o, 'block'), declarations(light, 'block'), declarations(dark, 'block')),
169 inlineClassName: this.classFor(declarations(o, 'inline'), declarations(light, 'inline'), declarations(dark, 'inline')),
170 isWholeLine: o.isWholeLine === true,
171 stickiness: STICK.has(o.rangeBehavior) ? o.rangeBehavior : undefined,
172 ruler: null,
173 before: null, after: null,
174 };
175 const rulerColor = o.overviewRulerColor && typeof o.overviewRulerColor === 'object' && typeof o.overviewRulerColor.themeColor === 'string'
176 ? (/^[A-Za-z0-9.]{1,100}$/.test(o.overviewRulerColor.themeColor) ? { id: o.overviewRulerColor.themeColor } : null)
177 : color(o.overviewRulerColor);
178 if (rulerColor) t.ruler = { color: rulerColor, position: LANES.has(o.overviewRulerLane) ? o.overviewRulerLane : 4 };
179 for (const side of ['before', 'after']) {
180 const c = o[side] && typeof o[side] === 'object' ? o[side] : null;
181 if (!c) continue;
182 t[side] = { text: contentText(c), cls: this.contentClass(c, light?.[side], dark?.[side]) };
183 }
184 this.types.set(key, t);
185 }
186
187 // rangos de una decoración en el documento `uri` (solo si es el activo)
188 set(key, uri, ranges) {
189 const t = this.types.get(key);
190 const model = this.docs.modelForUri(uri);
191 if (!t || !model || this.editor.getModel() !== model) return;
192 const out = [];
193 for (const r of ranges.slice(0, 10000)) {
194 if (!r || !Array.isArray(r.range)) continue;
195 const v = model.validateRange(new this.monaco.Range(r.range[0], r.range[1], r.range[2], r.range[3]));
196 const ro = r.ro && typeof r.ro === 'object' ? r.ro : null;
197 const opts = { description: 'x2-extension-decoration' };
198 if (t.className) opts.className = t.className;
199 if (t.inlineClassName) opts.inlineClassName = t.inlineClassName;
200 if (t.isWholeLine) opts.isWholeLine = true;
201 if (t.stickiness !== undefined) opts.stickiness = t.stickiness;
202 if (t.ruler) opts.overviewRuler = t.ruler;
203 for (const side of ['before', 'after']) {
204 // el texto por rango (renderOptions) manda sobre el del tipo
205 const per = ro && ro[side] && typeof ro[side] === 'object' ? ro[side] : null;
206 const text = contentText(per) ?? t[side]?.text;
207 if (!text) continue;
208 const cls = per ? this.contentClass(per, ro.light?.[side], ro.dark?.[side]) || t[side]?.cls : t[side]?.cls;
209 opts[side] = { content: text, ...(cls ? { inlineClassName: cls } : {}) };
210 }
211 const hover = Array.isArray(r.hover) ? r.hover : r.hover ? [r.hover] : [];
212 const msgs = hover.slice(0, 10).map(h => (h && typeof h.md === 'string' ? canonicalMarkdown(h.md) : h && typeof h.text === 'string' ? markdownFromText(h.text) : null)).filter(Boolean);
213 if (msgs.length) opts.hoverMessage = msgs;
214 out.push({ range: v, options: opts });
215 }
216 let c = this.collections.get(key);
217 if (!c) { c = this.editor.createDecorationsCollection(); this.collections.set(key, c); }
218 c.set(out);
219 }
220
221 remove(key) {
222 this.collections.get(key)?.clear();
223 this.collections.delete(key);
224 this.types.delete(key);
225 }
226
227 clear() { for (const c of this.collections.values()) c.clear(); }
228
229 dispose() {
230 this.sub?.dispose();
231 this.clear();
232 this.collections.clear();
233 this.types.clear();
234 this.style?.remove();
235 this.rules = [];
236 this.css.clear();
237 }
238}