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