@tooark/code 1.5.0 → 1.6.1
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 +45 -5
- package/README.pt-BR.md +45 -5
- package/dist/index.cjs +29 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +26 -3
- package/dist/index.d.ts +26 -3
- package/dist/index.js +29 -3
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -31,7 +31,7 @@ The `@tooark/code` package provides:
|
|
|
31
31
|
- `language` json / javascript / yaml / text, line numbers, folding, search (Ctrl+F), bracket matching, active line, placeholder, `readonly`, `wrap`, `min-height`;
|
|
32
32
|
- Tab indents (Shift+Tab outdents; Esc then Tab leaves the editor), `indent-style` spaces or tabs, `indent-size`, `line-ending` `auto`/`lf`/`crlf` converted at the value boundary;
|
|
33
33
|
- completions: the language's own, `variableKeys` after `{{`, `completions` (words in any language) and `completionSource`; `autocomplete="false"` turns them off;
|
|
34
|
-
- optional, off until you pass them: `variables` paints each `{{key}}` with its variable's intent (free-form scope, hover tooltip with scope and value), `mark-unknown-variables` flags keys that are not defined,
|
|
34
|
+
- optional, off until you pass them: `variables` paints each `{{key}}` with its variable's intent (free-form scope, hover tooltip with scope and value), `mark-unknown-variables` flags keys that are not defined, `single-line` turns the editor into a one-line field at control height (`size`), Enter emitting `ark-submit`, and `extensions` adds your own CodeMirror extensions after the library's (a grammar it does not ship, a blame gutter, decorations);
|
|
35
35
|
- `format()` and Shift+Alt+F: JSON built in with the configured indentation, other languages through the `formatter` hook (Prettier stays in the app);
|
|
36
36
|
- chrome on the `--ark-color-*` tokens with fallbacks, `theme="auto"` following the page at runtime; `createCodeEditor` engine without the element;
|
|
37
37
|
- CodeMirror packages as peer dependencies, so the page keeps one copy of `@codemirror/state`.
|
|
@@ -67,7 +67,7 @@ In React, Vue or Angular use the tag directly (the framework READMEs show how);
|
|
|
67
67
|
### `ark-code-editor`
|
|
68
68
|
|
|
69
69
|
- Attributes: `language` (`json` | `javascript` | `yaml` | `text`), `readonly`, `placeholder`, `min-height` (default `8rem`), `line-numbers` and `fold` (on; `"false"` turns off), `wrap`, `indent-style` (`space` | `tab`), `indent-size` (default 2), `line-ending` (`auto` | `lf` | `crlf`), `tab-indent` and `autocomplete` (on; `"false"` turns off), `mark-unknown-variables`, `single-line`, `size` (`xs` … `xl`, default `md`: font and side padding, plus the height in `single-line`), `theme`, `aria-label` (names the editable content, CodeMirror's `role="textbox"`), `testid`.
|
|
70
|
-
- Properties: `value`, `variableKeys`, `variables`, `completions`, `completionSource`, `formatter`, `canFormat`, `resolvedLineEnding`, `resolvedTheme`, `view` (the `EditorView`), and one per attribute except `aria-label` and `testid`; methods `format()`, `focus()`.
|
|
70
|
+
- Properties: `value`, `variableKeys`, `variables`, `completions`, `completionSource`, `formatter`, `extensions`, `canFormat`, `resolvedLineEnding`, `resolvedTheme`, `view` (the `EditorView`), and one per attribute except `aria-label` and `testid`; methods `format()`, `focus()`.
|
|
71
71
|
- Events: `change` (`detail: { value }`, user edits only), `ark-format-error` (`detail: { error }`), `ark-submit` (`detail: { value }`, Enter in `single-line`).
|
|
72
72
|
- Keys: Ctrl/Cmd+F search, Ctrl/Cmd+Z undo, Ctrl+Y redo (Cmd+Shift+Z on macOS), Ctrl+Space completions, Shift+Alt+F format, Tab/Shift+Tab indent, Esc+Tab leave, Ctrl+M (Shift+Alt+M on macOS) toggles CodeMirror's tab-focus mode.
|
|
73
73
|
- Hooks: the CodeMirror root carries `data-ark="code-editor"` and the `testid` as `data-testid`; each painted variable `data-ark="code-editor-variable"` with `data-key`; its tooltip `data-ark="code-editor-variable-tooltip"`.
|
|
@@ -85,11 +85,21 @@ Nothing changes until the app passes `variables` or sets `mark-unknown-variables
|
|
|
85
85
|
|
|
86
86
|
`single-line` makes a field such as a URL bar: the height of the controls of the same `size` (it lines up with `ark-button` and `ark-input`), no gutters and no active line, Enter emits `ark-submit` instead of breaking the line (when the completion list is open, Enter accepts the completion), pasted line breaks are removed as in an `<input>`, Tab leaves the field and Ctrl/Cmd+F is left to the browser. Turning it on over a multi-line text joins the lines without a `change`. Variables and completions work the same.
|
|
87
87
|
|
|
88
|
+
### App extensions
|
|
89
|
+
|
|
90
|
+
Nothing changes until the app assigns `extensions`, a JS property taking CodeMirror extensions (`ArkCodeExtension`, CodeMirror's `Extension`: one or a list).
|
|
91
|
+
|
|
92
|
+
- They come after the library's own: at the same precedence, the library's keymaps, gutters and language go first. Wrap one in `Prec.high` (from `@codemirror/state`) to put it before them, such as a blame gutter to the left of the line numbers.
|
|
93
|
+
- A grammar the library does not ship (`@codemirror/language-data` picks one by file name and loads only that one) needs `language="text"`, the default: with `json`, `javascript` or `yaml` the library's grammar wins. It is highlighted with the library's syntax colors. The editor still sees `text`, so `canFormat` is false unless a `formatter` is set, and the formatter receives `"text"`.
|
|
94
|
+
- Assigning a new value reconfigures the same editor (text, history and selection stay); assigning the same reference does nothing, so keep it stable (module scope, or `useMemo` in React). `null` or `[]` removes them, and they stay when the element moves in the DOM.
|
|
95
|
+
- Build them from the same `@codemirror/*` copies the editor uses (they are peer dependencies): a second `@codemirror/state` throws "Unrecognized extension value", and a grammar from a second `@codemirror/language` is not highlighted.
|
|
96
|
+
- In `single-line` the app's extensions stay on: leave gutters out of a one-line field.
|
|
97
|
+
|
|
88
98
|
### Engine
|
|
89
99
|
|
|
90
|
-
- `createCodeEditor(parent, options)` → `{ view, getValue, setValue, setLanguage, setTheme, setReadonly, setPlaceholder, setLineNumbers, setFold, setWrap, setMinHeight, setIndent, setLineEnding, resolvedLineEnding, setTabIndent, setAutocomplete, setVariableKeys, setVariables, setMarkUnknownVariables, setSingleLine, setSize, setCompletions, setCompletionSource, setFormatter, format, canFormat, resolvedTheme, focus, destroy }`; the options mirror the attributes and properties, plus `onChange`, `onFormatError` and `onSubmit`.
|
|
100
|
+
- `createCodeEditor(parent, options)` → `{ view, getValue, setValue, setLanguage, setTheme, setReadonly, setPlaceholder, setLineNumbers, setFold, setWrap, setMinHeight, setIndent, setLineEnding, resolvedLineEnding, setTabIndent, setAutocomplete, setVariableKeys, setVariables, setMarkUnknownVariables, setSingleLine, setSize, setCompletions, setCompletionSource, setFormatter, setExtensions, format, canFormat, resolvedTheme, focus, destroy }`; the options mirror the attributes and properties, plus `onChange`, `onFormatError` and `onSubmit`.
|
|
91
101
|
- `resolveCodeTheme(theme, element)`.
|
|
92
|
-
- Types: `ArkCodeEditorInstance`, `ArkCodeEditorOptions`, `ArkCodeVariable`, `ArkCodeLanguage`, `ArkCodeTheme`, `ArkCodeIndentStyle`, `ArkCodeLineEnding`, `ArkCodeCompletion`, `ArkCodeCompletionSource`, `ArkCodeFormatter`.
|
|
102
|
+
- Types: `ArkCodeEditorInstance`, `ArkCodeEditorOptions`, `ArkCodeVariable`, `ArkCodeLanguage`, `ArkCodeTheme`, `ArkCodeIndentStyle`, `ArkCodeLineEnding`, `ArkCodeCompletion`, `ArkCodeCompletionSource`, `ArkCodeFormatter`, `ArkCodeExtension`.
|
|
93
103
|
|
|
94
104
|
---
|
|
95
105
|
|
|
@@ -152,6 +162,36 @@ editor.formatter = (value) => dump(load(value), { indent: editor.indentSize });
|
|
|
152
162
|
editor.addEventListener("ark-format-error", (event) => toast.error(String((event as CustomEvent).detail.error)));
|
|
153
163
|
```
|
|
154
164
|
|
|
165
|
+
### A code viewer with any language and a blame gutter
|
|
166
|
+
|
|
167
|
+
```ts
|
|
168
|
+
import { LanguageDescription } from "@codemirror/language";
|
|
169
|
+
import { languages } from "@codemirror/language-data"; // your dependency, not the library's
|
|
170
|
+
import { Prec } from "@codemirror/state";
|
|
171
|
+
import { GutterMarker, gutter } from "@codemirror/view";
|
|
172
|
+
|
|
173
|
+
class Author extends GutterMarker {
|
|
174
|
+
constructor(readonly text: string) {
|
|
175
|
+
super();
|
|
176
|
+
}
|
|
177
|
+
toDOM() {
|
|
178
|
+
return document.createTextNode(this.text);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const viewer = document.querySelector("ark-code-editor")!; // readonly, language left at "text"
|
|
183
|
+
const grammar = await LanguageDescription.matchFilename(languages, file.path)?.load(); // loads only this one
|
|
184
|
+
const blame = gutter({
|
|
185
|
+
class: "blame",
|
|
186
|
+
lineMarker: (view, line) => {
|
|
187
|
+
const author = file.blame.get(view.state.doc.lineAt(line.from).number);
|
|
188
|
+
return author ? new Author(author) : null;
|
|
189
|
+
},
|
|
190
|
+
});
|
|
191
|
+
viewer.extensions = [grammar ?? [], Prec.high(blame)]; // Prec.high: left of the line numbers
|
|
192
|
+
viewer.value = file.content;
|
|
193
|
+
```
|
|
194
|
+
|
|
155
195
|
---
|
|
156
196
|
|
|
157
197
|
## 📋 Dependencies
|
|
@@ -160,7 +200,7 @@ Installed automatically unless marked as peer; peer dependencies are yours to in
|
|
|
160
200
|
|
|
161
201
|
| Package | Version | Description |
|
|
162
202
|
| ------------------------------------------------------------------------------------------ | ------------- | --------------------------------------------------------- |
|
|
163
|
-
| [`@tooark/tokens`](https://www.npmjs.com/package/@tooark/tokens) | ^1.
|
|
203
|
+
| [`@tooark/tokens`](https://www.npmjs.com/package/@tooark/tokens) | ^1.6.1 | Design tokens (colors, sizes, motion) and primitive types |
|
|
164
204
|
| [`tslib`](https://www.npmjs.com/package/tslib) | ^2.8.1 | TypeScript runtime helpers |
|
|
165
205
|
| [`@codemirror/autocomplete`](https://www.npmjs.com/package/@codemirror/autocomplete) | >=6 (peer) | Completions and bracket closing |
|
|
166
206
|
| [`@codemirror/commands`](https://www.npmjs.com/package/@codemirror/commands) | >=6.6 (peer) | Keymaps, history, indentation commands |
|
package/README.pt-BR.md
CHANGED
|
@@ -31,7 +31,7 @@ O pacote `@tooark/code` fornece:
|
|
|
31
31
|
- `language` json / javascript / yaml / text, numeração, dobra, busca (Ctrl+F), pares de colchetes, linha ativa, placeholder, `readonly`, `wrap`, `min-height`;
|
|
32
32
|
- Tab recua (Shift+Tab desfaz; Esc e depois Tab sai do editor), `indent-style` espaços ou tabulação, `indent-size`, `line-ending` `auto`/`lf`/`crlf` convertido na fronteira do valor;
|
|
33
33
|
- completions: as da linguagem, `variableKeys` depois de `{{`, `completions` (palavras em qualquer linguagem) e `completionSource`; `autocomplete="false"` desliga;
|
|
34
|
-
- opcionais, desligados até você passá-los: `variables` pinta cada `{{chave}}` pelo intent da variável (escopo livre, tooltip com escopo e valor), `mark-unknown-variables` marca as chaves não definidas
|
|
34
|
+
- opcionais, desligados até você passá-los: `variables` pinta cada `{{chave}}` pelo intent da variável (escopo livre, tooltip com escopo e valor), `mark-unknown-variables` marca as chaves não definidas, `single-line` faz do editor um campo de uma linha na altura dos controles (`size`), com Enter emitindo `ark-submit`, e `extensions` soma extensões do CodeMirror suas depois das da biblioteca (uma gramática que ela não traz, uma calha de blame, decorações);
|
|
35
35
|
- `format()` e Shift+Alt+F: JSON de fábrica com o recuo configurado, outras linguagens pelo gancho `formatter` (o Prettier fica no app);
|
|
36
36
|
- chrome sobre os tokens `--ark-color-*` com fallback, `theme="auto"` seguindo a página em tempo de execução; engine `createCodeEditor` sem o elemento;
|
|
37
37
|
- pacotes do CodeMirror como peer dependencies, para a página ter uma cópia de `@codemirror/state`.
|
|
@@ -67,7 +67,7 @@ Em React, Vue ou Angular use a tag diretamente (os READMEs dos wrappers mostram
|
|
|
67
67
|
### `ark-code-editor`
|
|
68
68
|
|
|
69
69
|
- Atributos: `language` (`json` | `javascript` | `yaml` | `text`), `readonly`, `placeholder`, `min-height` (padrão `8rem`), `line-numbers` e `fold` (ligados; `"false"` desliga), `wrap`, `indent-style` (`space` | `tab`), `indent-size` (padrão 2), `line-ending` (`auto` | `lf` | `crlf`), `tab-indent` e `autocomplete` (ligados; `"false"` desliga), `mark-unknown-variables`, `single-line`, `size` (`xs` … `xl`, padrão `md`: fonte e recuo lateral, e a altura em `single-line`), `theme`, `aria-label` (nomeia o conteúdo editável, o `role="textbox"` do CodeMirror), `testid`.
|
|
70
|
-
- Propriedades: `value`, `variableKeys`, `variables`, `completions`, `completionSource`, `formatter`, `canFormat`, `resolvedLineEnding`, `resolvedTheme`, `view` (o `EditorView`), e uma por atributo exceto `aria-label` e `testid`; métodos `format()`, `focus()`.
|
|
70
|
+
- Propriedades: `value`, `variableKeys`, `variables`, `completions`, `completionSource`, `formatter`, `extensions`, `canFormat`, `resolvedLineEnding`, `resolvedTheme`, `view` (o `EditorView`), e uma por atributo exceto `aria-label` e `testid`; métodos `format()`, `focus()`.
|
|
71
71
|
- Eventos: `change` (`detail: { value }`, só edições do usuário), `ark-format-error` (`detail: { error }`), `ark-submit` (`detail: { value }`, Enter em `single-line`).
|
|
72
72
|
- Teclas: Ctrl/Cmd+F busca, Ctrl/Cmd+Z desfazer, Ctrl+Y refazer (Cmd+Shift+Z no macOS), Ctrl+Espaço completions, Shift+Alt+F formatar, Tab/Shift+Tab recuo, Esc+Tab sair, Ctrl+M (Shift+Alt+M no macOS) alterna o modo tab-focus do CodeMirror.
|
|
73
73
|
- Hooks: a raiz do CodeMirror leva `data-ark="code-editor"` e o `testid` como `data-testid`; cada variável pintada, `data-ark="code-editor-variable"` com `data-key`; o tooltip dela, `data-ark="code-editor-variable-tooltip"`.
|
|
@@ -85,11 +85,21 @@ Nada muda até o app passar `variables` ou ligar `mark-unknown-variables`; `vari
|
|
|
85
85
|
|
|
86
86
|
`single-line` faz um campo como a barra de endereço: a altura dos controles do mesmo `size` (alinha com `ark-button` e `ark-input`), sem calhas nem linha ativa, Enter emite `ark-submit` em vez de quebrar a linha (com a lista de completions aberta, o Enter aceita a completion), quebras coladas são removidas como num `<input>`, Tab sai do campo e Ctrl/Cmd+F fica com o navegador. Ligar sobre um texto de várias linhas junta as linhas sem `change`. Variáveis e completions funcionam igual.
|
|
87
87
|
|
|
88
|
+
### Extensões do app
|
|
89
|
+
|
|
90
|
+
Nada muda até o app atribuir `extensions`, uma propriedade JS que recebe extensões do CodeMirror (`ArkCodeExtension`, o `Extension` do CodeMirror: uma ou uma lista).
|
|
91
|
+
|
|
92
|
+
- Elas vêm depois das da biblioteca: na mesma precedência, os keymaps, as calhas e a linguagem dela vêm antes. Envolva uma em `Prec.high` (de `@codemirror/state`) para pô-la antes, como uma calha de blame à esquerda da numeração.
|
|
93
|
+
- Uma gramática que a biblioteca não traz (o `@codemirror/language-data` escolhe uma pelo nome do arquivo e carrega só ela) pede `language="text"`, o padrão: com `json`, `javascript` ou `yaml` a gramática da biblioteca vence. Ela sai com as cores de sintaxe da biblioteca. O editor continua vendo `text`, então `canFormat` fica falso sem um `formatter`, e o formatador recebe `"text"`.
|
|
94
|
+
- Atribuir um valor novo reconfigura o mesmo editor (texto, histórico e seleção ficam); atribuir a mesma referência não faz nada, então mantenha-a estável (no escopo do módulo, ou num `useMemo` no React). `null` ou `[]` remove, e elas continuam quando o elemento muda de lugar no DOM.
|
|
95
|
+
- Monte-as com as mesmas cópias dos pacotes `@codemirror/*` que o editor usa (são peer dependencies): um segundo `@codemirror/state` lança "Unrecognized extension value", e uma gramática de um segundo `@codemirror/language` não é realçada.
|
|
96
|
+
- Em `single-line` as extensões do app continuam valendo: deixe calhas de fora de um campo de uma linha.
|
|
97
|
+
|
|
88
98
|
### Engine
|
|
89
99
|
|
|
90
|
-
- `createCodeEditor(parent, options)` → `{ view, getValue, setValue, setLanguage, setTheme, setReadonly, setPlaceholder, setLineNumbers, setFold, setWrap, setMinHeight, setIndent, setLineEnding, resolvedLineEnding, setTabIndent, setAutocomplete, setVariableKeys, setVariables, setMarkUnknownVariables, setSingleLine, setSize, setCompletions, setCompletionSource, setFormatter, format, canFormat, resolvedTheme, focus, destroy }`; as opções espelham atributos e propriedades, mais `onChange`, `onFormatError` e `onSubmit`.
|
|
100
|
+
- `createCodeEditor(parent, options)` → `{ view, getValue, setValue, setLanguage, setTheme, setReadonly, setPlaceholder, setLineNumbers, setFold, setWrap, setMinHeight, setIndent, setLineEnding, resolvedLineEnding, setTabIndent, setAutocomplete, setVariableKeys, setVariables, setMarkUnknownVariables, setSingleLine, setSize, setCompletions, setCompletionSource, setFormatter, setExtensions, format, canFormat, resolvedTheme, focus, destroy }`; as opções espelham atributos e propriedades, mais `onChange`, `onFormatError` e `onSubmit`.
|
|
91
101
|
- `resolveCodeTheme(theme, element)`.
|
|
92
|
-
- Tipos: `ArkCodeEditorInstance`, `ArkCodeEditorOptions`, `ArkCodeVariable`, `ArkCodeLanguage`, `ArkCodeTheme`, `ArkCodeIndentStyle`, `ArkCodeLineEnding`, `ArkCodeCompletion`, `ArkCodeCompletionSource`, `ArkCodeFormatter`.
|
|
102
|
+
- Tipos: `ArkCodeEditorInstance`, `ArkCodeEditorOptions`, `ArkCodeVariable`, `ArkCodeLanguage`, `ArkCodeTheme`, `ArkCodeIndentStyle`, `ArkCodeLineEnding`, `ArkCodeCompletion`, `ArkCodeCompletionSource`, `ArkCodeFormatter`, `ArkCodeExtension`.
|
|
93
103
|
|
|
94
104
|
---
|
|
95
105
|
|
|
@@ -152,6 +162,36 @@ editor.formatter = (value) => dump(load(value), { indent: editor.indentSize });
|
|
|
152
162
|
editor.addEventListener("ark-format-error", (event) => toast.error(String((event as CustomEvent).detail.error)));
|
|
153
163
|
```
|
|
154
164
|
|
|
165
|
+
### Um visualizador de código com qualquer linguagem e calha de blame
|
|
166
|
+
|
|
167
|
+
```ts
|
|
168
|
+
import { LanguageDescription } from "@codemirror/language";
|
|
169
|
+
import { languages } from "@codemirror/language-data"; // dependência sua, não da biblioteca
|
|
170
|
+
import { Prec } from "@codemirror/state";
|
|
171
|
+
import { GutterMarker, gutter } from "@codemirror/view";
|
|
172
|
+
|
|
173
|
+
class Autor extends GutterMarker {
|
|
174
|
+
constructor(readonly text: string) {
|
|
175
|
+
super();
|
|
176
|
+
}
|
|
177
|
+
toDOM() {
|
|
178
|
+
return document.createTextNode(this.text);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const viewer = document.querySelector("ark-code-editor")!; // readonly, language fica em "text"
|
|
183
|
+
const gramatica = await LanguageDescription.matchFilename(languages, arquivo.caminho)?.load(); // carrega só esta
|
|
184
|
+
const blame = gutter({
|
|
185
|
+
class: "blame",
|
|
186
|
+
lineMarker: (view, line) => {
|
|
187
|
+
const autor = arquivo.blame.get(view.state.doc.lineAt(line.from).number);
|
|
188
|
+
return autor ? new Autor(autor) : null;
|
|
189
|
+
},
|
|
190
|
+
});
|
|
191
|
+
viewer.extensions = [gramatica ?? [], Prec.high(blame)]; // Prec.high: à esquerda da numeração
|
|
192
|
+
viewer.value = arquivo.conteudo;
|
|
193
|
+
```
|
|
194
|
+
|
|
155
195
|
---
|
|
156
196
|
|
|
157
197
|
## 📋 Dependências
|
|
@@ -160,7 +200,7 @@ Instaladas automaticamente, salvo as marcadas como peer, que ficam por sua conta
|
|
|
160
200
|
|
|
161
201
|
| Pacote | Versão | Descrição |
|
|
162
202
|
| ------------------------------------------------------------------------------------------ | ------------- | ---------------------------------------------------------- |
|
|
163
|
-
| [`@tooark/tokens`](https://www.npmjs.com/package/@tooark/tokens) | ^1.
|
|
203
|
+
| [`@tooark/tokens`](https://www.npmjs.com/package/@tooark/tokens) | ^1.6.1 | Design tokens (cores, tamanhos, motion) e tipos primitivos |
|
|
164
204
|
| [`tslib`](https://www.npmjs.com/package/tslib) | ^2.8.1 | Helpers de runtime do TypeScript |
|
|
165
205
|
| [`@codemirror/autocomplete`](https://www.npmjs.com/package/@codemirror/autocomplete) | >=6 (peer) | Completions e fechamento de pares |
|
|
166
206
|
| [`@codemirror/commands`](https://www.npmjs.com/package/@codemirror/commands) | >=6.6 (peer) | Atalhos, histórico, comandos de recuo |
|
package/dist/index.cjs
CHANGED
|
@@ -500,7 +500,7 @@ function formatJson(value, unit) {
|
|
|
500
500
|
* `variableKeys`, de `completions` e de `completionSource`), Tab para recuar com saída por Esc+Tab, recuo por
|
|
501
501
|
* espaços ou tabulação, fim de linha LF/CRLF na fronteira do valor, formatação por Shift+Alt+F (JSON nativo ou o
|
|
502
502
|
* `formatter` do app) e tema pelos tokens. Opcionais, ligados só pelas opções: `variables` pintadas por intent com
|
|
503
|
-
* tooltip, `markUnknownVariables
|
|
503
|
+
* tooltip, `markUnknownVariables`, o campo `singleLine` e as `extensions` do app.
|
|
504
504
|
*/
|
|
505
505
|
function createCodeEditor(parent, options = {}) {
|
|
506
506
|
const language$1 = new state.Compartment();
|
|
@@ -517,6 +517,7 @@ function createCodeEditor(parent, options = {}) {
|
|
|
517
517
|
const variableMarks = new state.Compartment();
|
|
518
518
|
const lineMode = new state.Compartment();
|
|
519
519
|
const searchKeys = new state.Compartment();
|
|
520
|
+
const custom = new state.Compartment();
|
|
520
521
|
let resolved = resolveCodeTheme(options.theme ?? "auto", parent);
|
|
521
522
|
let applying = false;
|
|
522
523
|
let currentLanguage = options.language ?? "text";
|
|
@@ -647,7 +648,10 @@ function createCodeEditor(parent, options = {}) {
|
|
|
647
648
|
view.EditorView.updateListener.of((update) => {
|
|
648
649
|
if (update.docChanged && !applying)
|
|
649
650
|
options.onChange?.(update.state.doc.toString().split("\n").join(eol()));
|
|
650
|
-
})
|
|
651
|
+
}),
|
|
652
|
+
// As do app vêm por último: na mesma precedência, keymaps, calhas e linguagem da lib vêm antes, e quem precisa
|
|
653
|
+
// passar à frente usa `Prec`.
|
|
654
|
+
custom.of(options.extensions ?? [])
|
|
651
655
|
]
|
|
652
656
|
});
|
|
653
657
|
const view$1 = new view.EditorView({ state: state$1, parent });
|
|
@@ -768,6 +772,7 @@ function createCodeEditor(parent, options = {}) {
|
|
|
768
772
|
setFormatter: (next) => {
|
|
769
773
|
formatter = next;
|
|
770
774
|
},
|
|
775
|
+
setExtensions: (next) => view$1.dispatch({ effects: custom.reconfigure(next) }),
|
|
771
776
|
format,
|
|
772
777
|
canFormat: () => formatter !== undefined || currentLanguage === "json",
|
|
773
778
|
resolvedTheme: () => resolved,
|
|
@@ -819,6 +824,8 @@ function truthy(value) {
|
|
|
819
824
|
return false;
|
|
820
825
|
return Boolean(value);
|
|
821
826
|
}
|
|
827
|
+
/** Sem extensões do app; uma referência só, para `null` repetido não reconfigurar o editor. */
|
|
828
|
+
const NO_EXTENSIONS = [];
|
|
822
829
|
/**
|
|
823
830
|
* Custom Element que renderiza um editor de código CodeMirror 6.
|
|
824
831
|
*
|
|
@@ -843,7 +850,9 @@ function truthy(value) {
|
|
|
843
850
|
* cada `{{chave}}` pelo intent da variável, com tooltip do escopo e do valor;
|
|
844
851
|
* `mark-unknown-variables` pinta em `danger` a chave desconhecida;
|
|
845
852
|
* `single-line` vira um campo de uma linha na altura dos controles (`size`),
|
|
846
|
-
* com Enter emitindo `ark-submit` (`detail: { value }`)
|
|
853
|
+
* com Enter emitindo `ark-submit` (`detail: { value }`); a propriedade
|
|
854
|
+
* `extensions` soma extensões do CodeMirror do app (gramáticas que a lib não
|
|
855
|
+
* traz, calhas, decorações) às da lib, sem recriar o editor.
|
|
847
856
|
*/
|
|
848
857
|
class ArkCodeEditor extends HTMLElementBase {
|
|
849
858
|
constructor() {
|
|
@@ -854,6 +863,8 @@ class ArkCodeEditor extends HTMLElementBase {
|
|
|
854
863
|
this.keys = [];
|
|
855
864
|
this.vars = [];
|
|
856
865
|
this.items = [];
|
|
866
|
+
/** Extensões do app como vieram: a mesma referência atribuída de novo não reconfigura o editor. */
|
|
867
|
+
this.exts = NO_EXTENSIONS;
|
|
857
868
|
/** Para de observar o tema da página; só existe com `theme="auto"`. */
|
|
858
869
|
this.disposeTheme = null;
|
|
859
870
|
}
|
|
@@ -952,6 +963,20 @@ class ArkCodeEditor extends HTMLElementBase {
|
|
|
952
963
|
this.formatFn = typeof next === "function" ? next : undefined;
|
|
953
964
|
this.instance?.setFormatter(this.formatFn);
|
|
954
965
|
}
|
|
966
|
+
/**
|
|
967
|
+
* Extensões do CodeMirror do app (propriedade JS), depois das da lib: gramáticas que ela não traz (com `language`
|
|
968
|
+
* em "text"), calhas, decorações. Trocar reconfigura sem recriar o editor; `null` remove.
|
|
969
|
+
*/
|
|
970
|
+
get extensions() {
|
|
971
|
+
return this.exts;
|
|
972
|
+
}
|
|
973
|
+
set extensions(next) {
|
|
974
|
+
const value = next !== null && typeof next === "object" ? next : NO_EXTENSIONS;
|
|
975
|
+
if (value === this.exts)
|
|
976
|
+
return;
|
|
977
|
+
this.exts = value;
|
|
978
|
+
this.instance?.setExtensions(value);
|
|
979
|
+
}
|
|
955
980
|
/** Recuo com espaços ou tabulação (atributo `indent-style`). Padrão: "space". */
|
|
956
981
|
get indentStyle() {
|
|
957
982
|
return this.getAttribute("indent-style") === "tab" ? "tab" : "space";
|
|
@@ -1156,6 +1181,7 @@ class ArkCodeEditor extends HTMLElementBase {
|
|
|
1156
1181
|
completions: this.items,
|
|
1157
1182
|
completionSource: this.source,
|
|
1158
1183
|
formatter: this.formatFn,
|
|
1184
|
+
extensions: this.exts,
|
|
1159
1185
|
onChange: (value) => {
|
|
1160
1186
|
this.pendingValue = value;
|
|
1161
1187
|
this.dispatchEvent(new CustomEvent("change", { detail: { value }, bubbles: true, composed: true }));
|