obsidian-scraps/lib/format.ts
2024-10-28 11:03:02 -04:00

60 lines
1.7 KiB
TypeScript

import { moment } from "obsidian";
import { capitalize, sample } from "lodash-es";
import { adjectives } from "./resource/adjectives.js";
import { nouns } from "./resource/nouns.js";
/*
* A simple formatter/templater which uses a {tag} format for tokens.
*
* Supported tokens:
* - {N}: Random noun
* - {n}: Random noun (lower case)
* - {A}: Random adjective
* - {a}: Random adjective (lower case)
* - {MW}: Month week (1-5)
* - {time <moment format>}: Current date/time in the specified moment format
*
* Examples:
* format("Note {N} created at {time HH:mm}") -> "Note Apple created at 14:30"
* format("Note {n} created at {time HH:mm}") -> "Note apple created at 14:30"
* format("Scrap from {time YYYY-MM-DD}") -> "Scrap from 2024-06-01"
*/
export function format(str: string): string {
let formatted = str.trim();
// Replace {N} with a random noun
formatted = formatted.replace(/{N}/g, () => {
return capitalize(sample(nouns));
});
// Replace {n} with a random noun (lower case)
formatted = formatted.replace(/{n}/g, () => {
return sample(nouns);
});
// Replace {A} with a random adjective
formatted = formatted.replace(/{A}/g, () => {
return capitalize(sample(adjectives));
});
// Replace {a} with a random adjective (lower case)
formatted = formatted.replace(/{a}/g, () => {
return sample(adjectives);
});
// Replace {MW} with the current month week
const monthWeek = `${Math.ceil(new Date().getDate() / 7)}`;
formatted = formatted.replace(/{MW}/g, monthWeek);
// Replace {time <moment format>} with the moment-formatted string
formatted = formatted.replace(
/{time (.+?)}/g,
(_: string, pattern: string) => {
return moment().format(pattern);
}
);
return formatted;
}