Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

core: support natural sorting of numbered note titles

kashaf-ansari-dev9ed48c63f10c
diff --git a/packages/core/__tests__/notes.test.ts b/packages/core/__tests__/notes.test.ts
index b8b7a0419..61e7f287a 100644
--- a/packages/core/__tests__/notes.test.ts
+++ b/packages/core/__tests__/notes.test.ts
@@ -737,6 +737,41 @@ for (const group of groups) {
}
}
+test("natural sorting of numbered note titles", () =>
+ databaseTest().then(async (db) => {
+ const titles = [
+ "Lesson 10",
+ "Lesson 1",
+ "Lesson 2",
+ "10. Intro",
+ "1. Intro",
+ "2. Intro"
+ ];
+ for (const title of titles) {
+ await db.notes.add({ title });
+ }
+
+ const asc = await db.notes.all.grouped({
+ groupBy: "none",
+ sortBy: "title",
+ sortDirection: "asc"
+ });
+ const ascTitles: string[] = [];
+ for (let i = 0; i < asc.length; i++) {
+ const item = await asc.item(i);
+ if (item.item) ascTitles.push(item.item.title);
+ }
+
+ expect(ascTitles).toEqual([
+ "1. Intro",
+ "2. Intro",
+ "10. Intro",
+ "Lesson 1",
+ "Lesson 2",
+ "Lesson 10"
+ ]);
+ }));
+
test("get archived notes", () =>
noteTest().then(async ({ db, id }) => {
await db.notes.archive(true, id);
diff --git a/packages/core/__tests__/utils/index.ts b/packages/core/__tests__/utils/index.ts
index 5cea88224..d1a43ce80 100644
--- a/packages/core/__tests__/utils/index.ts
+++ b/packages/core/__tests__/utils/index.ts
@@ -52,6 +52,9 @@ function databaseTest(type: "memory" | "persistent" = "memory") {
const betterSqliteDb = BetterSQLite3(
type === "persistent" ? dbPath : ":memory:"
).unsafeMode(true);
+ betterSqliteDb.function("natural_key", (str: string | null) =>
+ str ? str.replace(/\d+/g, (n) => n.padStart(10, "0")) : ""
+ );
db.setup({
storage: new NodeStorageInterface(),
eventsource: EventSource,
diff --git a/packages/core/src/database/sql-collection.ts b/packages/core/src/database/sql-collection.ts
index f6fcff074..5a5812a3d 100644
--- a/packages/core/src/database/sql-collection.ts
+++ b/packages/core/src/database/sql-collection.ts
@@ -643,7 +643,7 @@ export class FilteredSelector<T extends Item> {
qb = qb.orderBy(
options.sortBy !== "title"
? sql`substring(ltrim(title, ' \u00a0\r\n\t\v'), 1, 1) COLLATE NOCASE`
- : sql`ltrim(title, ' \u00a0\r\n\t\v') COLLATE NOCASE`,
+ : sql`natural_key(ltrim(title, ' \u00a0\r\n\t\v')) COLLATE NOCASE`,
options.sortDirection
);
} else {