Skip to content

Build your personal knowledge base with Trilium Notes

feat(core): integrate special notes with route

Elian Doran77971a10d17f
diff --git a/apps/client-standalone/src/lightweight/browser_routes.ts b/apps/client-standalone/src/lightweight/browser_routes.ts
index b8d9e7cf8a..b2b5ba33da 100644
--- a/apps/client-standalone/src/lightweight/browser_routes.ts
+++ b/apps/client-standalone/src/lightweight/browser_routes.ts
@@ -34,9 +34,9 @@ function wrapHandler(handler: (req: any) => unknown, transactional: boolean) {
* Creates an apiRoute function compatible with buildSharedApiRoutes.
* This bridges the core's route registration to the BrowserRouter.
*/
-function createApiRoute(router: BrowserRouter) {
+function createApiRoute(router: BrowserRouter, transactional: boolean) {
return (method: HttpMethod, path: string, handler: (req: any) => unknown) => {
- router.register(method, path, wrapHandler(handler, true));
+ router.register(method, path, wrapHandler(handler, transactional));
};
}
@@ -46,21 +46,21 @@ function createApiRoute(router: BrowserRouter) {
* @param router - The browser router instance
*/
export function registerRoutes(router: BrowserRouter): void {
- const apiRoute = createApiRoute(router);
- routes.buildSharedApiRoutes(apiRoute);
+ const apiRoute = createApiRoute(router, true);
+ routes.buildSharedApiRoutes({
+ apiRoute,
+ asyncApiRoute: createApiRoute(router, false)
+ });
apiRoute('get', '/bootstrap', bootstrapRoute);
// Dummy routes for compatibility.
apiRoute("get", "/api/script/widgets", () => []);
apiRoute("get", "/api/script/startup", () => []);
apiRoute("get", "/api/system-checks", () => ({ isCpuArchMismatch: false }));
- apiRoute("get", "/api/search/:searchString", () => []);
- apiRoute("get", "/api/search-templates", () => []);
apiRoute("get", "/api/autocomplete", () => []);
}
function bootstrapRoute() {
-
const assetPath = ".";
return {
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index 6fbabf41fe..f0a8e7f109 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -38,7 +38,6 @@ import scriptRoute from "./api/script.js";
import senderRoute from "./api/sender.js";
import setupApiRoute from "./api/setup.js";
import similarNotesRoute from "./api/similar_notes.js";
-import specialNotesRoute from "./api/special_notes.js";
import syncApiRoute from "./api/sync.js";
import systemInfoRoute from "./api/system_info.js";
import totp from './api/totp.js';
@@ -86,7 +85,10 @@ function register(app: express.Application) {
apiRoute(GET, '/api/totp_recovery/enabled', recoveryCodes.checkForRecoveryKeys);
apiRoute(GET, '/api/totp_recovery/used', recoveryCodes.getUsedRecoveryCodes);
- routes.buildSharedApiRoutes(apiRoute);
+ routes.buildSharedApiRoutes({
+ apiRoute,
+ asyncApiRoute
+ });
route(PUT, "/api/notes/:noteId/file", [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], filesRoute.updateFile, apiResultHandler);
route(GET, "/api/notes/:noteId/open", [auth.checkApiAuthOrElectron], filesRoute.openFile);
@@ -193,22 +195,6 @@ function register(app: express.Application) {
route(PST, "/api/clipper/open/:noteId", clipperMiddleware, clipperRoute.openNote, apiResultHandler);
asyncRoute(GET, "/api/clipper/notes-by-url/:noteUrl", clipperMiddleware, clipperRoute.findNotesByUrl, apiResultHandler);
- asyncApiRoute(GET, "/api/special-notes/inbox/:date", specialNotesRoute.getInboxNote);
- asyncApiRoute(GET, "/api/special-notes/days/:date", specialNotesRoute.getDayNote);
- asyncApiRoute(GET, "/api/special-notes/week-first-day/:date", specialNotesRoute.getWeekFirstDayNote);
- asyncApiRoute(GET, "/api/special-notes/weeks/:week", specialNotesRoute.getWeekNote);
- asyncApiRoute(GET, "/api/special-notes/months/:month", specialNotesRoute.getMonthNote);
- asyncApiRoute(GET, "/api/special-notes/quarters/:quarter", specialNotesRoute.getQuarterNote);
- apiRoute(GET, "/api/special-notes/years/:year", specialNotesRoute.getYearNote);
- apiRoute(GET, "/api/special-notes/notes-for-month/:month", specialNotesRoute.getDayNotesForMonth);
- apiRoute(PST, "/api/special-notes/sql-console", specialNotesRoute.createSqlConsole);
- asyncApiRoute(PST, "/api/special-notes/save-sql-console", specialNotesRoute.saveSqlConsole);
- apiRoute(PST, "/api/special-notes/search-note", specialNotesRoute.createSearchNote);
- apiRoute(PST, "/api/special-notes/save-search-note", specialNotesRoute.saveSearchNote);
- apiRoute(PST, "/api/special-notes/launchers/:noteId/reset", specialNotesRoute.resetLauncher);
- apiRoute(PST, "/api/special-notes/launchers/:parentNoteId/:launcherType", specialNotesRoute.createLauncher);
- apiRoute(PUT, "/api/special-notes/api-script-launcher", specialNotesRoute.createOrUpdateScriptLauncherFromApi);
-
asyncRoute(PST, "/api/database/anonymize/:type", [auth.checkApiAuthOrElectron, csrfMiddleware], databaseRoute.anonymize, apiResultHandler);
apiRoute(GET, "/api/database/anonymized-databases", databaseRoute.getExistingAnonymizedDatabases);
diff --git a/apps/server/src/services/date_notes.ts b/apps/server/src/services/date_notes.ts
index 0aa15aa330..b36ff8b874 100644
--- a/apps/server/src/services/date_notes.ts
+++ b/apps/server/src/services/date_notes.ts
@@ -1,436 +1,2 @@
-import type BNote from "../becca/entities/bnote.js";
-
-import attributeService from "./attributes.js";
-import cloningService from "./cloning.js";
-import { dayjs, Dayjs, getFirstDayOfWeek1, getWeekInfo, WeekSettings } from "@triliumnext/commons";
-import hoistedNoteService from "./hoisted_note.js";
-import noteService from "./notes.js";
-import optionService from "./options.js";
-import protectedSessionService from "./protected_session.js";
-import searchContext from "../services/search/search_context.js";
-import searchService from "../services/search/services/search.js";
-import sql from "./sql.js";
-import { t } from "i18next";
-import { ordinal } from "./i18n.js";
-
-const CALENDAR_ROOT_LABEL = "calendarRoot";
-const YEAR_LABEL = "yearNote";
-const QUARTER_LABEL = "quarterNote";
-const MONTH_LABEL = "monthNote";
-const WEEK_LABEL = "weekNote";
-const DATE_LABEL = "dateNote";
-
-const WEEKDAY_TRANSLATION_IDS = [
- "weekdays.sunday", "weekdays.monday", "weekdays.tuesday",
- "weekdays.wednesday", "weekdays.thursday", "weekdays.friday",
- "weekdays.saturday", "weekdays.sunday"
-];
-
-const MONTH_TRANSLATION_IDS = [
- "months.january",
- "months.february",
- "months.march",
- "months.april",
- "months.may",
- "months.june",
- "months.july",
- "months.august",
- "months.september",
- "months.october",
- "months.november",
- "months.december"
-];
-
-type TimeUnit = "year" | "quarter" | "month" | "week" | "day";
-
-const baseReplacements = {
- year: [ "year" ],
- quarter: [ "quarterNumber", "shortQuarter" ],
- month: [ "isoMonth", "monthNumber", "monthNumberPadded",
- "month", "shortMonth3", "shortMonth4" ],
- week: [ "weekNumber", "weekNumberPadded", "shortWeek", "shortWeek3" ],
- day: [ "isoDate", "dateNumber", "dateNumberPadded",
- "ordinal", "weekDay", "weekDay3", "weekDay2" ]
-};
-
-function getTimeUnitReplacements(timeUnit: TimeUnit): string[] {
- const units: TimeUnit[] = [ "year", "quarter", "month", "week", "day" ];
- const index = units.indexOf(timeUnit);
- return units.slice(0, index + 1).flatMap(unit => baseReplacements[unit]);
-}
-
-function getJournalNoteTitle(
- rootNote: BNote,
- timeUnit: TimeUnit,
- dateObj: Dayjs,
- number: number,
- weekYear?: number // Optional: the week year for cross-year weeks
-) {
- const patterns = {
- year: rootNote.getOwnedLabelValue("yearPattern") || "{year}",
- quarter: rootNote.getOwnedLabelValue("quarterPattern") || t("quarterNumber"),
- month: rootNote.getOwnedLabelValue("monthPattern") || "{monthNumberPadded} - {month}",
- week: rootNote.getOwnedLabelValue("weekPattern") || t("weekdayNumber"),
- day: rootNote.getOwnedLabelValue("datePattern") || "{dateNumberPadded} - {weekDay}"
- };
-
- const pattern = patterns[timeUnit];
- const monthName = t(MONTH_TRANSLATION_IDS[dateObj.month()]);
- const weekDay = t(WEEKDAY_TRANSLATION_IDS[dateObj.day()]);
- const numberStr = number.toString();
- const ordinalStr = ordinal(dateObj);
-
- // For week notes, use the weekYear if provided (handles cross-year weeks)
- const yearForDisplay = (timeUnit === "week" && weekYear !== undefined)
- ? weekYear.toString()
- : dateObj.format("YYYY");
-
- const allReplacements: Record<string, string> = {
- // Common date formats
- "{year}": yearForDisplay,
-
- // Month related
- "{isoMonth}": dateObj.format("YYYY-MM"),
- "{monthNumber}": numberStr,
- "{monthNumberPadded}": numberStr.padStart(2, "0"),
- "{month}": monthName,
- "{shortMonth3}": monthName.slice(0, 3),
- "{shortMonth4}": monthName.slice(0, 4),
-
- // Quarter related
- "{quarterNumber}": numberStr,
- "{shortQuarter}": `Q${numberStr}`,
-
- // Week related
- "{weekNumber}": numberStr,
- "{weekNumberPadded}": numberStr.padStart(2, "0"),
- "{shortWeek}": `W${numberStr}`,
- "{shortWeek3}": `W${numberStr.padStart(2, "0")}`,
-
- // Day related
- "{isoDate}": dateObj.format("YYYY-MM-DD"),
- "{dateNumber}": numberStr,
- "{dateNumberPadded}": numberStr.padStart(2, "0"),
- "{ordinal}": ordinalStr,
- "{weekDay}": weekDay,
- "{weekDay3}": weekDay.substring(0, 3),
- "{weekDay2}": weekDay.substring(0, 2)
- };
-
- const allowedReplacements = Object.entries(allReplacements).reduce((acc, [ key, value ]) => {
- const replacementKey = key.slice(1, -1);
- if (getTimeUnitReplacements(timeUnit).includes(replacementKey)) {
- acc[key] = value;
- }
- return acc;
- }, {} as Record<string, string>);
-
- return Object.entries(allowedReplacements).reduce(
- (title, [ key, value ]) => title.replace(new RegExp(key, "g"), value),
- pattern
- );
-}
-
-function createNote(parentNote: BNote, noteTitle: string) {
- return noteService.createNewNote({
- parentNoteId: parentNote.noteId,
- title: noteTitle,
- content: "",
- isProtected: parentNote.isProtected &&
- protectedSessionService.isProtectedSessionAvailable(),
- type: "text"
- }).note;
-}
-
-function getRootCalendarNote(): BNote {
- let rootNote;
-
- const workspaceNote = hoistedNoteService.getWorkspaceNote();
-
- if (!workspaceNote || !workspaceNote.isRoot()) {
- rootNote = searchService.findFirstNoteWithQuery(
- "#workspaceCalendarRoot", new searchContext({ ignoreHoistedNote: false })
- );
- }
-
- if (!rootNote) {
- rootNote = attributeService.getNoteWithLabel(CALENDAR_ROOT_LABEL);
- }
-
- if (!rootNote) {
- sql.transactional(() => {
- rootNote = noteService.createNewNote({
- parentNoteId: "root",
- title: "Calendar",
- target: "into",
- isProtected: false,
- type: "text",
- content: ""
- }).note;
-
- attributeService.createLabel(rootNote.noteId, CALENDAR_ROOT_LABEL);
- attributeService.createLabel(rootNote.noteId, "sorted");
- });
- }
-
- return rootNote as BNote;
-}
-
-function getYearNote(dateStr: string, _rootNote: BNote | null = null): BNote {
- const rootNote = _rootNote || getRootCalendarNote();
-
- const yearStr = dateStr.trim().substring(0, 4);
-
- let yearNote = searchService.findFirstNoteWithQuery(
- `#${YEAR_LABEL}="${yearStr}"`, new searchContext({ ancestorNoteId: rootNote.noteId })
- );
-
- if (yearNote) {
- return yearNote;
- }
-
- sql.transactional(() => {
- yearNote = createNote(rootNote, yearStr);
-
- attributeService.createLabel(yearNote.noteId, YEAR_LABEL, yearStr);
- attributeService.createLabel(yearNote.noteId, "sorted");
-
- const yearTemplateAttr = rootNote.getOwnedAttribute("relation", "yearTemplate");
-
- if (yearTemplateAttr) {
- attributeService.createRelation(yearNote.noteId, "template", yearTemplateAttr.value);
- }
- });
-
- return yearNote as unknown as BNote;
-}
-
-function getQuarterNumberStr(date: Dayjs) {
- return `${date.year()}-Q${date.quarter()}`;
-}
-
-function getQuarterNote(quarterStr: string, _rootNote: BNote | null = null): BNote {
- const rootNote = _rootNote || getRootCalendarNote();
-
- quarterStr = quarterStr.trim().substring(0, 7);
-
- let quarterNote = searchService.findFirstNoteWithQuery(
- `#${QUARTER_LABEL}="${quarterStr}"`, new searchContext({ ancestorNoteId: rootNote.noteId })
- );
-
- if (quarterNote) {
- return quarterNote;
- }
-
- const [ yearStr, quarterNumberStr ] = quarterStr.trim().split("-Q");
- const quarterNumber = parseInt(quarterNumberStr);
- const firstMonth = (quarterNumber - 1) * 3;
- const quarterStartDate = dayjs().year(parseInt(yearStr)).month(firstMonth).date(1);
-
- const yearNote = getYearNote(yearStr, rootNote);
- const noteTitle = getJournalNoteTitle(
- rootNote, "quarter", quarterStartDate, quarterNumber
- );
-
- sql.transactional(() => {
- quarterNote = createNote(yearNote, noteTitle);
-
- attributeService.createLabel(quarterNote.noteId, QUARTER_LABEL, quarterStr);
- attributeService.createLabel(quarterNote.noteId, "sorted");
-
- const quarterTemplateAttr = rootNote.getOwnedAttribute("relation", "quarterTemplate");
-
- if (quarterTemplateAttr) {
- attributeService.createRelation(
- quarterNote.noteId, "template", quarterTemplateAttr.value
- );
- }
- });
-
- return quarterNote as unknown as BNote;
-}
-
-function getMonthNote(dateStr: string, _rootNote: BNote | null = null): BNote {
- const rootNote = _rootNote || getRootCalendarNote();
-
- const monthStr = dateStr.substring(0, 7);
- const monthNumber = dateStr.substring(5, 7);
-
- let monthNote = searchService.findFirstNoteWithQuery(
- `#${MONTH_LABEL}="${monthStr}"`, new searchContext({ ancestorNoteId: rootNote.noteId })
- );
-
- if (monthNote) {
- return monthNote;
- }
-
- let monthParentNote: BNote | null;
-
- if (rootNote.hasLabel("enableQuarterNote")) {
- monthParentNote = getQuarterNote(getQuarterNumberStr(dayjs(dateStr)), rootNote);
- } else {
- monthParentNote = getYearNote(dateStr, rootNote);
- }
-
- const noteTitle = getJournalNoteTitle(
- rootNote, "month", dayjs(dateStr), parseInt(monthNumber)
- );
-
- sql.transactional(() => {
- monthNote = createNote(monthParentNote, noteTitle);
-
- attributeService.createLabel(monthNote.noteId, MONTH_LABEL, monthStr);
- attributeService.createLabel(monthNote.noteId, "sorted");
-
- const monthTemplateAttr = rootNote.getOwnedAttribute("relation", "monthTemplate");
-
- if (monthTemplateAttr) {
- attributeService.createRelation(monthNote.noteId, "template", monthTemplateAttr.value);
- }
- });
-
- return monthNote as unknown as BNote;
-}
-
-function getWeekSettings(): WeekSettings {
- return {
- firstDayOfWeek: parseInt(optionService.getOptionOrNull("firstDayOfWeek") ?? "1", 10),
- firstWeekOfYear: parseInt(optionService.getOptionOrNull("firstWeekOfYear") ?? "0", 10),
- minDaysInFirstWeek: parseInt(optionService.getOptionOrNull("minDaysInFirstWeek") ?? "4", 10)
- };
-}
-
-function getWeekStartDate(date: Dayjs): Dayjs {
- const firstDayISO = parseInt(optionService.getOptionOrNull("firstDayOfWeek") ?? "1", 10);
- const day = date.isoWeekday();
- const diff = (day - firstDayISO + 7) % 7;
- return date.clone().subtract(diff, "day").startOf("day");
-}
-
-function getWeekNumberStr(date: Dayjs): string {
- const { weekYear, weekNumber } = getWeekInfo(date, getWeekSettings());
- return `${weekYear}-W${weekNumber.toString().padStart(2, "0")}`;
-}
-
-function getWeekFirstDayNote(dateStr: string, rootNote: BNote | null = null) {
- const weekStartDate = getWeekStartDate(dayjs(dateStr));
- return getDayNote(weekStartDate.format("YYYY-MM-DD"), rootNote);
-}
-
-/**
- * Returns the {@link BNote} corresponding to the given week. If there is no note associated yet to that week, it will be created and returned instead.
- *
- * @param weekStr the week for which to return the corresponding note, in the format `2024-W04`.
- * @param _rootNote a {@link BNote} representing the calendar root, or {@code null} or not specified to use the default root calendar note.
- * @returns a Promise that resolves to the {@link BNote} corresponding to the week note.
- */
-function getWeekNote(weekStr: string, _rootNote: BNote | null = null): BNote | null {
- const rootNote = _rootNote || getRootCalendarNote();
- if (!rootNote.hasLabel("enableWeekNote")) {
- return null;
- }
-
- weekStr = weekStr.trim().substring(0, 8);
-
- let weekNote = searchService.findFirstNoteWithQuery(
- `#${WEEK_LABEL}="${weekStr}"`, new searchContext({ ancestorNoteId: rootNote.noteId })
- );
-
- if (weekNote) {
- return weekNote;
- }
-
- const [ yearStr, weekNumStr ] = weekStr.trim().split("-W");
- const weekNumber = parseInt(weekNumStr);
- const weekYear = parseInt(yearStr);
-
- // Calculate week start date based on user's first week of year settings.
- // This correctly handles cross-year weeks based on user preferences.
- const firstDayOfWeek1 = getFirstDayOfWeek1(weekYear, getWeekSettings());
- const startDate = firstDayOfWeek1.add(weekNumber - 1, "week");
- const endDate = startDate.add(6, "day");
-
- const startMonth = startDate.month();
- const endMonth = endDate.month();
-
- const monthNote = getMonthNote(startDate.format("YYYY-MM-DD"), rootNote);
- const noteTitle = getJournalNoteTitle(rootNote, "week", startDate, weekNumber, weekYear);
-
- sql.transactional(() => {
- weekNote = createNote(monthNote, noteTitle);
-
- attributeService.createLabel(weekNote.noteId, WEEK_LABEL, weekStr);
- attributeService.createLabel(weekNote.noteId, "sorted");
-
- const weekTemplateAttr = rootNote.getOwnedAttribute("relation", "weekTemplate");
-
- if (weekTemplateAttr) {
- attributeService.createRelation(weekNote.noteId, "template", weekTemplateAttr.value);
- }
-
- // If the week spans different months, clone the week note in the other month as well
- if (startMonth !== endMonth) {
- const secondMonthNote = getMonthNote(endDate.format("YYYY-MM-DD"), rootNote);
- cloningService.cloneNoteToParentNote(weekNote.noteId, secondMonthNote.noteId);
- }
- });
-
- return weekNote as unknown as BNote;
-}
-
-function getDayNote(dateStr: string, _rootNote: BNote | null = null): BNote {
- const rootNote = _rootNote || getRootCalendarNote();
-
- dateStr = dateStr.trim().substring(0, 10);
-
- let dateNote = searchService.findFirstNoteWithQuery(
- `#${DATE_LABEL}="${dateStr}"`, new searchContext({ ancestorNoteId: rootNote.noteId })
- );
-
- if (dateNote) {
- return dateNote;
- }
-
- let dateParentNote: BNote | null;
-
- if (rootNote.hasLabel("enableWeekNote")) {
- dateParentNote = getWeekNote(getWeekNumberStr(dayjs(dateStr)), rootNote);
- } else {
- dateParentNote = getMonthNote(dateStr, rootNote);
- }
-
- const dayNumber = dateStr.substring(8, 10);
- const noteTitle = getJournalNoteTitle(
- rootNote, "day", dayjs(dateStr), parseInt(dayNumber)
- );
-
- sql.transactional(() => {
- dateNote = createNote(dateParentNote as BNote, noteTitle);
-
- attributeService.createLabel(dateNote.noteId, DATE_LABEL, dateStr.substring(0, 10));
-
- const dateTemplateAttr = rootNote.getOwnedAttribute("relation", "dateTemplate");
-
- if (dateTemplateAttr) {
- attributeService.createRelation(dateNote.noteId, "template", dateTemplateAttr.value);
- }
- });
-
- return dateNote as unknown as BNote;
-}
-
-function getTodayNote(rootNote: BNote | null = null) {
- return getDayNote(dayjs().format("YYYY-MM-DD"), rootNote);
-}
-
-export default {
- getRootCalendarNote,
- getYearNote,
- getQuarterNote,
- getMonthNote,
- getWeekNote,
- getWeekFirstDayNote,
- getDayNote,
- getTodayNote,
- getJournalNoteTitle
-};
+import { date_notes } from "@triliumnext/core";
+export default date_notes;
diff --git a/apps/server/src/services/special_notes.ts b/apps/server/src/services/special_notes.ts
index cf71311e6d..58070ff0c5 100644
--- a/apps/server/src/services/special_notes.ts
+++ b/apps/server/src/services/special_notes.ts
@@ -1,288 +1,2 @@
-import attributeService from "./attributes.js";
-import dateNoteService from "./date_notes.js";
-import becca from "../becca/becca.js";
-import noteService from "./notes.js";
-import dateUtils from "./date_utils.js";
-import log from "./log.js";
-import hoistedNoteService from "./hoisted_note.js";
-import searchService from "./search/services/search.js";
-import SearchContext from "./search/search_context.js";
-import { LBTPL_NOTE_LAUNCHER, LBTPL_CUSTOM_WIDGET, LBTPL_SPACER, LBTPL_SCRIPT } from "./hidden_subtree.js";
-import { t } from "i18next";
-import BNote from '../becca/entities/bnote.js';
-import { SaveSearchNoteResponse, SaveSqlConsoleResponse } from "@triliumnext/commons";
-
-function getInboxNote(date: string) {
- const workspaceNote = hoistedNoteService.getWorkspaceNote();
- if (!workspaceNote) {
- throw new Error("Unable to find workspace note");
- }
-
- let inbox: BNote;
-
- if (!workspaceNote.isRoot()) {
- inbox = workspaceNote.searchNoteInSubtree("#workspaceInbox");
-
- if (!inbox) {
- inbox = workspaceNote.searchNoteInSubtree("#inbox");
- }
-
- if (!inbox) {
- inbox = workspaceNote;
- }
- } else {
- inbox = attributeService.getNoteWithLabel("inbox") || dateNoteService.getDayNote(date);
- }
-
- return inbox;
-}
-
-function createSqlConsole() {
- const { note } = noteService.createNewNote({
- parentNoteId: getMonthlyParentNoteId("_sqlConsole", "sqlConsole"),
- title: "SQL Console - " + dateUtils.localNowDate(),
- content: "SELECT title, isDeleted, isProtected FROM notes WHERE noteId = ''\n\n\n\n",
- type: "code",
- mime: "text/x-sqlite;schema=trilium"
- });
-
- note.setLabel("iconClass", "bx bx-data");
- note.setLabel("keepCurrentHoisting");
-
- return note;
-}
-
-async function saveSqlConsole(sqlConsoleNoteId: string) {
- const sqlConsoleNote = becca.getNote(sqlConsoleNoteId);
- if (!sqlConsoleNote) throw new Error(`Unable to find SQL console note ID: ${sqlConsoleNoteId}`);
- const today = dateUtils.localNowDate();
-
- const sqlConsoleHome = attributeService.getNoteWithLabel("sqlConsoleHome") || await dateNoteService.getDayNote(today);
-
- const result = sqlConsoleNote.cloneTo(sqlConsoleHome.noteId);
-
- for (const parentBranch of sqlConsoleNote.getParentBranches()) {
- if (parentBranch.parentNote?.hasAncestor("_hidden")) {
- parentBranch.markAsDeleted();
- }
- }
-
- return result satisfies SaveSqlConsoleResponse;
-}
-
-function createSearchNote(searchString: string, ancestorNoteId: string) {
- const { note } = noteService.createNewNote({
- parentNoteId: getMonthlyParentNoteId("_search", "search"),
- title: `${t("special_notes.search_prefix")} ${searchString}`,
- content: "",
- type: "search",
- mime: "application/json"
- });
-
- note.setLabel("searchString", searchString);
- note.setLabel("keepCurrentHoisting");
-
- if (ancestorNoteId) {
- note.setRelation("ancestor", ancestorNoteId);
- }
-
- return note;
-}
-
-function getSearchHome() {
- const workspaceNote = hoistedNoteService.getWorkspaceNote();
- if (!workspaceNote) {
- throw new Error("Unable to find workspace note");
- }
-
- if (!workspaceNote.isRoot()) {
- return workspaceNote.searchNoteInSubtree("#workspaceSearchHome") || workspaceNote.searchNoteInSubtree("#searchHome") || workspaceNote;
- } else {
- const today = dateUtils.localNowDate();
-
- return workspaceNote.searchNoteInSubtree("#searchHome") || dateNoteService.getDayNote(today);
- }
-}
-
-function saveSearchNote(searchNoteId: string) {
- const searchNote = becca.getNote(searchNoteId);
- if (!searchNote) {
- throw new Error("Unable to find search note");
- }
-
- const searchHome = getSearchHome();
-
- const result = searchNote.cloneTo(searchHome.noteId);
-
- for (const parentBranch of searchNote.getParentBranches()) {
- if (parentBranch.parentNote?.hasAncestor("_hidden")) {
- parentBranch.markAsDeleted();
- }
- }
-
- return result satisfies SaveSearchNoteResponse;
-}
-
-function getMonthlyParentNoteId(rootNoteId: string, prefix: string) {
- const month = dateUtils.localNowDate().substring(0, 7);
- const labelName = `${prefix}MonthNote`;
-
- let monthNote = searchService.findFirstNoteWithQuery(`#${labelName}="${month}"`, new SearchContext({ ancestorNoteId: rootNoteId }));
-
- if (!monthNote) {
- monthNote = noteService.createNewNote({
- parentNoteId: rootNoteId,
- title: month,
- content: "",
- isProtected: false,
- type: "book"
- }).note;
-
- monthNote.addLabel(labelName, month);
- }
-
- return monthNote.noteId;
-}
-
-function createScriptLauncher(parentNoteId: string, forceNoteId?: string) {
- const note = noteService.createNewNote({
- noteId: forceNoteId,
- title: "Script Launcher",
- type: "launcher",
- content: "",
- parentNoteId: parentNoteId
- }).note;
-
- note.addRelation("template", LBTPL_SCRIPT);
- return note;
-}
-
-export type LauncherType = "launcher" | "note" | "script" | "customWidget" | "spacer";
-
-interface LauncherConfig {
- parentNoteId: string;
- launcherType: LauncherType;
- noteId?: string;
-}
-
-function createLauncher({ parentNoteId, launcherType, noteId }: LauncherConfig) {
- let note;
-
- if (launcherType === "note") {
- note = noteService.createNewNote({
- noteId: noteId,
- title: "Note Launcher",
- type: "launcher",
- content: "",
- parentNoteId: parentNoteId
- }).note;
-
- note.addRelation("template", LBTPL_NOTE_LAUNCHER);
- } else if (launcherType === "script") {
- note = createScriptLauncher(parentNoteId, noteId);
- } else if (launcherType === "customWidget") {
- note = noteService.createNewNote({
- noteId: noteId,
- title: "Widget Launcher",
- type: "launcher",
- content: "",
- parentNoteId: parentNoteId
- }).note;
-
- note.addRelation("template", LBTPL_CUSTOM_WIDGET);
- } else if (launcherType === "spacer") {
- note = noteService.createNewNote({
- noteId: noteId,
- branchId: noteId,
- title: "Spacer",
- type: "launcher",
- content: "",
- parentNoteId: parentNoteId
- }).note;
-
- note.addRelation("template", LBTPL_SPACER);
- } else {
- throw new Error(`Unrecognized launcher type '${launcherType}'`);
- }
-
- return {
- success: true,
- note
- };
-}
-
-function resetLauncher(noteId: string) {
- const note = becca.getNote(noteId);
-
- if (note?.isLaunchBarConfig()) {
- if (note) {
- if (noteId === "_lbRoot" || noteId === "_lbMobileRoot") {
- // deleting hoisted notes are not allowed, so we just reset the children
- for (const childNote of note.getChildNotes()) {
- childNote.deleteNote();
- }
- } else {
- note.deleteNote();
- }
- } else {
- log.info(`Note ${noteId} has not been found and cannot be reset.`);
- }
- } else {
- log.info(`Note ${noteId} is not a resettable launcher note.`);
- }
-
- // the re-building deleted launchers will be done in handlers
-}
-
-/**
- * This exists to ease transition into the new launchbar, but it's not meant to be a permanent functionality.
- * Previously, the launchbar was fixed and the only way to add buttons was through this API, so a lot of buttons have been
- * created just to fill this user hole.
- *
- * Another use case was for script-packages (e.g. demo Task manager) which could this way register automatically/easily
- * into the launchbar - for this it's recommended to use backend API's createOrUpdateLauncher()
- */
-function createOrUpdateScriptLauncherFromApi(opts: { id: string; title: string; action: string; icon?: string; shortcut?: string }) {
- if (opts.id && !/^[a-z0-9]+$/i.test(opts.id)) {
- throw new Error(`Launcher ID can be alphanumeric only, '${opts.id}' given`);
- }
-
- const launcherId = opts.id || `tb_${opts.title.toLowerCase().replace(/[^[a-z0-9]/gi, "")}`;
-
- if (!opts.title) {
- throw new Error("Title is mandatory property to create or update a launcher.");
- }
-
- const launcherNote = becca.getNote(launcherId) || createScriptLauncher("_lbVisibleLaunchers", launcherId);
-
- launcherNote.title = opts.title;
- launcherNote.setContent(`(${opts.action})()`);
- launcherNote.setLabel("scriptInLauncherContent"); // there's no target note, the script is in the launcher's content
- launcherNote.mime = "application/javascript;env=frontend";
- launcherNote.save();
-
- if (opts.shortcut) {
- launcherNote.setLabel("keyboardShortcut", opts.shortcut);
- } else {
- launcherNote.removeLabel("keyboardShortcut");
- }
-
- if (opts.icon) {
- launcherNote.setLabel("iconClass", `bx bx-${opts.icon}`);
- } else {
- launcherNote.removeLabel("iconClass");
- }
-
- return launcherNote;
-}
-
-export default {
- getInboxNote,
- createSqlConsole,
- saveSqlConsole,
- createSearchNote,
- saveSearchNote,
- createLauncher,
- resetLauncher,
- createOrUpdateScriptLauncherFromApi
-};
+import { special_notes } from "@triliumnext/core";
+export default special_notes;
diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.ts
index 4f9e0e6188..dc836c372a 100644
--- a/packages/trilium-core/src/index.ts
+++ b/packages/trilium-core/src/index.ts
@@ -41,6 +41,8 @@ export { default as getSharedBootstrapItems } from "./services/bootstrap_utils";
export { default as branches } from "./services/branches";
export { default as bulk_actions } from "./services/bulk_actions";
export { default as hoisted_note } from "./services/hoisted_note";
+export { default as special_notes } from "./services/special_notes";
+export { default as date_notes } from "./services/date_notes";
export { default as attribute_formatter} from "./services/attribute_formatter";
diff --git a/apps/server/src/routes/api/special_notes.ts b/packages/trilium-core/src/routes/api/special_notes.ts
similarity index 96%
rename from apps/server/src/routes/api/special_notes.ts
rename to packages/trilium-core/src/routes/api/special_notes.ts
index 5169260709..7f17ca7f5f 100644
--- a/apps/server/src/routes/api/special_notes.ts
+++ b/packages/trilium-core/src/routes/api/special_notes.ts
@@ -1,10 +1,10 @@
import type { Request } from "express";
import becca from "../../becca/becca.js";
-import cls from "../../services/cls.js";
+import * as cls from "../../services/context.js";
import dateNoteService from "../../services/date_notes.js";
import specialNotesService, { type LauncherType } from "../../services/special_notes.js";
-import sql from "../../services/sql.js";
+import { getSql } from "../../services/sql/index.js";
function getInboxNote(req: Request<{ date: string }>) {
return specialNotesService.getInboxNote(req.params.date);
@@ -51,6 +51,7 @@ function getDayNotesForMonth(req: Request) {
AND attr.name = 'dateNote'
AND attr.value LIKE '${month}%'`;
+ const sql = getSql();
if (calendarRoot) {
const rows = sql.getRows<{ date: string; noteId: string }>(query);
const result: Record<string, string> = {};
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index 0008314f0d..c517e0b485 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -18,6 +18,7 @@ import relationMapApiRoute from "./api/relation-map";
import recentChangesApiRoute from "./api/recent_changes";
import bulkActionRoute from "./api/bulk_action";
import searchRoute from "./api/search";
+import specialNotesRoute from "./api/special_notes";
// TODO: Deduplicate with routes.ts
const GET = "get",
@@ -26,7 +27,12 @@ const GET = "get",
PATCH = "patch",
DEL = "delete";
-export function buildSharedApiRoutes(apiRoute: any) {
+interface SharedApiRoutesContext {
+ apiRoute: any;
+ asyncApiRoute: any;
+}
+
+export function buildSharedApiRoutes({ apiRoute, asyncApiRoute }: SharedApiRoutesContext) {
apiRoute(GET, '/api/tree', treeApiRoute.getTree);
apiRoute(PST, '/api/tree/load', treeApiRoute.load);
@@ -105,6 +111,22 @@ export function buildSharedApiRoutes(apiRoute: any) {
apiRoute(PUT, "/api/notes/:noteId/clone-to-note/:parentNoteId", cloningApiRoute.cloneNoteToParentNote);
apiRoute(PUT, "/api/notes/:noteId/clone-after/:afterBranchId", cloningApiRoute.cloneNoteAfter);
+ asyncApiRoute(GET, "/api/special-notes/inbox/:date", specialNotesRoute.getInboxNote);
+ asyncApiRoute(GET, "/api/special-notes/days/:date", specialNotesRoute.getDayNote);
+ asyncApiRoute(GET, "/api/special-notes/week-first-day/:date", specialNotesRoute.getWeekFirstDayNote);
+ asyncApiRoute(GET, "/api/special-notes/weeks/:week", specialNotesRoute.getWeekNote);
+ asyncApiRoute(GET, "/api/special-notes/months/:month", specialNotesRoute.getMonthNote);
+ asyncApiRoute(GET, "/api/special-notes/quarters/:quarter", specialNotesRoute.getQuarterNote);
+ apiRoute(GET, "/api/special-notes/years/:year", specialNotesRoute.getYearNote);
+ apiRoute(GET, "/api/special-notes/notes-for-month/:month", specialNotesRoute.getDayNotesForMonth);
+ apiRoute(PST, "/api/special-notes/sql-console", specialNotesRoute.createSqlConsole);
+ asyncApiRoute(PST, "/api/special-notes/save-sql-console", specialNotesRoute.saveSqlConsole);
+ apiRoute(PST, "/api/special-notes/search-note", specialNotesRoute.createSearchNote);
+ apiRoute(PST, "/api/special-notes/save-search-note", specialNotesRoute.saveSearchNote);
+ apiRoute(PST, "/api/special-notes/launchers/:noteId/reset", specialNotesRoute.resetLauncher);
+ apiRoute(PST, "/api/special-notes/launchers/:parentNoteId/:launcherType", specialNotesRoute.createLauncher);
+ apiRoute(PUT, "/api/special-notes/api-script-launcher", specialNotesRoute.createOrUpdateScriptLauncherFromApi);
+
apiRoute(GET, "/api/note-map/:noteId/backlink-count", noteMapRoute.getBacklinkCount);
apiRoute(PST, "/api/recent-notes", recentNotesRoute.addRecentNote);
diff --git a/apps/server/src/services/date_notes.spec.ts b/packages/trilium-core/src/services/date_notes.spec.ts
similarity index 100%
rename from apps/server/src/services/date_notes.spec.ts
rename to packages/trilium-core/src/services/date_notes.spec.ts
diff --git a/packages/trilium-core/src/services/date_notes.ts b/packages/trilium-core/src/services/date_notes.ts
new file mode 100644
index 0000000000..fe0f4bd5e9
--- /dev/null
+++ b/packages/trilium-core/src/services/date_notes.ts
@@ -0,0 +1,436 @@
+import type BNote from "../becca/entities/bnote.js";
+
+import attributeService from "./attributes.js";
+import cloningService from "./cloning.js";
+import { dayjs, Dayjs, getFirstDayOfWeek1, getWeekInfo, WeekSettings } from "@triliumnext/commons";
+import hoistedNoteService from "./hoisted_note.js";
+import noteService from "./notes.js";
+import optionService from "./options.js";
+import protectedSessionService from "./protected_session.js";
+import searchContext from "../services/search/search_context.js";
+import searchService from "../services/search/services/search.js";
+import { getSql } from "./sql/index.js";
+import { t } from "i18next";
+import { ordinal } from "./i18n.js";
+
+const CALENDAR_ROOT_LABEL = "calendarRoot";
+const YEAR_LABEL = "yearNote";
+const QUARTER_LABEL = "quarterNote";
+const MONTH_LABEL = "monthNote";
+const WEEK_LABEL = "weekNote";
+const DATE_LABEL = "dateNote";
+
+const WEEKDAY_TRANSLATION_IDS = [
+ "weekdays.sunday", "weekdays.monday", "weekdays.tuesday",
+ "weekdays.wednesday", "weekdays.thursday", "weekdays.friday",
+ "weekdays.saturday", "weekdays.sunday"
+];
+
+const MONTH_TRANSLATION_IDS = [
+ "months.january",
+ "months.february",
+ "months.march",
+ "months.april",
+ "months.may",
+ "months.june",
+ "months.july",
+ "months.august",
+ "months.september",
+ "months.october",
+ "months.november",
+ "months.december"
+];
+
+type TimeUnit = "year" | "quarter" | "month" | "week" | "day";
+
+const baseReplacements = {
+ year: [ "year" ],
+ quarter: [ "quarterNumber", "shortQuarter" ],
+ month: [ "isoMonth", "monthNumber", "monthNumberPadded",
+ "month", "shortMonth3", "shortMonth4" ],
+ week: [ "weekNumber", "weekNumberPadded", "shortWeek", "shortWeek3" ],
+ day: [ "isoDate", "dateNumber", "dateNumberPadded",
+ "ordinal", "weekDay", "weekDay3", "weekDay2" ]
+};
+
+function getTimeUnitReplacements(timeUnit: TimeUnit): string[] {
+ const units: TimeUnit[] = [ "year", "quarter", "month", "week", "day" ];
+ const index = units.indexOf(timeUnit);
+ return units.slice(0, index + 1).flatMap(unit => baseReplacements[unit]);
+}
+
+function getJournalNoteTitle(
+ rootNote: BNote,
+ timeUnit: TimeUnit,
+ dateObj: Dayjs,
+ number: number,
+ weekYear?: number // Optional: the week year for cross-year weeks
+) {
+ const patterns = {
+ year: rootNote.getOwnedLabelValue("yearPattern") || "{year}",
+ quarter: rootNote.getOwnedLabelValue("quarterPattern") || t("quarterNumber"),
+ month: rootNote.getOwnedLabelValue("monthPattern") || "{monthNumberPadded} - {month}",
+ week: rootNote.getOwnedLabelValue("weekPattern") || t("weekdayNumber"),
+ day: rootNote.getOwnedLabelValue("datePattern") || "{dateNumberPadded} - {weekDay}"
+ };
+
+ const pattern = patterns[timeUnit];
+ const monthName = t(MONTH_TRANSLATION_IDS[dateObj.month()]);
+ const weekDay = t(WEEKDAY_TRANSLATION_IDS[dateObj.day()]);
+ const numberStr = number.toString();
+ const ordinalStr = ordinal(dateObj);
+
+ // For week notes, use the weekYear if provided (handles cross-year weeks)
+ const yearForDisplay = (timeUnit === "week" && weekYear !== undefined)
+ ? weekYear.toString()
+ : dateObj.format("YYYY");
+
+ const allReplacements: Record<string, string> = {
+ // Common date formats
+ "{year}": yearForDisplay,
+
+ // Month related
+ "{isoMonth}": dateObj.format("YYYY-MM"),
+ "{monthNumber}": numberStr,
+ "{monthNumberPadded}": numberStr.padStart(2, "0"),
+ "{month}": monthName,
+ "{shortMonth3}": monthName.slice(0, 3),
+ "{shortMonth4}": monthName.slice(0, 4),
+
+ // Quarter related
+ "{quarterNumber}": numberStr,
+ "{shortQuarter}": `Q${numberStr}`,
+
+ // Week related
+ "{weekNumber}": numberStr,
+ "{weekNumberPadded}": numberStr.padStart(2, "0"),
+ "{shortWeek}": `W${numberStr}`,
+ "{shortWeek3}": `W${numberStr.padStart(2, "0")}`,
+
+ // Day related
+ "{isoDate}": dateObj.format("YYYY-MM-DD"),
+ "{dateNumber}": numberStr,
+ "{dateNumberPadded}": numberStr.padStart(2, "0"),
+ "{ordinal}": ordinalStr,
+ "{weekDay}": weekDay,
+ "{weekDay3}": weekDay.substring(0, 3),
+ "{weekDay2}": weekDay.substring(0, 2)
+ };
+
+ const allowedReplacements = Object.entries(allReplacements).reduce((acc, [ key, value ]) => {
+ const replacementKey = key.slice(1, -1);
+ if (getTimeUnitReplacements(timeUnit).includes(replacementKey)) {
+ acc[key] = value;
+ }
+ return acc;
+ }, {} as Record<string, string>);
+
+ return Object.entries(allowedReplacements).reduce(
+ (title, [ key, value ]) => title.replace(new RegExp(key, "g"), value),
+ pattern
+ );
+}
+
+function createNote(parentNote: BNote, noteTitle: string) {
+ return noteService.createNewNote({
+ parentNoteId: parentNote.noteId,
+ title: noteTitle,
+ content: "",
+ isProtected: parentNote.isProtected &&
+ protectedSessionService.isProtectedSessionAvailable(),
+ type: "text"
+ }).note;
+}
+
+function getRootCalendarNote(): BNote {
+ let rootNote;
+
+ const workspaceNote = hoistedNoteService.getWorkspaceNote();
+
+ if (!workspaceNote || !workspaceNote.isRoot()) {
+ rootNote = searchService.findFirstNoteWithQuery(
+ "#workspaceCalendarRoot", new searchContext({ ignoreHoistedNote: false })
+ );
+ }
+
+ if (!rootNote) {
+ rootNote = attributeService.getNoteWithLabel(CALENDAR_ROOT_LABEL);
+ }
+
+ if (!rootNote) {
+ getSql().transactional(() => {
+ rootNote = noteService.createNewNote({
+ parentNoteId: "root",
+ title: "Calendar",
+ target: "into",
+ isProtected: false,
+ type: "text",
+ content: ""
+ }).note;
+
+ attributeService.createLabel(rootNote.noteId, CALENDAR_ROOT_LABEL);
+ attributeService.createLabel(rootNote.noteId, "sorted");
+ });
+ }
+
+ return rootNote as BNote;
+}
+
+function getYearNote(dateStr: string, _rootNote: BNote | null = null): BNote {
+ const rootNote = _rootNote || getRootCalendarNote();
+
+ const yearStr = dateStr.trim().substring(0, 4);
+
+ let yearNote = searchService.findFirstNoteWithQuery(
+ `#${YEAR_LABEL}="${yearStr}"`, new searchContext({ ancestorNoteId: rootNote.noteId })
+ );
+
+ if (yearNote) {
+ return yearNote;
+ }
+
+ getSql().transactional(() => {
+ yearNote = createNote(rootNote, yearStr);
+
+ attributeService.createLabel(yearNote.noteId, YEAR_LABEL, yearStr);
+ attributeService.createLabel(yearNote.noteId, "sorted");
+
+ const yearTemplateAttr = rootNote.getOwnedAttribute("relation", "yearTemplate");
+
+ if (yearTemplateAttr) {
+ attributeService.createRelation(yearNote.noteId, "template", yearTemplateAttr.value);
+ }
+ });
+
+ return yearNote as unknown as BNote;
+}
+
+function getQuarterNumberStr(date: Dayjs) {
+ return `${date.year()}-Q${date.quarter()}`;
+}
+
+function getQuarterNote(quarterStr: string, _rootNote: BNote | null = null): BNote {
+ const rootNote = _rootNote || getRootCalendarNote();
+
+ quarterStr = quarterStr.trim().substring(0, 7);
+
+ let quarterNote = searchService.findFirstNoteWithQuery(
+ `#${QUARTER_LABEL}="${quarterStr}"`, new searchContext({ ancestorNoteId: rootNote.noteId })
+ );
+
+ if (quarterNote) {
+ return quarterNote;
+ }
+
+ const [ yearStr, quarterNumberStr ] = quarterStr.trim().split("-Q");
+ const quarterNumber = parseInt(quarterNumberStr);
+ const firstMonth = (quarterNumber - 1) * 3;
+ const quarterStartDate = dayjs().year(parseInt(yearStr)).month(firstMonth).date(1);
+
+ const yearNote = getYearNote(yearStr, rootNote);
+ const noteTitle = getJournalNoteTitle(
+ rootNote, "quarter", quarterStartDate, quarterNumber
+ );
+
+ getSql().transactional(() => {
+ quarterNote = createNote(yearNote, noteTitle);
+
+ attributeService.createLabel(quarterNote.noteId, QUARTER_LABEL, quarterStr);
+ attributeService.createLabel(quarterNote.noteId, "sorted");
+
+ const quarterTemplateAttr = rootNote.getOwnedAttribute("relation", "quarterTemplate");
+
+ if (quarterTemplateAttr) {
+ attributeService.createRelation(
+ quarterNote.noteId, "template", quarterTemplateAttr.value
+ );
+ }
+ });
+
+ return quarterNote as unknown as BNote;
+}
+
+function getMonthNote(dateStr: string, _rootNote: BNote | null = null): BNote {
+ const rootNote = _rootNote || getRootCalendarNote();
+
+ const monthStr = dateStr.substring(0, 7);
+ const monthNumber = dateStr.substring(5, 7);
+
+ let monthNote = searchService.findFirstNoteWithQuery(
+ `#${MONTH_LABEL}="${monthStr}"`, new searchContext({ ancestorNoteId: rootNote.noteId })
+ );
+
+ if (monthNote) {
+ return monthNote;
+ }
+
+ let monthParentNote: BNote | null;
+
+ if (rootNote.hasLabel("enableQuarterNote")) {
+ monthParentNote = getQuarterNote(getQuarterNumberStr(dayjs(dateStr)), rootNote);
+ } else {
+ monthParentNote = getYearNote(dateStr, rootNote);
+ }
+
+ const noteTitle = getJournalNoteTitle(
+ rootNote, "month", dayjs(dateStr), parseInt(monthNumber)
+ );
+
+ getSql().transactional(() => {
+ monthNote = createNote(monthParentNote, noteTitle);
+
+ attributeService.createLabel(monthNote.noteId, MONTH_LABEL, monthStr);
+ attributeService.createLabel(monthNote.noteId, "sorted");
+
+ const monthTemplateAttr = rootNote.getOwnedAttribute("relation", "monthTemplate");
+
+ if (monthTemplateAttr) {
+ attributeService.createRelation(monthNote.noteId, "template", monthTemplateAttr.value);
+ }
+ });
+
+ return monthNote as unknown as BNote;
+}
+
+function getWeekSettings(): WeekSettings {
+ return {
+ firstDayOfWeek: parseInt(optionService.getOptionOrNull("firstDayOfWeek") ?? "1", 10),
+ firstWeekOfYear: parseInt(optionService.getOptionOrNull("firstWeekOfYear") ?? "0", 10),
+ minDaysInFirstWeek: parseInt(optionService.getOptionOrNull("minDaysInFirstWeek") ?? "4", 10)
+ };
+}
+
+function getWeekStartDate(date: Dayjs): Dayjs {
+ const firstDayISO = parseInt(optionService.getOptionOrNull("firstDayOfWeek") ?? "1", 10);
+ const day = date.isoWeekday();
+ const diff = (day - firstDayISO + 7) % 7;
+ return date.clone().subtract(diff, "day").startOf("day");
+}
+
+function getWeekNumberStr(date: Dayjs): string {
+ const { weekYear, weekNumber } = getWeekInfo(date, getWeekSettings());
+ return `${weekYear}-W${weekNumber.toString().padStart(2, "0")}`;
+}
+
+function getWeekFirstDayNote(dateStr: string, rootNote: BNote | null = null) {
+ const weekStartDate = getWeekStartDate(dayjs(dateStr));
+ return getDayNote(weekStartDate.format("YYYY-MM-DD"), rootNote);
+}
+
+/**
+ * Returns the {@link BNote} corresponding to the given week. If there is no note associated yet to that week, it will be created and returned instead.
+ *
+ * @param weekStr the week for which to return the corresponding note, in the format `2024-W04`.
+ * @param _rootNote a {@link BNote} representing the calendar root, or {@code null} or not specified to use the default root calendar note.
+ * @returns a Promise that resolves to the {@link BNote} corresponding to the week note.
+ */
+function getWeekNote(weekStr: string, _rootNote: BNote | null = null): BNote | null {
+ const rootNote = _rootNote || getRootCalendarNote();
+ if (!rootNote.hasLabel("enableWeekNote")) {
+ return null;
+ }
+
+ weekStr = weekStr.trim().substring(0, 8);
+
+ let weekNote = searchService.findFirstNoteWithQuery(
+ `#${WEEK_LABEL}="${weekStr}"`, new searchContext({ ancestorNoteId: rootNote.noteId })
+ );
+
+ if (weekNote) {
+ return weekNote;
+ }
+
+ const [ yearStr, weekNumStr ] = weekStr.trim().split("-W");
+ const weekNumber = parseInt(weekNumStr);
+ const weekYear = parseInt(yearStr);
+
+ // Calculate week start date based on user's first week of year settings.
+ // This correctly handles cross-year weeks based on user preferences.
+ const firstDayOfWeek1 = getFirstDayOfWeek1(weekYear, getWeekSettings());
+ const startDate = firstDayOfWeek1.add(weekNumber - 1, "week");
+ const endDate = startDate.add(6, "day");
+
+ const startMonth = startDate.month();
+ const endMonth = endDate.month();
+
+ const monthNote = getMonthNote(startDate.format("YYYY-MM-DD"), rootNote);
+ const noteTitle = getJournalNoteTitle(rootNote, "week", startDate, weekNumber, weekYear);
+
+ getSql().transactional(() => {
+ weekNote = createNote(monthNote, noteTitle);
+
+ attributeService.createLabel(weekNote.noteId, WEEK_LABEL, weekStr);
+ attributeService.createLabel(weekNote.noteId, "sorted");
+
+ const weekTemplateAttr = rootNote.getOwnedAttribute("relation", "weekTemplate");
+
+ if (weekTemplateAttr) {
+ attributeService.createRelation(weekNote.noteId, "template", weekTemplateAttr.value);
+ }
+
+ // If the week spans different months, clone the week note in the other month as well
+ if (startMonth !== endMonth) {
+ const secondMonthNote = getMonthNote(endDate.format("YYYY-MM-DD"), rootNote);
+ cloningService.cloneNoteToParentNote(weekNote.noteId, secondMonthNote.noteId);
+ }
+ });
+
+ return weekNote as unknown as BNote;
+}
+
+function getDayNote(dateStr: string, _rootNote: BNote | null = null): BNote {
+ const rootNote = _rootNote || getRootCalendarNote();
+
+ dateStr = dateStr.trim().substring(0, 10);
+
+ let dateNote = searchService.findFirstNoteWithQuery(
+ `#${DATE_LABEL}="${dateStr}"`, new searchContext({ ancestorNoteId: rootNote.noteId })
+ );
+
+ if (dateNote) {
+ return dateNote;
+ }
+
+ let dateParentNote: BNote | null;
+
+ if (rootNote.hasLabel("enableWeekNote")) {
+ dateParentNote = getWeekNote(getWeekNumberStr(dayjs(dateStr)), rootNote);
+ } else {
+ dateParentNote = getMonthNote(dateStr, rootNote);
+ }
+
+ const dayNumber = dateStr.substring(8, 10);
+ const noteTitle = getJournalNoteTitle(
+ rootNote, "day", dayjs(dateStr), parseInt(dayNumber)
+ );
+
+ getSql().transactional(() => {
+ dateNote = createNote(dateParentNote as BNote, noteTitle);
+
+ attributeService.createLabel(dateNote.noteId, DATE_LABEL, dateStr.substring(0, 10));
+
+ const dateTemplateAttr = rootNote.getOwnedAttribute("relation", "dateTemplate");
+
+ if (dateTemplateAttr) {
+ attributeService.createRelation(dateNote.noteId, "template", dateTemplateAttr.value);
+ }
+ });
+
+ return dateNote as unknown as BNote;
+}
+
+function getTodayNote(rootNote: BNote | null = null) {
+ return getDayNote(dayjs().format("YYYY-MM-DD"), rootNote);
+}
+
+export default {
+ getRootCalendarNote,
+ getYearNote,
+ getQuarterNote,
+ getMonthNote,
+ getWeekNote,
+ getWeekFirstDayNote,
+ getDayNote,
+ getTodayNote,
+ getJournalNoteTitle
+};
diff --git a/packages/trilium-core/src/services/special_notes.ts b/packages/trilium-core/src/services/special_notes.ts
new file mode 100644
index 0000000000..03d5ca1f8d
--- /dev/null
+++ b/packages/trilium-core/src/services/special_notes.ts
@@ -0,0 +1,288 @@
+import attributeService from "./attributes.js";
+import dateNoteService from "./date_notes.js";
+import becca from "../becca/becca.js";
+import noteService from "./notes.js";
+import dateUtils from "./utils/date.js";
+import { getLog } from "./log.js";
+import hoistedNoteService from "./hoisted_note.js";
+import searchService from "./search/services/search.js";
+import SearchContext from "./search/search_context.js";
+import { LBTPL_NOTE_LAUNCHER, LBTPL_CUSTOM_WIDGET, LBTPL_SPACER, LBTPL_SCRIPT } from "./hidden_subtree.js";
+import { t } from "i18next";
+import BNote from '../becca/entities/bnote.js';
+import { SaveSearchNoteResponse, SaveSqlConsoleResponse } from "@triliumnext/commons";
+
+function getInboxNote(date: string) {
+ const workspaceNote = hoistedNoteService.getWorkspaceNote();
+ if (!workspaceNote) {
+ throw new Error("Unable to find workspace note");
+ }
+
+ let inbox: BNote;
+
+ if (!workspaceNote.isRoot()) {
+ inbox = workspaceNote.searchNoteInSubtree("#workspaceInbox");
+
+ if (!inbox) {
+ inbox = workspaceNote.searchNoteInSubtree("#inbox");
+ }
+
+ if (!inbox) {
+ inbox = workspaceNote;
+ }
+ } else {
+ inbox = attributeService.getNoteWithLabel("inbox") || dateNoteService.getDayNote(date);
+ }
+
+ return inbox;
+}
+
+function createSqlConsole() {
+ const { note } = noteService.createNewNote({
+ parentNoteId: getMonthlyParentNoteId("_sqlConsole", "sqlConsole"),
+ title: "SQL Console - " + dateUtils.localNowDate(),
+ content: "SELECT title, isDeleted, isProtected FROM notes WHERE noteId = ''\n\n\n\n",
+ type: "code",
+ mime: "text/x-sqlite;schema=trilium"
+ });
+
+ note.setLabel("iconClass", "bx bx-data");
+ note.setLabel("keepCurrentHoisting");
+
+ return note;
+}
+
+async function saveSqlConsole(sqlConsoleNoteId: string) {
+ const sqlConsoleNote = becca.getNote(sqlConsoleNoteId);
+ if (!sqlConsoleNote) throw new Error(`Unable to find SQL console note ID: ${sqlConsoleNoteId}`);
+ const today = dateUtils.localNowDate();
+
+ const sqlConsoleHome = attributeService.getNoteWithLabel("sqlConsoleHome") || await dateNoteService.getDayNote(today);
+
+ const result = sqlConsoleNote.cloneTo(sqlConsoleHome.noteId);
+
+ for (const parentBranch of sqlConsoleNote.getParentBranches()) {
+ if (parentBranch.parentNote?.hasAncestor("_hidden")) {
+ parentBranch.markAsDeleted();
+ }
+ }
+
+ return result satisfies SaveSqlConsoleResponse;
+}
+
+function createSearchNote(searchString: string, ancestorNoteId: string) {
+ const { note } = noteService.createNewNote({
+ parentNoteId: getMonthlyParentNoteId("_search", "search"),
+ title: `${t("special_notes.search_prefix")} ${searchString}`,
+ content: "",
+ type: "search",
+ mime: "application/json"
+ });
+
+ note.setLabel("searchString", searchString);
+ note.setLabel("keepCurrentHoisting");
+
+ if (ancestorNoteId) {
+ note.setRelation("ancestor", ancestorNoteId);
+ }
+
+ return note;
+}
+
+function getSearchHome() {
+ const workspaceNote = hoistedNoteService.getWorkspaceNote();
+ if (!workspaceNote) {
+ throw new Error("Unable to find workspace note");
+ }
+
+ if (!workspaceNote.isRoot()) {
+ return workspaceNote.searchNoteInSubtree("#workspaceSearchHome") || workspaceNote.searchNoteInSubtree("#searchHome") || workspaceNote;
+ } else {
+ const today = dateUtils.localNowDate();
+
+ return workspaceNote.searchNoteInSubtree("#searchHome") || dateNoteService.getDayNote(today);
+ }
+}
+
+function saveSearchNote(searchNoteId: string) {
+ const searchNote = becca.getNote(searchNoteId);
+ if (!searchNote) {
+ throw new Error("Unable to find search note");
+ }
+
+ const searchHome = getSearchHome();
+
+ const result = searchNote.cloneTo(searchHome.noteId);
+
+ for (const parentBranch of searchNote.getParentBranches()) {
+ if (parentBranch.parentNote?.hasAncestor("_hidden")) {
+ parentBranch.markAsDeleted();
+ }
+ }
+
+ return result satisfies SaveSearchNoteResponse;
+}
+
+function getMonthlyParentNoteId(rootNoteId: string, prefix: string) {
+ const month = dateUtils.localNowDate().substring(0, 7);
+ const labelName = `${prefix}MonthNote`;
+
+ let monthNote = searchService.findFirstNoteWithQuery(`#${labelName}="${month}"`, new SearchContext({ ancestorNoteId: rootNoteId }));
+
+ if (!monthNote) {
+ monthNote = noteService.createNewNote({
+ parentNoteId: rootNoteId,
+ title: month,
+ content: "",
+ isProtected: false,
+ type: "book"
+ }).note;
+
+ monthNote.addLabel(labelName, month);
+ }
+
+ return monthNote.noteId;
+}
+
+function createScriptLauncher(parentNoteId: string, forceNoteId?: string) {
+ const note = noteService.createNewNote({
+ noteId: forceNoteId,
+ title: "Script Launcher",
+ type: "launcher",
+ content: "",
+ parentNoteId: parentNoteId
+ }).note;
+
+ note.addRelation("template", LBTPL_SCRIPT);
+ return note;
+}
+
+export type LauncherType = "launcher" | "note" | "script" | "customWidget" | "spacer";
+
+interface LauncherConfig {
+ parentNoteId: string;
+ launcherType: LauncherType;
+ noteId?: string;
+}
+
+function createLauncher({ parentNoteId, launcherType, noteId }: LauncherConfig) {
+ let note;
+
+ if (launcherType === "note") {
+ note = noteService.createNewNote({
+ noteId: noteId,
+ title: "Note Launcher",
+ type: "launcher",
+ content: "",
+ parentNoteId: parentNoteId
+ }).note;
+
+ note.addRelation("template", LBTPL_NOTE_LAUNCHER);
+ } else if (launcherType === "script") {
+ note = createScriptLauncher(parentNoteId, noteId);
+ } else if (launcherType === "customWidget") {
+ note = noteService.createNewNote({
+ noteId: noteId,
+ title: "Widget Launcher",
+ type: "launcher",
+ content: "",
+ parentNoteId: parentNoteId
+ }).note;
+
+ note.addRelation("template", LBTPL_CUSTOM_WIDGET);
+ } else if (launcherType === "spacer") {
+ note = noteService.createNewNote({
+ noteId: noteId,
+ branchId: noteId,
+ title: "Spacer",
+ type: "launcher",
+ content: "",
+ parentNoteId: parentNoteId
+ }).note;
+
+ note.addRelation("template", LBTPL_SPACER);
+ } else {
+ throw new Error(`Unrecognized launcher type '${launcherType}'`);
+ }
+
+ return {
+ success: true,
+ note
+ };
+}
+
+function resetLauncher(noteId: string) {
+ const note = becca.getNote(noteId);
+
+ if (note?.isLaunchBarConfig()) {
+ if (note) {
+ if (noteId === "_lbRoot" || noteId === "_lbMobileRoot") {
+ // deleting hoisted notes are not allowed, so we just reset the children
+ for (const childNote of note.getChildNotes()) {
+ childNote.deleteNote();
+ }
+ } else {
+ note.deleteNote();
+ }
+ } else {
+ getLog().info(`Note ${noteId} has not been found and cannot be reset.`);
+ }
+ } else {
+ getLog().info(`Note ${noteId} is not a resettable launcher note.`);
+ }
+
+ // the re-building deleted launchers will be done in handlers
+}
+
+/**
+ * This exists to ease transition into the new launchbar, but it's not meant to be a permanent functionality.
+ * Previously, the launchbar was fixed and the only way to add buttons was through this API, so a lot of buttons have been
+ * created just to fill this user hole.
+ *
+ * Another use case was for script-packages (e.g. demo Task manager) which could this way register automatically/easily
+ * into the launchbar - for this it's recommended to use backend API's createOrUpdateLauncher()
+ */
+function createOrUpdateScriptLauncherFromApi(opts: { id: string; title: string; action: string; icon?: string; shortcut?: string }) {
+ if (opts.id && !/^[a-z0-9]+$/i.test(opts.id)) {
+ throw new Error(`Launcher ID can be alphanumeric only, '${opts.id}' given`);
+ }
+
+ const launcherId = opts.id || `tb_${opts.title.toLowerCase().replace(/[^[a-z0-9]/gi, "")}`;
+
+ if (!opts.title) {
+ throw new Error("Title is mandatory property to create or update a launcher.");
+ }
+
+ const launcherNote = becca.getNote(launcherId) || createScriptLauncher("_lbVisibleLaunchers", launcherId);
+
+ launcherNote.title = opts.title;
+ launcherNote.setContent(`(${opts.action})()`);
+ launcherNote.setLabel("scriptInLauncherContent"); // there's no target note, the script is in the launcher's content
+ launcherNote.mime = "application/javascript;env=frontend";
+ launcherNote.save();
+
+ if (opts.shortcut) {
+ launcherNote.setLabel("keyboardShortcut", opts.shortcut);
+ } else {
+ launcherNote.removeLabel("keyboardShortcut");
+ }
+
+ if (opts.icon) {
+ launcherNote.setLabel("iconClass", `bx bx-${opts.icon}`);
+ } else {
+ launcherNote.removeLabel("iconClass");
+ }
+
+ return launcherNote;
+}
+
+export default {
+ getInboxNote,
+ createSqlConsole,
+ saveSqlConsole,
+ createSearchNote,
+ saveSearchNote,
+ createLauncher,
+ resetLauncher,
+ createOrUpdateScriptLauncherFromApi
+};