Skip to content

armgit / dashy

Public Imported from GitHub
0

πŸš€ A self-hostable personal dashboard built for you. Includes status-checking, widgets, themes, icon packs, a UI editor and tons more!

✨ Schema-powered auto-complete for the YAML editor

Alicia Sykes43e18b6c590b
diff --git a/src/components/Configuration/JsonEditor.vue b/src/components/Configuration/JsonEditor.vue
index ee19f091..b9bb98e2 100644
--- a/src/components/Configuration/JsonEditor.vue
+++ b/src/components/Configuration/JsonEditor.vue
@@ -119,19 +119,24 @@
<script>
import { shallowRef, markRaw } from 'vue';
import { EditorView, keymap, lineNumbers, highlightActiveLine, highlightActiveLineGutter } from '@codemirror/view';
-import { EditorState, Compartment } from '@codemirror/state';
+import { EditorState, Compartment, Prec } from '@codemirror/state';
import { yaml } from '@codemirror/lang-yaml';
import { linter, lintGutter, forEachDiagnostic } from '@codemirror/lint';
-import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands';
+import {
+ defaultKeymap, history, historyKeymap, indentWithTab, insertNewlineAndIndent,
+} from '@codemirror/commands';
import {
bracketMatching, foldGutter, foldKeymap, indentOnInput, syntaxHighlighting, HighlightStyle,
} from '@codemirror/language';
-import { closeBrackets, closeBracketsKeymap } from '@codemirror/autocomplete';
+import {
+ acceptCompletion, autocompletion, closeBrackets, closeBracketsKeymap, closeCompletion, startCompletion,
+} from '@codemirror/autocomplete';
import { highlightSelectionMatches, searchKeymap } from '@codemirror/search';
import { tags as t } from '@lezer/highlight';
import { load as yamlLoad, dump as yamlDump } from '@/utils/yaml';
import { schemaLinter } from '@/utils/config/schemaLinter';
import { schemaHover } from '@/utils/config/schemaHover';
+import { schemaComplete } from '@/utils/config/schemaComplete';
import ConfigSavingMixin from '@/mixins/ConfigSaving';
import ErrorHandler, { InfoHandler, InfoKeys } from '@/utils/logging/ErrorHandler';
import StoreKeys from '@/utils/StoreMutations';
@@ -260,7 +265,22 @@ export default {
indentOnInput(),
syntaxHighlighting(dashyHighlight, { fallback: true }),
highlightSelectionMatches(),
+ // Esc closes an open suggestion list, without reaching the modal (which
+ // would close the whole editor). Falls through when nothing is open
+ Prec.highest(keymap.of([
+ { key: 'Escape', run: closeCompletion, stopPropagation: true },
+ ])),
keymap.of([
+ // Tab accepts an open suggestion; Enter starts a new line, then offers them
+ { key: 'Tab', run: acceptCompletion },
+ {
+ key: 'Enter',
+ run: (view) => {
+ if (!insertNewlineAndIndent(view)) return false;
+ startCompletion(view);
+ return true;
+ },
+ },
...closeBracketsKeymap,
...defaultKeymap,
...searchKeymap,
@@ -272,6 +292,7 @@ export default {
lintGutter(),
linter(schemaLinter, { delay: 300 }),
schemaHover,
+ autocompletion({ override: [schemaComplete], icons: false }),
this.wrapCompartment.of(this.wordWrap ? EditorView.lineWrapping : []),
EditorView.darkTheme.of(true),
updateListener,
@@ -728,6 +749,25 @@ p.no-permission-note {
}
}
+/* Autocomplete popup. Extra classes needed to out-weigh CodeMirror's own theme */
+.cm-editor .cm-tooltip.cm-tooltip-autocomplete {
+ ul li[aria-selected] {
+ background: var(--config-settings-background);
+ color: var(--config-settings-color);
+ }
+ .cm-completionDetail {
+ color: var(--medium-grey);
+ font-style: normal;
+ float: right;
+ margin-left: 1rem;
+ }
+}
+
+.cm-editor .cm-tooltip.cm-completionInfo {
+ max-width: 22rem;
+ padding: 0.5rem 0.75rem;
+}
+
.cm-schema-hover {
max-width: 22rem;
padding: 0.5rem 0.75rem;
diff --git a/src/utils/config/schemaComplete.js b/src/utils/config/schemaComplete.js
new file mode 100644
index 00000000..0fdb4901
--- /dev/null
+++ b/src/utils/config/schemaComplete.js
@@ -0,0 +1,75 @@
+/**
+ * A completion source for CodeMirror 6,
+ * suggests property names and enum/boolean values from
+ * ConfigSchema.json, based on the cursor's path in the YAML doc
+ */
+import { parseDocument } from 'yaml';
+import schema from './ConfigSchema.json';
+import { yamlPathAtOffset, yamlNodeAt, schemaAt } from './schemaPath';
+
+// Spliced in at the cursor before parsing, so blank lines still resolve to a path
+const PROBE = 'xProbex';
+
+const describeType = (s) => (Array.isArray(s.type) ? s.type.join(' | ') : s.type);
+
+// Whether the offset falls within a node's source range
+const insideNode = (node, offset) => {
+ const r = node?.range;
+ return !!r && offset >= r[0] && offset <= (r[2] ?? r[1] ?? r[0]);
+};
+
+// Property names for an object schema, minus keys already used in the map
+const keyOptions = (target, mapNode, currentKey, colonAfter) => {
+ const existing = new Set((mapNode?.items || [])
+ .map((p) => String(p.key && 'value' in p.key ? p.key.value : p.key))
+ // A half-typed key can parse merged with the next line, as "pa sections"
+ .flatMap((k) => k.split(/\s+/)));
+ return Object.entries(target?.properties || {})
+ .filter(([name]) => !existing.has(name) || name === currentKey)
+ .map(([name, s]) => ({
+ label: name,
+ type: 'property',
+ detail: describeType(s),
+ info: s.description,
+ apply: colonAfter ? name : `${name}: `,
+ }));
+};
+
+// Value completions: the schema's allowed enum entries, or true/false for booleans
+const valueOptions = (target) => {
+ if (Array.isArray(target?.enum)) {
+ return target.enum.map((v) => ({ label: String(v), type: 'constant' }));
+ }
+ if ([].concat(target?.type || []).includes('boolean')) {
+ return [{ label: 'true', type: 'constant' }, { label: 'false', type: 'constant' }];
+ }
+ return [];
+};
+
+export const schemaComplete = (context) => {
+ const { state, pos } = context;
+ const word = context.matchBefore(/[\w$-]*/);
+ if (!word) return null;
+
+ const line = state.doc.lineAt(pos);
+ const beforeCursor = line.text.slice(0, pos - line.from);
+ const afterCursor = line.text.slice(pos - line.from);
+ const typingKey = /^[\s-]*[\w$-]*$/.test(beforeCursor); // ` ti` or ` - `
+ const typingValue = /:\s+[\w$-]*$/.test(beforeCursor); // ` layout: au` or ` layout: `
+ if (!typingKey && !typingValue) return null;
+
+ const doc = parseDocument(state.sliceDoc(0, pos) + PROBE + state.sliceDoc(pos));
+ const path = yamlPathAtOffset(doc, pos);
+ const [wordAfter] = /^[\w$-]*/.exec(afterCursor);
+ const result = (options) => (options.length
+ ? { from: word.from, to: pos + wordAfter.length, options, validFor: /^[\w$-]*$/ }
+ : null);
+
+ if (typingValue) return result(valueOptions(schemaAt(schema, path)));
+
+ // When the cursor is on a key (not inside a value), complete against its parent
+ const onKey = path.length && !insideNode(yamlNodeAt(doc.contents, path), pos);
+ const currentKey = onKey ? String(path.pop()).replace(PROBE, '') : null;
+ const colonAfter = /^\s*:/.test(afterCursor.slice(wordAfter.length));
+ return result(keyOptions(schemaAt(schema, path), yamlNodeAt(doc.contents, path), currentKey, colonAfter));
+};
diff --git a/tests/unit/schema-complete.test.js b/tests/unit/schema-complete.test.js
new file mode 100644
index 00000000..1bd7a30b
--- /dev/null
+++ b/tests/unit/schema-complete.test.js
@@ -0,0 +1,72 @@
+import { describe, it, expect } from 'vitest';
+import { EditorState } from '@codemirror/state';
+import { CompletionContext } from '@codemirror/autocomplete';
+import { schemaComplete } from '../../src/utils/config/schemaComplete';
+
+const at = (text, explicit = false) => {
+ const pos = text.indexOf('|');
+ const state = EditorState.create({ doc: text.replace('|', '') });
+ return schemaComplete(new CompletionContext(state, pos, explicit));
+};
+const labels = (r) => (r ? r.options.map((o) => o.label) : null);
+
+describe('schemaComplete', () => {
+ it('completes nested keys', () => {
+ const r = at('pageInfo:\n ti|\n');
+ expect(labels(r)).toContain('title');
+ expect(r.options.find((o) => o.label === 'title').apply).toBe('title: ');
+ });
+ it('excludes keys already present', () => {
+ const l = labels(at('pageInfo:\n title: x\n na|\n'));
+ expect(l).toContain('navLinks');
+ expect(l).not.toContain('title');
+ });
+ it('completes root keys, excluding present ones', () => {
+ const l = labels(at('pa|\nsections: []\n'));
+ expect(l).toEqual(expect.arrayContaining(['pages', 'pageInfo', '$schema']));
+ expect(l).not.toContain('sections');
+ });
+ it('word that prefixes the PARENT key stays scoped to parent', () => {
+ const l = labels(at('pageInfo:\n pa|\n'));
+ expect(l).toContain('title'); // pageInfo's props...
+ expect(l).not.toContain('pages'); // ...not root's
+ });
+ it('completes enum values', () => {
+ expect(labels(at('appConfig:\n layout: |\n'))).toContain('horizontal');
+ });
+ it('completes enum values with a typed prefix', () => {
+ expect(labels(at('appConfig:\n layout: ho|\n'))).toContain('horizontal');
+ });
+ it('completes booleans', () => {
+ expect(labels(at('appConfig:\n statusCheck: |\n'))).toEqual(['true', 'false']);
+ });
+ it('completes keys inside a section item', () => {
+ const l = labels(at('sections:\n - name: A\n items:\n - ti|\n'));
+ expect(l).toEqual(expect.arrayContaining(['title']));
+ });
+ it('silent for free-text values', () => {
+ expect(at('pageInfo:\n title: My|\n')).toBeNull();
+ expect(at('pageInfo:\n title: My Da|\n')).toBeNull();
+ });
+ it('resolves blank nested lines to the parent', () => {
+ expect(labels(at('pageInfo:\n |\n', true))).toContain('title');
+ const l = labels(at('pageInfo:\n title: x\n |\n', true));
+ expect(l).toContain('navLinks');
+ expect(l).not.toContain('title');
+ });
+ it('offers item keys on a bare new list entry', () => {
+ expect(labels(at('sections:\n - name: A\n - |\n', true))).toContain('name');
+ });
+ it('explicit trigger on empty root doc offers root keys', () => {
+ expect(labels(at('|', true))).toContain('sections');
+ });
+ it('mid-key edit applies name without a colon', () => {
+ const r = at('pageInfo:\n tit|le: x\n');
+ expect(r.options.find((o) => o.label === 'title').apply).toBe('title');
+ });
+ it('info and detail carry schema docs', () => {
+ const o = at('pageInfo:\n ti|\n').options.find((x) => x.label === 'title');
+ expect(o.detail).toBe('string');
+ expect(o.info).toBeTruthy();
+ });
+});