@tooark/code 1.9.3 → 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.
package/dist/index.cjs CHANGED
@@ -1,1287 +1,13 @@
1
1
  'use strict';
2
2
 
3
- var tokens = require('@tooark/tokens');
4
- var autocomplete = require('@codemirror/autocomplete');
5
- var commands = require('@codemirror/commands');
6
- var langJavascript = require('@codemirror/lang-javascript');
7
- var langJson = require('@codemirror/lang-json');
8
- var langYaml = require('@codemirror/lang-yaml');
9
- var language = require('@codemirror/language');
10
- var search = require('@codemirror/search');
11
- var state = require('@codemirror/state');
12
- var view = require('@codemirror/view');
13
- var highlight = require('@lezer/highlight');
3
+ var arkCodeEditor = require('./components/ark-code-editor.cjs');
4
+ var index = require('./engine/index.cjs');
5
+ var register = require('./register.cjs');
14
6
 
15
- /** Resolve "auto" para "light"/"dark" pelo color-scheme computado de `element`, ou pela preferência do sistema. */
16
- function resolveCodeTheme(theme, element) {
17
- if (theme === "dark")
18
- return "dark";
19
- if (theme === "light")
20
- return "light";
21
- return tokens.resolveColorScheme(element);
22
- }
23
- // --- Tema ---
24
- // Cores de sintaxe por lado, fallback dos tokens --ark-syntax-* (os mesmos valores, em light-dark() no tokens.css); o
25
- // chrome (fundo, texto, bordas, seleção) vem dos tokens --ark-color-* com fallback, para o editor seguir o tema do app
26
- // mesmo sem o CSS do @tooark/web-components na página.
27
- const SYNTAX = {
28
- light: {
29
- keyword: "#6d28d9",
30
- string: "#15803d",
31
- number: "#b45309",
32
- property: "#1d4ed8",
33
- comment: "#64748b",
34
- atom: "#0f766e",
35
- punctuation: "#475569",
36
- invalid: "#dc2626"
37
- },
38
- dark: {
39
- keyword: "#c4b5fd",
40
- string: "#86efac",
41
- number: "#fcd34d",
42
- property: "#93c5fd",
43
- comment: "#94a3b8",
44
- atom: "#5eead4",
45
- punctuation: "#cbd5e1",
46
- invalid: "#f87171"
47
- }
48
- };
49
- const FALLBACK = {
50
- light: {
51
- surface: "#ffffff",
52
- surfaceMuted: "#f8fafc",
53
- fg: "#0f172a",
54
- fgMuted: "#64748b",
55
- placeholder: "#94a3b8",
56
- border: "#e2e8f0",
57
- primary: "#4f46e5",
58
- ring: "#a5b4fc",
59
- match: "#fef3c7"
60
- },
61
- dark: {
62
- surface: "#0f172a",
63
- surfaceMuted: "#1e293b",
64
- fg: "#e2e8f0",
65
- fgMuted: "#94a3b8",
66
- placeholder: "#64748b",
67
- border: "#334155",
68
- primary: "#818cf8",
69
- ring: "#6366f1",
70
- match: "#78350f"
71
- }
72
- };
73
- const MONO = 'var(--ark-font-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace)';
74
- const INTENTS = Object.keys(tokens.ARK_INTENT_SOFT_CSS);
75
- // Fonte e recuo lateral por `size`, os mesmos do ark-input; "md" é o editor de sempre.
76
- const SIZES = {
77
- xs: { font: "0.75rem", paddingX: "0.5rem" },
78
- sm: { font: "0.75rem", paddingX: "0.625rem" },
79
- md: { font: "0.875rem", paddingX: "0.75rem" },
80
- lg: { font: "1rem", paddingX: "1rem" },
81
- xl: { font: "1.125rem", paddingX: "1.25rem" }
82
- };
83
- function normalizeSize(size) {
84
- return size && Object.keys(SIZES).includes(size) ? size : "md";
85
- }
86
- // Fundo e texto suaves do intent; o fallback é o próprio `light-dark()` dos tokens, resolvido pelo color-scheme
87
- // que o editor declara.
88
- function variableColors(intent) {
89
- const soft = tokens.ARK_INTENT_SOFT_CSS[intent];
90
- return {
91
- backgroundColor: `var(--ark-color-${intent}-soft, ${soft.soft})`,
92
- color: `var(--ark-color-${intent}-soft-fg, ${soft.softFg})`
93
- };
94
- }
95
- function chromeTheme(side) {
96
- const f = FALLBACK[side];
97
- const v = (token, fallback) => `var(--ark-color-${token}, ${fallback})`;
98
- const tint = (token, fallback, amount) => `color-mix(in oklab, ${v(token, fallback)} ${amount}%, transparent)`;
99
- const intentRules = Object.fromEntries(INTENTS.map((intent) => [`.cm-ark-variable-${intent}`, variableColors(intent)]));
100
- return view.EditorView.theme({
101
- "&": {
102
- colorScheme: side,
103
- backgroundColor: v("surface", f.surface),
104
- color: v("fg", f.fg),
105
- border: `1px solid ${v("border", f.border)}`,
106
- borderRadius: "0.5rem",
107
- fontSize: "var(--ark-code-font-size, 0.875rem)",
108
- minHeight: "var(--ark-code-min-height, 8rem)",
109
- // Sem `max-height` a variável não existe e o editor cresce com o conteúdo; com ela o scroller do CodeMirror
110
- // (overflow-x auto, logo também y) rola por dentro.
111
- maxHeight: "var(--ark-code-max-height, none)"
112
- },
113
- // Uma linha na altura do controle: a borda (2px) e a linha (1.5em) saem da altura, o resto vira respiro
114
- // vertical do conteúdo, que ocupa a caixa toda (o clique em qualquer ponto posiciona o cursor).
115
- "&.cm-ark-single-line": {
116
- minHeight: "var(--ark-code-control-height, 2.25rem)",
117
- maxHeight: "none"
118
- },
119
- "&.cm-ark-single-line .cm-scroller": {
120
- minHeight: "0",
121
- scrollbarWidth: "none"
122
- },
123
- "&.cm-ark-single-line .cm-content": {
124
- padding: "max(0px, calc((var(--ark-code-control-height, 2.25rem) - 2px - 1.5em) / 2)) 0"
125
- },
126
- "&.cm-focused": {
127
- outline: `2px solid ${v("primary-ring", f.ring)}`,
128
- outlineOffset: "1px"
129
- },
130
- ".cm-scroller": {
131
- fontFamily: MONO,
132
- lineHeight: "1.5",
133
- borderRadius: "inherit",
134
- // A calha e o conteúdo esticam até a altura mínima do editor, não só até o texto.
135
- minHeight: "inherit"
136
- },
137
- ".cm-content": {
138
- padding: "0.5rem 0",
139
- caretColor: v("fg", f.fg)
140
- },
141
- ".cm-line": {
142
- padding: "0 var(--ark-code-padding-x, 0.75rem)"
143
- },
144
- ".cm-gutters": {
145
- backgroundColor: v("surface-muted", f.surfaceMuted),
146
- color: v("fg-muted", f.fgMuted),
147
- borderRight: `1px solid ${v("border", f.border)}`,
148
- borderRadius: "0.5rem 0 0 0.5rem"
149
- },
150
- ".cm-activeLine": {
151
- backgroundColor: tint("fg", f.fg, 6)
152
- },
153
- ".cm-activeLineGutter": {
154
- backgroundColor: tint("fg", f.fg, 8)
155
- },
156
- ".cm-cursor, .cm-dropCursor": {
157
- borderLeftColor: v("fg", f.fg)
158
- },
159
- "&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground": {
160
- backgroundColor: tint("primary", f.primary, 22)
161
- },
162
- ".cm-selectionMatch": {
163
- backgroundColor: tint("primary", f.primary, 14)
164
- },
165
- ".cm-searchMatch": {
166
- backgroundColor: v("warning-soft", f.match),
167
- outline: `1px solid ${v("warning-border", f.match)}`
168
- },
169
- ".cm-searchMatch.cm-searchMatch-selected": {
170
- backgroundColor: v("warning-soft", f.match)
171
- },
172
- "&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket": {
173
- backgroundColor: tint("primary", f.primary, 18),
174
- outline: "none"
175
- },
176
- ".cm-placeholder": {
177
- color: v("fg-placeholder", f.placeholder),
178
- fontStyle: "italic"
179
- },
180
- ".cm-foldGutter .cm-gutterElement": {
181
- cursor: "pointer"
182
- },
183
- ".cm-foldPlaceholder": {
184
- backgroundColor: v("surface-muted", f.surfaceMuted),
185
- border: `1px solid ${v("border", f.border)}`,
186
- color: v("fg-muted", f.fgMuted)
187
- },
188
- ".cm-panels": {
189
- backgroundColor: v("surface-muted", f.surfaceMuted),
190
- color: v("fg", f.fg)
191
- },
192
- ".cm-panels.cm-panels-top": {
193
- borderBottom: `1px solid ${v("border", f.border)}`
194
- },
195
- ".cm-panels.cm-panels-bottom": {
196
- borderTop: `1px solid ${v("border", f.border)}`
197
- },
198
- ".cm-panel.cm-search input, .cm-panel.cm-search button, .cm-panel.cm-search label": {
199
- fontFamily: "inherit",
200
- fontSize: "0.75rem"
201
- },
202
- ".cm-panel.cm-search input": {
203
- backgroundColor: v("surface", f.surface),
204
- color: v("fg", f.fg),
205
- border: `1px solid ${v("border", f.border)}`,
206
- borderRadius: "0.25rem"
207
- },
208
- ".cm-tooltip": {
209
- backgroundColor: v("surface", f.surface),
210
- color: v("fg", f.fg),
211
- border: `1px solid ${v("border", f.border)}`,
212
- borderRadius: "0.5rem",
213
- boxShadow: "0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)"
214
- },
215
- ".cm-tooltip.cm-tooltip-autocomplete > ul": {
216
- fontFamily: "inherit",
217
- maxHeight: "14rem"
218
- },
219
- ".cm-tooltip.cm-tooltip-autocomplete > ul > li": {
220
- padding: "0.25rem 0.5rem"
221
- },
222
- ".cm-tooltip.cm-tooltip-autocomplete > ul > li[aria-selected]": {
223
- backgroundColor: v("primary-soft", tint("primary", f.primary, 15)),
224
- color: v("primary-soft-fg", f.fg)
225
- },
226
- ".cm-completionIcon": {
227
- color: v("fg-muted", f.fgMuted)
228
- },
229
- ".cm-ark-variable": {
230
- borderRadius: "0.25rem"
231
- },
232
- // O realce da sintaxe fica dentro do span da variável (uma string JSON, por exemplo): herda a cor dela.
233
- ".cm-ark-variable *": {
234
- color: "inherit"
235
- },
236
- ...intentRules,
237
- // Desconhecida: além da cor, o sublinhado ondulado distingue sem depender dela.
238
- ".cm-ark-variable-unknown": {
239
- ...variableColors("danger"),
240
- textDecoration: "underline wavy",
241
- textDecorationSkipInk: "none",
242
- textUnderlineOffset: "0.2em"
243
- },
244
- ".cm-tooltip .cm-ark-variable-tooltip": {
245
- display: "flex",
246
- alignItems: "baseline",
247
- gap: "0.5rem",
248
- maxWidth: "24rem",
249
- padding: "0.25rem 0.5rem",
250
- fontSize: "0.75rem"
251
- },
252
- ".cm-ark-variable-tooltip-scope": {
253
- flexShrink: "0",
254
- padding: "0 0.375rem",
255
- borderRadius: "0.25rem",
256
- fontWeight: "500"
257
- },
258
- ".cm-ark-variable-tooltip-value": {
259
- fontFamily: MONO,
260
- color: v("fg-muted", f.fgMuted),
261
- overflowWrap: "anywhere"
262
- }
263
- }, { dark: side === "dark" });
264
- }
265
- function syntaxTheme(side) {
266
- // Cada papel lê o token do app; sem ele, a cor embutida do lado. O light-dark() do token resolve pelo color-scheme
267
- // que o editor declara, então um tema fixo (`theme="dark"` numa página clara) pega o lado certo.
268
- const c = Object.fromEntries(Object.entries(SYNTAX[side]).map(([role, color]) => [role, `var(--ark-syntax-${role}, ${color})`]));
269
- return language.syntaxHighlighting(language.HighlightStyle.define([
270
- { tag: [highlight.tags.keyword, highlight.tags.modifier, highlight.tags.operatorKeyword, highlight.tags.controlKeyword], color: c.keyword },
271
- { tag: [highlight.tags.string, highlight.tags.special(highlight.tags.string)], color: c.string },
272
- { tag: [highlight.tags.number, highlight.tags.integer, highlight.tags.float], color: c.number },
273
- { tag: [highlight.tags.propertyName, highlight.tags.definition(highlight.tags.propertyName), highlight.tags.attributeName], color: c.property },
274
- { tag: [highlight.tags.comment, highlight.tags.lineComment, highlight.tags.blockComment], color: c.comment, fontStyle: "italic" },
275
- { tag: [highlight.tags.bool, highlight.tags.null, highlight.tags.atom, highlight.tags.self], color: c.atom },
276
- { tag: [highlight.tags.function(highlight.tags.variableName), highlight.tags.function(highlight.tags.propertyName)], color: c.property },
277
- { tag: [highlight.tags.typeName, highlight.tags.className, highlight.tags.namespace], color: c.keyword },
278
- { tag: [highlight.tags.punctuation, highlight.tags.separator, highlight.tags.bracket, highlight.tags.operator], color: c.punctuation },
279
- { tag: highlight.tags.invalid, color: c.invalid, textDecoration: "underline" }
280
- ]));
281
- }
282
- function themeFor(side) {
283
- return [chromeTheme(side), syntaxTheme(side)];
284
- }
285
- // --- Linguagens e completions ---
286
- function languageFor(language) {
287
- if (language === "json")
288
- return langJson.json();
289
- if (language === "javascript")
290
- return langJavascript.javascript();
291
- if (language === "yaml")
292
- return langYaml.yaml();
293
- return [];
294
- }
295
- // `{{ chave }}` com espaços opcionais por dentro; a chave usa o mesmo conjunto de caracteres da completion.
296
- const VARIABLE_PATTERN = /\{\{\s*([\w$.-]+)\s*\}\}/g;
297
- // Chave repetida: vale a primeira ocorrência (o app resolve a precedência entre escopos antes de mandar).
298
- function normalizeVariables(variables) {
299
- const map = new Map();
300
- for (const variable of variables) {
301
- if (!variable || typeof variable.key !== "string" || !variable.key || map.has(variable.key))
302
- continue;
303
- map.set(variable.key, {
304
- key: variable.key,
305
- scope: typeof variable.scope === "string" && variable.scope ? variable.scope : undefined,
306
- intent: INTENTS.includes(variable.intent) ? variable.intent : "primary",
307
- value: typeof variable.value === "string" ? variable.value : undefined
308
- });
309
- }
310
- return map;
311
- }
312
- // Completions de variáveis: depois de `{{`, oferece as chaves e insere `{{chave}}`; se o `}}` já está adiante
313
- // (closeBrackets fechou o par), só a chave entra e o cursor pula o fechamento. O escopo vai como detalhe e o valor
314
- // como info.
315
- function variableSource(variables) {
316
- return (context) => {
317
- const match = context.matchBefore(/\{\{\s*[\w$.-]*$/);
318
- if (!match)
319
- return null;
320
- const typed = match.text.match(/[\w$.-]*$/)?.[0] ?? "";
321
- const from = match.to - typed.length;
322
- const options = variables.map(({ key, scope, value }) => ({
323
- label: key,
324
- type: "variable",
325
- ...(scope ? { detail: scope } : {}),
326
- ...(value !== undefined ? { info: value } : {}),
327
- apply: (view, _completion, start, end) => {
328
- const closed = view.state.sliceDoc(end, end + 2) === "}}";
329
- const insert = closed ? key : `${key}}}`;
330
- view.dispatch({
331
- changes: { from: start, to: end, insert },
332
- selection: { anchor: start + insert.length + (closed ? 2 : 0) }
333
- });
334
- }
335
- }));
336
- return { from, options, validFor: /^[\w$.-]*$/ };
337
- };
338
- }
339
- function variableTooltip(variable) {
340
- const dom = document.createElement("div");
341
- dom.className = "cm-ark-variable-tooltip";
342
- dom.setAttribute("data-ark", "code-editor-variable-tooltip");
343
- if (variable.scope) {
344
- const scope = document.createElement("span");
345
- scope.className = `cm-ark-variable-tooltip-scope cm-ark-variable-${variable.intent}`;
346
- scope.textContent = variable.scope;
347
- dom.appendChild(scope);
348
- }
349
- if (variable.value !== undefined) {
350
- const value = document.createElement("span");
351
- value.className = "cm-ark-variable-tooltip-value";
352
- value.textContent = variable.value;
353
- dom.appendChild(value);
354
- }
355
- return dom;
356
- }
357
- /**
358
- * Pinta cada `{{chave}}` de `variables` com o intent dela e, com `markUnknown`, em `danger` a chave que não está
359
- * nem em `variables` nem em `known` (as `variableKeys`, que completam mas não pintam). Sem variáveis e sem
360
- * `markUnknown` não há extensão nenhuma: o editor fica como sem o recurso.
361
- */
362
- function variableExtensions(variables, known, markUnknown) {
363
- if (variables.size === 0 && !markUnknown)
364
- return [];
365
- const marks = new Map();
366
- const markFor = (key) => {
367
- const cached = marks.get(key);
368
- if (cached)
369
- return cached;
370
- const variable = variables.get(key);
371
- let mark = null;
372
- if (variable) {
373
- mark = view.Decoration.mark({
374
- class: `cm-ark-variable cm-ark-variable-${variable.intent}`,
375
- attributes: {
376
- "data-ark": "code-editor-variable",
377
- "data-key": key,
378
- "data-intent": variable.intent,
379
- ...(variable.scope ? { "data-scope": variable.scope } : {})
380
- }
381
- });
382
- }
383
- else if (markUnknown && !known.has(key)) {
384
- mark = view.Decoration.mark({
385
- class: "cm-ark-variable cm-ark-variable-unknown",
386
- attributes: { "data-ark": "code-editor-variable", "data-key": key, "data-intent": "danger", "data-unknown": "" }
387
- });
388
- }
389
- if (mark)
390
- marks.set(key, mark);
391
- return mark;
392
- };
393
- const decorator = new view.MatchDecorator({ regexp: VARIABLE_PATTERN, decoration: (match) => markFor(match[1]) });
394
- const painter = view.ViewPlugin.fromClass(class {
395
- constructor(view) {
396
- this.decorations = decorator.createDeco(view);
397
- }
398
- update(update) {
399
- this.decorations = decorator.updateDeco(update, this.decorations);
400
- }
401
- }, {
402
- // Por fora de todas as outras decorações: a variável fica num span só, que o realce da sintaxe, o par de
403
- // colchetes e a busca não cortam; a cor chega ao texto de dentro pela regra `.cm-ark-variable *`.
404
- provide: (plugin) => view.EditorView.outerDecorations.of((view$1) => view$1.plugin(plugin)?.decorations ?? view.Decoration.none)
405
- });
406
- // O tooltip só existe para variável conhecida com escopo ou valor: o texto é todo do app, a lib não traduz nada.
407
- const tooltip = view.hoverTooltip((view, pos, side) => {
408
- const line = view.state.doc.lineAt(pos);
409
- for (const match of line.text.matchAll(VARIABLE_PATTERN)) {
410
- const from = line.from + (match.index ?? 0);
411
- const to = from + match[0].length;
412
- if (pos < from || pos > to || (pos === from && side < 0) || (pos === to && side > 0))
413
- continue;
414
- const variable = variables.get(match[1]);
415
- if (!variable || (!variable.scope && variable.value === undefined))
416
- return null;
417
- return { pos: from, end: to, above: true, create: () => ({ dom: variableTooltip(variable) }) };
418
- }
419
- return null;
420
- });
421
- return [painter, tooltip];
422
- }
423
- // --- Uma linha ---
424
- // As quebras que entram (colar, arrastar, comando) saem na mesma transação, como o `<input>` faz com o valor.
425
- function joinLines(tr) {
426
- if (!tr.docChanged || tr.newDoc.lines === 1)
427
- return tr;
428
- const changes = [];
429
- for (let n = 1; n < tr.newDoc.lines; n++) {
430
- const end = tr.newDoc.line(n).to;
431
- changes.push({ from: end, to: end + 1 });
432
- }
433
- return [tr, { changes, sequential: true }];
434
- }
435
- // O conteúdo editável é o `role="textbox"` do CodeMirror: é nele que o nome acessível precisa estar.
436
- function labelExtension(label) {
437
- return label ? view.EditorView.contentAttributes.of({ "aria-label": label }) : [];
438
- }
439
- function singleLineExtensions(on, submit) {
440
- if (!on)
441
- return [];
442
- // Com a lista de completions aberta o Enter é dela (o keymap do autocomplete vem antes); se ela acabou de abrir
443
- // e ainda ignora o Enter, ele não envia a meia variável.
444
- const run = (view) => {
445
- if (autocomplete.completionStatus(view.state) !== "active")
446
- submit();
447
- return true;
448
- };
449
- return [
450
- view.EditorView.editorAttributes.of({ class: "cm-ark-single-line" }),
451
- view.EditorView.contentAttributes.of({ "aria-multiline": "false" }),
452
- state.EditorState.transactionFilter.of(joinLines),
453
- state.Prec.high(view.keymap.of([
454
- { key: "Enter", run, shift: run },
455
- { key: "Mod-Enter", run }
456
- ]))
457
- ];
458
- }
459
- // --- Recuo, fim de linha e formatação ---
460
- function indentExtensions(style, size) {
461
- const width = Math.max(1, Math.min(16, Math.floor(size) || 2));
462
- return [language.indentUnit.of(style === "tab" ? "\t" : " ".repeat(width)), state.EditorState.tabSize.of(width)];
463
- }
464
- // O documento fica sempre em LF por dentro (colar CRLF num doc LF não deixa \r solto); o fim de linha só vale
465
- // na fronteira: `getValue` junta com o configurado e `setValue`/`auto` detectam o que entrou.
466
- function detectLineEnding(value) {
467
- return value.includes("\r\n") ? "crlf" : "lf";
468
- }
469
- function normalizeNewlines(value) {
470
- return value.replace(/\r\n?/g, "\n");
471
- }
472
- function completionsSource(items) {
473
- return (context) => {
474
- const word = context.matchBefore(/[\w$.-]+/);
475
- if (!word && !context.explicit)
476
- return null;
477
- return { from: word ? word.from : context.pos, options: items, validFor: /^[\w$.-]*$/ };
478
- };
479
- }
480
- function completionExtensions(on, variables, items, source) {
481
- if (!on)
482
- return [];
483
- // languageData é o que o autocompletion consulta no cursor: assim as fontes valem em qualquer linguagem. Cada
484
- // fonte é criada uma vez por configuração: o autocompletion identifica a consulta pela identidade da função, e
485
- // uma nova a cada leitura deixaria a completion pendente para sempre.
486
- const sources = [];
487
- if (variables.length > 0)
488
- sources.push({ autocomplete: variableSource(variables) });
489
- if (items.length > 0)
490
- sources.push({ autocomplete: completionsSource(items) });
491
- if (source)
492
- sources.push({ autocomplete: source });
493
- return [autocomplete.autocompletion(), sources.length > 0 ? state.EditorState.languageData.of(() => sources) : []];
494
- }
495
- // Tab recua e Shift+Tab desfaz. A saída por teclado é do próprio CodeMirror: Esc arma o tab-focus mode por dois
496
- // segundos (o Tab seguinte só move o foco) e Ctrl+M, do keymap padrão, alterna o modo de vez.
497
- function tabExtensions(on) {
498
- return on ? view.keymap.of([commands.indentWithTab]) : [];
499
- }
500
- function formatJson(value, unit) {
501
- return JSON.stringify(JSON.parse(value), null, unit);
502
- }
503
- // --- Instância ---
504
- /**
505
- * Cria um editor CodeMirror 6 dentro de `parent` com o setup básico do Tooark: numeração e dobra, histórico,
506
- * fechamento de pares, realce da linha ativa (só editável), busca por Ctrl+F, completions (da linguagem, de
507
- * `variableKeys`, de `completions` e de `completionSource`), Tab para recuar com saída por Esc+Tab, recuo por
508
- * espaços ou tabulação, fim de linha LF/CRLF na fronteira do valor, formatação por Shift+Alt+F (JSON nativo ou o
509
- * `formatter` do app) e tema pelos tokens. Opcionais, ligados só pelas opções: `variables` pintadas por intent com
510
- * tooltip, `markUnknownVariables`, o campo `singleLine` e as `extensions` do app.
511
- */
512
- function createCodeEditor(parent, options = {}) {
513
- const language$1 = new state.Compartment();
514
- const theme = new state.Compartment();
515
- const readonly = new state.Compartment();
516
- const placeholder = new state.Compartment();
517
- const labelling = new state.Compartment();
518
- const gutterNumbers = new state.Compartment();
519
- const gutterFold = new state.Compartment();
520
- const wrapping = new state.Compartment();
521
- const indentation = new state.Compartment();
522
- const tabKey = new state.Compartment();
523
- const completion = new state.Compartment();
524
- const variableMarks = new state.Compartment();
525
- const lineMode = new state.Compartment();
526
- const searchKeys = new state.Compartment();
527
- const custom = new state.Compartment();
528
- let resolved = resolveCodeTheme(options.theme ?? "auto", parent);
529
- let applying = false;
530
- let currentLanguage = options.language ?? "text";
531
- let indentStyle = options.indentStyle ?? "space";
532
- let indentSize = options.indentSize ?? 2;
533
- let lineEnding = options.lineEnding ?? "auto";
534
- let detected = detectLineEnding(options.value ?? "");
535
- let autocomplete$1 = options.autocomplete !== false;
536
- let variableKeys = options.variableKeys ?? [];
537
- let variables = normalizeVariables(options.variables ?? []);
538
- let markUnknown = options.markUnknownVariables === true;
539
- let completions = options.completions ?? [];
540
- let completionSource = options.completionSource;
541
- let formatter = options.formatter;
542
- let readonlyOn = options.readonly === true;
543
- let lineNumbersOn = options.lineNumbers !== false;
544
- let foldOn = options.fold !== false;
545
- let tabIndentOn = options.tabIndent !== false;
546
- let singleLine = options.singleLine === true;
547
- // Em `singleLine` calhas, linha ativa, recuo por Tab e busca ficam desligados, seja qual for a opção de cada um;
548
- // desligar o modo devolve o que as opções pedem.
549
- const readonlyExtensions = () => [
550
- state.EditorState.readOnly.of(readonlyOn),
551
- view.EditorView.editable.of(!readonlyOn),
552
- readonlyOn || singleLine ? [] : [view.highlightActiveLine(), view.highlightActiveLineGutter()]
553
- ];
554
- const numbersExtension = () => (lineNumbersOn && !singleLine ? view.lineNumbers() : []);
555
- const foldExtension = () => (foldOn && !singleLine ? language.foldGutter() : []);
556
- const tabExtension = () => tabExtensions(tabIndentOn && !singleLine);
557
- const searchExtension = () => (singleLine ? [] : view.keymap.of(search.searchKeymap));
558
- const lineModeExtension = () => singleLineExtensions(singleLine, () => options.onSubmit?.(view$1.state.doc.toString().split("\n").join(eol())));
559
- // Variáveis com escopo primeiro; as `variableKeys` que elas não cobrem entram só como completion.
560
- const variableEntries = () => [
561
- ...variables.values(),
562
- ...variableKeys.filter((key) => !variables.has(key)).map((key) => ({ key, intent: "primary" }))
563
- ];
564
- const marksExtension = () => variableExtensions(variables, new Set(variableKeys), markUnknown);
565
- const reconfigureCompletion = () => {
566
- view$1.dispatch({
567
- effects: completion.reconfigure(completionExtensions(autocomplete$1, variableEntries(), completions, completionSource))
568
- });
569
- };
570
- const eol = () => ((lineEnding === "auto" ? detected : lineEnding) === "crlf" ? "\r\n" : "\n");
571
- // Texto como o documento guarda: sempre LF e, em `singleLine`, sem quebras.
572
- const toDoc = (value) => {
573
- const text = normalizeNewlines(value);
574
- return singleLine ? text.replace(/\n/g, "") : text;
575
- };
576
- const applySize = (size) => {
577
- const scale = SIZES[size];
578
- view$1.dom.style.setProperty("--ark-code-font-size", scale.font);
579
- view$1.dom.style.setProperty("--ark-code-padding-x", scale.paddingX);
580
- view$1.dom.style.setProperty("--ark-code-control-height", `var(--ark-size-${size}, ${tokens.ARK_SIZE_CSS[size]})`);
581
- };
582
- const format = async () => {
583
- const source = view$1.state.doc.toString();
584
- try {
585
- let next;
586
- if (formatter) {
587
- next = normalizeNewlines(await formatter(source, currentLanguage));
588
- }
589
- else if (currentLanguage === "json") {
590
- next = formatJson(source, indentStyle === "tab" ? "\t" : " ".repeat(indentSize));
591
- }
592
- else {
593
- return false;
594
- }
595
- if (view$1.state.doc.toString() !== source)
596
- return false;
597
- if (next !== source) {
598
- // Edição de verdade: entra no histórico e dispara onChange, como se o usuário tivesse digitado.
599
- view$1.dispatch({
600
- changes: { from: 0, to: view$1.state.doc.length, insert: next },
601
- selection: { anchor: Math.min(view$1.state.selection.main.head, next.length) },
602
- userEvent: "format"
603
- });
604
- }
605
- return true;
606
- }
607
- catch (error) {
608
- options.onFormatError?.(error);
609
- return false;
610
- }
611
- };
612
- const state$1 = state.EditorState.create({
613
- doc: toDoc(options.value ?? ""),
614
- extensions: [
615
- gutterNumbers.of(numbersExtension()),
616
- gutterFold.of(foldExtension()),
617
- view.highlightSpecialChars(),
618
- commands.history(),
619
- view.drawSelection(),
620
- view.dropCursor(),
621
- state.EditorState.allowMultipleSelections.of(true),
622
- language.indentOnInput(),
623
- language.bracketMatching(),
624
- autocomplete.closeBrackets(),
625
- view.rectangularSelection(),
626
- view.crosshairCursor(),
627
- search.highlightSelectionMatches(),
628
- view.keymap.of([
629
- ...autocomplete.closeBracketsKeymap,
630
- ...commands.defaultKeymap,
631
- ...commands.historyKeymap,
632
- ...language.foldKeymap,
633
- ...autocomplete.completionKeymap,
634
- {
635
- key: "Shift-Alt-f",
636
- run: () => {
637
- void format();
638
- return true;
639
- }
640
- }
641
- ]),
642
- // A busca fica num keymap à parte, depois do principal, para sair em `singleLine`.
643
- searchKeys.of(searchExtension()),
644
- language$1.of(languageFor(currentLanguage)),
645
- theme.of(themeFor(resolved)),
646
- readonly.of(readonlyExtensions()),
647
- placeholder.of(options.placeholder ? view.placeholder(options.placeholder) : []),
648
- labelling.of(labelExtension(options.label)),
649
- wrapping.of(options.wrap ? view.EditorView.lineWrapping : []),
650
- indentation.of(indentExtensions(indentStyle, indentSize)),
651
- tabKey.of(tabExtension()),
652
- completion.of(completionExtensions(autocomplete$1, variableEntries(), completions, completionSource)),
653
- variableMarks.of(marksExtension()),
654
- lineMode.of(lineModeExtension()),
655
- view.EditorView.updateListener.of((update) => {
656
- if (update.docChanged && !applying)
657
- options.onChange?.(update.state.doc.toString().split("\n").join(eol()));
658
- }),
659
- // As do app vêm por último: na mesma precedência, keymaps, calhas e linguagem da lib vêm antes, e quem precisa
660
- // passar à frente usa `Prec`.
661
- custom.of(options.extensions ?? [])
662
- ]
663
- });
664
- const view$1 = new view.EditorView({ state: state$1, parent });
665
- view$1.dom.style.setProperty("--ark-code-min-height", options.minHeight ?? "8rem");
666
- const applyMaxHeight = (value) => {
667
- if (value?.trim()) {
668
- view$1.dom.style.setProperty("--ark-code-max-height", value.trim());
669
- }
670
- else {
671
- view$1.dom.style.removeProperty("--ark-code-max-height");
672
- }
673
- };
674
- applyMaxHeight(options.maxHeight);
675
- applySize(normalizeSize(options.size));
676
- return {
677
- view: view$1,
678
- getValue: () => view$1.state.doc.toString().split("\n").join(eol()),
679
- setValue: (value) => {
680
- detected = detectLineEnding(value);
681
- const text = toDoc(value);
682
- if (text === view$1.state.doc.toString())
683
- return;
684
- applying = true;
685
- try {
686
- view$1.dispatch({ changes: { from: 0, to: view$1.state.doc.length, insert: text }, selection: { anchor: 0 } });
687
- }
688
- finally {
689
- applying = false;
690
- }
691
- },
692
- setLanguage: (next) => {
693
- currentLanguage = next;
694
- view$1.dispatch({ effects: language$1.reconfigure(languageFor(next)) });
695
- },
696
- setTheme: (next) => {
697
- const side = resolveCodeTheme(next, parent);
698
- if (side === resolved)
699
- return;
700
- resolved = side;
701
- view$1.dispatch({ effects: theme.reconfigure(themeFor(side)) });
702
- },
703
- setReadonly: (on) => {
704
- readonlyOn = on;
705
- view$1.dispatch({ effects: readonly.reconfigure(readonlyExtensions()) });
706
- },
707
- setPlaceholder: (text) => view$1.dispatch({ effects: placeholder.reconfigure(text ? view.placeholder(text) : []) }),
708
- setLabel: (label) => view$1.dispatch({ effects: labelling.reconfigure(labelExtension(label)) }),
709
- setLineNumbers: (on) => {
710
- lineNumbersOn = on;
711
- view$1.dispatch({ effects: gutterNumbers.reconfigure(numbersExtension()) });
712
- },
713
- setFold: (on) => {
714
- foldOn = on;
715
- view$1.dispatch({ effects: gutterFold.reconfigure(foldExtension()) });
716
- },
717
- setWrap: (on) => view$1.dispatch({ effects: wrapping.reconfigure(on ? view.EditorView.lineWrapping : []) }),
718
- setMinHeight: (value) => view$1.dom.style.setProperty("--ark-code-min-height", value),
719
- setMaxHeight: applyMaxHeight,
720
- setIndent: (style, size) => {
721
- indentStyle = style;
722
- indentSize = size;
723
- view$1.dispatch({ effects: indentation.reconfigure(indentExtensions(style, size)) });
724
- },
725
- setLineEnding: (next) => {
726
- lineEnding = next;
727
- },
728
- resolvedLineEnding: () => (lineEnding === "auto" ? detected : lineEnding),
729
- setTabIndent: (on) => {
730
- tabIndentOn = on;
731
- view$1.dispatch({ effects: tabKey.reconfigure(tabExtension()) });
732
- },
733
- setAutocomplete: (on) => {
734
- autocomplete$1 = on;
735
- reconfigureCompletion();
736
- },
737
- setVariableKeys: (keys) => {
738
- variableKeys = keys;
739
- reconfigureCompletion();
740
- // As chaves só completam, mas contam como conhecidas para a marcação das desconhecidas.
741
- view$1.dispatch({ effects: variableMarks.reconfigure(marksExtension()) });
742
- },
743
- setVariables: (next) => {
744
- variables = normalizeVariables(next);
745
- reconfigureCompletion();
746
- view$1.dispatch({ effects: variableMarks.reconfigure(marksExtension()) });
747
- },
748
- setMarkUnknownVariables: (on) => {
749
- markUnknown = on;
750
- view$1.dispatch({ effects: variableMarks.reconfigure(marksExtension()) });
751
- },
752
- setSingleLine: (on) => {
753
- if (on === singleLine)
754
- return;
755
- singleLine = on;
756
- if (on)
757
- search.closeSearchPanel(view$1);
758
- view$1.dispatch({
759
- effects: [
760
- lineMode.reconfigure(lineModeExtension()),
761
- searchKeys.reconfigure(searchExtension()),
762
- readonly.reconfigure(readonlyExtensions()),
763
- gutterNumbers.reconfigure(numbersExtension()),
764
- gutterFold.reconfigure(foldExtension()),
765
- tabKey.reconfigure(tabExtension())
766
- ]
767
- });
768
- // O filtro só age nas próximas edições: o texto que já estava junta aqui, como um `setValue`.
769
- const text = view$1.state.doc.toString();
770
- if (!on || !text.includes("\n"))
771
- return;
772
- applying = true;
773
- try {
774
- view$1.dispatch({ changes: { from: 0, to: text.length, insert: toDoc(text) } });
775
- }
776
- finally {
777
- applying = false;
778
- }
779
- },
780
- setSize: (size) => applySize(normalizeSize(size)),
781
- setCompletions: (items) => {
782
- completions = items;
783
- reconfigureCompletion();
784
- },
785
- setCompletionSource: (source) => {
786
- completionSource = source;
787
- reconfigureCompletion();
788
- },
789
- setFormatter: (next) => {
790
- formatter = next;
791
- },
792
- setExtensions: (next) => view$1.dispatch({ effects: custom.reconfigure(next) }),
793
- format,
794
- canFormat: () => formatter !== undefined || currentLanguage === "json",
795
- resolvedTheme: () => resolved,
796
- focus: () => view$1.focus(),
797
- destroy: () => view$1.destroy()
798
- };
799
- }
800
7
 
801
- // Base dos Custom Elements que também carrega fora do navegador. No SSR (Node, Angular SSR, Next, Nuxt) não existe
802
- // HTMLElement, e um `extends HTMLElement` no topo do módulo derrubaria o import de quem só renderiza o HTML; lá a
803
- // base é uma classe vazia, e os elementos só passam a existir no cliente, quando registerTooark*() os define.
804
- /** `HTMLElement` no navegador; fora dele, uma classe vazia para o módulo poder ser importado no servidor. */
805
- const HTMLElementBase = typeof HTMLElement === "undefined" ? class {
806
- } : HTMLElement;
807
8
 
808
- // Um framework (ou o app) pode gravar uma propriedade no elemento antes de registerTooark*() defini-lo: sem a classe,
809
- // `el.rows = x` vira uma propriedade própria do nó, que depois do upgrade esconde o setter da classe e o valor nunca
810
- // chega ao componente. Ao conectar, toda propriedade própria que tem setter na classe é retirada e regravada por ele,
811
- // na ordem em que foi gravada. Os campos da própria classe e o que os frameworks penduram no nó (chaves internas do
812
- // React e do Vue) não têm setter e ficam como estão.
813
- /** Reaplica pelo setter da classe as propriedades gravadas no nó antes de o elemento ser registrado. */
814
- function upgradeProperties(element) {
815
- const target = element;
816
- for (const name of Object.keys(element)) {
817
- if (!hasSetter(Object.getPrototypeOf(element), name))
818
- continue;
819
- const value = target[name];
820
- delete target[name];
821
- target[name] = value;
822
- }
823
- }
824
- // Procura o acessor na cadeia de protótipos até o HTMLElement: as propriedades nativas nunca viram propriedade própria,
825
- // porque o nó já é um HTMLElement antes do registro.
826
- function hasSetter(prototype, name) {
827
- for (let proto = prototype; proto && proto !== HTMLElement.prototype; proto = Object.getPrototypeOf(proto)) {
828
- const descriptor = Object.getOwnPropertyDescriptor(proto, name);
829
- if (descriptor)
830
- return typeof descriptor.set === "function";
831
- }
832
- return false;
833
- }
834
-
835
- // Mesma regra do coerceBooleanAttr de @tooark/core (este pacote só depende de tokens): frameworks passam o valor do
836
- // atributo como propriedade, então "" é presente e "false" é ausente.
837
- function truthy(value) {
838
- if (value === "" || value === true)
839
- return true;
840
- if (value === false || value === null || value === undefined || value === "false")
841
- return false;
842
- return Boolean(value);
843
- }
844
- /** Sem extensões do app; uma referência só, para `null` repetido não reconfigurar o editor. */
845
- const NO_EXTENSIONS = [];
846
- /**
847
- * Custom Element que renderiza um editor de código CodeMirror 6.
848
- *
849
- * O texto vai pela propriedade `value` (ou pelo atributo `value` como valor
850
- * inicial) e volta em `change` com `detail: { value }` a cada edição do
851
- * usuário. Atributos: `language` (json | javascript | yaml | text),
852
- * `readonly`, `placeholder`, `min-height` e `max-height` (comprimentos CSS;
853
- * acima da máxima o conteúdo rola por dentro), `line-numbers`,
854
- * `fold`, `tab-indent` e `autocomplete` (ligados por padrão; "false"
855
- * desliga), `wrap`, `indent-style` (space | tab), `indent-size`,
856
- * `line-ending` (lf | crlf | auto), `theme` (auto | light | dark),
857
- * `aria-label` (vai para o conteúdo editável, o `role="textbox"`) e
858
- * `testid`. Propriedades JS: `variableKeys` (completions depois de `{{`),
859
- * `completions` (palavras oferecidas em qualquer linguagem),
860
- * `completionSource` (fonte própria), `formatter` (formatador do app;
861
- * sem ele só JSON formata) e `format()`, também por Shift+Alt+F. Tab recua e
862
- * Esc+Tab sai do editor. Em `auto` o tema segue o color-scheme da página e
863
- * acompanha a troca em tempo de execução (`observeColorScheme` de
864
- * @tooark/tokens). O nó do CodeMirror leva `data-ark="code-editor"` e o
865
- * `testid` como `data-testid`.
866
- *
867
- * Opcionais, desligados até o app pedir: a propriedade `variables` pinta
868
- * cada `{{chave}}` pelo intent da variável, com tooltip do escopo e do valor;
869
- * `mark-unknown-variables` pinta em `danger` a chave desconhecida;
870
- * `single-line` vira um campo de uma linha na altura dos controles (`size`),
871
- * com Enter emitindo `ark-submit` (`detail: { value }`); a propriedade
872
- * `extensions` soma extensões do CodeMirror do app (gramáticas que a lib não
873
- * traz, calhas, decorações) às da lib, sem recriar o editor.
874
- */
875
- class ArkCodeEditor extends HTMLElementBase {
876
- constructor() {
877
- super(...arguments);
878
- this.instance = null;
879
- /** Texto antes de montar, ou o último conhecido depois de desmontar. */
880
- this.pendingValue = "";
881
- this.keys = [];
882
- this.vars = [];
883
- this.items = [];
884
- /** Extensões do app como vieram: a mesma referência atribuída de novo não reconfigura o editor. */
885
- this.exts = NO_EXTENSIONS;
886
- /** Para de observar o tema da página; só existe com `theme="auto"`. */
887
- this.disposeTheme = null;
888
- }
889
- static get observedAttributes() {
890
- return [
891
- "language",
892
- "readonly",
893
- "placeholder",
894
- "min-height",
895
- "max-height",
896
- "line-numbers",
897
- "fold",
898
- "wrap",
899
- "indent-style",
900
- "indent-size",
901
- "line-ending",
902
- "tab-indent",
903
- "autocomplete",
904
- "mark-unknown-variables",
905
- "single-line",
906
- "size",
907
- "theme",
908
- "aria-label",
909
- "testid"
910
- ];
911
- }
912
- /** Texto do editor. Atribuir substitui tudo sem disparar `change`. */
913
- get value() {
914
- return this.instance ? this.instance.getValue() : this.pendingValue;
915
- }
916
- set value(next) {
917
- const text = next ?? "";
918
- this.pendingValue = text;
919
- this.instance?.setValue(text);
920
- }
921
- /** Chaves oferecidas como completions depois de `{{` (propriedade JS). */
922
- get variableKeys() {
923
- return [...this.keys];
924
- }
925
- set variableKeys(next) {
926
- this.keys = Array.isArray(next) ? next.filter((key) => typeof key === "string" && key.length > 0) : [];
927
- this.instance?.setVariableKeys(this.keys);
928
- }
929
- /** Variáveis com escopo e cor (propriedade JS): completam depois de `{{` e pintam o `{{chave}}` no texto. */
930
- get variables() {
931
- return this.vars.map((variable) => ({ ...variable }));
932
- }
933
- set variables(next) {
934
- this.vars = Array.isArray(next)
935
- ? next.filter((variable) => variable && typeof variable.key === "string" && variable.key.length > 0)
936
- : [];
937
- this.instance?.setVariables(this.vars);
938
- }
939
- /** Pinta em `danger` o `{{chave}}` fora de `variables` e `variableKeys` (atributo `mark-unknown-variables`). */
940
- get markUnknownVariables() {
941
- return this.hasAttribute("mark-unknown-variables");
942
- }
943
- set markUnknownVariables(value) {
944
- this.toggleAttribute("mark-unknown-variables", truthy(value));
945
- }
946
- /** Campo de uma linha na altura dos controles (atributo `single-line`); Enter emite `ark-submit`. */
947
- get singleLine() {
948
- return this.hasAttribute("single-line");
949
- }
950
- set singleLine(value) {
951
- this.toggleAttribute("single-line", truthy(value));
952
- }
953
- /** Escala da fonte e do recuo; em `single-line`, também a altura (atributo `size`). Padrão: "md". */
954
- get size() {
955
- const value = (this.getAttribute("size") || "md").toLowerCase();
956
- return Object.keys(tokens.ARK_SIZE_CSS).includes(value) ? value : "md";
957
- }
958
- set size(value) {
959
- this.setAttribute("size", value);
960
- }
961
- /** Palavras oferecidas como completion em qualquer linguagem (propriedade JS, formato do CodeMirror). */
962
- get completions() {
963
- return [...this.items];
964
- }
965
- set completions(next) {
966
- this.items = Array.isArray(next) ? next.filter((item) => item && typeof item.label === "string") : [];
967
- this.instance?.setCompletions(this.items);
968
- }
969
- /** Fonte de completion própria (propriedade JS), somada às da linguagem. */
970
- get completionSource() {
971
- return this.source;
972
- }
973
- set completionSource(next) {
974
- this.source = typeof next === "function" ? next : undefined;
975
- this.instance?.setCompletionSource(this.source);
976
- }
977
- /** Formatador do app (propriedade JS); sem ele só `language="json"` formata. */
978
- get formatter() {
979
- return this.formatFn;
980
- }
981
- set formatter(next) {
982
- this.formatFn = typeof next === "function" ? next : undefined;
983
- this.instance?.setFormatter(this.formatFn);
984
- }
985
- /**
986
- * Extensões do CodeMirror do app (propriedade JS), depois das da lib: gramáticas que ela não traz (com `language`
987
- * em "text"), calhas, decorações. Trocar reconfigura sem recriar o editor; `null` remove.
988
- */
989
- get extensions() {
990
- return this.exts;
991
- }
992
- set extensions(next) {
993
- const value = next !== null && typeof next === "object" ? next : NO_EXTENSIONS;
994
- if (value === this.exts)
995
- return;
996
- this.exts = value;
997
- this.instance?.setExtensions(value);
998
- }
999
- /** Recuo com espaços ou tabulação (atributo `indent-style`). Padrão: "space". */
1000
- get indentStyle() {
1001
- return this.getAttribute("indent-style") === "tab" ? "tab" : "space";
1002
- }
1003
- set indentStyle(value) {
1004
- this.setAttribute("indent-style", value);
1005
- }
1006
- /** Espaços por nível, ou largura da tabulação (atributo `indent-size`). Padrão: 2. */
1007
- get indentSize() {
1008
- const raw = Number(this.getAttribute("indent-size"));
1009
- return this.hasAttribute("indent-size") && Number.isInteger(raw) && raw >= 1 && raw <= 16 ? raw : 2;
1010
- }
1011
- set indentSize(value) {
1012
- this.setAttribute("indent-size", String(value));
1013
- }
1014
- /** Fim de linha do valor (atributo `line-ending`): lf, crlf ou auto. Padrão: "auto". */
1015
- get lineEnding() {
1016
- const value = (this.getAttribute("line-ending") || "auto").toLowerCase();
1017
- return value === "lf" || value === "crlf" ? value : "auto";
1018
- }
1019
- set lineEnding(value) {
1020
- this.setAttribute("line-ending", value);
1021
- }
1022
- /** Fim de linha em vigor depois de resolver `auto` (o do último valor atribuído). */
1023
- get resolvedLineEnding() {
1024
- return this.instance ? this.instance.resolvedLineEnding() : this.pendingValue.includes("\r\n") ? "crlf" : "lf";
1025
- }
1026
- /** Tab recua e Esc+Tab sai; ligado salvo `tab-indent="false"`. */
1027
- get tabIndent() {
1028
- return this.getAttribute("tab-indent") !== "false";
1029
- }
1030
- set tabIndent(value) {
1031
- this.setAttribute("tab-indent", truthy(value) ? "true" : "false");
1032
- }
1033
- /** Completions ligadas salvo `autocomplete="false"`. */
1034
- get autocomplete() {
1035
- return this.getAttribute("autocomplete") !== "false";
1036
- }
1037
- set autocomplete(value) {
1038
- this.setAttribute("autocomplete", truthy(value) ? "true" : "false");
1039
- }
1040
- /** Linguagem do realce (atributo `language`). Padrão: "text". */
1041
- get language() {
1042
- const value = (this.getAttribute("language") || "text").toLowerCase();
1043
- return value === "json" || value === "javascript" || value === "yaml" ? value : "text";
1044
- }
1045
- set language(next) {
1046
- this.setAttribute("language", next);
1047
- }
1048
- get readonly() {
1049
- return this.hasAttribute("readonly");
1050
- }
1051
- set readonly(value) {
1052
- this.toggleAttribute("readonly", truthy(value));
1053
- }
1054
- /** Quebra de linha visual (atributo `wrap`). */
1055
- get wrap() {
1056
- return this.hasAttribute("wrap");
1057
- }
1058
- set wrap(value) {
1059
- this.toggleAttribute("wrap", truthy(value));
1060
- }
1061
- /** Numeração das linhas; ligada salvo `line-numbers="false"`. */
1062
- get lineNumbers() {
1063
- return this.getAttribute("line-numbers") !== "false";
1064
- }
1065
- set lineNumbers(value) {
1066
- this.setAttribute("line-numbers", truthy(value) ? "true" : "false");
1067
- }
1068
- /** Calha de dobra; ligada salvo `fold="false"`. */
1069
- get fold() {
1070
- return this.getAttribute("fold") !== "false";
1071
- }
1072
- set fold(value) {
1073
- this.setAttribute("fold", truthy(value) ? "true" : "false");
1074
- }
1075
- get placeholder() {
1076
- return this.getAttribute("placeholder") || "";
1077
- }
1078
- set placeholder(value) {
1079
- if (value) {
1080
- this.setAttribute("placeholder", value);
1081
- }
1082
- else {
1083
- this.removeAttribute("placeholder");
1084
- }
1085
- }
1086
- /** Altura mínima do editor (atributo `min-height`, comprimento CSS). Padrão: "8rem". */
1087
- get minHeight() {
1088
- return this.getAttribute("min-height")?.trim() || "8rem";
1089
- }
1090
- set minHeight(value) {
1091
- if (value) {
1092
- this.setAttribute("min-height", value);
1093
- }
1094
- else {
1095
- this.removeAttribute("min-height");
1096
- }
1097
- }
1098
- /**
1099
- * Altura máxima do editor (atributo `max-height`, comprimento CSS): acima dela o conteúdo rola dentro do editor.
1100
- * Ignorada em `single-line`. Padrão: "" (sem limite, cresce com o conteúdo).
1101
- */
1102
- get maxHeight() {
1103
- return this.getAttribute("max-height")?.trim() || "";
1104
- }
1105
- set maxHeight(value) {
1106
- if (value) {
1107
- this.setAttribute("max-height", value);
1108
- }
1109
- else {
1110
- this.removeAttribute("max-height");
1111
- }
1112
- }
1113
- get theme() {
1114
- const value = (this.getAttribute("theme") || "auto").toLowerCase();
1115
- return value === "light" || value === "dark" ? value : "auto";
1116
- }
1117
- set theme(value) {
1118
- this.setAttribute("theme", value);
1119
- }
1120
- /** Tema efetivamente aplicado (depois de resolver `auto`); `null` antes de renderizar. */
1121
- get resolvedTheme() {
1122
- return this.instance?.resolvedTheme() ?? null;
1123
- }
1124
- /** Instância nativa do CodeMirror (uso avançado); `null` antes de renderizar. */
1125
- get view() {
1126
- return this.instance?.view ?? null;
1127
- }
1128
- connectedCallback() {
1129
- upgradeProperties(this);
1130
- // O atributo `value` só dá o texto inicial; depois a propriedade manda.
1131
- if (!this.instance && !this.pendingValue && this.hasAttribute("value")) {
1132
- this.pendingValue = this.getAttribute("value") ?? "";
1133
- }
1134
- this.render();
1135
- }
1136
- disconnectedCallback() {
1137
- this.teardown();
1138
- }
1139
- attributeChangedCallback(name, oldValue, newValue) {
1140
- if (oldValue === newValue || !this.instance)
1141
- return;
1142
- if (name === "language")
1143
- this.instance.setLanguage(this.language);
1144
- if (name === "readonly")
1145
- this.instance.setReadonly(this.readonly);
1146
- if (name === "placeholder")
1147
- this.instance.setPlaceholder(this.placeholder);
1148
- if (name === "aria-label")
1149
- this.instance.setLabel(newValue || undefined);
1150
- if (name === "min-height")
1151
- this.instance.setMinHeight(this.minHeight);
1152
- if (name === "max-height")
1153
- this.instance.setMaxHeight(this.maxHeight);
1154
- if (name === "line-numbers")
1155
- this.instance.setLineNumbers(this.lineNumbers);
1156
- if (name === "fold")
1157
- this.instance.setFold(this.fold);
1158
- if (name === "wrap")
1159
- this.instance.setWrap(this.wrap);
1160
- if (name === "indent-style" || name === "indent-size")
1161
- this.instance.setIndent(this.indentStyle, this.indentSize);
1162
- if (name === "line-ending")
1163
- this.instance.setLineEnding(this.lineEnding);
1164
- if (name === "tab-indent")
1165
- this.instance.setTabIndent(this.tabIndent);
1166
- if (name === "autocomplete")
1167
- this.instance.setAutocomplete(this.autocomplete);
1168
- if (name === "mark-unknown-variables")
1169
- this.instance.setMarkUnknownVariables(this.markUnknownVariables);
1170
- if (name === "single-line")
1171
- this.instance.setSingleLine(this.singleLine);
1172
- if (name === "size")
1173
- this.instance.setSize(this.size);
1174
- if (name === "theme") {
1175
- this.instance.setTheme(this.theme);
1176
- this.syncThemeObserver();
1177
- }
1178
- if (name === "testid")
1179
- this.applyHooks();
1180
- }
1181
- /** Foca o editor. */
1182
- focus() {
1183
- this.instance?.focus();
1184
- }
1185
- /** Formata o documento com `formatter` (ou JSON nativo); `false` sem formatador ou quando falha (`ark-format-error`). */
1186
- format() {
1187
- return this.instance ? this.instance.format() : Promise.resolve(false);
1188
- }
1189
- /** Indica se a linguagem atual tem como ser formatada. */
1190
- get canFormat() {
1191
- return this.instance ? this.instance.canFormat() : this.formatFn !== undefined || this.language === "json";
1192
- }
1193
- render() {
1194
- this.teardown();
1195
- this.style.display = this.style.display || "block";
1196
- this.instance = createCodeEditor(this, {
1197
- value: this.pendingValue,
1198
- language: this.language,
1199
- theme: this.theme,
1200
- readonly: this.readonly,
1201
- placeholder: this.placeholder || undefined,
1202
- label: this.getAttribute("aria-label") || undefined,
1203
- lineNumbers: this.lineNumbers,
1204
- fold: this.fold,
1205
- wrap: this.wrap,
1206
- minHeight: this.minHeight,
1207
- maxHeight: this.maxHeight || undefined,
1208
- indentStyle: this.indentStyle,
1209
- indentSize: this.indentSize,
1210
- lineEnding: this.lineEnding,
1211
- tabIndent: this.tabIndent,
1212
- autocomplete: this.autocomplete,
1213
- variableKeys: this.keys,
1214
- variables: this.vars,
1215
- markUnknownVariables: this.markUnknownVariables,
1216
- singleLine: this.singleLine,
1217
- size: this.size,
1218
- completions: this.items,
1219
- completionSource: this.source,
1220
- formatter: this.formatFn,
1221
- extensions: this.exts,
1222
- onChange: (value) => {
1223
- this.pendingValue = value;
1224
- this.dispatchEvent(new CustomEvent("change", { detail: { value }, bubbles: true, composed: true }));
1225
- },
1226
- onSubmit: (value) => {
1227
- this.dispatchEvent(new CustomEvent("ark-submit", { detail: { value }, bubbles: true, composed: true }));
1228
- },
1229
- onFormatError: (error) => {
1230
- this.dispatchEvent(new CustomEvent("ark-format-error", { detail: { error }, bubbles: true, composed: true }));
1231
- }
1232
- });
1233
- this.applyHooks();
1234
- this.syncThemeObserver();
1235
- }
1236
- // O nó raiz do CodeMirror leva o hook de E2E, como os componentes de @tooark/web-components.
1237
- applyHooks() {
1238
- const dom = this.instance?.view.dom;
1239
- if (!dom)
1240
- return;
1241
- dom.setAttribute("data-ark", "code-editor");
1242
- const testid = this.getAttribute("testid");
1243
- if (testid) {
1244
- dom.setAttribute("data-testid", testid);
1245
- }
1246
- else {
1247
- dom.removeAttribute("data-testid");
1248
- }
1249
- }
1250
- // Em `auto`, a troca de tema da página re-resolve o tema do editor; com tema fixo não há o que observar.
1251
- syncThemeObserver() {
1252
- this.disposeTheme?.();
1253
- this.disposeTheme = null;
1254
- if (this.theme !== "auto")
1255
- return;
1256
- this.disposeTheme = tokens.observeColorScheme(this, () => this.instance?.setTheme("auto"));
1257
- }
1258
- teardown() {
1259
- this.disposeTheme?.();
1260
- this.disposeTheme = null;
1261
- if (this.instance) {
1262
- this.pendingValue = this.instance.getValue();
1263
- this.instance.destroy();
1264
- this.instance = null;
1265
- }
1266
- }
1267
- }
1268
- ArkCodeEditor.tagName = "ark-code-editor";
1269
-
1270
- /**
1271
- * Registra o Custom Element `<ark-code-editor>` no navegador.
1272
- * Chame antes de usar o componente em qualquer ambiente (puro, React, Angular, Vue).
1273
- */
1274
- function registerTooarkCode() {
1275
- // Fora do navegador (SSR) não há registro de elementos: no-op, e o cliente registra na hidratação.
1276
- if (typeof customElements === "undefined")
1277
- return;
1278
- if (!customElements.get(ArkCodeEditor.tagName)) {
1279
- customElements.define(ArkCodeEditor.tagName, ArkCodeEditor);
1280
- }
1281
- }
1282
-
1283
- exports.ArkCodeEditor = ArkCodeEditor;
1284
- exports.createCodeEditor = createCodeEditor;
1285
- exports.registerTooarkCode = registerTooarkCode;
1286
- exports.resolveCodeTheme = resolveCodeTheme;
9
+ exports.ArkCodeEditor = arkCodeEditor.ArkCodeEditor;
10
+ exports.createCodeEditor = index.createCodeEditor;
11
+ exports.resolveCodeTheme = index.resolveCodeTheme;
12
+ exports.registerTooarkCode = register.registerTooarkCode;
1287
13
  //# sourceMappingURL=index.cjs.map