Mari's guided journal software.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

51 lines
2.3 KiB

import {SchemaData} from "./SchemaData";
import {dump, load} from "js-yaml";
import {EditorQuestionOptions} from "inquirer";
import {InquireFunction, ShowFunction} from "../prompts/Inquire";
const RETRY = "Retry"
const ABORT = "Abort"
export async function editYaml<ObjectT>({schema, currentValue, name, inquire, showError}: {schema: SchemaData<ObjectT, any, any, any>, currentValue: ObjectT, name: string, inquire: InquireFunction, showError: ShowFunction}): Promise<ObjectT>
export async function editYaml<ObjectT>({schema, currentValue, name, inquire, showError}: {schema: SchemaData<ObjectT, any, any, any>, currentValue: ObjectT|undefined, name: string, inquire: InquireFunction, showError: ShowFunction}): Promise<ObjectT|undefined>
export async function editYaml<ObjectT>({schema, currentValue, name, inquire, showError}: {schema: SchemaData<ObjectT, any, any, any>, currentValue: ObjectT|undefined, name: string, inquire: InquireFunction, showError: ShowFunction}): Promise<ObjectT|undefined> {
const original = dump(currentValue)
let text = original
while (true) {
const modified = await inquire({
type: "editor",
message: `View and edit ${name}:`,
default: text,
} as EditorQuestionOptions)
if (original !== modified) {
try {
const result = load(modified)
if (schema.validate(result)) {
return result
} else {
await showError(schema.validate.errors?.map((e) => e.toString()).join("; ") || "Failed validation")
}
} catch (e) {
await showError(e.toString())
}
const option = await inquire({
type: "expand",
message: "Choose how to proceed:",
choices: [
{key: "r", name: "Retry edits with current text", value: RETRY},
{key: "a", name: "Abort editing and keep original state", value: ABORT}
],
})
switch (option) {
default:
case RETRY:
text = modified
break
case ABORT:
return currentValue
}
} else {
return currentValue
}
}
}