@tooark/code 1.0.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 ADDED
@@ -0,0 +1,824 @@
1
+ 'use strict';
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');
14
+
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; o chrome (fundo, texto, bordas, seleção) vem dos tokens --ark-color-* com fallback,
25
+ // para o editor seguir o tema do app mesmo sem o CSS do @tooark/web-components na página.
26
+ const SYNTAX = {
27
+ light: {
28
+ keyword: "#6d28d9",
29
+ string: "#15803d",
30
+ number: "#b45309",
31
+ property: "#1d4ed8",
32
+ comment: "#64748b",
33
+ atom: "#0f766e",
34
+ punctuation: "#475569",
35
+ invalid: "#dc2626"
36
+ },
37
+ dark: {
38
+ keyword: "#c4b5fd",
39
+ string: "#86efac",
40
+ number: "#fcd34d",
41
+ property: "#93c5fd",
42
+ comment: "#94a3b8",
43
+ atom: "#5eead4",
44
+ punctuation: "#cbd5e1",
45
+ invalid: "#f87171"
46
+ }
47
+ };
48
+ const FALLBACK = {
49
+ light: {
50
+ surface: "#ffffff",
51
+ surfaceMuted: "#f8fafc",
52
+ fg: "#0f172a",
53
+ fgMuted: "#64748b",
54
+ placeholder: "#94a3b8",
55
+ border: "#e2e8f0",
56
+ primary: "#4f46e5",
57
+ ring: "#a5b4fc",
58
+ match: "#fef3c7"
59
+ },
60
+ dark: {
61
+ surface: "#0f172a",
62
+ surfaceMuted: "#1e293b",
63
+ fg: "#e2e8f0",
64
+ fgMuted: "#94a3b8",
65
+ placeholder: "#64748b",
66
+ border: "#334155",
67
+ primary: "#818cf8",
68
+ ring: "#6366f1",
69
+ match: "#78350f"
70
+ }
71
+ };
72
+ const MONO = 'var(--ark-font-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace)';
73
+ function chromeTheme(side) {
74
+ const f = FALLBACK[side];
75
+ const v = (token, fallback) => `var(--ark-color-${token}, ${fallback})`;
76
+ const tint = (token, fallback, amount) => `color-mix(in oklab, ${v(token, fallback)} ${amount}%, transparent)`;
77
+ return view.EditorView.theme({
78
+ "&": {
79
+ colorScheme: side,
80
+ backgroundColor: v("surface", f.surface),
81
+ color: v("fg", f.fg),
82
+ border: `1px solid ${v("border", f.border)}`,
83
+ borderRadius: "0.5rem",
84
+ fontSize: "0.875rem",
85
+ minHeight: "var(--ark-code-min-height, 8rem)"
86
+ },
87
+ "&.cm-focused": {
88
+ outline: `2px solid ${v("primary-ring", f.ring)}`,
89
+ outlineOffset: "1px"
90
+ },
91
+ ".cm-scroller": {
92
+ fontFamily: MONO,
93
+ lineHeight: "1.5",
94
+ borderRadius: "inherit",
95
+ // A calha e o conteúdo esticam até a altura mínima do editor, não só até o texto.
96
+ minHeight: "inherit"
97
+ },
98
+ ".cm-content": {
99
+ padding: "0.5rem 0",
100
+ caretColor: v("fg", f.fg)
101
+ },
102
+ ".cm-line": {
103
+ padding: "0 0.75rem"
104
+ },
105
+ ".cm-gutters": {
106
+ backgroundColor: v("surface-muted", f.surfaceMuted),
107
+ color: v("fg-muted", f.fgMuted),
108
+ borderRight: `1px solid ${v("border", f.border)}`,
109
+ borderRadius: "0.5rem 0 0 0.5rem"
110
+ },
111
+ ".cm-activeLine": {
112
+ backgroundColor: tint("fg", f.fg, 6)
113
+ },
114
+ ".cm-activeLineGutter": {
115
+ backgroundColor: tint("fg", f.fg, 8)
116
+ },
117
+ ".cm-cursor, .cm-dropCursor": {
118
+ borderLeftColor: v("fg", f.fg)
119
+ },
120
+ "&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground": {
121
+ backgroundColor: tint("primary", f.primary, 22)
122
+ },
123
+ ".cm-selectionMatch": {
124
+ backgroundColor: tint("primary", f.primary, 14)
125
+ },
126
+ ".cm-searchMatch": {
127
+ backgroundColor: v("warning-soft", f.match),
128
+ outline: `1px solid ${v("warning-border", f.match)}`
129
+ },
130
+ ".cm-searchMatch.cm-searchMatch-selected": {
131
+ backgroundColor: v("warning-soft", f.match)
132
+ },
133
+ "&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket": {
134
+ backgroundColor: tint("primary", f.primary, 18),
135
+ outline: "none"
136
+ },
137
+ ".cm-placeholder": {
138
+ color: v("fg-placeholder", f.placeholder),
139
+ fontStyle: "italic"
140
+ },
141
+ ".cm-foldGutter .cm-gutterElement": {
142
+ cursor: "pointer"
143
+ },
144
+ ".cm-foldPlaceholder": {
145
+ backgroundColor: v("surface-muted", f.surfaceMuted),
146
+ border: `1px solid ${v("border", f.border)}`,
147
+ color: v("fg-muted", f.fgMuted)
148
+ },
149
+ ".cm-panels": {
150
+ backgroundColor: v("surface-muted", f.surfaceMuted),
151
+ color: v("fg", f.fg)
152
+ },
153
+ ".cm-panels.cm-panels-top": {
154
+ borderBottom: `1px solid ${v("border", f.border)}`
155
+ },
156
+ ".cm-panels.cm-panels-bottom": {
157
+ borderTop: `1px solid ${v("border", f.border)}`
158
+ },
159
+ ".cm-panel.cm-search input, .cm-panel.cm-search button, .cm-panel.cm-search label": {
160
+ fontFamily: "inherit",
161
+ fontSize: "0.75rem"
162
+ },
163
+ ".cm-panel.cm-search input": {
164
+ backgroundColor: v("surface", f.surface),
165
+ color: v("fg", f.fg),
166
+ border: `1px solid ${v("border", f.border)}`,
167
+ borderRadius: "0.25rem"
168
+ },
169
+ ".cm-tooltip": {
170
+ backgroundColor: v("surface", f.surface),
171
+ color: v("fg", f.fg),
172
+ border: `1px solid ${v("border", f.border)}`,
173
+ borderRadius: "0.5rem",
174
+ boxShadow: "0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)"
175
+ },
176
+ ".cm-tooltip.cm-tooltip-autocomplete > ul": {
177
+ fontFamily: "inherit",
178
+ maxHeight: "14rem"
179
+ },
180
+ ".cm-tooltip.cm-tooltip-autocomplete > ul > li": {
181
+ padding: "0.25rem 0.5rem"
182
+ },
183
+ ".cm-tooltip.cm-tooltip-autocomplete > ul > li[aria-selected]": {
184
+ backgroundColor: v("primary-soft", tint("primary", f.primary, 15)),
185
+ color: v("primary-soft-fg", f.fg)
186
+ },
187
+ ".cm-completionIcon": {
188
+ color: v("fg-muted", f.fgMuted)
189
+ }
190
+ }, { dark: side === "dark" });
191
+ }
192
+ function syntaxTheme(side) {
193
+ const c = SYNTAX[side];
194
+ return language.syntaxHighlighting(language.HighlightStyle.define([
195
+ { tag: [highlight.tags.keyword, highlight.tags.modifier, highlight.tags.operatorKeyword, highlight.tags.controlKeyword], color: c.keyword },
196
+ { tag: [highlight.tags.string, highlight.tags.special(highlight.tags.string)], color: c.string },
197
+ { tag: [highlight.tags.number, highlight.tags.integer, highlight.tags.float], color: c.number },
198
+ { tag: [highlight.tags.propertyName, highlight.tags.definition(highlight.tags.propertyName), highlight.tags.attributeName], color: c.property },
199
+ { tag: [highlight.tags.comment, highlight.tags.lineComment, highlight.tags.blockComment], color: c.comment, fontStyle: "italic" },
200
+ { tag: [highlight.tags.bool, highlight.tags.null, highlight.tags.atom, highlight.tags.self], color: c.atom },
201
+ { tag: [highlight.tags.function(highlight.tags.variableName), highlight.tags.function(highlight.tags.propertyName)], color: c.property },
202
+ { tag: [highlight.tags.typeName, highlight.tags.className, highlight.tags.namespace], color: c.keyword },
203
+ { tag: [highlight.tags.punctuation, highlight.tags.separator, highlight.tags.bracket, highlight.tags.operator], color: c.punctuation },
204
+ { tag: highlight.tags.invalid, color: c.invalid, textDecoration: "underline" }
205
+ ]));
206
+ }
207
+ function themeFor(side) {
208
+ return [chromeTheme(side), syntaxTheme(side)];
209
+ }
210
+ // --- Linguagens e completions ---
211
+ function languageFor(language) {
212
+ if (language === "json")
213
+ return langJson.json();
214
+ if (language === "javascript")
215
+ return langJavascript.javascript();
216
+ if (language === "yaml")
217
+ return langYaml.yaml();
218
+ return [];
219
+ }
220
+ // Completions de variáveis: depois de `{{`, oferece as chaves e insere `{{chave}}`; se o `}}` já está adiante
221
+ // (closeBrackets fechou o par), só a chave entra e o cursor pula o fechamento.
222
+ function variableSource(keys) {
223
+ return (context) => {
224
+ const match = context.matchBefore(/\{\{\s*[\w.-]*$/);
225
+ if (!match)
226
+ return null;
227
+ const typed = match.text.match(/[\w.-]*$/)?.[0] ?? "";
228
+ const from = match.to - typed.length;
229
+ const options = keys.map((key) => ({
230
+ label: key,
231
+ type: "variable",
232
+ apply: (view, _completion, start, end) => {
233
+ const closed = view.state.sliceDoc(end, end + 2) === "}}";
234
+ const insert = closed ? key : `${key}}}`;
235
+ view.dispatch({
236
+ changes: { from: start, to: end, insert },
237
+ selection: { anchor: start + insert.length + (closed ? 2 : 0) }
238
+ });
239
+ }
240
+ }));
241
+ return { from, options, validFor: /^[\w.-]*$/ };
242
+ };
243
+ }
244
+ // --- Recuo, fim de linha e formatação ---
245
+ function indentExtensions(style, size) {
246
+ const width = Math.max(1, Math.min(16, Math.floor(size) || 2));
247
+ return [language.indentUnit.of(style === "tab" ? "\t" : " ".repeat(width)), state.EditorState.tabSize.of(width)];
248
+ }
249
+ // O documento fica sempre em LF por dentro (colar CRLF num doc LF não deixa \r solto); o fim de linha só vale
250
+ // na fronteira: `getValue` junta com o configurado e `setValue`/`auto` detectam o que entrou.
251
+ function detectLineEnding(value) {
252
+ return value.includes("\r\n") ? "crlf" : "lf";
253
+ }
254
+ function normalizeNewlines(value) {
255
+ return value.replace(/\r\n?/g, "\n");
256
+ }
257
+ function completionsSource(items) {
258
+ return (context) => {
259
+ const word = context.matchBefore(/[\w$.-]+/);
260
+ if (!word && !context.explicit)
261
+ return null;
262
+ return { from: word ? word.from : context.pos, options: items, validFor: /^[\w$.-]*$/ };
263
+ };
264
+ }
265
+ function completionExtensions(on, keys, items, source) {
266
+ if (!on)
267
+ return [];
268
+ // languageData é o que o autocompletion consulta no cursor: assim as fontes valem em qualquer linguagem. Cada
269
+ // fonte é criada uma vez por configuração: o autocompletion identifica a consulta pela identidade da função, e
270
+ // uma nova a cada leitura deixaria a completion pendente para sempre.
271
+ const sources = [];
272
+ if (keys.length > 0)
273
+ sources.push({ autocomplete: variableSource(keys) });
274
+ if (items.length > 0)
275
+ sources.push({ autocomplete: completionsSource(items) });
276
+ if (source)
277
+ sources.push({ autocomplete: source });
278
+ return [autocomplete.autocompletion(), sources.length > 0 ? state.EditorState.languageData.of(() => sources) : []];
279
+ }
280
+ // Tab recua e Shift+Tab desfaz. A saída por teclado é do próprio CodeMirror: Esc arma o tab-focus mode por dois
281
+ // segundos (o Tab seguinte só move o foco) e Ctrl+M, do keymap padrão, alterna o modo de vez.
282
+ function tabExtensions(on) {
283
+ return on ? view.keymap.of([commands.indentWithTab]) : [];
284
+ }
285
+ function formatJson(value, unit) {
286
+ return JSON.stringify(JSON.parse(value), null, unit);
287
+ }
288
+ // --- Instância ---
289
+ /**
290
+ * Cria um editor CodeMirror 6 dentro de `parent` com o setup básico do Tooark: numeração e dobra, histórico,
291
+ * fechamento de pares, realce da linha ativa (só editável), busca por Ctrl+F, completions (da linguagem, de
292
+ * `variableKeys`, de `completions` e de `completionSource`), Tab para recuar com saída por Esc+Tab, recuo por
293
+ * espaços ou tabulação, fim de linha LF/CRLF na fronteira do valor, formatação por Shift+Alt+F (JSON nativo ou o
294
+ * `formatter` do app) e tema pelos tokens.
295
+ */
296
+ function createCodeEditor(parent, options = {}) {
297
+ const language$1 = new state.Compartment();
298
+ const theme = new state.Compartment();
299
+ const readonly = new state.Compartment();
300
+ const placeholder = new state.Compartment();
301
+ const gutterNumbers = new state.Compartment();
302
+ const gutterFold = new state.Compartment();
303
+ const wrapping = new state.Compartment();
304
+ const indentation = new state.Compartment();
305
+ const tabKey = new state.Compartment();
306
+ const completion = new state.Compartment();
307
+ let resolved = resolveCodeTheme(options.theme ?? "auto", parent);
308
+ let applying = false;
309
+ let currentLanguage = options.language ?? "text";
310
+ let indentStyle = options.indentStyle ?? "space";
311
+ let indentSize = options.indentSize ?? 2;
312
+ let lineEnding = options.lineEnding ?? "auto";
313
+ let detected = detectLineEnding(options.value ?? "");
314
+ let autocomplete$1 = options.autocomplete !== false;
315
+ let variableKeys = options.variableKeys ?? [];
316
+ let completions = options.completions ?? [];
317
+ let completionSource = options.completionSource;
318
+ let formatter = options.formatter;
319
+ const readonlyExtensions = (on) => [
320
+ state.EditorState.readOnly.of(on),
321
+ view.EditorView.editable.of(!on),
322
+ on ? [] : [view.highlightActiveLine(), view.highlightActiveLineGutter()]
323
+ ];
324
+ const reconfigureCompletion = () => {
325
+ view$1.dispatch({
326
+ effects: completion.reconfigure(completionExtensions(autocomplete$1, variableKeys, completions, completionSource))
327
+ });
328
+ };
329
+ const eol = () => ((lineEnding === "auto" ? detected : lineEnding) === "crlf" ? "\r\n" : "\n");
330
+ const format = async () => {
331
+ const source = view$1.state.doc.toString();
332
+ try {
333
+ let next;
334
+ if (formatter) {
335
+ next = normalizeNewlines(await formatter(source, currentLanguage));
336
+ }
337
+ else if (currentLanguage === "json") {
338
+ next = formatJson(source, indentStyle === "tab" ? "\t" : " ".repeat(indentSize));
339
+ }
340
+ else {
341
+ return false;
342
+ }
343
+ if (view$1.state.doc.toString() !== source)
344
+ return false;
345
+ if (next !== source) {
346
+ // Edição de verdade: entra no histórico e dispara onChange, como se o usuário tivesse digitado.
347
+ view$1.dispatch({
348
+ changes: { from: 0, to: view$1.state.doc.length, insert: next },
349
+ selection: { anchor: Math.min(view$1.state.selection.main.head, next.length) },
350
+ userEvent: "format"
351
+ });
352
+ }
353
+ return true;
354
+ }
355
+ catch (error) {
356
+ options.onFormatError?.(error);
357
+ return false;
358
+ }
359
+ };
360
+ const state$1 = state.EditorState.create({
361
+ doc: normalizeNewlines(options.value ?? ""),
362
+ extensions: [
363
+ gutterNumbers.of(options.lineNumbers === false ? [] : view.lineNumbers()),
364
+ gutterFold.of(options.fold === false ? [] : language.foldGutter()),
365
+ view.highlightSpecialChars(),
366
+ commands.history(),
367
+ view.drawSelection(),
368
+ view.dropCursor(),
369
+ state.EditorState.allowMultipleSelections.of(true),
370
+ language.indentOnInput(),
371
+ language.bracketMatching(),
372
+ autocomplete.closeBrackets(),
373
+ view.rectangularSelection(),
374
+ view.crosshairCursor(),
375
+ search.highlightSelectionMatches(),
376
+ view.keymap.of([
377
+ ...autocomplete.closeBracketsKeymap,
378
+ ...commands.defaultKeymap,
379
+ ...search.searchKeymap,
380
+ ...commands.historyKeymap,
381
+ ...language.foldKeymap,
382
+ ...autocomplete.completionKeymap,
383
+ {
384
+ key: "Shift-Alt-f",
385
+ run: () => {
386
+ void format();
387
+ return true;
388
+ }
389
+ }
390
+ ]),
391
+ language$1.of(languageFor(currentLanguage)),
392
+ theme.of(themeFor(resolved)),
393
+ readonly.of(readonlyExtensions(options.readonly === true)),
394
+ placeholder.of(options.placeholder ? view.placeholder(options.placeholder) : []),
395
+ wrapping.of(options.wrap ? view.EditorView.lineWrapping : []),
396
+ indentation.of(indentExtensions(indentStyle, indentSize)),
397
+ tabKey.of(tabExtensions(options.tabIndent !== false)),
398
+ completion.of(completionExtensions(autocomplete$1, variableKeys, completions, completionSource)),
399
+ view.EditorView.updateListener.of((update) => {
400
+ if (update.docChanged && !applying)
401
+ options.onChange?.(update.state.doc.toString().split("\n").join(eol()));
402
+ })
403
+ ]
404
+ });
405
+ const view$1 = new view.EditorView({ state: state$1, parent });
406
+ view$1.dom.style.setProperty("--ark-code-min-height", options.minHeight ?? "8rem");
407
+ return {
408
+ view: view$1,
409
+ getValue: () => view$1.state.doc.toString().split("\n").join(eol()),
410
+ setValue: (value) => {
411
+ detected = detectLineEnding(value);
412
+ const text = normalizeNewlines(value);
413
+ if (text === view$1.state.doc.toString())
414
+ return;
415
+ applying = true;
416
+ try {
417
+ view$1.dispatch({ changes: { from: 0, to: view$1.state.doc.length, insert: text }, selection: { anchor: 0 } });
418
+ }
419
+ finally {
420
+ applying = false;
421
+ }
422
+ },
423
+ setLanguage: (next) => {
424
+ currentLanguage = next;
425
+ view$1.dispatch({ effects: language$1.reconfigure(languageFor(next)) });
426
+ },
427
+ setTheme: (next) => {
428
+ const side = resolveCodeTheme(next, parent);
429
+ if (side === resolved)
430
+ return;
431
+ resolved = side;
432
+ view$1.dispatch({ effects: theme.reconfigure(themeFor(side)) });
433
+ },
434
+ setReadonly: (on) => view$1.dispatch({ effects: readonly.reconfigure(readonlyExtensions(on)) }),
435
+ setPlaceholder: (text) => view$1.dispatch({ effects: placeholder.reconfigure(text ? view.placeholder(text) : []) }),
436
+ setLineNumbers: (on) => view$1.dispatch({ effects: gutterNumbers.reconfigure(on ? view.lineNumbers() : []) }),
437
+ setFold: (on) => view$1.dispatch({ effects: gutterFold.reconfigure(on ? language.foldGutter() : []) }),
438
+ setWrap: (on) => view$1.dispatch({ effects: wrapping.reconfigure(on ? view.EditorView.lineWrapping : []) }),
439
+ setMinHeight: (value) => view$1.dom.style.setProperty("--ark-code-min-height", value),
440
+ setIndent: (style, size) => {
441
+ indentStyle = style;
442
+ indentSize = size;
443
+ view$1.dispatch({ effects: indentation.reconfigure(indentExtensions(style, size)) });
444
+ },
445
+ setLineEnding: (next) => {
446
+ lineEnding = next;
447
+ },
448
+ resolvedLineEnding: () => (lineEnding === "auto" ? detected : lineEnding),
449
+ setTabIndent: (on) => view$1.dispatch({ effects: tabKey.reconfigure(tabExtensions(on)) }),
450
+ setAutocomplete: (on) => {
451
+ autocomplete$1 = on;
452
+ reconfigureCompletion();
453
+ },
454
+ setVariableKeys: (keys) => {
455
+ variableKeys = keys;
456
+ reconfigureCompletion();
457
+ },
458
+ setCompletions: (items) => {
459
+ completions = items;
460
+ reconfigureCompletion();
461
+ },
462
+ setCompletionSource: (source) => {
463
+ completionSource = source;
464
+ reconfigureCompletion();
465
+ },
466
+ setFormatter: (next) => {
467
+ formatter = next;
468
+ },
469
+ format,
470
+ canFormat: () => formatter !== undefined || currentLanguage === "json",
471
+ resolvedTheme: () => resolved,
472
+ focus: () => view$1.focus(),
473
+ destroy: () => view$1.destroy()
474
+ };
475
+ }
476
+
477
+ // Mesma regra do coerceBooleanAttr de @tooark/core (este pacote só depende de tokens): frameworks passam o valor do
478
+ // atributo como propriedade, então "" é presente e "false" é ausente.
479
+ function truthy(value) {
480
+ if (value === "" || value === true)
481
+ return true;
482
+ if (value === false || value === null || value === undefined || value === "false")
483
+ return false;
484
+ return Boolean(value);
485
+ }
486
+ /**
487
+ * Custom Element que renderiza um editor de código CodeMirror 6.
488
+ *
489
+ * O texto vai pela propriedade `value` (ou pelo atributo `value` como valor
490
+ * inicial) e volta em `change` com `detail: { value }` a cada edição do
491
+ * usuário. Atributos: `language` (json | javascript | yaml | text),
492
+ * `readonly`, `placeholder`, `min-height` (comprimento CSS), `line-numbers`,
493
+ * `fold`, `tab-indent` e `autocomplete` (ligados por padrão; "false"
494
+ * desliga), `wrap`, `indent-style` (space | tab), `indent-size`,
495
+ * `line-ending` (lf | crlf | auto), `theme` (auto | light | dark) e
496
+ * `testid`. Propriedades JS: `variableKeys` (completions depois de `{{`),
497
+ * `completions` (palavras oferecidas em qualquer linguagem),
498
+ * `completionSource` (fonte própria), `formatter` (formatador do app;
499
+ * sem ele só JSON formata) e `format()`, também por Shift+Alt+F. Tab recua e
500
+ * Esc+Tab sai do editor. Em `auto` o tema segue o color-scheme da página e
501
+ * acompanha a troca em tempo de execução (`observeColorScheme` de
502
+ * @tooark/tokens). O nó do CodeMirror leva `data-ark="code-editor"` e o
503
+ * `testid` como `data-testid`.
504
+ */
505
+ class ArkCodeEditor extends HTMLElement {
506
+ constructor() {
507
+ super(...arguments);
508
+ this.instance = null;
509
+ /** Texto antes de montar, ou o último conhecido depois de desmontar. */
510
+ this.pendingValue = "";
511
+ this.keys = [];
512
+ this.items = [];
513
+ /** Para de observar o tema da página; só existe com `theme="auto"`. */
514
+ this.disposeTheme = null;
515
+ }
516
+ static get observedAttributes() {
517
+ return [
518
+ "language",
519
+ "readonly",
520
+ "placeholder",
521
+ "min-height",
522
+ "line-numbers",
523
+ "fold",
524
+ "wrap",
525
+ "indent-style",
526
+ "indent-size",
527
+ "line-ending",
528
+ "tab-indent",
529
+ "autocomplete",
530
+ "theme",
531
+ "testid"
532
+ ];
533
+ }
534
+ /** Texto do editor. Atribuir substitui tudo sem disparar `change`. */
535
+ get value() {
536
+ return this.instance ? this.instance.getValue() : this.pendingValue;
537
+ }
538
+ set value(next) {
539
+ const text = next ?? "";
540
+ this.pendingValue = text;
541
+ this.instance?.setValue(text);
542
+ }
543
+ /** Chaves oferecidas como completions depois de `{{` (propriedade JS). */
544
+ get variableKeys() {
545
+ return [...this.keys];
546
+ }
547
+ set variableKeys(next) {
548
+ this.keys = Array.isArray(next) ? next.filter((key) => typeof key === "string" && key.length > 0) : [];
549
+ this.instance?.setVariableKeys(this.keys);
550
+ }
551
+ /** Palavras oferecidas como completion em qualquer linguagem (propriedade JS, formato do CodeMirror). */
552
+ get completions() {
553
+ return [...this.items];
554
+ }
555
+ set completions(next) {
556
+ this.items = Array.isArray(next) ? next.filter((item) => item && typeof item.label === "string") : [];
557
+ this.instance?.setCompletions(this.items);
558
+ }
559
+ /** Fonte de completion própria (propriedade JS), somada às da linguagem. */
560
+ get completionSource() {
561
+ return this.source;
562
+ }
563
+ set completionSource(next) {
564
+ this.source = typeof next === "function" ? next : undefined;
565
+ this.instance?.setCompletionSource(this.source);
566
+ }
567
+ /** Formatador do app (propriedade JS); sem ele só `language="json"` formata. */
568
+ get formatter() {
569
+ return this.formatFn;
570
+ }
571
+ set formatter(next) {
572
+ this.formatFn = typeof next === "function" ? next : undefined;
573
+ this.instance?.setFormatter(this.formatFn);
574
+ }
575
+ /** Recuo com espaços ou tabulação (atributo `indent-style`). Padrão: "space". */
576
+ get indentStyle() {
577
+ return this.getAttribute("indent-style") === "tab" ? "tab" : "space";
578
+ }
579
+ set indentStyle(value) {
580
+ this.setAttribute("indent-style", value);
581
+ }
582
+ /** Espaços por nível, ou largura da tabulação (atributo `indent-size`). Padrão: 2. */
583
+ get indentSize() {
584
+ const raw = Number(this.getAttribute("indent-size"));
585
+ return this.hasAttribute("indent-size") && Number.isInteger(raw) && raw >= 1 && raw <= 16 ? raw : 2;
586
+ }
587
+ set indentSize(value) {
588
+ this.setAttribute("indent-size", String(value));
589
+ }
590
+ /** Fim de linha do valor (atributo `line-ending`): lf, crlf ou auto. Padrão: "auto". */
591
+ get lineEnding() {
592
+ const value = (this.getAttribute("line-ending") || "auto").toLowerCase();
593
+ return value === "lf" || value === "crlf" ? value : "auto";
594
+ }
595
+ set lineEnding(value) {
596
+ this.setAttribute("line-ending", value);
597
+ }
598
+ /** Fim de linha em vigor depois de resolver `auto` (o do último valor atribuído). */
599
+ get resolvedLineEnding() {
600
+ return this.instance ? this.instance.resolvedLineEnding() : this.pendingValue.includes("\r\n") ? "crlf" : "lf";
601
+ }
602
+ /** Tab recua e Esc+Tab sai; ligado salvo `tab-indent="false"`. */
603
+ get tabIndent() {
604
+ return this.getAttribute("tab-indent") !== "false";
605
+ }
606
+ set tabIndent(value) {
607
+ this.setAttribute("tab-indent", truthy(value) ? "true" : "false");
608
+ }
609
+ /** Completions ligadas salvo `autocomplete="false"`. */
610
+ get autocomplete() {
611
+ return this.getAttribute("autocomplete") !== "false";
612
+ }
613
+ set autocomplete(value) {
614
+ this.setAttribute("autocomplete", truthy(value) ? "true" : "false");
615
+ }
616
+ /** Linguagem do realce (atributo `language`). Padrão: "text". */
617
+ get language() {
618
+ const value = (this.getAttribute("language") || "text").toLowerCase();
619
+ return value === "json" || value === "javascript" || value === "yaml" ? value : "text";
620
+ }
621
+ set language(next) {
622
+ this.setAttribute("language", next);
623
+ }
624
+ get readonly() {
625
+ return this.hasAttribute("readonly");
626
+ }
627
+ set readonly(value) {
628
+ this.toggleAttribute("readonly", truthy(value));
629
+ }
630
+ /** Quebra de linha visual (atributo `wrap`). */
631
+ get wrap() {
632
+ return this.hasAttribute("wrap");
633
+ }
634
+ set wrap(value) {
635
+ this.toggleAttribute("wrap", truthy(value));
636
+ }
637
+ /** Numeração das linhas; ligada salvo `line-numbers="false"`. */
638
+ get lineNumbers() {
639
+ return this.getAttribute("line-numbers") !== "false";
640
+ }
641
+ set lineNumbers(value) {
642
+ this.setAttribute("line-numbers", truthy(value) ? "true" : "false");
643
+ }
644
+ /** Calha de dobra; ligada salvo `fold="false"`. */
645
+ get fold() {
646
+ return this.getAttribute("fold") !== "false";
647
+ }
648
+ set fold(value) {
649
+ this.setAttribute("fold", truthy(value) ? "true" : "false");
650
+ }
651
+ get placeholder() {
652
+ return this.getAttribute("placeholder") || "";
653
+ }
654
+ set placeholder(value) {
655
+ if (value) {
656
+ this.setAttribute("placeholder", value);
657
+ }
658
+ else {
659
+ this.removeAttribute("placeholder");
660
+ }
661
+ }
662
+ /** Altura mínima do editor (atributo `min-height`, comprimento CSS). Padrão: "8rem". */
663
+ get minHeight() {
664
+ return this.getAttribute("min-height")?.trim() || "8rem";
665
+ }
666
+ set minHeight(value) {
667
+ if (value) {
668
+ this.setAttribute("min-height", value);
669
+ }
670
+ else {
671
+ this.removeAttribute("min-height");
672
+ }
673
+ }
674
+ get theme() {
675
+ const value = (this.getAttribute("theme") || "auto").toLowerCase();
676
+ return value === "light" || value === "dark" ? value : "auto";
677
+ }
678
+ set theme(value) {
679
+ this.setAttribute("theme", value);
680
+ }
681
+ /** Tema efetivamente aplicado (depois de resolver `auto`); `null` antes de renderizar. */
682
+ get resolvedTheme() {
683
+ return this.instance?.resolvedTheme() ?? null;
684
+ }
685
+ /** Instância nativa do CodeMirror (uso avançado); `null` antes de renderizar. */
686
+ get view() {
687
+ return this.instance?.view ?? null;
688
+ }
689
+ connectedCallback() {
690
+ // O atributo `value` só dá o texto inicial; depois a propriedade manda.
691
+ if (!this.instance && !this.pendingValue && this.hasAttribute("value")) {
692
+ this.pendingValue = this.getAttribute("value") ?? "";
693
+ }
694
+ this.render();
695
+ }
696
+ disconnectedCallback() {
697
+ this.teardown();
698
+ }
699
+ attributeChangedCallback(name, oldValue, newValue) {
700
+ if (oldValue === newValue || !this.instance)
701
+ return;
702
+ if (name === "language")
703
+ this.instance.setLanguage(this.language);
704
+ if (name === "readonly")
705
+ this.instance.setReadonly(this.readonly);
706
+ if (name === "placeholder")
707
+ this.instance.setPlaceholder(this.placeholder);
708
+ if (name === "min-height")
709
+ this.instance.setMinHeight(this.minHeight);
710
+ if (name === "line-numbers")
711
+ this.instance.setLineNumbers(this.lineNumbers);
712
+ if (name === "fold")
713
+ this.instance.setFold(this.fold);
714
+ if (name === "wrap")
715
+ this.instance.setWrap(this.wrap);
716
+ if (name === "indent-style" || name === "indent-size")
717
+ this.instance.setIndent(this.indentStyle, this.indentSize);
718
+ if (name === "line-ending")
719
+ this.instance.setLineEnding(this.lineEnding);
720
+ if (name === "tab-indent")
721
+ this.instance.setTabIndent(this.tabIndent);
722
+ if (name === "autocomplete")
723
+ this.instance.setAutocomplete(this.autocomplete);
724
+ if (name === "theme") {
725
+ this.instance.setTheme(this.theme);
726
+ this.syncThemeObserver();
727
+ }
728
+ if (name === "testid")
729
+ this.applyHooks();
730
+ }
731
+ /** Foca o editor. */
732
+ focus() {
733
+ this.instance?.focus();
734
+ }
735
+ /** Formata o documento com `formatter` (ou JSON nativo); `false` sem formatador ou quando falha (`ark-format-error`). */
736
+ format() {
737
+ return this.instance ? this.instance.format() : Promise.resolve(false);
738
+ }
739
+ /** Indica se a linguagem atual tem como ser formatada. */
740
+ get canFormat() {
741
+ return this.instance ? this.instance.canFormat() : this.formatFn !== undefined || this.language === "json";
742
+ }
743
+ render() {
744
+ this.teardown();
745
+ this.style.display = this.style.display || "block";
746
+ this.instance = createCodeEditor(this, {
747
+ value: this.pendingValue,
748
+ language: this.language,
749
+ theme: this.theme,
750
+ readonly: this.readonly,
751
+ placeholder: this.placeholder || undefined,
752
+ lineNumbers: this.lineNumbers,
753
+ fold: this.fold,
754
+ wrap: this.wrap,
755
+ minHeight: this.minHeight,
756
+ indentStyle: this.indentStyle,
757
+ indentSize: this.indentSize,
758
+ lineEnding: this.lineEnding,
759
+ tabIndent: this.tabIndent,
760
+ autocomplete: this.autocomplete,
761
+ variableKeys: this.keys,
762
+ completions: this.items,
763
+ completionSource: this.source,
764
+ formatter: this.formatFn,
765
+ onChange: (value) => {
766
+ this.pendingValue = value;
767
+ this.dispatchEvent(new CustomEvent("change", { detail: { value }, bubbles: true, composed: true }));
768
+ },
769
+ onFormatError: (error) => {
770
+ this.dispatchEvent(new CustomEvent("ark-format-error", { detail: { error }, bubbles: true, composed: true }));
771
+ }
772
+ });
773
+ this.applyHooks();
774
+ this.syncThemeObserver();
775
+ }
776
+ // O nó raiz do CodeMirror leva o hook de E2E, como os componentes de @tooark/web-components.
777
+ applyHooks() {
778
+ const dom = this.instance?.view.dom;
779
+ if (!dom)
780
+ return;
781
+ dom.setAttribute("data-ark", "code-editor");
782
+ const testid = this.getAttribute("testid");
783
+ if (testid) {
784
+ dom.setAttribute("data-testid", testid);
785
+ }
786
+ else {
787
+ dom.removeAttribute("data-testid");
788
+ }
789
+ }
790
+ // Em `auto`, a troca de tema da página re-resolve o tema do editor; com tema fixo não há o que observar.
791
+ syncThemeObserver() {
792
+ this.disposeTheme?.();
793
+ this.disposeTheme = null;
794
+ if (this.theme !== "auto")
795
+ return;
796
+ this.disposeTheme = tokens.observeColorScheme(this, () => this.instance?.setTheme("auto"));
797
+ }
798
+ teardown() {
799
+ this.disposeTheme?.();
800
+ this.disposeTheme = null;
801
+ if (this.instance) {
802
+ this.pendingValue = this.instance.getValue();
803
+ this.instance.destroy();
804
+ this.instance = null;
805
+ }
806
+ }
807
+ }
808
+ ArkCodeEditor.tagName = "ark-code-editor";
809
+
810
+ /**
811
+ * Registra o Custom Element `<ark-code-editor>` no navegador.
812
+ * Chame antes de usar o componente em qualquer ambiente (puro, React, Angular, Vue).
813
+ */
814
+ function registerTooarkCode() {
815
+ if (!customElements.get(ArkCodeEditor.tagName)) {
816
+ customElements.define(ArkCodeEditor.tagName, ArkCodeEditor);
817
+ }
818
+ }
819
+
820
+ exports.ArkCodeEditor = ArkCodeEditor;
821
+ exports.createCodeEditor = createCodeEditor;
822
+ exports.registerTooarkCode = registerTooarkCode;
823
+ exports.resolveCodeTheme = resolveCodeTheme;
824
+ //# sourceMappingURL=index.cjs.map