Skip to content

Commit

Permalink
Handle yaml reorder
Browse files Browse the repository at this point in the history
- #20
  • Loading branch information
riccardoperra committed Nov 5, 2024
1 parent ada1fc0 commit 3bec97a
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion packages/app/src/store/editor/plugins/yamlSession.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {type GenericStoreApi, makePlugin} from 'statebuilder';
import {type Accessor, createSignal, JSX} from 'solid-js';
import YAML, {Document, type ParsedNode} from 'yaml';
import YAML, {Document, YAMLMap, type ParsedNode} from 'yaml';

export type YAMLDocument = Document.Parsed<ParsedNode, true>;

Expand Down Expand Up @@ -33,6 +33,34 @@ export const withYamlDocumentSession = () => {
setInitialSource(yaml.toString() ?? '');
};

const order = [
'name',
'run-name',
'on',
'permissions',
'env',
'defaults',
'concurrency',
'jobs',
];

const yamlApplyPropertiesReordering = (doc: YAMLDocument) => {
const contents = doc.contents;
if (!(contents instanceof YAML.YAMLMap)) {
return;
}

// TODO: optimize subscribing to slices. this should not be done every time...
contents.items = contents.items.sort((a, b) => {
const indexA = order.indexOf(a.key.toString());
const indexB = order.indexOf(b.key.toString());
if (indexA === -1 && indexB === -1) return 0;
if (indexA === -1) return 1;
if (indexB === -1) return -1;
return indexA - indexB;
});
};

const yamlUpdater = (cb: (yaml: YAMLDocument) => boolean | void) => {
// TODO: handle errors?
const doc = yaml();
Expand All @@ -41,7 +69,9 @@ export const withYamlDocumentSession = () => {
return;
}
const result = cb(doc);

if (result === undefined || result) {
yamlApplyPropertiesReordering(doc);
setNotifier({});
}
};
Expand Down

0 comments on commit 3bec97a

Please sign in to comment.