Elffuss BraidHub

utopia-ia/elffuss-code public

main · 20.4 KiBRawPermalink
1// Temas de color de VS Code → Monaco.
2//
3// Un tema de VS Code trae dos cosas: `colors` (los del editor y del resto del
4// banco de trabajo, que Monaco entiende tal cual) y `tokenColors`, reglas
5// TextMate por ámbito («keyword.control», «string.quoted»…). Monaco colorea sus
6// lenguajes de serie (Monarch) con clases propias («keyword», «string»,
7// «comment»…), así que a cada clase se le da el color del ámbito TextMate que
8// la representa, con la misma regla que usa TextMate: gana el selector más
9// largo que sea prefijo del ámbito. Los ficheros con gramática TextMate de una
10// extensión no pasan por esta tabla: llevan los colores exactos (grammars.js).
11import { parseJsonc, parsePlist, isHexColor, hex6 } from './formats.js';
12
13export const BASES = ['vs-dark', 'vs', 'hc-black', 'hc-light'];
14
15// ── cargar un tema desde el paquete (como colorThemeData.ts de VS Code) ─────
16const dirname = p => (p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : '');
17export function joinPath(base, rel) {
18 const out = [];
19 for (const seg of (base ? base + '/' : '').concat(String(rel)).split('/')) {
20 if (!seg || seg === '.') continue;
21 if (seg === '..') { if (!out.length) throw Object.assign(new Error('ruta fuera del paquete: ' + rel), { code: 'outside' }); out.pop(); } else out.push(seg);
22 }
23 return out.join('/');
24}
25
26// Ajustes globales de un .tmTheme (regla sin ámbito) → colores del editor.
27const TMTHEME_COLORES = {
28 background: ['editor.background'], foreground: ['editor.foreground'],
29 selection: ['editor.selectionBackground'], inactiveSelection: ['editor.inactiveSelectionBackground'],
30 selectionHighlightColor: ['editor.selectionHighlightBackground'],
31 findMatchHighlight: ['editor.findMatchHighlightBackground'], currentFindMatchHighlight: ['editor.findMatchBackground'],
32 hoverHighlight: ['editor.hoverHighlightBackground'], wordHighlight: ['editor.wordHighlightBackground'],
33 wordHighlightStrong: ['editor.wordHighlightStrongBackground'], findRangeHighlight: ['editor.findRangeHighlightBackground'],
34 lineHighlight: ['editor.lineHighlightBackground'], rangeHighlight: ['editor.rangeHighlightBackground'],
35 caret: ['editorCursor.foreground'], invisibles: ['editorWhitespace.foreground'],
36 guide: ['editorIndentGuide.background'], activeGuide: ['editorIndentGuide.activeBackground'],
37};
38function convertSettings(settings, out) {
39 for (const regla of settings) {
40 if (!regla || typeof regla !== 'object') continue;
41 if (!regla.scope && regla.settings && typeof regla.settings === 'object') {
42 for (const [k, v] of Object.entries(regla.settings)) {
43 for (const id of TMTHEME_COLORES[k] || []) if (typeof v === 'string') out.colors[id] = v;
44 }
45 }
46 out.tokenColors.push(regla);
47 }
48}
49
50async function cargaEn(path, readText, out, prof) {
51 if (prof > 8) throw Object.assign(new Error('demasiados include en el tema'), { code: 'notheme' });
52 if (/\.json$/i.test(path)) {
53 const j = parseJsonc(await readText(path));
54 if (typeof j.include === 'string') await cargaEn(joinPath(dirname(path), j.include), readText, out, prof + 1);
55 if (Array.isArray(j.settings)) { convertSettings(j.settings, out); return; }
56 if (j.colors && typeof j.colors === 'object') {
57 for (const [k, v] of Object.entries(j.colors)) {
58 if (v === 'default') delete out.colors[k];
59 else if (typeof v === 'string') out.colors[k] = v;
60 }
61 }
62 if (Array.isArray(j.tokenColors)) out.tokenColors.push(...j.tokenColors);
63 else if (typeof j.tokenColors === 'string') {
64 const t = parsePlist(await readText(joinPath(dirname(path), j.tokenColors)));
65 if (Array.isArray(t?.settings)) convertSettings(t.settings, out);
66 }
67 if (typeof j.type === 'string') out.type = j.type;
68 } else {
69 const t = parsePlist(await readText(path));
70 if (!Array.isArray(t?.settings)) throw Object.assign(new Error('el .tmTheme no tiene settings'), { code: 'notheme' });
71 convertSettings(t.settings, out);
72 }
73}
74
75// Reglas TextMate normalizadas: { scope: [selectores], settings: { foreground,
76// background, fontStyle } } con colores ya validados.
77function normalizaReglas(reglas) {
78 const out = [];
79 for (const r of reglas) {
80 if (!r || typeof r !== 'object' || !r.settings || typeof r.settings !== 'object') continue;
81 const st = {};
82 if (isHexColor(r.settings.foreground)) st.foreground = r.settings.foreground;
83 if (isHexColor(r.settings.background)) st.background = r.settings.background;
84 if (typeof r.settings.fontStyle === 'string') {
85 st.fontStyle = r.settings.fontStyle.split(/\s+/).filter(w => ['italic', 'bold', 'underline', 'strikethrough'].includes(w)).join(' ');
86 }
87 if (!Object.keys(st).length) continue;
88 const scope = Array.isArray(r.scope) ? r.scope.filter(x => typeof x === 'string').map(x => x.trim()).filter(Boolean)
89 : typeof r.scope === 'string' ? r.scope.split(',').map(x => x.trim()).filter(Boolean) : [];
90 out.push(scope.length ? { scope, settings: st } : { settings: st });
91 }
92 return out;
93}
94
95// Tema listo para guardar: { label, uiTheme, colors, tokenColors }.
96export async function loadTheme(path, readText, { label = '', uiTheme = '' } = {}) {
97 const out = { colors: {}, tokenColors: [], type: '' };
98 await cargaEn(path, readText, out, 0);
99 const colors = {};
100 for (const [k, v] of Object.entries(out.colors)) if (isHexColor(v)) colors[k] = v;
101 const porTipo = { dark: 'vs-dark', light: 'vs', hc: 'hc-black', hcLight: 'hc-light', 'hc-light': 'hc-light' };
102 const base = BASES.includes(uiTheme) ? uiTheme : porTipo[out.type] || 'vs-dark';
103 return { label: String(label || ''), uiTheme: base, colors, tokenColors: normalizaReglas(out.tokenColors) };
104}
105
106// ── resolución TextMate: qué estilo toca a un ámbito ─────────────────────────
107// Solo selectores simples («keyword.control»); los de contexto («source.js
108// keyword») o con exclusiones no sirven para las clases sueltas de Monarch.
109function selectoresSimples(regla) {
110 return (regla.scope || []).filter(s => !/[\s()|&,]|^-/.test(s));
111}
112export function resolveScope(tokenColors, scope) {
113 const cands = [];
114 tokenColors.forEach((r, idx) => {
115 for (const sel of selectoresSimples(r)) {
116 if (scope === sel || scope.startsWith(sel + '.')) cands.push({ spec: sel.split('.').length, idx, st: r.settings });
117 }
118 });
119 cands.sort((a, b) => b.spec - a.spec || b.idx - a.idx);
120 const out = {};
121 for (const c of cands) {
122 if (out.foreground === undefined && c.st.foreground) out.foreground = c.st.foreground;
123 if (out.fontStyle === undefined && typeof c.st.fontStyle === 'string') out.fontStyle = c.st.fontStyle;
124 }
125 return out;
126}
127
128// Clase de Monaco (Monarch) → ámbitos TextMate que la representan, por orden.
129// Incluye las clases con regla propia en los temas de serie de Monaco
130// (string.key.json, delimiter.html…): si no se cubrieran, ganaría el color
131// del tema de serie y el tema de la extensión quedaría a medias.
132const MONARCH = [
133 ['comment', ['comment']],
134 ['comment.doc', ['comment.block.documentation', 'comment']],
135 ['string', ['string']],
136 ['string.escape', ['constant.character.escape', 'string']],
137 ['string.key.json', ['support.type.property-name.json', 'support.type.property-name', 'variable.other.property']],
138 ['string.value.json', ['string.quoted.double.json', 'string']],
139 ['string.html', ['string.quoted.double.html', 'string']],
140 ['string.sql', ['string.quoted.single.sql', 'string']],
141 ['string.yaml', ['string.unquoted.plain.out.yaml', 'string']],
142 ['string.link', ['markup.underline.link', 'string']],
143 ['regexp', ['string.regexp']],
144 ['number', ['constant.numeric']],
145 ['number.hex', ['constant.numeric.hex', 'constant.numeric']],
146 ['constant', ['constant.language', 'constant']],
147 ['keyword', ['keyword', 'storage.type', 'storage']],
148 ['keyword.flow', ['keyword.control']],
149 ['keyword.flow.scss', ['keyword.control.at-rule', 'keyword.control', 'keyword']],
150 ['keyword.json', ['constant.language.json', 'constant.language']],
151 ['operator', ['keyword.operator']],
152 ['operator.scss', ['keyword.operator']],
153 ['operator.sql', ['keyword.operator']],
154 ['operator.swift', ['keyword.operator']],
155 ['delimiter', ['punctuation', 'meta.brace']],
156 ['delimiter.html', ['punctuation.definition.tag']],
157 ['delimiter.xml', ['punctuation.definition.tag']],
158 ['type', ['entity.name.type', 'support.type', 'storage.type']],
159 ['type.identifier', ['entity.name.type', 'entity.name.class', 'support.class']],
160 ['identifier', ['variable', 'variable.other.readwrite']],
161 ['variable', ['variable']],
162 ['variable.predefined', ['variable.language', 'support.variable']],
163 ['variable.parameter', ['variable.parameter']],
164 ['predefined', ['support.function', 'entity.name.function']],
165 ['predefined.sql', ['support.function', 'entity.name.function']],
166 ['annotation', ['meta.decorator', 'storage.type.annotation', 'entity.name.function.decorator']],
167 ['tag', ['entity.name.tag']],
168 ['tag.id.pug', ['entity.other.attribute-name.id', 'entity.name.tag']],
169 ['tag.class.pug', ['entity.other.attribute-name.class', 'entity.name.tag']],
170 ['meta.tag', ['entity.name.tag']],
171 ['meta.scss', ['keyword.control.at-rule', 'keyword']],
172 ['metatag', ['meta.tag.sgml', 'punctuation.definition.tag', 'entity.name.tag']],
173 ['metatag.html', ['meta.tag.sgml.doctype', 'punctuation.definition.tag', 'entity.name.tag']],
174 ['metatag.xml', ['meta.tag.preprocessor.xml', 'punctuation.definition.tag', 'entity.name.tag']],
175 ['metatag.content.html', ['string']],
176 ['key', ['support.type.property-name', 'entity.name.tag.yaml', 'variable.other.property']],
177 ['attribute.name', ['entity.other.attribute-name', 'support.type.property-name']],
178 ['attribute.value', ['string', 'support.constant.property-value']],
179 ['attribute.value.number', ['constant.numeric']],
180 ['attribute.value.number.css', ['constant.numeric']],
181 ['attribute.value.unit', ['keyword.other.unit', 'constant.numeric']],
182 ['attribute.value.unit.css', ['keyword.other.unit', 'constant.numeric']],
183 ['attribute.value.hex.css', ['constant.other.color', 'constant.numeric']],
184 ['attribute.value.html', ['string']],
185 ['attribute.value.xml', ['string']],
186 ['invalid', ['invalid']],
187 ['emphasis', ['markup.italic'], 'estilo'],
188 ['strong', ['markup.bold'], 'estilo'],
189 ['metatag.php', ['punctuation.section.embedded'], 'estilo'],
190];
191
192const DEF = {
193 'vs-dark': { fg: '#D4D4D4', bg: '#1E1E1E' }, vs: { fg: '#000000', bg: '#FFFFFE' },
194 'hc-black': { fg: '#FFFFFF', bg: '#000000' }, 'hc-light': { fg: '#292929', bg: '#FFFFFF' },
195};
196function defaults(theme) {
197 const d = DEF[theme.uiTheme] || DEF['vs-dark'];
198 const global = (theme.tokenColors || []).find(r => !r.scope)?.settings || {};
199 const bg = hex6(theme.colors?.['editor.background']) || hex6(global.background) || d.bg;
200 const fg = hex6(theme.colors?.['editor.foreground'], bg) || hex6(global.foreground, bg) || d.fg;
201 return { fg, bg };
202}
203
204export function monarchRules(theme) {
205 const { fg: defFg, bg } = defaults(theme);
206 const reglas = [];
207 for (const [token, scopes, modo] of MONARCH) {
208 let fg = null, fs;
209 for (const sc of scopes) {
210 const m = resolveScope(theme.tokenColors || [], sc);
211 if (modo === 'estilo') { if (m.fontStyle !== undefined) { fs = m.fontStyle; break; } continue; }
212 if (m.foreground) { fg = hex6(m.foreground, bg); fs = m.fontStyle; break; }
213 }
214 if (modo === 'estilo') { if (fs !== undefined) reglas.push({ token, fontStyle: fs }); continue; }
215 // sin regla en el tema: el color por defecto, que es lo que haría VS Code
216 // con un ámbito sin pintar (no el del tema de serie de Monaco)
217 const r = { token, foreground: (fg || defFg).slice(1) };
218 if (fs !== undefined) r.fontStyle = fs;
219 reglas.push(r);
220 }
221 return reglas;
222}
223
224// Datos para monaco.editor.defineTheme. `encodedTokensColors` (el mapa de
225// colores de TextMate) solo cuando hay gramáticas TextMate activas.
226export function toMonacoTheme(theme, encodedTokensColors = null) {
227 const colors = {};
228 for (const [k, v] of Object.entries(theme.colors || {})) if (isHexColor(v)) colors[k] = v;
229 const data = { base: BASES.includes(theme.uiTheme) ? theme.uiTheme : 'vs-dark', inherit: true, rules: monarchRules(theme), colors };
230 if (encodedTokensColors) data.encodedTokensColors = encodedTokensColors;
231 return data;
232}
233
234// Tema en formato vscode-textmate (IRawTheme). Los colores van a '#RRGGBB'
235// (el alfa mezclado sobre el fondo): Monaco no admite otra forma en su mapa de
236// colores y los dos mapas tienen que deduplicar igual para que los índices
237// coincidan.
238//
239// El motor guarda los ámbitos del tema en un árbol de objetos normales y
240// pregunta con `hijos.hasOwnProperty(trozo)`: un trozo «hasOwnProperty» tapa
241// ese método y el motor revienta con TODOS los temas siguientes; uno
242// «__proto__» cambia el prototipo del nodo. Esos selectores no pasan.
243const TROZOS_PELIGROSOS = new Set(['__proto__', 'hasOwnProperty']);
244const selectorSeguro = s => !s.split(/[^\w$]+/).some(t => TROZOS_PELIGROSOS.has(t));
245export function toTextMateTheme(theme) {
246 const { fg, bg } = defaults(theme);
247 const settings = [{ settings: { foreground: fg, background: bg } }];
248 for (const r0 of theme.tokenColors || []) {
249 if (!r0?.settings || !Array.isArray(r0.scope)) continue;
250 const r = { ...r0, scope: r0.scope.filter(s => typeof s === 'string' && selectorSeguro(s)) };
251 if (!r.scope.length) continue;
252 const st = {};
253 const f = hex6(r.settings.foreground, bg); if (f) st.foreground = f;
254 const b = hex6(r.settings.background, bg); if (b) st.background = b;
255 if (typeof r.settings.fontStyle === 'string') st.fontStyle = r.settings.fontStyle;
256 if (Object.keys(st).length) settings.push({ scope: r.scope, settings: st });
257 }
258 return { name: theme.label || 'tema', settings };
259}
260
261// Colores TextMate para los temas de serie de Monaco: un fichero con gramática
262// de una extensión se ve como en VS Code con Dark+/Light+/Alto contraste.
263// Colores de los temas por defecto de VS Code (licencia MIT).
264const R = (scope, foreground, fontStyle) => ({ scope: scope.split(',').map(s => s.trim()), settings: { ...(foreground && { foreground }), ...(fontStyle !== undefined && { fontStyle }) } });
265const TM_SERIE = {
266 'vs-dark': ['#D4D4D4', '#1E1E1E', [
267 R('comment', '#6A9955'), R('string', '#CE9178'), R('string.regexp', '#D16969'), R('constant.numeric, keyword.other.unit, markup.inserted', '#B5CEA8'),
268 R('constant.language, constant.character, keyword, storage, variable.language, entity.name.tag, meta.preprocessor', '#569CD6'),
269 R('constant.character.escape', '#D7BA7D'), R('keyword.control, entity.name.operator', '#C586C0'), R('keyword.operator', '#D4D4D4'),
270 R('entity.name.function, support.function', '#DCDCAA'),
271 R('entity.name.type, entity.name.class, entity.name.namespace, support.type, support.class', '#4EC9B0'),
272 R('variable, variable.parameter, support.variable, entity.other.attribute-name, support.type.property-name, constant.other.placeholder', '#9CDCFE'),
273 R('variable.other.constant', '#4FC1FF'), R('punctuation.definition.tag', '#808080'), R('invalid', '#F44747'),
274 R('entity.name.label', '#C8C8C8'), R('markup.deleted, markup.inline.raw', '#CE9178'),
275 R('markup.heading', '#569CD6', 'bold'), R('markup.bold', null, 'bold'), R('markup.italic', null, 'italic'), R('markup.underline.link', null, 'underline'),
276 ]],
277 vs: ['#000000', '#FFFFFE', [
278 R('comment', '#008000'), R('string', '#A31515'), R('string.regexp', '#811F3F'), R('constant.numeric, keyword.other.unit, markup.inserted', '#098658'),
279 R('constant.language, constant.character, keyword, storage, variable.language, meta.preprocessor', '#0000FF'),
280 R('constant.character.escape', '#EE0000'), R('keyword.control, entity.name.operator', '#AF00DB'), R('keyword.operator', '#000000'),
281 R('entity.name.function, support.function', '#795E26'),
282 R('entity.name.type, entity.name.class, entity.name.namespace, support.type, support.class', '#267F99'),
283 R('variable, variable.parameter, support.variable, constant.other.placeholder', '#001080'),
284 R('entity.other.attribute-name, support.type.property-name', '#E50000'), R('variable.other.constant', '#0070C1'),
285 R('entity.name.tag, punctuation.definition.tag, markup.inline.raw', '#800000'), R('invalid', '#CD3131'), R('markup.deleted', '#A31515'),
286 R('markup.heading', '#800000', 'bold'), R('markup.bold', '#000080', 'bold'), R('markup.italic', null, 'italic'), R('markup.underline.link', null, 'underline'),
287 ]],
288 'hc-black': ['#FFFFFF', '#000000', [
289 R('comment', '#7CA668'), R('string', '#CE9178'), R('string.regexp', '#D16969'), R('constant.numeric, keyword.other.unit, markup.inserted', '#B5CEA8'),
290 R('constant.language, constant.character, keyword, storage, entity.name.tag, meta.preprocessor', '#569CD6'),
291 R('keyword.control', '#C586C0'), R('keyword.operator', '#D4D4D4'), R('entity.name.function, support.function', '#DCDCAA'),
292 R('entity.name.type, entity.name.class, entity.name.namespace, support.type, support.class', '#4EC9B0'),
293 R('variable, variable.language, variable.parameter, support.variable, entity.other.attribute-name', '#9CDCFE'),
294 R('punctuation.definition.tag', '#808080'), R('invalid', '#F44747'), R('markup.deleted', '#CE9178'),
295 R('markup.heading', '#6796E6', 'bold'), R('markup.bold', null, 'bold'), R('markup.italic', null, 'italic'), R('markup.underline.link', null, 'underline'),
296 ]],
297 'hc-light': ['#292929', '#FFFFFF', [
298 R('comment', '#515151'), R('string, constant.language, constant.character, keyword, storage, variable.language, entity.name.tag, meta.preprocessor, markup.inline.raw', '#0F4A85'),
299 R('string.regexp', '#811F3F'), R('constant.numeric, keyword.other.unit, markup.inserted', '#096D48'),
300 R('constant.character.escape', '#EE0000'), R('keyword.control, entity.name.operator, invalid', '#B5200D'), R('keyword.operator', '#000000'),
301 R('entity.name.function, support.function', '#5E2CBC'),
302 R('entity.name.type, entity.name.class, entity.name.namespace, support.type, support.class', '#185E73'),
303 R('variable, variable.parameter, support.variable, constant.other.placeholder', '#001080'),
304 R('entity.other.attribute-name, support.type.property-name', '#264F78'), R('variable.other.constant', '#02715D'),
305 R('punctuation.definition.tag', '#0F4A85'), R('markup.deleted', '#5A5A5A'),
306 R('markup.heading', '#0F4A85', 'bold'), R('markup.bold', '#000080', 'bold'), R('markup.italic', null, 'italic'), R('markup.underline.link', null, 'underline'),
307 ]],
308};
309export function builtinTheme(id) {
310 const [fg, bg, tokenColors] = TM_SERIE[id] || TM_SERIE['vs-dark'];
311 return { label: id, uiTheme: TM_SERIE[id] ? id : 'vs-dark', colors: { 'editor.foreground': fg, 'editor.background': bg }, tokenColors, builtin: true };
312}
313
314// Ids de tema que Monaco acepta (/^[a-z0-9-]+$/i, o lanza «Illegal theme name!»).
315const slug = s => String(s || '').toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
316export function themeIdFor(extId, contrib, index, usados = new Set()) {
317 const base = ('x-' + slug(extId) + '-' + (slug(contrib.id || contrib.label) || 't' + index)).slice(0, 90).replace(/-+$/, '');
318 let id = base;
319 for (let n = 2; usados.has(id); n++) id = base + '-' + n;
320 usados.add(id);
321 return id;
322}
323
324// Las pestañas y el estado vacío del editor siguen al tema; el resto del IDE
325// conserva su aspecto. Solo entran colores hex validados.
326export function chromeCss(theme) {
327 const c = k => (isHexColor(theme.colors?.[k]) ? theme.colors[k] : null);
328 const { fg, bg } = defaults(theme);
329 const tabs = c('editorGroupHeader.tabsBackground') || c('tab.inactiveBackground') || bg;
330 const activa = c('tab.activeBackground') || bg;
331 const texto = c('tab.inactiveForeground') || fg;
332 const textoActiva = c('tab.activeForeground') || fg;
333 const borde = c('tab.border') || c('editorGroupHeader.tabsBorder') || c('editorGroup.border') || c('contrastBorder');
334 const acento = c('tab.activeBorderTop') || c('tab.activeBorder') || c('focusBorder');
335 return [
336 `#tabs-bar { background: ${tabs};${borde ? ` border-bottom-color: ${borde};` : ''} }`,
337 `#tabs-bar .tab { color: ${texto};${borde ? ` border-right-color: ${borde};` : ''} }`,
338 `#tabs-bar .tab.active { background: ${activa}; color: ${textoActiva};${acento ? ` box-shadow: inset 0 2px 0 ${acento};` : ''} }`,
339 // el ● de «sin guardar» lleva el color claro del IDE (code.css): con un
340 // tema claro desaparecería, y es el único aviso de cambios sin guardar. Es
341 // el botón .tab-x desde que la × dejó de ser un <b> (a02733c).
342 `#tabs-bar .tab .tab-x.dirty { color: inherit; }`,
343 `#editor-empty { background: ${bg}; color: ${texto}; }`,
344 ].join('\n');
345}