@tooark/code 1.0.1 → 1.2.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/README.md +62 -20
- package/README.pt-BR.md +62 -20
- package/dist/index.cjs +390 -30
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +72 -4
- package/dist/index.d.ts +72 -4
- package/dist/index.js +396 -36
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -70,10 +70,32 @@ const FALLBACK = {
|
|
|
70
70
|
}
|
|
71
71
|
};
|
|
72
72
|
const MONO = 'var(--ark-font-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace)';
|
|
73
|
+
const INTENTS = Object.keys(tokens.ARK_INTENT_SOFT_CSS);
|
|
74
|
+
// Fonte e recuo lateral por `size`, os mesmos do ark-input; "md" é o editor de sempre.
|
|
75
|
+
const SIZES = {
|
|
76
|
+
xs: { font: "0.75rem", paddingX: "0.5rem" },
|
|
77
|
+
sm: { font: "0.75rem", paddingX: "0.625rem" },
|
|
78
|
+
md: { font: "0.875rem", paddingX: "0.75rem" },
|
|
79
|
+
lg: { font: "1rem", paddingX: "1rem" },
|
|
80
|
+
xl: { font: "1.125rem", paddingX: "1.25rem" }
|
|
81
|
+
};
|
|
82
|
+
function normalizeSize(size) {
|
|
83
|
+
return size && Object.keys(SIZES).includes(size) ? size : "md";
|
|
84
|
+
}
|
|
85
|
+
// Fundo e texto suaves do intent; o fallback é o próprio `light-dark()` dos tokens, resolvido pelo color-scheme
|
|
86
|
+
// que o editor declara.
|
|
87
|
+
function variableColors(intent) {
|
|
88
|
+
const soft = tokens.ARK_INTENT_SOFT_CSS[intent];
|
|
89
|
+
return {
|
|
90
|
+
backgroundColor: `var(--ark-color-${intent}-soft, ${soft.soft})`,
|
|
91
|
+
color: `var(--ark-color-${intent}-soft-fg, ${soft.softFg})`
|
|
92
|
+
};
|
|
93
|
+
}
|
|
73
94
|
function chromeTheme(side) {
|
|
74
95
|
const f = FALLBACK[side];
|
|
75
96
|
const v = (token, fallback) => `var(--ark-color-${token}, ${fallback})`;
|
|
76
97
|
const tint = (token, fallback, amount) => `color-mix(in oklab, ${v(token, fallback)} ${amount}%, transparent)`;
|
|
98
|
+
const intentRules = Object.fromEntries(INTENTS.map((intent) => [`.cm-ark-variable-${intent}`, variableColors(intent)]));
|
|
77
99
|
return view.EditorView.theme({
|
|
78
100
|
"&": {
|
|
79
101
|
colorScheme: side,
|
|
@@ -81,9 +103,21 @@ function chromeTheme(side) {
|
|
|
81
103
|
color: v("fg", f.fg),
|
|
82
104
|
border: `1px solid ${v("border", f.border)}`,
|
|
83
105
|
borderRadius: "0.5rem",
|
|
84
|
-
fontSize: "0.875rem",
|
|
106
|
+
fontSize: "var(--ark-code-font-size, 0.875rem)",
|
|
85
107
|
minHeight: "var(--ark-code-min-height, 8rem)"
|
|
86
108
|
},
|
|
109
|
+
// Uma linha na altura do controle: a borda (2px) e a linha (1.5em) saem da altura, o resto vira respiro
|
|
110
|
+
// vertical do conteúdo, que ocupa a caixa toda (o clique em qualquer ponto posiciona o cursor).
|
|
111
|
+
"&.cm-ark-single-line": {
|
|
112
|
+
minHeight: "var(--ark-code-control-height, 2.25rem)"
|
|
113
|
+
},
|
|
114
|
+
"&.cm-ark-single-line .cm-scroller": {
|
|
115
|
+
minHeight: "0",
|
|
116
|
+
scrollbarWidth: "none"
|
|
117
|
+
},
|
|
118
|
+
"&.cm-ark-single-line .cm-content": {
|
|
119
|
+
padding: "max(0px, calc((var(--ark-code-control-height, 2.25rem) - 2px - 1.5em) / 2)) 0"
|
|
120
|
+
},
|
|
87
121
|
"&.cm-focused": {
|
|
88
122
|
outline: `2px solid ${v("primary-ring", f.ring)}`,
|
|
89
123
|
outlineOffset: "1px"
|
|
@@ -100,7 +134,7 @@ function chromeTheme(side) {
|
|
|
100
134
|
caretColor: v("fg", f.fg)
|
|
101
135
|
},
|
|
102
136
|
".cm-line": {
|
|
103
|
-
padding: "0 0.75rem"
|
|
137
|
+
padding: "0 var(--ark-code-padding-x, 0.75rem)"
|
|
104
138
|
},
|
|
105
139
|
".cm-gutters": {
|
|
106
140
|
backgroundColor: v("surface-muted", f.surfaceMuted),
|
|
@@ -186,6 +220,40 @@ function chromeTheme(side) {
|
|
|
186
220
|
},
|
|
187
221
|
".cm-completionIcon": {
|
|
188
222
|
color: v("fg-muted", f.fgMuted)
|
|
223
|
+
},
|
|
224
|
+
".cm-ark-variable": {
|
|
225
|
+
borderRadius: "0.25rem"
|
|
226
|
+
},
|
|
227
|
+
// O realce da sintaxe fica dentro do span da variável (uma string JSON, por exemplo): herda a cor dela.
|
|
228
|
+
".cm-ark-variable *": {
|
|
229
|
+
color: "inherit"
|
|
230
|
+
},
|
|
231
|
+
...intentRules,
|
|
232
|
+
// Desconhecida: além da cor, o sublinhado ondulado distingue sem depender dela.
|
|
233
|
+
".cm-ark-variable-unknown": {
|
|
234
|
+
...variableColors("danger"),
|
|
235
|
+
textDecoration: "underline wavy",
|
|
236
|
+
textDecorationSkipInk: "none",
|
|
237
|
+
textUnderlineOffset: "0.2em"
|
|
238
|
+
},
|
|
239
|
+
".cm-tooltip .cm-ark-variable-tooltip": {
|
|
240
|
+
display: "flex",
|
|
241
|
+
alignItems: "baseline",
|
|
242
|
+
gap: "0.5rem",
|
|
243
|
+
maxWidth: "24rem",
|
|
244
|
+
padding: "0.25rem 0.5rem",
|
|
245
|
+
fontSize: "0.75rem"
|
|
246
|
+
},
|
|
247
|
+
".cm-ark-variable-tooltip-scope": {
|
|
248
|
+
flexShrink: "0",
|
|
249
|
+
padding: "0 0.375rem",
|
|
250
|
+
borderRadius: "0.25rem",
|
|
251
|
+
fontWeight: "500"
|
|
252
|
+
},
|
|
253
|
+
".cm-ark-variable-tooltip-value": {
|
|
254
|
+
fontFamily: MONO,
|
|
255
|
+
color: v("fg-muted", f.fgMuted),
|
|
256
|
+
overflowWrap: "anywhere"
|
|
189
257
|
}
|
|
190
258
|
}, { dark: side === "dark" });
|
|
191
259
|
}
|
|
@@ -217,18 +285,38 @@ function languageFor(language) {
|
|
|
217
285
|
return langYaml.yaml();
|
|
218
286
|
return [];
|
|
219
287
|
}
|
|
288
|
+
// `{{ chave }}` com espaços opcionais por dentro; a chave usa o mesmo conjunto de caracteres da completion.
|
|
289
|
+
const VARIABLE_PATTERN = /\{\{\s*([\w$.-]+)\s*\}\}/g;
|
|
290
|
+
// Chave repetida: vale a primeira ocorrência (o app resolve a precedência entre escopos antes de mandar).
|
|
291
|
+
function normalizeVariables(variables) {
|
|
292
|
+
const map = new Map();
|
|
293
|
+
for (const variable of variables) {
|
|
294
|
+
if (!variable || typeof variable.key !== "string" || !variable.key || map.has(variable.key))
|
|
295
|
+
continue;
|
|
296
|
+
map.set(variable.key, {
|
|
297
|
+
key: variable.key,
|
|
298
|
+
scope: typeof variable.scope === "string" && variable.scope ? variable.scope : undefined,
|
|
299
|
+
intent: INTENTS.includes(variable.intent) ? variable.intent : "primary",
|
|
300
|
+
value: typeof variable.value === "string" ? variable.value : undefined
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
return map;
|
|
304
|
+
}
|
|
220
305
|
// 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
|
-
|
|
306
|
+
// (closeBrackets fechou o par), só a chave entra e o cursor pula o fechamento. O escopo vai como detalhe e o valor
|
|
307
|
+
// como info.
|
|
308
|
+
function variableSource(variables) {
|
|
223
309
|
return (context) => {
|
|
224
|
-
const match = context.matchBefore(/\{\{\s*[\w
|
|
310
|
+
const match = context.matchBefore(/\{\{\s*[\w$.-]*$/);
|
|
225
311
|
if (!match)
|
|
226
312
|
return null;
|
|
227
|
-
const typed = match.text.match(/[\w
|
|
313
|
+
const typed = match.text.match(/[\w$.-]*$/)?.[0] ?? "";
|
|
228
314
|
const from = match.to - typed.length;
|
|
229
|
-
const options =
|
|
315
|
+
const options = variables.map(({ key, scope, value }) => ({
|
|
230
316
|
label: key,
|
|
231
317
|
type: "variable",
|
|
318
|
+
...(scope ? { detail: scope } : {}),
|
|
319
|
+
...(value !== undefined ? { info: value } : {}),
|
|
232
320
|
apply: (view, _completion, start, end) => {
|
|
233
321
|
const closed = view.state.sliceDoc(end, end + 2) === "}}";
|
|
234
322
|
const insert = closed ? key : `${key}}}`;
|
|
@@ -238,9 +326,125 @@ function variableSource(keys) {
|
|
|
238
326
|
});
|
|
239
327
|
}
|
|
240
328
|
}));
|
|
241
|
-
return { from, options, validFor: /^[\w
|
|
329
|
+
return { from, options, validFor: /^[\w$.-]*$/ };
|
|
242
330
|
};
|
|
243
331
|
}
|
|
332
|
+
function variableTooltip(variable) {
|
|
333
|
+
const dom = document.createElement("div");
|
|
334
|
+
dom.className = "cm-ark-variable-tooltip";
|
|
335
|
+
dom.setAttribute("data-ark", "code-editor-variable-tooltip");
|
|
336
|
+
if (variable.scope) {
|
|
337
|
+
const scope = document.createElement("span");
|
|
338
|
+
scope.className = `cm-ark-variable-tooltip-scope cm-ark-variable-${variable.intent}`;
|
|
339
|
+
scope.textContent = variable.scope;
|
|
340
|
+
dom.appendChild(scope);
|
|
341
|
+
}
|
|
342
|
+
if (variable.value !== undefined) {
|
|
343
|
+
const value = document.createElement("span");
|
|
344
|
+
value.className = "cm-ark-variable-tooltip-value";
|
|
345
|
+
value.textContent = variable.value;
|
|
346
|
+
dom.appendChild(value);
|
|
347
|
+
}
|
|
348
|
+
return dom;
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Pinta cada `{{chave}}` de `variables` com o intent dela e, com `markUnknown`, em `danger` a chave que não está
|
|
352
|
+
* nem em `variables` nem em `known` (as `variableKeys`, que completam mas não pintam). Sem variáveis e sem
|
|
353
|
+
* `markUnknown` não há extensão nenhuma: o editor fica como sem o recurso.
|
|
354
|
+
*/
|
|
355
|
+
function variableExtensions(variables, known, markUnknown) {
|
|
356
|
+
if (variables.size === 0 && !markUnknown)
|
|
357
|
+
return [];
|
|
358
|
+
const marks = new Map();
|
|
359
|
+
const markFor = (key) => {
|
|
360
|
+
const cached = marks.get(key);
|
|
361
|
+
if (cached)
|
|
362
|
+
return cached;
|
|
363
|
+
const variable = variables.get(key);
|
|
364
|
+
let mark = null;
|
|
365
|
+
if (variable) {
|
|
366
|
+
mark = view.Decoration.mark({
|
|
367
|
+
class: `cm-ark-variable cm-ark-variable-${variable.intent}`,
|
|
368
|
+
attributes: {
|
|
369
|
+
"data-ark": "code-editor-variable",
|
|
370
|
+
"data-key": key,
|
|
371
|
+
"data-intent": variable.intent,
|
|
372
|
+
...(variable.scope ? { "data-scope": variable.scope } : {})
|
|
373
|
+
}
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
else if (markUnknown && !known.has(key)) {
|
|
377
|
+
mark = view.Decoration.mark({
|
|
378
|
+
class: "cm-ark-variable cm-ark-variable-unknown",
|
|
379
|
+
attributes: { "data-ark": "code-editor-variable", "data-key": key, "data-intent": "danger", "data-unknown": "" }
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
if (mark)
|
|
383
|
+
marks.set(key, mark);
|
|
384
|
+
return mark;
|
|
385
|
+
};
|
|
386
|
+
const decorator = new view.MatchDecorator({ regexp: VARIABLE_PATTERN, decoration: (match) => markFor(match[1]) });
|
|
387
|
+
const painter = view.ViewPlugin.fromClass(class {
|
|
388
|
+
constructor(view) {
|
|
389
|
+
this.decorations = decorator.createDeco(view);
|
|
390
|
+
}
|
|
391
|
+
update(update) {
|
|
392
|
+
this.decorations = decorator.updateDeco(update, this.decorations);
|
|
393
|
+
}
|
|
394
|
+
}, {
|
|
395
|
+
// Por fora de todas as outras decorações: a variável fica num span só, que o realce da sintaxe, o par de
|
|
396
|
+
// colchetes e a busca não cortam; a cor chega ao texto de dentro pela regra `.cm-ark-variable *`.
|
|
397
|
+
provide: (plugin) => view.EditorView.outerDecorations.of((view$1) => view$1.plugin(plugin)?.decorations ?? view.Decoration.none)
|
|
398
|
+
});
|
|
399
|
+
// O tooltip só existe para variável conhecida com escopo ou valor: o texto é todo do app, a lib não traduz nada.
|
|
400
|
+
const tooltip = view.hoverTooltip((view, pos, side) => {
|
|
401
|
+
const line = view.state.doc.lineAt(pos);
|
|
402
|
+
for (const match of line.text.matchAll(VARIABLE_PATTERN)) {
|
|
403
|
+
const from = line.from + (match.index ?? 0);
|
|
404
|
+
const to = from + match[0].length;
|
|
405
|
+
if (pos < from || pos > to || (pos === from && side < 0) || (pos === to && side > 0))
|
|
406
|
+
continue;
|
|
407
|
+
const variable = variables.get(match[1]);
|
|
408
|
+
if (!variable || (!variable.scope && variable.value === undefined))
|
|
409
|
+
return null;
|
|
410
|
+
return { pos: from, end: to, above: true, create: () => ({ dom: variableTooltip(variable) }) };
|
|
411
|
+
}
|
|
412
|
+
return null;
|
|
413
|
+
});
|
|
414
|
+
return [painter, tooltip];
|
|
415
|
+
}
|
|
416
|
+
// --- Uma linha ---
|
|
417
|
+
// As quebras que entram (colar, arrastar, comando) saem na mesma transação, como o `<input>` faz com o valor.
|
|
418
|
+
function joinLines(tr) {
|
|
419
|
+
if (!tr.docChanged || tr.newDoc.lines === 1)
|
|
420
|
+
return tr;
|
|
421
|
+
const changes = [];
|
|
422
|
+
for (let n = 1; n < tr.newDoc.lines; n++) {
|
|
423
|
+
const end = tr.newDoc.line(n).to;
|
|
424
|
+
changes.push({ from: end, to: end + 1 });
|
|
425
|
+
}
|
|
426
|
+
return [tr, { changes, sequential: true }];
|
|
427
|
+
}
|
|
428
|
+
function singleLineExtensions(on, submit) {
|
|
429
|
+
if (!on)
|
|
430
|
+
return [];
|
|
431
|
+
// Com a lista de completions aberta o Enter é dela (o keymap do autocomplete vem antes); se ela acabou de abrir
|
|
432
|
+
// e ainda ignora o Enter, ele não envia a meia variável.
|
|
433
|
+
const run = (view) => {
|
|
434
|
+
if (autocomplete.completionStatus(view.state) !== "active")
|
|
435
|
+
submit();
|
|
436
|
+
return true;
|
|
437
|
+
};
|
|
438
|
+
return [
|
|
439
|
+
view.EditorView.editorAttributes.of({ class: "cm-ark-single-line" }),
|
|
440
|
+
view.EditorView.contentAttributes.of({ "aria-multiline": "false" }),
|
|
441
|
+
state.EditorState.transactionFilter.of(joinLines),
|
|
442
|
+
state.Prec.high(view.keymap.of([
|
|
443
|
+
{ key: "Enter", run, shift: run },
|
|
444
|
+
{ key: "Mod-Enter", run }
|
|
445
|
+
]))
|
|
446
|
+
];
|
|
447
|
+
}
|
|
244
448
|
// --- Recuo, fim de linha e formatação ---
|
|
245
449
|
function indentExtensions(style, size) {
|
|
246
450
|
const width = Math.max(1, Math.min(16, Math.floor(size) || 2));
|
|
@@ -262,15 +466,15 @@ function completionsSource(items) {
|
|
|
262
466
|
return { from: word ? word.from : context.pos, options: items, validFor: /^[\w$.-]*$/ };
|
|
263
467
|
};
|
|
264
468
|
}
|
|
265
|
-
function completionExtensions(on,
|
|
469
|
+
function completionExtensions(on, variables, items, source) {
|
|
266
470
|
if (!on)
|
|
267
471
|
return [];
|
|
268
472
|
// languageData é o que o autocompletion consulta no cursor: assim as fontes valem em qualquer linguagem. Cada
|
|
269
473
|
// fonte é criada uma vez por configuração: o autocompletion identifica a consulta pela identidade da função, e
|
|
270
474
|
// uma nova a cada leitura deixaria a completion pendente para sempre.
|
|
271
475
|
const sources = [];
|
|
272
|
-
if (
|
|
273
|
-
sources.push({ autocomplete: variableSource(
|
|
476
|
+
if (variables.length > 0)
|
|
477
|
+
sources.push({ autocomplete: variableSource(variables) });
|
|
274
478
|
if (items.length > 0)
|
|
275
479
|
sources.push({ autocomplete: completionsSource(items) });
|
|
276
480
|
if (source)
|
|
@@ -291,7 +495,8 @@ function formatJson(value, unit) {
|
|
|
291
495
|
* fechamento de pares, realce da linha ativa (só editável), busca por Ctrl+F, completions (da linguagem, de
|
|
292
496
|
* `variableKeys`, de `completions` e de `completionSource`), Tab para recuar com saída por Esc+Tab, recuo por
|
|
293
497
|
* 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.
|
|
498
|
+
* `formatter` do app) e tema pelos tokens. Opcionais, ligados só pelas opções: `variables` pintadas por intent com
|
|
499
|
+
* tooltip, `markUnknownVariables` e o campo `singleLine`.
|
|
295
500
|
*/
|
|
296
501
|
function createCodeEditor(parent, options = {}) {
|
|
297
502
|
const language$1 = new state.Compartment();
|
|
@@ -304,6 +509,9 @@ function createCodeEditor(parent, options = {}) {
|
|
|
304
509
|
const indentation = new state.Compartment();
|
|
305
510
|
const tabKey = new state.Compartment();
|
|
306
511
|
const completion = new state.Compartment();
|
|
512
|
+
const variableMarks = new state.Compartment();
|
|
513
|
+
const lineMode = new state.Compartment();
|
|
514
|
+
const searchKeys = new state.Compartment();
|
|
307
515
|
let resolved = resolveCodeTheme(options.theme ?? "auto", parent);
|
|
308
516
|
let applying = false;
|
|
309
517
|
let currentLanguage = options.language ?? "text";
|
|
@@ -313,20 +521,51 @@ function createCodeEditor(parent, options = {}) {
|
|
|
313
521
|
let detected = detectLineEnding(options.value ?? "");
|
|
314
522
|
let autocomplete$1 = options.autocomplete !== false;
|
|
315
523
|
let variableKeys = options.variableKeys ?? [];
|
|
524
|
+
let variables = normalizeVariables(options.variables ?? []);
|
|
525
|
+
let markUnknown = options.markUnknownVariables === true;
|
|
316
526
|
let completions = options.completions ?? [];
|
|
317
527
|
let completionSource = options.completionSource;
|
|
318
528
|
let formatter = options.formatter;
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
529
|
+
let readonlyOn = options.readonly === true;
|
|
530
|
+
let lineNumbersOn = options.lineNumbers !== false;
|
|
531
|
+
let foldOn = options.fold !== false;
|
|
532
|
+
let tabIndentOn = options.tabIndent !== false;
|
|
533
|
+
let singleLine = options.singleLine === true;
|
|
534
|
+
// Em `singleLine` calhas, linha ativa, recuo por Tab e busca ficam desligados, seja qual for a opção de cada um;
|
|
535
|
+
// desligar o modo devolve o que as opções pedem.
|
|
536
|
+
const readonlyExtensions = () => [
|
|
537
|
+
state.EditorState.readOnly.of(readonlyOn),
|
|
538
|
+
view.EditorView.editable.of(!readonlyOn),
|
|
539
|
+
readonlyOn || singleLine ? [] : [view.highlightActiveLine(), view.highlightActiveLineGutter()]
|
|
540
|
+
];
|
|
541
|
+
const numbersExtension = () => (lineNumbersOn && !singleLine ? view.lineNumbers() : []);
|
|
542
|
+
const foldExtension = () => (foldOn && !singleLine ? language.foldGutter() : []);
|
|
543
|
+
const tabExtension = () => tabExtensions(tabIndentOn && !singleLine);
|
|
544
|
+
const searchExtension = () => (singleLine ? [] : view.keymap.of(search.searchKeymap));
|
|
545
|
+
const lineModeExtension = () => singleLineExtensions(singleLine, () => options.onSubmit?.(view$1.state.doc.toString().split("\n").join(eol())));
|
|
546
|
+
// Variáveis com escopo primeiro; as `variableKeys` que elas não cobrem entram só como completion.
|
|
547
|
+
const variableEntries = () => [
|
|
548
|
+
...variables.values(),
|
|
549
|
+
...variableKeys.filter((key) => !variables.has(key)).map((key) => ({ key, intent: "primary" }))
|
|
323
550
|
];
|
|
551
|
+
const marksExtension = () => variableExtensions(variables, new Set(variableKeys), markUnknown);
|
|
324
552
|
const reconfigureCompletion = () => {
|
|
325
553
|
view$1.dispatch({
|
|
326
|
-
effects: completion.reconfigure(completionExtensions(autocomplete$1,
|
|
554
|
+
effects: completion.reconfigure(completionExtensions(autocomplete$1, variableEntries(), completions, completionSource))
|
|
327
555
|
});
|
|
328
556
|
};
|
|
329
557
|
const eol = () => ((lineEnding === "auto" ? detected : lineEnding) === "crlf" ? "\r\n" : "\n");
|
|
558
|
+
// Texto como o documento guarda: sempre LF e, em `singleLine`, sem quebras.
|
|
559
|
+
const toDoc = (value) => {
|
|
560
|
+
const text = normalizeNewlines(value);
|
|
561
|
+
return singleLine ? text.replace(/\n/g, "") : text;
|
|
562
|
+
};
|
|
563
|
+
const applySize = (size) => {
|
|
564
|
+
const scale = SIZES[size];
|
|
565
|
+
view$1.dom.style.setProperty("--ark-code-font-size", scale.font);
|
|
566
|
+
view$1.dom.style.setProperty("--ark-code-padding-x", scale.paddingX);
|
|
567
|
+
view$1.dom.style.setProperty("--ark-code-control-height", `var(--ark-size-${size}, ${tokens.ARK_SIZE_CSS[size]})`);
|
|
568
|
+
};
|
|
330
569
|
const format = async () => {
|
|
331
570
|
const source = view$1.state.doc.toString();
|
|
332
571
|
try {
|
|
@@ -358,10 +597,10 @@ function createCodeEditor(parent, options = {}) {
|
|
|
358
597
|
}
|
|
359
598
|
};
|
|
360
599
|
const state$1 = state.EditorState.create({
|
|
361
|
-
doc:
|
|
600
|
+
doc: toDoc(options.value ?? ""),
|
|
362
601
|
extensions: [
|
|
363
|
-
gutterNumbers.of(
|
|
364
|
-
gutterFold.of(
|
|
602
|
+
gutterNumbers.of(numbersExtension()),
|
|
603
|
+
gutterFold.of(foldExtension()),
|
|
365
604
|
view.highlightSpecialChars(),
|
|
366
605
|
commands.history(),
|
|
367
606
|
view.drawSelection(),
|
|
@@ -376,7 +615,6 @@ function createCodeEditor(parent, options = {}) {
|
|
|
376
615
|
view.keymap.of([
|
|
377
616
|
...autocomplete.closeBracketsKeymap,
|
|
378
617
|
...commands.defaultKeymap,
|
|
379
|
-
...search.searchKeymap,
|
|
380
618
|
...commands.historyKeymap,
|
|
381
619
|
...language.foldKeymap,
|
|
382
620
|
...autocomplete.completionKeymap,
|
|
@@ -388,14 +626,18 @@ function createCodeEditor(parent, options = {}) {
|
|
|
388
626
|
}
|
|
389
627
|
}
|
|
390
628
|
]),
|
|
629
|
+
// A busca fica num keymap à parte, depois do principal, para sair em `singleLine`.
|
|
630
|
+
searchKeys.of(searchExtension()),
|
|
391
631
|
language$1.of(languageFor(currentLanguage)),
|
|
392
632
|
theme.of(themeFor(resolved)),
|
|
393
|
-
readonly.of(readonlyExtensions(
|
|
633
|
+
readonly.of(readonlyExtensions()),
|
|
394
634
|
placeholder.of(options.placeholder ? view.placeholder(options.placeholder) : []),
|
|
395
635
|
wrapping.of(options.wrap ? view.EditorView.lineWrapping : []),
|
|
396
636
|
indentation.of(indentExtensions(indentStyle, indentSize)),
|
|
397
|
-
tabKey.of(
|
|
398
|
-
completion.of(completionExtensions(autocomplete$1,
|
|
637
|
+
tabKey.of(tabExtension()),
|
|
638
|
+
completion.of(completionExtensions(autocomplete$1, variableEntries(), completions, completionSource)),
|
|
639
|
+
variableMarks.of(marksExtension()),
|
|
640
|
+
lineMode.of(lineModeExtension()),
|
|
399
641
|
view.EditorView.updateListener.of((update) => {
|
|
400
642
|
if (update.docChanged && !applying)
|
|
401
643
|
options.onChange?.(update.state.doc.toString().split("\n").join(eol()));
|
|
@@ -404,12 +646,13 @@ function createCodeEditor(parent, options = {}) {
|
|
|
404
646
|
});
|
|
405
647
|
const view$1 = new view.EditorView({ state: state$1, parent });
|
|
406
648
|
view$1.dom.style.setProperty("--ark-code-min-height", options.minHeight ?? "8rem");
|
|
649
|
+
applySize(normalizeSize(options.size));
|
|
407
650
|
return {
|
|
408
651
|
view: view$1,
|
|
409
652
|
getValue: () => view$1.state.doc.toString().split("\n").join(eol()),
|
|
410
653
|
setValue: (value) => {
|
|
411
654
|
detected = detectLineEnding(value);
|
|
412
|
-
const text =
|
|
655
|
+
const text = toDoc(value);
|
|
413
656
|
if (text === view$1.state.doc.toString())
|
|
414
657
|
return;
|
|
415
658
|
applying = true;
|
|
@@ -431,10 +674,19 @@ function createCodeEditor(parent, options = {}) {
|
|
|
431
674
|
resolved = side;
|
|
432
675
|
view$1.dispatch({ effects: theme.reconfigure(themeFor(side)) });
|
|
433
676
|
},
|
|
434
|
-
setReadonly: (on) =>
|
|
677
|
+
setReadonly: (on) => {
|
|
678
|
+
readonlyOn = on;
|
|
679
|
+
view$1.dispatch({ effects: readonly.reconfigure(readonlyExtensions()) });
|
|
680
|
+
},
|
|
435
681
|
setPlaceholder: (text) => view$1.dispatch({ effects: placeholder.reconfigure(text ? view.placeholder(text) : []) }),
|
|
436
|
-
setLineNumbers: (on) =>
|
|
437
|
-
|
|
682
|
+
setLineNumbers: (on) => {
|
|
683
|
+
lineNumbersOn = on;
|
|
684
|
+
view$1.dispatch({ effects: gutterNumbers.reconfigure(numbersExtension()) });
|
|
685
|
+
},
|
|
686
|
+
setFold: (on) => {
|
|
687
|
+
foldOn = on;
|
|
688
|
+
view$1.dispatch({ effects: gutterFold.reconfigure(foldExtension()) });
|
|
689
|
+
},
|
|
438
690
|
setWrap: (on) => view$1.dispatch({ effects: wrapping.reconfigure(on ? view.EditorView.lineWrapping : []) }),
|
|
439
691
|
setMinHeight: (value) => view$1.dom.style.setProperty("--ark-code-min-height", value),
|
|
440
692
|
setIndent: (style, size) => {
|
|
@@ -446,7 +698,10 @@ function createCodeEditor(parent, options = {}) {
|
|
|
446
698
|
lineEnding = next;
|
|
447
699
|
},
|
|
448
700
|
resolvedLineEnding: () => (lineEnding === "auto" ? detected : lineEnding),
|
|
449
|
-
setTabIndent: (on) =>
|
|
701
|
+
setTabIndent: (on) => {
|
|
702
|
+
tabIndentOn = on;
|
|
703
|
+
view$1.dispatch({ effects: tabKey.reconfigure(tabExtension()) });
|
|
704
|
+
},
|
|
450
705
|
setAutocomplete: (on) => {
|
|
451
706
|
autocomplete$1 = on;
|
|
452
707
|
reconfigureCompletion();
|
|
@@ -454,7 +709,47 @@ function createCodeEditor(parent, options = {}) {
|
|
|
454
709
|
setVariableKeys: (keys) => {
|
|
455
710
|
variableKeys = keys;
|
|
456
711
|
reconfigureCompletion();
|
|
712
|
+
// As chaves só completam, mas contam como conhecidas para a marcação das desconhecidas.
|
|
713
|
+
view$1.dispatch({ effects: variableMarks.reconfigure(marksExtension()) });
|
|
457
714
|
},
|
|
715
|
+
setVariables: (next) => {
|
|
716
|
+
variables = normalizeVariables(next);
|
|
717
|
+
reconfigureCompletion();
|
|
718
|
+
view$1.dispatch({ effects: variableMarks.reconfigure(marksExtension()) });
|
|
719
|
+
},
|
|
720
|
+
setMarkUnknownVariables: (on) => {
|
|
721
|
+
markUnknown = on;
|
|
722
|
+
view$1.dispatch({ effects: variableMarks.reconfigure(marksExtension()) });
|
|
723
|
+
},
|
|
724
|
+
setSingleLine: (on) => {
|
|
725
|
+
if (on === singleLine)
|
|
726
|
+
return;
|
|
727
|
+
singleLine = on;
|
|
728
|
+
if (on)
|
|
729
|
+
search.closeSearchPanel(view$1);
|
|
730
|
+
view$1.dispatch({
|
|
731
|
+
effects: [
|
|
732
|
+
lineMode.reconfigure(lineModeExtension()),
|
|
733
|
+
searchKeys.reconfigure(searchExtension()),
|
|
734
|
+
readonly.reconfigure(readonlyExtensions()),
|
|
735
|
+
gutterNumbers.reconfigure(numbersExtension()),
|
|
736
|
+
gutterFold.reconfigure(foldExtension()),
|
|
737
|
+
tabKey.reconfigure(tabExtension())
|
|
738
|
+
]
|
|
739
|
+
});
|
|
740
|
+
// O filtro só age nas próximas edições: o texto que já estava junta aqui, como um `setValue`.
|
|
741
|
+
const text = view$1.state.doc.toString();
|
|
742
|
+
if (!on || !text.includes("\n"))
|
|
743
|
+
return;
|
|
744
|
+
applying = true;
|
|
745
|
+
try {
|
|
746
|
+
view$1.dispatch({ changes: { from: 0, to: text.length, insert: toDoc(text) } });
|
|
747
|
+
}
|
|
748
|
+
finally {
|
|
749
|
+
applying = false;
|
|
750
|
+
}
|
|
751
|
+
},
|
|
752
|
+
setSize: (size) => applySize(normalizeSize(size)),
|
|
458
753
|
setCompletions: (items) => {
|
|
459
754
|
completions = items;
|
|
460
755
|
reconfigureCompletion();
|
|
@@ -474,6 +769,13 @@ function createCodeEditor(parent, options = {}) {
|
|
|
474
769
|
};
|
|
475
770
|
}
|
|
476
771
|
|
|
772
|
+
// Base dos Custom Elements que também carrega fora do navegador. No SSR (Node, Angular SSR, Next, Nuxt) não existe
|
|
773
|
+
// HTMLElement, e um `extends HTMLElement` no topo do módulo derrubaria o import de quem só renderiza o HTML; lá a
|
|
774
|
+
// base é uma classe vazia, e os elementos só passam a existir no cliente, quando registerTooark*() os define.
|
|
775
|
+
/** `HTMLElement` no navegador; fora dele, uma classe vazia para o módulo poder ser importado no servidor. */
|
|
776
|
+
const HTMLElementBase = typeof HTMLElement === "undefined" ? class {
|
|
777
|
+
} : HTMLElement;
|
|
778
|
+
|
|
477
779
|
// Mesma regra do coerceBooleanAttr de @tooark/core (este pacote só depende de tokens): frameworks passam o valor do
|
|
478
780
|
// atributo como propriedade, então "" é presente e "false" é ausente.
|
|
479
781
|
function truthy(value) {
|
|
@@ -501,14 +803,21 @@ function truthy(value) {
|
|
|
501
803
|
* acompanha a troca em tempo de execução (`observeColorScheme` de
|
|
502
804
|
* @tooark/tokens). O nó do CodeMirror leva `data-ark="code-editor"` e o
|
|
503
805
|
* `testid` como `data-testid`.
|
|
806
|
+
*
|
|
807
|
+
* Opcionais, desligados até o app pedir: a propriedade `variables` pinta
|
|
808
|
+
* cada `{{chave}}` pelo intent da variável, com tooltip do escopo e do valor;
|
|
809
|
+
* `mark-unknown-variables` pinta em `danger` a chave desconhecida;
|
|
810
|
+
* `single-line` vira um campo de uma linha na altura dos controles (`size`),
|
|
811
|
+
* com Enter emitindo `ark-submit` (`detail: { value }`).
|
|
504
812
|
*/
|
|
505
|
-
class ArkCodeEditor extends
|
|
813
|
+
class ArkCodeEditor extends HTMLElementBase {
|
|
506
814
|
constructor() {
|
|
507
815
|
super(...arguments);
|
|
508
816
|
this.instance = null;
|
|
509
817
|
/** Texto antes de montar, ou o último conhecido depois de desmontar. */
|
|
510
818
|
this.pendingValue = "";
|
|
511
819
|
this.keys = [];
|
|
820
|
+
this.vars = [];
|
|
512
821
|
this.items = [];
|
|
513
822
|
/** Para de observar o tema da página; só existe com `theme="auto"`. */
|
|
514
823
|
this.disposeTheme = null;
|
|
@@ -527,6 +836,9 @@ class ArkCodeEditor extends HTMLElement {
|
|
|
527
836
|
"line-ending",
|
|
528
837
|
"tab-indent",
|
|
529
838
|
"autocomplete",
|
|
839
|
+
"mark-unknown-variables",
|
|
840
|
+
"single-line",
|
|
841
|
+
"size",
|
|
530
842
|
"theme",
|
|
531
843
|
"testid"
|
|
532
844
|
];
|
|
@@ -548,6 +860,38 @@ class ArkCodeEditor extends HTMLElement {
|
|
|
548
860
|
this.keys = Array.isArray(next) ? next.filter((key) => typeof key === "string" && key.length > 0) : [];
|
|
549
861
|
this.instance?.setVariableKeys(this.keys);
|
|
550
862
|
}
|
|
863
|
+
/** Variáveis com escopo e cor (propriedade JS): completam depois de `{{` e pintam o `{{chave}}` no texto. */
|
|
864
|
+
get variables() {
|
|
865
|
+
return this.vars.map((variable) => ({ ...variable }));
|
|
866
|
+
}
|
|
867
|
+
set variables(next) {
|
|
868
|
+
this.vars = Array.isArray(next)
|
|
869
|
+
? next.filter((variable) => variable && typeof variable.key === "string" && variable.key.length > 0)
|
|
870
|
+
: [];
|
|
871
|
+
this.instance?.setVariables(this.vars);
|
|
872
|
+
}
|
|
873
|
+
/** Pinta em `danger` o `{{chave}}` fora de `variables` e `variableKeys` (atributo `mark-unknown-variables`). */
|
|
874
|
+
get markUnknownVariables() {
|
|
875
|
+
return this.hasAttribute("mark-unknown-variables");
|
|
876
|
+
}
|
|
877
|
+
set markUnknownVariables(value) {
|
|
878
|
+
this.toggleAttribute("mark-unknown-variables", truthy(value));
|
|
879
|
+
}
|
|
880
|
+
/** Campo de uma linha na altura dos controles (atributo `single-line`); Enter emite `ark-submit`. */
|
|
881
|
+
get singleLine() {
|
|
882
|
+
return this.hasAttribute("single-line");
|
|
883
|
+
}
|
|
884
|
+
set singleLine(value) {
|
|
885
|
+
this.toggleAttribute("single-line", truthy(value));
|
|
886
|
+
}
|
|
887
|
+
/** Escala da fonte e do recuo; em `single-line`, também a altura (atributo `size`). Padrão: "md". */
|
|
888
|
+
get size() {
|
|
889
|
+
const value = (this.getAttribute("size") || "md").toLowerCase();
|
|
890
|
+
return Object.keys(tokens.ARK_SIZE_CSS).includes(value) ? value : "md";
|
|
891
|
+
}
|
|
892
|
+
set size(value) {
|
|
893
|
+
this.setAttribute("size", value);
|
|
894
|
+
}
|
|
551
895
|
/** Palavras oferecidas como completion em qualquer linguagem (propriedade JS, formato do CodeMirror). */
|
|
552
896
|
get completions() {
|
|
553
897
|
return [...this.items];
|
|
@@ -721,6 +1065,12 @@ class ArkCodeEditor extends HTMLElement {
|
|
|
721
1065
|
this.instance.setTabIndent(this.tabIndent);
|
|
722
1066
|
if (name === "autocomplete")
|
|
723
1067
|
this.instance.setAutocomplete(this.autocomplete);
|
|
1068
|
+
if (name === "mark-unknown-variables")
|
|
1069
|
+
this.instance.setMarkUnknownVariables(this.markUnknownVariables);
|
|
1070
|
+
if (name === "single-line")
|
|
1071
|
+
this.instance.setSingleLine(this.singleLine);
|
|
1072
|
+
if (name === "size")
|
|
1073
|
+
this.instance.setSize(this.size);
|
|
724
1074
|
if (name === "theme") {
|
|
725
1075
|
this.instance.setTheme(this.theme);
|
|
726
1076
|
this.syncThemeObserver();
|
|
@@ -759,6 +1109,10 @@ class ArkCodeEditor extends HTMLElement {
|
|
|
759
1109
|
tabIndent: this.tabIndent,
|
|
760
1110
|
autocomplete: this.autocomplete,
|
|
761
1111
|
variableKeys: this.keys,
|
|
1112
|
+
variables: this.vars,
|
|
1113
|
+
markUnknownVariables: this.markUnknownVariables,
|
|
1114
|
+
singleLine: this.singleLine,
|
|
1115
|
+
size: this.size,
|
|
762
1116
|
completions: this.items,
|
|
763
1117
|
completionSource: this.source,
|
|
764
1118
|
formatter: this.formatFn,
|
|
@@ -766,6 +1120,9 @@ class ArkCodeEditor extends HTMLElement {
|
|
|
766
1120
|
this.pendingValue = value;
|
|
767
1121
|
this.dispatchEvent(new CustomEvent("change", { detail: { value }, bubbles: true, composed: true }));
|
|
768
1122
|
},
|
|
1123
|
+
onSubmit: (value) => {
|
|
1124
|
+
this.dispatchEvent(new CustomEvent("ark-submit", { detail: { value }, bubbles: true, composed: true }));
|
|
1125
|
+
},
|
|
769
1126
|
onFormatError: (error) => {
|
|
770
1127
|
this.dispatchEvent(new CustomEvent("ark-format-error", { detail: { error }, bubbles: true, composed: true }));
|
|
771
1128
|
}
|
|
@@ -812,6 +1169,9 @@ ArkCodeEditor.tagName = "ark-code-editor";
|
|
|
812
1169
|
* Chame antes de usar o componente em qualquer ambiente (puro, React, Angular, Vue).
|
|
813
1170
|
*/
|
|
814
1171
|
function registerTooarkCode() {
|
|
1172
|
+
// Fora do navegador (SSR) não há registro de elementos: no-op, e o cliente registra na hidratação.
|
|
1173
|
+
if (typeof customElements === "undefined")
|
|
1174
|
+
return;
|
|
815
1175
|
if (!customElements.get(ArkCodeEditor.tagName)) {
|
|
816
1176
|
customElements.define(ArkCodeEditor.tagName, ArkCodeEditor);
|
|
817
1177
|
}
|