@tooark/code 1.9.4 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,800 @@
1
+ import { closeBrackets, closeBracketsKeymap, completionKeymap, autocompletion, completionStatus } from '@codemirror/autocomplete';
2
+ import { history, defaultKeymap, historyKeymap, indentWithTab } from '@codemirror/commands';
3
+ import { javascript } from '@codemirror/lang-javascript';
4
+ import { json } from '@codemirror/lang-json';
5
+ import { yaml } from '@codemirror/lang-yaml';
6
+ import { indentOnInput, bracketMatching, foldKeymap, foldGutter, indentUnit, syntaxHighlighting, HighlightStyle } from '@codemirror/language';
7
+ import { highlightSelectionMatches, closeSearchPanel, searchKeymap } from '@codemirror/search';
8
+ import { Compartment, EditorState, Prec } from '@codemirror/state';
9
+ import { highlightSpecialChars, drawSelection, dropCursor, rectangularSelection, crosshairCursor, keymap, placeholder, EditorView, lineNumbers, highlightActiveLine, highlightActiveLineGutter, MatchDecorator, ViewPlugin, Decoration, hoverTooltip } from '@codemirror/view';
10
+ import { tags } from '@lezer/highlight';
11
+ import { resolveColorScheme, ARK_SIZE_CSS, ARK_INTENT_SOFT_CSS } from '@tooark/tokens';
12
+
13
+ /** Resolve "auto" para "light"/"dark" pelo color-scheme computado de `element`, ou pela preferência do sistema. */
14
+ function resolveCodeTheme(theme, element) {
15
+ if (theme === "dark")
16
+ return "dark";
17
+ if (theme === "light")
18
+ return "light";
19
+ return resolveColorScheme(element);
20
+ }
21
+ // --- Tema ---
22
+ // Cores de sintaxe por lado, fallback dos tokens --ark-syntax-* (os mesmos valores, em light-dark() no tokens.css); o
23
+ // chrome (fundo, texto, bordas, seleção) vem dos tokens --ark-color-* com fallback, para o editor seguir o tema do app
24
+ // mesmo sem o CSS do @tooark/web-components na página.
25
+ const SYNTAX = {
26
+ light: {
27
+ keyword: "#6d28d9",
28
+ string: "#15803d",
29
+ number: "#b45309",
30
+ property: "#1d4ed8",
31
+ comment: "#64748b",
32
+ atom: "#0f766e",
33
+ punctuation: "#475569",
34
+ invalid: "#dc2626"
35
+ },
36
+ dark: {
37
+ keyword: "#c4b5fd",
38
+ string: "#86efac",
39
+ number: "#fcd34d",
40
+ property: "#93c5fd",
41
+ comment: "#94a3b8",
42
+ atom: "#5eead4",
43
+ punctuation: "#cbd5e1",
44
+ invalid: "#f87171"
45
+ }
46
+ };
47
+ const FALLBACK = {
48
+ light: {
49
+ surface: "#ffffff",
50
+ surfaceMuted: "#f8fafc",
51
+ fg: "#0f172a",
52
+ fgMuted: "#64748b",
53
+ placeholder: "#94a3b8",
54
+ border: "#e2e8f0",
55
+ primary: "#4f46e5",
56
+ ring: "#a5b4fc",
57
+ match: "#fef3c7"
58
+ },
59
+ dark: {
60
+ surface: "#0f172a",
61
+ surfaceMuted: "#1e293b",
62
+ fg: "#e2e8f0",
63
+ fgMuted: "#94a3b8",
64
+ placeholder: "#64748b",
65
+ border: "#334155",
66
+ primary: "#818cf8",
67
+ ring: "#6366f1",
68
+ match: "#78350f"
69
+ }
70
+ };
71
+ const MONO = 'var(--ark-font-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace)';
72
+ const INTENTS = Object.keys(ARK_INTENT_SOFT_CSS);
73
+ // Fonte e recuo lateral por `size`, os mesmos do ark-input; "md" é o editor de sempre.
74
+ const SIZES = {
75
+ xs: { font: "0.75rem", paddingX: "0.5rem" },
76
+ sm: { font: "0.75rem", paddingX: "0.625rem" },
77
+ md: { font: "0.875rem", paddingX: "0.75rem" },
78
+ lg: { font: "1rem", paddingX: "1rem" },
79
+ xl: { font: "1.125rem", paddingX: "1.25rem" }
80
+ };
81
+ function normalizeSize(size) {
82
+ return size && Object.keys(SIZES).includes(size) ? size : "md";
83
+ }
84
+ // Fundo e texto suaves do intent; o fallback é o próprio `light-dark()` dos tokens, resolvido pelo color-scheme
85
+ // que o editor declara.
86
+ function variableColors(intent) {
87
+ const soft = ARK_INTENT_SOFT_CSS[intent];
88
+ return {
89
+ backgroundColor: `var(--ark-color-${intent}-soft, ${soft.soft})`,
90
+ color: `var(--ark-color-${intent}-soft-fg, ${soft.softFg})`
91
+ };
92
+ }
93
+ function chromeTheme(side) {
94
+ const f = FALLBACK[side];
95
+ const v = (token, fallback) => `var(--ark-color-${token}, ${fallback})`;
96
+ const tint = (token, fallback, amount) => `color-mix(in oklab, ${v(token, fallback)} ${amount}%, transparent)`;
97
+ const intentRules = Object.fromEntries(INTENTS.map((intent) => [`.cm-ark-variable-${intent}`, variableColors(intent)]));
98
+ return EditorView.theme({
99
+ "&": {
100
+ colorScheme: side,
101
+ backgroundColor: v("surface", f.surface),
102
+ color: v("fg", f.fg),
103
+ border: `1px solid ${v("border", f.border)}`,
104
+ borderRadius: "0.5rem",
105
+ fontSize: "var(--ark-code-font-size, 0.875rem)",
106
+ minHeight: "var(--ark-code-min-height, 8rem)",
107
+ // Sem `max-height` a variável não existe e o editor cresce com o conteúdo; com ela o scroller do CodeMirror
108
+ // (overflow-x auto, logo também y) rola por dentro.
109
+ maxHeight: "var(--ark-code-max-height, none)"
110
+ },
111
+ // Uma linha na altura do controle: a borda (2px) e a linha (1.5em) saem da altura, o resto vira respiro
112
+ // vertical do conteúdo, que ocupa a caixa toda (o clique em qualquer ponto posiciona o cursor).
113
+ "&.cm-ark-single-line": {
114
+ minHeight: "var(--ark-code-control-height, 2.25rem)",
115
+ maxHeight: "none"
116
+ },
117
+ "&.cm-ark-single-line .cm-scroller": {
118
+ minHeight: "0",
119
+ scrollbarWidth: "none"
120
+ },
121
+ "&.cm-ark-single-line .cm-content": {
122
+ padding: "max(0px, calc((var(--ark-code-control-height, 2.25rem) - 2px - 1.5em) / 2)) 0"
123
+ },
124
+ "&.cm-focused": {
125
+ outline: `2px solid ${v("primary-ring", f.ring)}`,
126
+ outlineOffset: "1px"
127
+ },
128
+ ".cm-scroller": {
129
+ fontFamily: MONO,
130
+ lineHeight: "1.5",
131
+ borderRadius: "inherit",
132
+ // A calha e o conteúdo esticam até a altura mínima do editor, não só até o texto.
133
+ minHeight: "inherit"
134
+ },
135
+ ".cm-content": {
136
+ padding: "0.5rem 0",
137
+ caretColor: v("fg", f.fg)
138
+ },
139
+ ".cm-line": {
140
+ padding: "0 var(--ark-code-padding-x, 0.75rem)"
141
+ },
142
+ ".cm-gutters": {
143
+ backgroundColor: v("surface-muted", f.surfaceMuted),
144
+ color: v("fg-muted", f.fgMuted),
145
+ borderRight: `1px solid ${v("border", f.border)}`,
146
+ borderRadius: "0.5rem 0 0 0.5rem"
147
+ },
148
+ ".cm-activeLine": {
149
+ backgroundColor: tint("fg", f.fg, 6)
150
+ },
151
+ ".cm-activeLineGutter": {
152
+ backgroundColor: tint("fg", f.fg, 8)
153
+ },
154
+ ".cm-cursor, .cm-dropCursor": {
155
+ borderLeftColor: v("fg", f.fg)
156
+ },
157
+ "&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground": {
158
+ backgroundColor: tint("primary", f.primary, 22)
159
+ },
160
+ ".cm-selectionMatch": {
161
+ backgroundColor: tint("primary", f.primary, 14)
162
+ },
163
+ ".cm-searchMatch": {
164
+ backgroundColor: v("warning-soft", f.match),
165
+ outline: `1px solid ${v("warning-border", f.match)}`
166
+ },
167
+ ".cm-searchMatch.cm-searchMatch-selected": {
168
+ backgroundColor: v("warning-soft", f.match)
169
+ },
170
+ "&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket": {
171
+ backgroundColor: tint("primary", f.primary, 18),
172
+ outline: "none"
173
+ },
174
+ ".cm-placeholder": {
175
+ color: v("fg-placeholder", f.placeholder),
176
+ fontStyle: "italic"
177
+ },
178
+ ".cm-foldGutter .cm-gutterElement": {
179
+ cursor: "pointer"
180
+ },
181
+ ".cm-foldPlaceholder": {
182
+ backgroundColor: v("surface-muted", f.surfaceMuted),
183
+ border: `1px solid ${v("border", f.border)}`,
184
+ color: v("fg-muted", f.fgMuted)
185
+ },
186
+ ".cm-panels": {
187
+ backgroundColor: v("surface-muted", f.surfaceMuted),
188
+ color: v("fg", f.fg)
189
+ },
190
+ ".cm-panels.cm-panels-top": {
191
+ borderBottom: `1px solid ${v("border", f.border)}`
192
+ },
193
+ ".cm-panels.cm-panels-bottom": {
194
+ borderTop: `1px solid ${v("border", f.border)}`
195
+ },
196
+ ".cm-panel.cm-search input, .cm-panel.cm-search button, .cm-panel.cm-search label": {
197
+ fontFamily: "inherit",
198
+ fontSize: "0.75rem"
199
+ },
200
+ ".cm-panel.cm-search input": {
201
+ backgroundColor: v("surface", f.surface),
202
+ color: v("fg", f.fg),
203
+ border: `1px solid ${v("border", f.border)}`,
204
+ borderRadius: "0.25rem"
205
+ },
206
+ ".cm-tooltip": {
207
+ backgroundColor: v("surface", f.surface),
208
+ color: v("fg", f.fg),
209
+ border: `1px solid ${v("border", f.border)}`,
210
+ borderRadius: "0.5rem",
211
+ boxShadow: "0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)"
212
+ },
213
+ ".cm-tooltip.cm-tooltip-autocomplete > ul": {
214
+ fontFamily: "inherit",
215
+ maxHeight: "14rem"
216
+ },
217
+ ".cm-tooltip.cm-tooltip-autocomplete > ul > li": {
218
+ padding: "0.25rem 0.5rem"
219
+ },
220
+ ".cm-tooltip.cm-tooltip-autocomplete > ul > li[aria-selected]": {
221
+ backgroundColor: v("primary-soft", tint("primary", f.primary, 15)),
222
+ color: v("primary-soft-fg", f.fg)
223
+ },
224
+ ".cm-completionIcon": {
225
+ color: v("fg-muted", f.fgMuted)
226
+ },
227
+ ".cm-ark-variable": {
228
+ borderRadius: "0.25rem"
229
+ },
230
+ // O realce da sintaxe fica dentro do span da variável (uma string JSON, por exemplo): herda a cor dela.
231
+ ".cm-ark-variable *": {
232
+ color: "inherit"
233
+ },
234
+ ...intentRules,
235
+ // Desconhecida: além da cor, o sublinhado ondulado distingue sem depender dela.
236
+ ".cm-ark-variable-unknown": {
237
+ ...variableColors("danger"),
238
+ textDecoration: "underline wavy",
239
+ textDecorationSkipInk: "none",
240
+ textUnderlineOffset: "0.2em"
241
+ },
242
+ ".cm-tooltip .cm-ark-variable-tooltip": {
243
+ display: "flex",
244
+ alignItems: "baseline",
245
+ gap: "0.5rem",
246
+ maxWidth: "24rem",
247
+ padding: "0.25rem 0.5rem",
248
+ fontSize: "0.75rem"
249
+ },
250
+ ".cm-ark-variable-tooltip-scope": {
251
+ flexShrink: "0",
252
+ padding: "0 0.375rem",
253
+ borderRadius: "0.25rem",
254
+ fontWeight: "500"
255
+ },
256
+ ".cm-ark-variable-tooltip-value": {
257
+ fontFamily: MONO,
258
+ color: v("fg-muted", f.fgMuted),
259
+ overflowWrap: "anywhere"
260
+ }
261
+ }, { dark: side === "dark" });
262
+ }
263
+ function syntaxTheme(side) {
264
+ // Cada papel lê o token do app; sem ele, a cor embutida do lado. O light-dark() do token resolve pelo color-scheme
265
+ // que o editor declara, então um tema fixo (`theme="dark"` numa página clara) pega o lado certo.
266
+ const c = Object.fromEntries(Object.entries(SYNTAX[side]).map(([role, color]) => [role, `var(--ark-syntax-${role}, ${color})`]));
267
+ return syntaxHighlighting(HighlightStyle.define([
268
+ { tag: [tags.keyword, tags.modifier, tags.operatorKeyword, tags.controlKeyword], color: c.keyword },
269
+ { tag: [tags.string, tags.special(tags.string)], color: c.string },
270
+ { tag: [tags.number, tags.integer, tags.float], color: c.number },
271
+ { tag: [tags.propertyName, tags.definition(tags.propertyName), tags.attributeName], color: c.property },
272
+ { tag: [tags.comment, tags.lineComment, tags.blockComment], color: c.comment, fontStyle: "italic" },
273
+ { tag: [tags.bool, tags.null, tags.atom, tags.self], color: c.atom },
274
+ { tag: [tags.function(tags.variableName), tags.function(tags.propertyName)], color: c.property },
275
+ { tag: [tags.typeName, tags.className, tags.namespace], color: c.keyword },
276
+ { tag: [tags.punctuation, tags.separator, tags.bracket, tags.operator], color: c.punctuation },
277
+ { tag: tags.invalid, color: c.invalid, textDecoration: "underline" }
278
+ ]));
279
+ }
280
+ function themeFor(side) {
281
+ return [chromeTheme(side), syntaxTheme(side)];
282
+ }
283
+ // --- Linguagens e completions ---
284
+ function languageFor(language) {
285
+ if (language === "json")
286
+ return json();
287
+ if (language === "javascript")
288
+ return javascript();
289
+ if (language === "yaml")
290
+ return yaml();
291
+ return [];
292
+ }
293
+ // `{{ chave }}` com espaços opcionais por dentro; a chave usa o mesmo conjunto de caracteres da completion.
294
+ const VARIABLE_PATTERN = /\{\{\s*([\w$.-]+)\s*\}\}/g;
295
+ // Chave repetida: vale a primeira ocorrência (o app resolve a precedência entre escopos antes de mandar).
296
+ function normalizeVariables(variables) {
297
+ const map = new Map();
298
+ for (const variable of variables) {
299
+ if (!variable || typeof variable.key !== "string" || !variable.key || map.has(variable.key))
300
+ continue;
301
+ map.set(variable.key, {
302
+ key: variable.key,
303
+ scope: typeof variable.scope === "string" && variable.scope ? variable.scope : undefined,
304
+ intent: INTENTS.includes(variable.intent) ? variable.intent : "primary",
305
+ value: typeof variable.value === "string" ? variable.value : undefined
306
+ });
307
+ }
308
+ return map;
309
+ }
310
+ // Completions de variáveis: depois de `{{`, oferece as chaves e insere `{{chave}}`; se o `}}` já está adiante
311
+ // (closeBrackets fechou o par), só a chave entra e o cursor pula o fechamento. O escopo vai como detalhe e o valor
312
+ // como info.
313
+ function variableSource(variables) {
314
+ return (context) => {
315
+ const match = context.matchBefore(/\{\{\s*[\w$.-]*$/);
316
+ if (!match)
317
+ return null;
318
+ const typed = match.text.match(/[\w$.-]*$/)?.[0] ?? "";
319
+ const from = match.to - typed.length;
320
+ const options = variables.map(({ key, scope, value }) => ({
321
+ label: key,
322
+ type: "variable",
323
+ ...(scope ? { detail: scope } : {}),
324
+ ...(value !== undefined ? { info: value } : {}),
325
+ apply: (view, _completion, start, end) => {
326
+ const closed = view.state.sliceDoc(end, end + 2) === "}}";
327
+ const insert = closed ? key : `${key}}}`;
328
+ view.dispatch({
329
+ changes: { from: start, to: end, insert },
330
+ selection: { anchor: start + insert.length + (closed ? 2 : 0) }
331
+ });
332
+ }
333
+ }));
334
+ return { from, options, validFor: /^[\w$.-]*$/ };
335
+ };
336
+ }
337
+ function variableTooltip(variable) {
338
+ const dom = document.createElement("div");
339
+ dom.className = "cm-ark-variable-tooltip";
340
+ dom.setAttribute("data-ark", "code-editor-variable-tooltip");
341
+ if (variable.scope) {
342
+ const scope = document.createElement("span");
343
+ scope.className = `cm-ark-variable-tooltip-scope cm-ark-variable-${variable.intent}`;
344
+ scope.textContent = variable.scope;
345
+ dom.appendChild(scope);
346
+ }
347
+ if (variable.value !== undefined) {
348
+ const value = document.createElement("span");
349
+ value.className = "cm-ark-variable-tooltip-value";
350
+ value.textContent = variable.value;
351
+ dom.appendChild(value);
352
+ }
353
+ return dom;
354
+ }
355
+ /**
356
+ * Pinta cada `{{chave}}` de `variables` com o intent dela e, com `markUnknown`, em `danger` a chave que não está
357
+ * nem em `variables` nem em `known` (as `variableKeys`, que completam mas não pintam). Sem variáveis e sem
358
+ * `markUnknown` não há extensão nenhuma: o editor fica como sem o recurso.
359
+ */
360
+ function variableExtensions(variables, known, markUnknown) {
361
+ if (variables.size === 0 && !markUnknown)
362
+ return [];
363
+ const marks = new Map();
364
+ const markFor = (key) => {
365
+ const cached = marks.get(key);
366
+ if (cached)
367
+ return cached;
368
+ const variable = variables.get(key);
369
+ let mark = null;
370
+ if (variable) {
371
+ mark = Decoration.mark({
372
+ class: `cm-ark-variable cm-ark-variable-${variable.intent}`,
373
+ attributes: {
374
+ "data-ark": "code-editor-variable",
375
+ "data-key": key,
376
+ "data-intent": variable.intent,
377
+ ...(variable.scope ? { "data-scope": variable.scope } : {})
378
+ }
379
+ });
380
+ }
381
+ else if (markUnknown && !known.has(key)) {
382
+ mark = Decoration.mark({
383
+ class: "cm-ark-variable cm-ark-variable-unknown",
384
+ attributes: { "data-ark": "code-editor-variable", "data-key": key, "data-intent": "danger", "data-unknown": "" }
385
+ });
386
+ }
387
+ if (mark)
388
+ marks.set(key, mark);
389
+ return mark;
390
+ };
391
+ const decorator = new MatchDecorator({ regexp: VARIABLE_PATTERN, decoration: (match) => markFor(match[1]) });
392
+ const painter = ViewPlugin.fromClass(class {
393
+ constructor(view) {
394
+ this.decorations = decorator.createDeco(view);
395
+ }
396
+ update(update) {
397
+ this.decorations = decorator.updateDeco(update, this.decorations);
398
+ }
399
+ }, {
400
+ // Por fora de todas as outras decorações: a variável fica num span só, que o realce da sintaxe, o par de
401
+ // colchetes e a busca não cortam; a cor chega ao texto de dentro pela regra `.cm-ark-variable *`.
402
+ provide: (plugin) => EditorView.outerDecorations.of((view) => view.plugin(plugin)?.decorations ?? Decoration.none)
403
+ });
404
+ // O tooltip só existe para variável conhecida com escopo ou valor: o texto é todo do app, a lib não traduz nada.
405
+ const tooltip = hoverTooltip((view, pos, side) => {
406
+ const line = view.state.doc.lineAt(pos);
407
+ for (const match of line.text.matchAll(VARIABLE_PATTERN)) {
408
+ const from = line.from + (match.index ?? 0);
409
+ const to = from + match[0].length;
410
+ if (pos < from || pos > to || (pos === from && side < 0) || (pos === to && side > 0))
411
+ continue;
412
+ const variable = variables.get(match[1]);
413
+ if (!variable || (!variable.scope && variable.value === undefined))
414
+ return null;
415
+ return { pos: from, end: to, above: true, create: () => ({ dom: variableTooltip(variable) }) };
416
+ }
417
+ return null;
418
+ });
419
+ return [painter, tooltip];
420
+ }
421
+ // --- Uma linha ---
422
+ // As quebras que entram (colar, arrastar, comando) saem na mesma transação, como o `<input>` faz com o valor.
423
+ function joinLines(tr) {
424
+ if (!tr.docChanged || tr.newDoc.lines === 1)
425
+ return tr;
426
+ const changes = [];
427
+ for (let n = 1; n < tr.newDoc.lines; n++) {
428
+ const end = tr.newDoc.line(n).to;
429
+ changes.push({ from: end, to: end + 1 });
430
+ }
431
+ return [tr, { changes, sequential: true }];
432
+ }
433
+ // O conteúdo editável é o `role="textbox"` do CodeMirror: é nele que o nome acessível precisa estar.
434
+ function labelExtension(label) {
435
+ return label ? EditorView.contentAttributes.of({ "aria-label": label }) : [];
436
+ }
437
+ function singleLineExtensions(on, submit) {
438
+ if (!on)
439
+ return [];
440
+ // Com a lista de completions aberta o Enter é dela (o keymap do autocomplete vem antes); se ela acabou de abrir
441
+ // e ainda ignora o Enter, ele não envia a meia variável.
442
+ const run = (view) => {
443
+ if (completionStatus(view.state) !== "active")
444
+ submit();
445
+ return true;
446
+ };
447
+ return [
448
+ EditorView.editorAttributes.of({ class: "cm-ark-single-line" }),
449
+ EditorView.contentAttributes.of({ "aria-multiline": "false" }),
450
+ EditorState.transactionFilter.of(joinLines),
451
+ Prec.high(keymap.of([
452
+ { key: "Enter", run, shift: run },
453
+ { key: "Mod-Enter", run }
454
+ ]))
455
+ ];
456
+ }
457
+ // --- Recuo, fim de linha e formatação ---
458
+ function indentExtensions(style, size) {
459
+ const width = Math.max(1, Math.min(16, Math.floor(size) || 2));
460
+ return [indentUnit.of(style === "tab" ? "\t" : " ".repeat(width)), EditorState.tabSize.of(width)];
461
+ }
462
+ // O documento fica sempre em LF por dentro (colar CRLF num doc LF não deixa \r solto); o fim de linha só vale
463
+ // na fronteira: `getValue` junta com o configurado e `setValue`/`auto` detectam o que entrou.
464
+ function detectLineEnding(value) {
465
+ return value.includes("\r\n") ? "crlf" : "lf";
466
+ }
467
+ function normalizeNewlines(value) {
468
+ return value.replace(/\r\n?/g, "\n");
469
+ }
470
+ function completionsSource(items) {
471
+ return (context) => {
472
+ const word = context.matchBefore(/[\w$.-]+/);
473
+ if (!word && !context.explicit)
474
+ return null;
475
+ return { from: word ? word.from : context.pos, options: items, validFor: /^[\w$.-]*$/ };
476
+ };
477
+ }
478
+ function completionExtensions(on, variables, items, source) {
479
+ if (!on)
480
+ return [];
481
+ // languageData é o que o autocompletion consulta no cursor: assim as fontes valem em qualquer linguagem. Cada
482
+ // fonte é criada uma vez por configuração: o autocompletion identifica a consulta pela identidade da função, e
483
+ // uma nova a cada leitura deixaria a completion pendente para sempre.
484
+ const sources = [];
485
+ if (variables.length > 0)
486
+ sources.push({ autocomplete: variableSource(variables) });
487
+ if (items.length > 0)
488
+ sources.push({ autocomplete: completionsSource(items) });
489
+ if (source)
490
+ sources.push({ autocomplete: source });
491
+ return [autocompletion(), sources.length > 0 ? EditorState.languageData.of(() => sources) : []];
492
+ }
493
+ // Tab recua e Shift+Tab desfaz. A saída por teclado é do próprio CodeMirror: Esc arma o tab-focus mode por dois
494
+ // segundos (o Tab seguinte só move o foco) e Ctrl+M, do keymap padrão, alterna o modo de vez.
495
+ function tabExtensions(on) {
496
+ return on ? keymap.of([indentWithTab]) : [];
497
+ }
498
+ function formatJson(value, unit) {
499
+ return JSON.stringify(JSON.parse(value), null, unit);
500
+ }
501
+ // --- Instância ---
502
+ /**
503
+ * Cria um editor CodeMirror 6 dentro de `parent` com o setup básico do Tooark: numeração e dobra, histórico,
504
+ * fechamento de pares, realce da linha ativa (só editável), busca por Ctrl+F, completions (da linguagem, de
505
+ * `variableKeys`, de `completions` e de `completionSource`), Tab para recuar com saída por Esc+Tab, recuo por
506
+ * espaços ou tabulação, fim de linha LF/CRLF na fronteira do valor, formatação por Shift+Alt+F (JSON nativo ou o
507
+ * `formatter` do app) e tema pelos tokens. Opcionais, ligados só pelas opções: `variables` pintadas por intent com
508
+ * tooltip, `markUnknownVariables`, o campo `singleLine` e as `extensions` do app.
509
+ */
510
+ function createCodeEditor(parent, options = {}) {
511
+ const language = new Compartment();
512
+ const theme = new Compartment();
513
+ const readonly = new Compartment();
514
+ const placeholder$1 = new Compartment();
515
+ const labelling = new Compartment();
516
+ const gutterNumbers = new Compartment();
517
+ const gutterFold = new Compartment();
518
+ const wrapping = new Compartment();
519
+ const indentation = new Compartment();
520
+ const tabKey = new Compartment();
521
+ const completion = new Compartment();
522
+ const variableMarks = new Compartment();
523
+ const lineMode = new Compartment();
524
+ const searchKeys = new Compartment();
525
+ const custom = new Compartment();
526
+ let resolved = resolveCodeTheme(options.theme ?? "auto", parent);
527
+ let applying = false;
528
+ let currentLanguage = options.language ?? "text";
529
+ let indentStyle = options.indentStyle ?? "space";
530
+ let indentSize = options.indentSize ?? 2;
531
+ let lineEnding = options.lineEnding ?? "auto";
532
+ let detected = detectLineEnding(options.value ?? "");
533
+ let autocomplete = options.autocomplete !== false;
534
+ let variableKeys = options.variableKeys ?? [];
535
+ let variables = normalizeVariables(options.variables ?? []);
536
+ let markUnknown = options.markUnknownVariables === true;
537
+ let completions = options.completions ?? [];
538
+ let completionSource = options.completionSource;
539
+ let formatter = options.formatter;
540
+ let readonlyOn = options.readonly === true;
541
+ let lineNumbersOn = options.lineNumbers !== false;
542
+ let foldOn = options.fold !== false;
543
+ let tabIndentOn = options.tabIndent !== false;
544
+ let singleLine = options.singleLine === true;
545
+ // Em `singleLine` calhas, linha ativa, recuo por Tab e busca ficam desligados, seja qual for a opção de cada um;
546
+ // desligar o modo devolve o que as opções pedem.
547
+ const readonlyExtensions = () => [
548
+ EditorState.readOnly.of(readonlyOn),
549
+ EditorView.editable.of(!readonlyOn),
550
+ readonlyOn || singleLine ? [] : [highlightActiveLine(), highlightActiveLineGutter()]
551
+ ];
552
+ const numbersExtension = () => (lineNumbersOn && !singleLine ? lineNumbers() : []);
553
+ const foldExtension = () => (foldOn && !singleLine ? foldGutter() : []);
554
+ const tabExtension = () => tabExtensions(tabIndentOn && !singleLine);
555
+ const searchExtension = () => (singleLine ? [] : keymap.of(searchKeymap));
556
+ const lineModeExtension = () => singleLineExtensions(singleLine, () => options.onSubmit?.(view.state.doc.toString().split("\n").join(eol())));
557
+ // Variáveis com escopo primeiro; as `variableKeys` que elas não cobrem entram só como completion.
558
+ const variableEntries = () => [
559
+ ...variables.values(),
560
+ ...variableKeys.filter((key) => !variables.has(key)).map((key) => ({ key, intent: "primary" }))
561
+ ];
562
+ const marksExtension = () => variableExtensions(variables, new Set(variableKeys), markUnknown);
563
+ const reconfigureCompletion = () => {
564
+ view.dispatch({
565
+ effects: completion.reconfigure(completionExtensions(autocomplete, variableEntries(), completions, completionSource))
566
+ });
567
+ };
568
+ const eol = () => ((lineEnding === "auto" ? detected : lineEnding) === "crlf" ? "\r\n" : "\n");
569
+ // Texto como o documento guarda: sempre LF e, em `singleLine`, sem quebras.
570
+ const toDoc = (value) => {
571
+ const text = normalizeNewlines(value);
572
+ return singleLine ? text.replace(/\n/g, "") : text;
573
+ };
574
+ const applySize = (size) => {
575
+ const scale = SIZES[size];
576
+ view.dom.style.setProperty("--ark-code-font-size", scale.font);
577
+ view.dom.style.setProperty("--ark-code-padding-x", scale.paddingX);
578
+ view.dom.style.setProperty("--ark-code-control-height", `var(--ark-size-${size}, ${ARK_SIZE_CSS[size]})`);
579
+ };
580
+ const format = async () => {
581
+ const source = view.state.doc.toString();
582
+ try {
583
+ let next;
584
+ if (formatter) {
585
+ next = normalizeNewlines(await formatter(source, currentLanguage));
586
+ }
587
+ else if (currentLanguage === "json") {
588
+ next = formatJson(source, indentStyle === "tab" ? "\t" : " ".repeat(indentSize));
589
+ }
590
+ else {
591
+ return false;
592
+ }
593
+ if (view.state.doc.toString() !== source)
594
+ return false;
595
+ if (next !== source) {
596
+ // Edição de verdade: entra no histórico e dispara onChange, como se o usuário tivesse digitado.
597
+ view.dispatch({
598
+ changes: { from: 0, to: view.state.doc.length, insert: next },
599
+ selection: { anchor: Math.min(view.state.selection.main.head, next.length) },
600
+ userEvent: "format"
601
+ });
602
+ }
603
+ return true;
604
+ }
605
+ catch (error) {
606
+ options.onFormatError?.(error);
607
+ return false;
608
+ }
609
+ };
610
+ const state = EditorState.create({
611
+ doc: toDoc(options.value ?? ""),
612
+ extensions: [
613
+ gutterNumbers.of(numbersExtension()),
614
+ gutterFold.of(foldExtension()),
615
+ highlightSpecialChars(),
616
+ history(),
617
+ drawSelection(),
618
+ dropCursor(),
619
+ EditorState.allowMultipleSelections.of(true),
620
+ indentOnInput(),
621
+ bracketMatching(),
622
+ closeBrackets(),
623
+ rectangularSelection(),
624
+ crosshairCursor(),
625
+ highlightSelectionMatches(),
626
+ keymap.of([
627
+ ...closeBracketsKeymap,
628
+ ...defaultKeymap,
629
+ ...historyKeymap,
630
+ ...foldKeymap,
631
+ ...completionKeymap,
632
+ {
633
+ key: "Shift-Alt-f",
634
+ run: () => {
635
+ void format();
636
+ return true;
637
+ }
638
+ }
639
+ ]),
640
+ // A busca fica num keymap à parte, depois do principal, para sair em `singleLine`.
641
+ searchKeys.of(searchExtension()),
642
+ language.of(languageFor(currentLanguage)),
643
+ theme.of(themeFor(resolved)),
644
+ readonly.of(readonlyExtensions()),
645
+ placeholder$1.of(options.placeholder ? placeholder(options.placeholder) : []),
646
+ labelling.of(labelExtension(options.label)),
647
+ wrapping.of(options.wrap ? EditorView.lineWrapping : []),
648
+ indentation.of(indentExtensions(indentStyle, indentSize)),
649
+ tabKey.of(tabExtension()),
650
+ completion.of(completionExtensions(autocomplete, variableEntries(), completions, completionSource)),
651
+ variableMarks.of(marksExtension()),
652
+ lineMode.of(lineModeExtension()),
653
+ EditorView.updateListener.of((update) => {
654
+ if (update.docChanged && !applying)
655
+ options.onChange?.(update.state.doc.toString().split("\n").join(eol()));
656
+ }),
657
+ // As do app vêm por último: na mesma precedência, keymaps, calhas e linguagem da lib vêm antes, e quem precisa
658
+ // passar à frente usa `Prec`.
659
+ custom.of(options.extensions ?? [])
660
+ ]
661
+ });
662
+ const view = new EditorView({ state, parent });
663
+ view.dom.style.setProperty("--ark-code-min-height", options.minHeight ?? "8rem");
664
+ const applyMaxHeight = (value) => {
665
+ if (value?.trim()) {
666
+ view.dom.style.setProperty("--ark-code-max-height", value.trim());
667
+ }
668
+ else {
669
+ view.dom.style.removeProperty("--ark-code-max-height");
670
+ }
671
+ };
672
+ applyMaxHeight(options.maxHeight);
673
+ applySize(normalizeSize(options.size));
674
+ return {
675
+ view,
676
+ getValue: () => view.state.doc.toString().split("\n").join(eol()),
677
+ setValue: (value) => {
678
+ detected = detectLineEnding(value);
679
+ const text = toDoc(value);
680
+ if (text === view.state.doc.toString())
681
+ return;
682
+ applying = true;
683
+ try {
684
+ view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text }, selection: { anchor: 0 } });
685
+ }
686
+ finally {
687
+ applying = false;
688
+ }
689
+ },
690
+ setLanguage: (next) => {
691
+ currentLanguage = next;
692
+ view.dispatch({ effects: language.reconfigure(languageFor(next)) });
693
+ },
694
+ setTheme: (next) => {
695
+ const side = resolveCodeTheme(next, parent);
696
+ if (side === resolved)
697
+ return;
698
+ resolved = side;
699
+ view.dispatch({ effects: theme.reconfigure(themeFor(side)) });
700
+ },
701
+ setReadonly: (on) => {
702
+ readonlyOn = on;
703
+ view.dispatch({ effects: readonly.reconfigure(readonlyExtensions()) });
704
+ },
705
+ setPlaceholder: (text) => view.dispatch({ effects: placeholder$1.reconfigure(text ? placeholder(text) : []) }),
706
+ setLabel: (label) => view.dispatch({ effects: labelling.reconfigure(labelExtension(label)) }),
707
+ setLineNumbers: (on) => {
708
+ lineNumbersOn = on;
709
+ view.dispatch({ effects: gutterNumbers.reconfigure(numbersExtension()) });
710
+ },
711
+ setFold: (on) => {
712
+ foldOn = on;
713
+ view.dispatch({ effects: gutterFold.reconfigure(foldExtension()) });
714
+ },
715
+ setWrap: (on) => view.dispatch({ effects: wrapping.reconfigure(on ? EditorView.lineWrapping : []) }),
716
+ setMinHeight: (value) => view.dom.style.setProperty("--ark-code-min-height", value),
717
+ setMaxHeight: applyMaxHeight,
718
+ setIndent: (style, size) => {
719
+ indentStyle = style;
720
+ indentSize = size;
721
+ view.dispatch({ effects: indentation.reconfigure(indentExtensions(style, size)) });
722
+ },
723
+ setLineEnding: (next) => {
724
+ lineEnding = next;
725
+ },
726
+ resolvedLineEnding: () => (lineEnding === "auto" ? detected : lineEnding),
727
+ setTabIndent: (on) => {
728
+ tabIndentOn = on;
729
+ view.dispatch({ effects: tabKey.reconfigure(tabExtension()) });
730
+ },
731
+ setAutocomplete: (on) => {
732
+ autocomplete = on;
733
+ reconfigureCompletion();
734
+ },
735
+ setVariableKeys: (keys) => {
736
+ variableKeys = keys;
737
+ reconfigureCompletion();
738
+ // As chaves só completam, mas contam como conhecidas para a marcação das desconhecidas.
739
+ view.dispatch({ effects: variableMarks.reconfigure(marksExtension()) });
740
+ },
741
+ setVariables: (next) => {
742
+ variables = normalizeVariables(next);
743
+ reconfigureCompletion();
744
+ view.dispatch({ effects: variableMarks.reconfigure(marksExtension()) });
745
+ },
746
+ setMarkUnknownVariables: (on) => {
747
+ markUnknown = on;
748
+ view.dispatch({ effects: variableMarks.reconfigure(marksExtension()) });
749
+ },
750
+ setSingleLine: (on) => {
751
+ if (on === singleLine)
752
+ return;
753
+ singleLine = on;
754
+ if (on)
755
+ closeSearchPanel(view);
756
+ view.dispatch({
757
+ effects: [
758
+ lineMode.reconfigure(lineModeExtension()),
759
+ searchKeys.reconfigure(searchExtension()),
760
+ readonly.reconfigure(readonlyExtensions()),
761
+ gutterNumbers.reconfigure(numbersExtension()),
762
+ gutterFold.reconfigure(foldExtension()),
763
+ tabKey.reconfigure(tabExtension())
764
+ ]
765
+ });
766
+ // O filtro só age nas próximas edições: o texto que já estava junta aqui, como um `setValue`.
767
+ const text = view.state.doc.toString();
768
+ if (!on || !text.includes("\n"))
769
+ return;
770
+ applying = true;
771
+ try {
772
+ view.dispatch({ changes: { from: 0, to: text.length, insert: toDoc(text) } });
773
+ }
774
+ finally {
775
+ applying = false;
776
+ }
777
+ },
778
+ setSize: (size) => applySize(normalizeSize(size)),
779
+ setCompletions: (items) => {
780
+ completions = items;
781
+ reconfigureCompletion();
782
+ },
783
+ setCompletionSource: (source) => {
784
+ completionSource = source;
785
+ reconfigureCompletion();
786
+ },
787
+ setFormatter: (next) => {
788
+ formatter = next;
789
+ },
790
+ setExtensions: (next) => view.dispatch({ effects: custom.reconfigure(next) }),
791
+ format,
792
+ canFormat: () => formatter !== undefined || currentLanguage === "json",
793
+ resolvedTheme: () => resolved,
794
+ focus: () => view.focus(),
795
+ destroy: () => view.destroy()
796
+ };
797
+ }
798
+
799
+ export { createCodeEditor, resolveCodeTheme };
800
+ //# sourceMappingURL=index.js.map