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!

πŸ₯… Catch any config warn/errs and display cleanly

Alicia Sykes1e3355742186
diff --git a/src/assets/locales/en.json b/src/assets/locales/en.json
index 63aed843..d299a29c 100644
--- a/src/assets/locales/en.json
+++ b/src/assets/locales/en.json
@@ -201,7 +201,9 @@
"status-valid": "Valid",
"status-invalid": "Invalid",
"status-warning": "{n} Warning",
- "status-warnings": "{n} Warnings"
+ "status-warnings": "{n} Warnings",
+ "parse-fail-msg": "YAML parse error: {message}",
+ "editor-init-fail-msg": "Editor failed to start: {message}"
},
"app-rebuild": {
"title": "Rebuild Application",
diff --git a/src/components/Configuration/JsonEditor.vue b/src/components/Configuration/JsonEditor.vue
index 14eaefab..93494d97 100644
--- a/src/components/Configuration/JsonEditor.vue
+++ b/src/components/Configuration/JsonEditor.vue
@@ -122,7 +122,7 @@ import { tags as t } from '@lezer/highlight';
import { schemaLinter } from '@/utils/config/schemaLinter';
import { schemaHover } from '@/utils/config/schemaHover';
import ConfigSavingMixin from '@/mixins/ConfigSaving';
-import { InfoHandler, InfoKeys } from '@/utils/logging/ErrorHandler';
+import ErrorHandler, { InfoHandler, InfoKeys } from '@/utils/logging/ErrorHandler';
import StoreKeys from '@/utils/StoreMutations';
import Button from '@/components/FormElements/Button';
import AccessError from '@/components/Configuration/AccessError';
@@ -220,47 +220,49 @@ export default {
return jsYaml.dump(data, DUMP_OPTS);
},
createEditor() {
- this.initialDoc = this.initialText();
-
- const updateListener = EditorView.updateListener.of((u) => {
- if (u.docChanged || u.transactions.some((tr) => tr.effects.length)) {
- this.syncDiagnostics();
- }
- });
-
- const state = EditorState.create({
- doc: this.initialDoc,
- extensions: [
- lineNumbers(),
- highlightActiveLineGutter(),
- highlightActiveLine(),
- foldGutter(),
- history(),
- bracketMatching(),
- closeBrackets(),
- indentOnInput(),
- syntaxHighlighting(dashyHighlight, { fallback: true }),
- highlightSelectionMatches(),
- keymap.of([
- ...closeBracketsKeymap,
- ...defaultKeymap,
- ...searchKeymap,
- ...historyKeymap,
- ...foldKeymap,
- indentWithTab,
- ]),
- yaml(),
- lintGutter(),
- linter(schemaLinter, { delay: 300 }),
- schemaHover,
- this.wrapCompartment.of(this.wordWrap ? EditorView.lineWrapping : []),
- EditorView.darkTheme.of(true),
- updateListener,
- ],
- });
-
- this.view = markRaw(new EditorView({ state, parent: this.$refs.editorEl }));
- this.syncDiagnostics();
+ try {
+ this.initialDoc = this.initialText();
+ const updateListener = EditorView.updateListener.of((u) => {
+ if (u.docChanged || u.transactions.some((tr) => tr.effects.length)) {
+ this.syncDiagnostics();
+ }
+ });
+ const state = EditorState.create({
+ doc: this.initialDoc,
+ extensions: [
+ lineNumbers(),
+ highlightActiveLineGutter(),
+ highlightActiveLine(),
+ foldGutter(),
+ history(),
+ bracketMatching(),
+ closeBrackets(),
+ indentOnInput(),
+ syntaxHighlighting(dashyHighlight, { fallback: true }),
+ highlightSelectionMatches(),
+ keymap.of([
+ ...closeBracketsKeymap,
+ ...defaultKeymap,
+ ...searchKeymap,
+ ...historyKeymap,
+ ...foldKeymap,
+ indentWithTab,
+ ]),
+ yaml(),
+ lintGutter(),
+ linter(schemaLinter, { delay: 300 }),
+ schemaHover,
+ this.wrapCompartment.of(this.wordWrap ? EditorView.lineWrapping : []),
+ EditorView.darkTheme.of(true),
+ updateListener,
+ ],
+ });
+ this.view = markRaw(new EditorView({ state, parent: this.$refs.editorEl }));
+ this.syncDiagnostics();
+ } catch (e) {
+ ErrorHandler(`Editor failed to initialize: ${e.message}`);
+ this.$toast.error(this.$t('config-editor.editor-init-fail-msg', { message: e.message }));
+ }
},
syncDiagnostics() {
if (!this.view) return;
@@ -294,10 +296,11 @@ export default {
},
jumpTo(err) {
if (!this.view) return;
+ const pos = Math.min(err.from, this.view.state.doc.length);
this.view.focus();
this.view.dispatch({
- selection: { anchor: err.from, head: err.from },
- effects: EditorView.scrollIntoView(err.from, { y: 'center' }),
+ selection: { anchor: pos, head: pos },
+ effects: EditorView.scrollIntoView(pos, { y: 'center' }),
});
},
currentText() {
@@ -307,14 +310,17 @@ export default {
try {
return jsYaml.load(this.currentText());
} catch (e) {
- this.$toast.error(e.message);
+ this.$toast.error(this.$t('config-editor.parse-fail-msg', { message: e.message }));
return null;
}
},
- onSaveToDisk() {
+ // Only sync local store with edits when the disk write actually succeeded,
+ // so a failed save leaves dashboard state matching the saved config.
+ async onSaveToDisk() {
const data = this.parseCurrent();
if (data == null) return;
- this.writeConfigToDisk(data);
+ const ok = await this.writeConfigToDisk(data);
+ if (!ok) return;
this.$store.commit(StoreKeys.SET_PAGE_INFO, data.pageInfo);
this.$store.commit(StoreKeys.SET_SECTIONS, data.sections);
this.$store.commit(StoreKeys.SET_PAGES, data.pages || []);
@@ -327,11 +333,13 @@ export default {
this.saveConfigLocally(data);
}
},
- // Commits a full parsed config object to the Vuex store to preview or reset
+ // Commits a full parsed config object to the Vuex store (preview / reset).
+ // Each top-level section is only committed when present, so a user saving
+ // a YAML that omits e.g. `appConfig:` can't nuke existing store state.
applyConfigToStore(data) {
- this.$store.commit(StoreKeys.SET_APP_CONFIG, data.appConfig);
- this.$store.commit(StoreKeys.SET_PAGE_INFO, data.pageInfo);
- this.$store.commit(StoreKeys.SET_SECTIONS, data.sections);
+ if (data.appConfig !== undefined) this.$store.commit(StoreKeys.SET_APP_CONFIG, data.appConfig);
+ if (data.pageInfo !== undefined) this.$store.commit(StoreKeys.SET_PAGE_INFO, data.pageInfo);
+ if (data.sections !== undefined) this.$store.commit(StoreKeys.SET_SECTIONS, data.sections);
this.$store.commit(StoreKeys.SET_PAGES, data.pages || []);
},
onPreview() {
@@ -395,6 +403,7 @@ export default {
.editor-toolbar {
display: flex;
+ flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 1rem;
@@ -566,7 +575,7 @@ export default {
}
p.note {
- font-size: 0.8rem;
+ font-size: 0.85rem;
color: var(--medium-grey);
margin: 0.5rem auto;
text-align: center;
@@ -636,7 +645,7 @@ p.no-permission-note {
padding: 0.4rem 0.75rem;
margin: 0;
min-width: unset;
- font-size: 0.95rem;
+ font-size: 0.9rem;
background: transparent;
color: var(--config-settings-color);
border: 1px solid var(--config-settings-color);
@@ -713,7 +722,6 @@ p.no-permission-note {
}
.meta {
- font-size: 0.8rem;
color: var(--medium-grey);
margin-top: 0.25rem;
diff --git a/src/mixins/ConfigSaving.js b/src/mixins/ConfigSaving.js
index fc91b646..e28d186b 100644
--- a/src/mixins/ConfigSaving.js
+++ b/src/mixins/ConfigSaving.js
@@ -19,7 +19,7 @@ export default {
writeConfigToDisk(config) {
if (config.appConfig.preventWriteToDisk) {
ErrorHandler('Unable to write changed to disk, as this functionality is disabled');
- return;
+ return Promise.resolve(false);
}
// 1. Get the config, and strip appConfig if is sub-page
const isSubPag = !!this.$store.state.currentConfigInfo.confId;
@@ -30,7 +30,7 @@ export default {
delete jsonConfig.appConfig;
if (this.$store.state.currentConfigInfo.confPath.includes('http')) {
ErrorHandler('Cannot save to an external URL');
- return;
+ return Promise.resolve(false);
}
}
// 2. Convert JSON into YAML
@@ -47,7 +47,7 @@ export default {
const saveRequest = request.post(endpoint, body);
// 4. Make the request, and handle response
this.progress.start();
- saveRequest.then((response) => {
+ return saveRequest.then((response) => {
this.saveSuccess = response.data.success || false;
this.responseText = response.data.message;
if (this.saveSuccess) {
@@ -59,6 +59,7 @@ export default {
InfoHandler('Config has been written to disk successfully', 'Config Update');
this.progress.end();
this.$store.commit(StoreKeys.SET_EDIT_MODE, false);
+ return this.saveSuccess;
})
.catch((error) => {
this.saveSuccess = false;
@@ -66,6 +67,7 @@ export default {
this.showToast(error, false);
ErrorHandler(`Failed to save config. ${error}`);
this.progress.end();
+ return false;
});
},
saveConfigLocally(config) {
diff --git a/src/utils/config/schemaLinter.js b/src/utils/config/schemaLinter.js
index b02d2951..d846702d 100644
--- a/src/utils/config/schemaLinter.js
+++ b/src/utils/config/schemaLinter.js
@@ -11,7 +11,7 @@ import Ajv from 'ajv';
import addFormats from 'ajv-formats';
import schema from './ConfigSchema.json';
-import { pointerToPath, yamlNodeAt } from './schemaPath';
+import { pointerToPath, yamlNodeAt, pairRange } from './schemaPath';
const ajv = new Ajv({ allErrors: true, strict: false });
addFormats(ajv);
@@ -22,6 +22,7 @@ const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));
// Turn Ajv's raw errors into user readable strings
const formatError = (err) => {
const { keyword, params, message } = err;
+ const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
switch (keyword) {
case 'enum':
return `must be one of: ${(params.allowedValues || []).join(', ')}`;
@@ -31,19 +32,46 @@ const formatError = (err) => {
return `missing required field: ${params.missingProperty}`;
case 'additionalProperties':
return `unknown property: ${params.additionalProperty}`;
+ case 'propertyNames':
+ return `invalid property name: ${params.propertyName}`;
+ case 'dependencies':
+ case 'dependentRequired':
+ return `missing required field: ${params.missingProperty} (needed when ${params.property} is set)`;
case 'type':
- return `must be ${params.type}`;
+ return `must be ${Array.isArray(params.type) ? params.type.join(' or ') : params.type}`;
case 'minLength':
- return `must be at least ${params.limit} characters`;
+ return `must be at least ${plural(params.limit, 'character')}`;
case 'maxLength':
- return `must be at most ${params.limit} characters`;
+ return `must be at most ${plural(params.limit, 'character')}`;
case 'minimum':
case 'maximum':
return `must be ${keyword === 'minimum' ? 'β‰₯' : '≀'} ${params.limit}`;
+ case 'exclusiveMinimum':
+ case 'exclusiveMaximum':
+ return `must be ${keyword === 'exclusiveMinimum' ? '>' : '<'} ${params.limit}`;
+ case 'multipleOf':
+ return `must be a multiple of ${params.multipleOf}`;
+ case 'minItems':
+ return `must have at least ${plural(params.limit, 'item')}`;
+ case 'maxItems':
+ return `must have at most ${plural(params.limit, 'item')}`;
+ case 'uniqueItems':
+ return 'must not contain duplicate items';
+ case 'minProperties':
+ return `must have at least ${plural(params.limit, 'property')}`;
+ case 'maxProperties':
+ return `must have at most ${plural(params.limit, 'property')}`;
case 'pattern':
return `must match pattern ${params.pattern}`;
case 'format':
return `must be a valid ${params.format}`;
+ case 'anyOf':
+ case 'oneOf':
+ return 'must match one of the allowed shapes for this field';
+ case 'not':
+ return 'must not match the disallowed shape for this field';
+ case 'if':
+ return 'does not match the conditional schema for this field';
default:
return message;
}
@@ -76,10 +104,7 @@ export function schemaLinter(view) {
if (validate(data)) return [];
const doc = parseDocument(text);
- return (validate.errors || []).map((err) => {
- const path = pointerToPath(err.instancePath);
- const node = yamlNodeAt(doc.contents, path);
- const [start, end] = node?.range ?? [0, 0];
+ const diag = (err, start, end) => {
const from = clamp(start, 0, docLen);
const to = clamp(end || start + 1, from + 1, docLen);
return {
@@ -89,5 +114,27 @@ export function schemaLinter(view) {
source: 'schema',
message: `${prefix(err.instancePath)}${formatError(err)}`,
};
+ };
+
+ return (validate.errors || []).map((err) => {
+ const path = pointerToPath(err.instancePath);
+ const node = yamlNodeAt(doc.contents, path);
+
+ // Unknown property: Ajv reports the PARENT's path + the bad key name.
+ // Narrow the highlight to just the offending key's pair, not the parent.
+ if (err.keyword === 'additionalProperties' && err.params.additionalProperty) {
+ const range = pairRange(node, err.params.additionalProperty);
+ if (range) return diag(err, range[0], range[1]);
+ }
+
+ // Missing required: no child exists to point at, so shrink to one char
+ // at the parent's opening β€” the gutter icon lands on its first line only.
+ if (err.keyword === 'required') {
+ const start = node?.range?.[0] ?? 0;
+ return diag(err, start, start + 1);
+ }
+
+ const [start, end] = node?.range ?? [0, 0];
+ return diag(err, start, end);
});
}
diff --git a/src/utils/config/schemaPath.js b/src/utils/config/schemaPath.js
index 5068b8c4..ed8d5eed 100644
--- a/src/utils/config/schemaPath.js
+++ b/src/utils/config/schemaPath.js
@@ -10,6 +10,22 @@ export const pointerToPath = (pointer) => (pointer
? pointer.split('/').slice(1).map(decodeToken)
: []);
+// Return the source range [start, end] for a specific key's pair inside a map
+// (covers both the key and its value). Null if the map or key doesn't exist.
+export const pairRange = (map, key) => {
+ if (!isMap(map)) return null;
+ const pair = map.items.find((p) => {
+ const k = p.key && 'value' in p.key ? p.key.value : p.key;
+ return String(k) === String(key);
+ });
+ if (!pair) return null;
+ const keyRange = pair.key?.range;
+ const valRange = pair.value?.range;
+ const start = keyRange?.[0] ?? valRange?.[0];
+ const end = valRange?.[2] ?? valRange?.[1] ?? keyRange?.[1];
+ return (start != null && end != null) ? [start, end] : null;
+};
+
// Walk a parsed YAML Document by path parts, returning the target Node or null.
export const yamlNodeAt = (root, parts) => {
let node = root;