@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/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { EditorView } from '@codemirror/view';
2
2
  import { ArkIntent, ArkThemeSelected, ArkSize } from '@tooark/tokens';
3
3
  import { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
4
+ import { Extension } from '@codemirror/state';
4
5
 
5
6
  /** Tema do editor. "auto" segue o color-scheme do host, ou a preferência do sistema sem lado fixo. */
6
7
  type ArkCodeTheme = "auto" | ArkThemeSelected;
@@ -19,6 +20,11 @@ type ArkCodeCompletionSource = (context: CompletionContext) => CompletionResult
19
20
  * Sem ele, só `json` tem formatação (nativa, com o recuo configurado).
20
21
  */
21
22
  type ArkCodeFormatter = (value: string, language: ArkCodeLanguage) => string | Promise<string>;
23
+ /**
24
+ * Extensões do CodeMirror fornecidas pelo app (uma ou uma lista): gramáticas que a lib não traz, calhas próprias,
25
+ * decorações, keymaps. Entram depois das da lib; `Prec.high`/`Prec.highest` põem uma antes.
26
+ */
27
+ type ArkCodeExtension = Extension;
22
28
  /**
23
29
  * Variável `{{chave}}` informada pelo app: oferecida depois de `{{` e pintada no texto. O escopo é livre (a lib não
24
30
  * conhece nenhum); quando a mesma chave existe em mais de um escopo, o app manda só a que vale.
@@ -88,6 +94,11 @@ type ArkCodeEditorOptions = {
88
94
  completionSource?: ArkCodeCompletionSource;
89
95
  /** Formatador do app; `format()` e Shift+Alt+F usam. */
90
96
  formatter?: ArkCodeFormatter;
97
+ /**
98
+ * Extensões do CodeMirror do app, somadas às da lib sem recriar o editor. Uma gramática própria pede
99
+ * `language: "text"`, senão a da lib vence. Padrão: nenhuma.
100
+ */
101
+ extensions?: ArkCodeExtension;
91
102
  /** Chamado a cada edição do usuário com o texto atual (não dispara em `setValue`). */
92
103
  onChange?: (value: string) => void;
93
104
  /** Chamado com o texto atual quando Enter é pressionado em `singleLine` (fora da lista de completions). */
@@ -123,7 +134,9 @@ declare const HTMLElementBase: typeof HTMLElement;
123
134
  * cada `{{chave}}` pelo intent da variável, com tooltip do escopo e do valor;
124
135
  * `mark-unknown-variables` pinta em `danger` a chave desconhecida;
125
136
  * `single-line` vira um campo de uma linha na altura dos controles (`size`),
126
- * com Enter emitindo `ark-submit` (`detail: { value }`).
137
+ * com Enter emitindo `ark-submit` (`detail: { value }`); a propriedade
138
+ * `extensions` soma extensões do CodeMirror do app (gramáticas que a lib não
139
+ * traz, calhas, decorações) às da lib, sem recriar o editor.
127
140
  */
128
141
  declare class ArkCodeEditor extends HTMLElementBase {
129
142
  static readonly tagName = "ark-code-editor";
@@ -135,6 +148,8 @@ declare class ArkCodeEditor extends HTMLElementBase {
135
148
  private items;
136
149
  private source;
137
150
  private formatFn;
151
+ /** Extensões do app como vieram: a mesma referência atribuída de novo não reconfigura o editor. */
152
+ private exts;
138
153
  /** Para de observar o tema da página; só existe com `theme="auto"`. */
139
154
  private disposeTheme;
140
155
  static get observedAttributes(): string[];
@@ -165,6 +180,12 @@ declare class ArkCodeEditor extends HTMLElementBase {
165
180
  /** Formatador do app (propriedade JS); sem ele só `language="json"` formata. */
166
181
  get formatter(): ArkCodeFormatter | undefined;
167
182
  set formatter(next: ArkCodeFormatter | null | undefined);
183
+ /**
184
+ * Extensões do CodeMirror do app (propriedade JS), depois das da lib: gramáticas que ela não traz (com `language`
185
+ * em "text"), calhas, decorações. Trocar reconfigura sem recriar o editor; `null` remove.
186
+ */
187
+ get extensions(): ArkCodeExtension;
188
+ set extensions(next: ArkCodeExtension | null | undefined);
168
189
  /** Recuo com espaços ou tabulação (atributo `indent-style`). Padrão: "space". */
169
190
  get indentStyle(): ArkCodeIndentStyle;
170
191
  set indentStyle(value: ArkCodeIndentStyle);
@@ -279,6 +300,8 @@ type ArkCodeEditorInstance = {
279
300
  setCompletionSource(source: ArkCodeCompletionSource | undefined): void;
280
301
  /** Troca o formatador do app. */
281
302
  setFormatter(formatter: ArkCodeFormatter | undefined): void;
303
+ /** Troca as extensões do app sem recriar o editor (texto, histórico e seleção ficam); `[]` remove todas. */
304
+ setExtensions(extensions: ArkCodeExtension): void;
282
305
  /** Formata o documento (formatador do app, ou JSON nativo); `false` sem formatador ou quando falha. */
283
306
  format(): Promise<boolean>;
284
307
  /** Indica se há como formatar a linguagem atual. */
@@ -298,7 +321,7 @@ declare function resolveCodeTheme(theme: ArkCodeTheme | undefined, element?: Ele
298
321
  * `variableKeys`, de `completions` e de `completionSource`), Tab para recuar com saída por Esc+Tab, recuo por
299
322
  * espaços ou tabulação, fim de linha LF/CRLF na fronteira do valor, formatação por Shift+Alt+F (JSON nativo ou o
300
323
  * `formatter` do app) e tema pelos tokens. Opcionais, ligados só pelas opções: `variables` pintadas por intent com
301
- * tooltip, `markUnknownVariables` e o campo `singleLine`.
324
+ * tooltip, `markUnknownVariables`, o campo `singleLine` e as `extensions` do app.
302
325
  */
303
326
  declare function createCodeEditor(parent: HTMLElement, options?: ArkCodeEditorOptions): ArkCodeEditorInstance;
304
327
 
@@ -309,4 +332,4 @@ declare function createCodeEditor(parent: HTMLElement, options?: ArkCodeEditorOp
309
332
  declare function registerTooarkCode(): void;
310
333
 
311
334
  export { ArkCodeEditor, createCodeEditor, registerTooarkCode, resolveCodeTheme };
312
- export type { ArkCodeCompletion, ArkCodeCompletionSource, ArkCodeEditorInstance, ArkCodeEditorOptions, ArkCodeFormatter, ArkCodeIndentStyle, ArkCodeLanguage, ArkCodeLineEnding, ArkCodeTheme, ArkCodeVariable };
335
+ export type { ArkCodeCompletion, ArkCodeCompletionSource, ArkCodeEditorInstance, ArkCodeEditorOptions, ArkCodeExtension, ArkCodeFormatter, ArkCodeIndentStyle, ArkCodeLanguage, ArkCodeLineEnding, ArkCodeTheme, ArkCodeVariable };
package/dist/index.js CHANGED
@@ -498,7 +498,7 @@ function formatJson(value, unit) {
498
498
  * `variableKeys`, de `completions` e de `completionSource`), Tab para recuar com saída por Esc+Tab, recuo por
499
499
  * espaços ou tabulação, fim de linha LF/CRLF na fronteira do valor, formatação por Shift+Alt+F (JSON nativo ou o
500
500
  * `formatter` do app) e tema pelos tokens. Opcionais, ligados só pelas opções: `variables` pintadas por intent com
501
- * tooltip, `markUnknownVariables` e o campo `singleLine`.
501
+ * tooltip, `markUnknownVariables`, o campo `singleLine` e as `extensions` do app.
502
502
  */
503
503
  function createCodeEditor(parent, options = {}) {
504
504
  const language = new Compartment();
@@ -515,6 +515,7 @@ function createCodeEditor(parent, options = {}) {
515
515
  const variableMarks = new Compartment();
516
516
  const lineMode = new Compartment();
517
517
  const searchKeys = new Compartment();
518
+ const custom = new Compartment();
518
519
  let resolved = resolveCodeTheme(options.theme ?? "auto", parent);
519
520
  let applying = false;
520
521
  let currentLanguage = options.language ?? "text";
@@ -645,7 +646,10 @@ function createCodeEditor(parent, options = {}) {
645
646
  EditorView.updateListener.of((update) => {
646
647
  if (update.docChanged && !applying)
647
648
  options.onChange?.(update.state.doc.toString().split("\n").join(eol()));
648
- })
649
+ }),
650
+ // As do app vêm por último: na mesma precedência, keymaps, calhas e linguagem da lib vêm antes, e quem precisa
651
+ // passar à frente usa `Prec`.
652
+ custom.of(options.extensions ?? [])
649
653
  ]
650
654
  });
651
655
  const view = new EditorView({ state, parent });
@@ -766,6 +770,7 @@ function createCodeEditor(parent, options = {}) {
766
770
  setFormatter: (next) => {
767
771
  formatter = next;
768
772
  },
773
+ setExtensions: (next) => view.dispatch({ effects: custom.reconfigure(next) }),
769
774
  format,
770
775
  canFormat: () => formatter !== undefined || currentLanguage === "json",
771
776
  resolvedTheme: () => resolved,
@@ -817,6 +822,8 @@ function truthy(value) {
817
822
  return false;
818
823
  return Boolean(value);
819
824
  }
825
+ /** Sem extensões do app; uma referência só, para `null` repetido não reconfigurar o editor. */
826
+ const NO_EXTENSIONS = [];
820
827
  /**
821
828
  * Custom Element que renderiza um editor de código CodeMirror 6.
822
829
  *
@@ -841,7 +848,9 @@ function truthy(value) {
841
848
  * cada `{{chave}}` pelo intent da variável, com tooltip do escopo e do valor;
842
849
  * `mark-unknown-variables` pinta em `danger` a chave desconhecida;
843
850
  * `single-line` vira um campo de uma linha na altura dos controles (`size`),
844
- * com Enter emitindo `ark-submit` (`detail: { value }`).
851
+ * com Enter emitindo `ark-submit` (`detail: { value }`); a propriedade
852
+ * `extensions` soma extensões do CodeMirror do app (gramáticas que a lib não
853
+ * traz, calhas, decorações) às da lib, sem recriar o editor.
845
854
  */
846
855
  class ArkCodeEditor extends HTMLElementBase {
847
856
  constructor() {
@@ -852,6 +861,8 @@ class ArkCodeEditor extends HTMLElementBase {
852
861
  this.keys = [];
853
862
  this.vars = [];
854
863
  this.items = [];
864
+ /** Extensões do app como vieram: a mesma referência atribuída de novo não reconfigura o editor. */
865
+ this.exts = NO_EXTENSIONS;
855
866
  /** Para de observar o tema da página; só existe com `theme="auto"`. */
856
867
  this.disposeTheme = null;
857
868
  }
@@ -950,6 +961,20 @@ class ArkCodeEditor extends HTMLElementBase {
950
961
  this.formatFn = typeof next === "function" ? next : undefined;
951
962
  this.instance?.setFormatter(this.formatFn);
952
963
  }
964
+ /**
965
+ * Extensões do CodeMirror do app (propriedade JS), depois das da lib: gramáticas que ela não traz (com `language`
966
+ * em "text"), calhas, decorações. Trocar reconfigura sem recriar o editor; `null` remove.
967
+ */
968
+ get extensions() {
969
+ return this.exts;
970
+ }
971
+ set extensions(next) {
972
+ const value = next !== null && typeof next === "object" ? next : NO_EXTENSIONS;
973
+ if (value === this.exts)
974
+ return;
975
+ this.exts = value;
976
+ this.instance?.setExtensions(value);
977
+ }
953
978
  /** Recuo com espaços ou tabulação (atributo `indent-style`). Padrão: "space". */
954
979
  get indentStyle() {
955
980
  return this.getAttribute("indent-style") === "tab" ? "tab" : "space";
@@ -1154,6 +1179,7 @@ class ArkCodeEditor extends HTMLElementBase {
1154
1179
  completions: this.items,
1155
1180
  completionSource: this.source,
1156
1181
  formatter: this.formatFn,
1182
+ extensions: this.exts,
1157
1183
  onChange: (value) => {
1158
1184
  this.pendingValue = value;
1159
1185
  this.dispatchEvent(new CustomEvent("change", { detail: { value }, bubbles: true, composed: true }));