« get me outta code hell

data: DocumentSortingRule.apply - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/data
diff options
context:
space:
mode:
author(quasar) nebula <qznebula@protonmail.com>2025-02-22 14:57:58 -0400
committer(quasar) nebula <qznebula@protonmail.com>2025-02-22 21:12:24 -0400
commitdcf6dd2d44006628c963e8555d98603109785589 (patch)
treec9d86e6000552d654dd06c8a74e66ab98e01a3e4 /src/data
parent1be8ada330ca2d49eb1681a23a7b0f8a8145c49a (diff)
data: DocumentSortingRule.apply
Diffstat (limited to 'src/data')
-rw-r--r--src/data/things/sorting-rule.js33
1 files changed, 31 insertions, 2 deletions
diff --git a/src/data/things/sorting-rule.js b/src/data/things/sorting-rule.js
index 8d1c61b9..890a798b 100644
--- a/src/data/things/sorting-rule.js
+++ b/src/data/things/sorting-rule.js
@@ -1,9 +1,11 @@
 export const SORTING_RULE_DATA_FILE = 'sorting-rules.yaml';
 
+import {readFile, writeFile} from 'node:fs/promises';
+import * as path from 'node:path';
+
 import {input} from '#composite';
 import Thing from '#thing';
 import {isStringNonEmpty, strictArrayOf} from '#validators';
-import {documentModes} from '#yaml';
 
 import {
   compareCaseLessSensitive,
@@ -12,6 +14,13 @@ import {
   sortByName,
 } from '#sort';
 
+import {
+  documentModes,
+  flattenThingLayoutToDocumentOrder,
+  getThingLayoutForFilename,
+  reorderDocumentsInYAMLSourceText,
+} from '#yaml';
+
 import {flag} from '#composite/wiki-properties';
 
 export class SortingRule extends Thing {
@@ -130,7 +139,27 @@ export class DocumentSortingRule extends ThingSortingRule {
     },
   });
 
-  apply(layout) {
+  async apply({wikiData, dataPath}) {
+    let layout = getThingLayoutForFilename(this.filename, wikiData);
+    if (!layout) return;
+
+    layout = this.#processLayout(layout);
+
+    const order = flattenThingLayoutToDocumentOrder(layout);
+
+    const realPath =
+      path.join(
+        dataPath,
+        this.filename.split(path.posix.sep).join(path.sep));
+
+    let sourceText = await readFile(realPath, 'utf8');
+
+    sourceText = reorderDocumentsInYAMLSourceText(sourceText, order);
+
+    await writeFile(realPath, sourceText);
+  }
+
+  #processLayout(layout) {
     const fresh = {...layout};
 
     let sortable = null;