Skip to content

Commit 7a3cb43

Browse files
authored
Merge pull request #15 from labloom-dev/refactor/calendar
feat: rebuild the calendar, add a date picker and a notification centre
2 parents 56ba5fa + 18217aa commit 7a3cb43

53 files changed

Lines changed: 1727 additions & 390 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎configs/components.preview.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { defineConfig } from "vite";
55
export default defineConfig({
66
root: resolve("renderer/preview/components"),
77
worker: { format: "es" },
8-
optimizeDeps: { entries: ["index.html", "../../components/Editor/code-worker.ts"] },
8+
optimizeDeps: { entries: ["index.html", "../../components/Editor/code-worker.ts"], exclude: ["svelte/elements"] },
99
plugins: [svelte({ configFile: resolve("configs/svelte.config.js") })],
1010
server: { host: "127.0.0.1", port: 15175, strictPort: true }
1111
});

‎locales/en.json‎

Lines changed: 50 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,7 @@
380380
"group3": "Focus Third Editor Group",
381381
"about": "About Labloom",
382382
"devtools": "Developer Tools",
383+
"showNotices": "Show notifications",
383384
"blockMenu": "Block menu",
384385
"toggleProperties": "Toggle properties panel"
385386
},
@@ -501,7 +502,6 @@
501502
"resizeGroup": "Resize Editor Group",
502503
"trashView": "Recycle Bin",
503504
"pinnedView": "Pinned Pages",
504-
"calendarView": "Research Calendar",
505505
"feedView": "Feed Activity",
506506
"targetDeleted": "Target has been deleted"
507507
},
@@ -630,7 +630,55 @@
630630
"feed_last_modified": "Last-Modified"
631631
},
632632
"notice": {
633-
"reminderTitle": "Labloom reminder"
633+
"reminderTitle": "Labloom reminder",
634+
"title": "Notifications",
635+
"unreadCount": "Show notifications ({{count}} unread)",
636+
"readAll": "Mark all as read",
637+
"clearAll": "Clear all",
638+
"markRead": "Mark as read",
639+
"markUnread": "Mark as unread",
640+
"clear": "Clear",
641+
"empty": "No notifications"
642+
},
643+
"datePicker": {
644+
"previous": "Previous page",
645+
"next": "Next page",
646+
"now": "Now",
647+
"empty": "Empty",
648+
"clock": "Time of day",
649+
"clear": "Clear",
650+
"format": "Use the format {{format}}.",
651+
"weekdays": {
652+
"monday": "Mon",
653+
"tuesday": "Tue",
654+
"wednesday": "Wed",
655+
"thursday": "Thu",
656+
"friday": "Fri",
657+
"saturday": "Sat",
658+
"sunday": "Sun"
659+
},
660+
"examples": {
661+
"title": "Date picker",
662+
"precision": "Precision",
663+
"filled": "With value",
664+
"readonly": "Read-only",
665+
"clock": "Time options",
666+
"invalid": "Invalid input"
667+
}
668+
},
669+
"calendar": {
670+
"previousMonth": "Previous month",
671+
"nextMonth": "Next month",
672+
"today": "Today",
673+
"chooseDate": "Choose date property",
674+
"chooseStart": "Choose start time property",
675+
"chooseStatus": "Choose status property",
676+
"missingDate": "Date property not found",
677+
"agendaWidth": "Day list width",
678+
"remaining": "{{count}} more",
679+
"noPages": "No pages",
680+
"complete": "Mark complete",
681+
"reopen": "Reopen"
634682
},
635683
"block": {
636684
"title": "Page title",
@@ -683,8 +731,6 @@
683731
"openPage": "Open page",
684732
"removeItem": "Remove {{name}}",
685733
"json": "JSON value",
686-
"hour": "Hour",
687-
"year": "Four-digit year",
688734
"addTag": "Add tag…",
689735
"createTag": "Create tag {{name}}",
690736
"files": "Files for {{name}}",
@@ -701,7 +747,6 @@
701747
"weekBefore": "1 week before",
702748
"morning": "At 9:00 that day",
703749
"loadingFile": "Loading file…",
704-
"yearHint": "YYYY",
705750
"repeatPeriod": "Every {{period}}",
706751
"enabled": "Enabled",
707752
"paused": "Paused",

‎locales/zh-CN.json‎

Lines changed: 50 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,7 @@
380380
"group3": "聚焦第3标签组",
381381
"about": "关于知织",
382382
"devtools": "开发者工具",
383+
"showNotices": "显示通知",
383384
"blockMenu": "块菜单",
384385
"toggleProperties": "切换属性面板"
385386
},
@@ -501,7 +502,6 @@
501502
"resizeGroup": "调整标签组大小",
502503
"trashView": "回收站",
503504
"pinnedView": "已固定",
504-
"calendarView": "研究日历",
505505
"feedView": "订阅动态",
506506
"targetDeleted": "目标已删除"
507507
},
@@ -630,7 +630,55 @@
630630
"feed_last_modified": "Last-Modified"
631631
},
632632
"notice": {
633-
"reminderTitle": "知织提醒"
633+
"reminderTitle": "知织提醒",
634+
"title": "通知",
635+
"unreadCount": "显示通知({{count}}条未读)",
636+
"readAll": "全部标为已读",
637+
"clearAll": "全部清除",
638+
"markRead": "标为已读",
639+
"markUnread": "标为未读",
640+
"clear": "清除",
641+
"empty": "没有通知"
642+
},
643+
"datePicker": {
644+
"previous": "上一页",
645+
"next": "下一页",
646+
"now": "现在",
647+
"empty": "空",
648+
"clock": "钟点",
649+
"clear": "清除",
650+
"format": "请输入 {{format}} 格式的值。",
651+
"weekdays": {
652+
"monday": "一",
653+
"tuesday": "二",
654+
"wednesday": "三",
655+
"thursday": "四",
656+
"friday": "五",
657+
"saturday": "六",
658+
"sunday": "日"
659+
},
660+
"examples": {
661+
"title": "日期选择器",
662+
"precision": "精度",
663+
"filled": "有值",
664+
"readonly": "只读",
665+
"clock": "钟点列",
666+
"invalid": "输入错误"
667+
}
668+
},
669+
"calendar": {
670+
"previousMonth": "上个月",
671+
"nextMonth": "下个月",
672+
"today": "今天",
673+
"chooseDate": "选择日期属性",
674+
"chooseStart": "选择开始时间属性",
675+
"chooseStatus": "选择状态属性",
676+
"missingDate": "找不到日期属性",
677+
"agendaWidth": "当天列表宽度",
678+
"remaining": "还有 {{count}} 条",
679+
"noPages": "没有页面",
680+
"complete": "标为完成",
681+
"reopen": "重新打开"
634682
},
635683
"block": {
636684
"title": "标题",
@@ -683,8 +731,6 @@
683731
"openPage": "打开页面",
684732
"removeItem": "移除{{name}}",
685733
"json": "JSON 值",
686-
"hour": "小时",
687-
"year": "四位年份",
688734
"addTag": "添加标签…",
689735
"createTag": "新建标签 {{name}}",
690736
"files": "{{name}}文件列表",
@@ -701,7 +747,6 @@
701747
"weekBefore": "提前 1 周",
702748
"morning": "当天 9:00",
703749
"loadingFile": "正在读取文件…",
704-
"yearHint": "YYYY",
705750
"repeatPeriod": "每{{period}}",
706751
"enabled": "启用",
707752
"paused": "暂停",

‎main/index.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import * as settingsEffects from "./settings/effects";
99
import * as lifecycle from "./lifecycle";
1010
import * as windows from "./ui/window";
1111
import * as reminders from "./ui/reminders";
12+
import { openReminderPage } from "../shared/timers/ipc";
1213

1314
// Set both paths before ready, so development also isolates Chromium state.
1415
const dataPath = app.isPackaged
@@ -33,7 +34,14 @@ else {
3334
settingsEffects.initialize();
3435
lifecycle.initialize();
3536
session.configureNetwork((input, init) => net.fetch(input instanceof URL ? input.toString() : input, init));
36-
reminders.initialize();
37+
reminders.initialize(pageId => {
38+
const contents = windows.show(applicationLog).webContents;
39+
const send = (): void => {
40+
if (!contents.isDestroyed()) contents.send(openReminderPage, pageId);
41+
};
42+
if (contents.isLoadingMainFrame()) contents.once("did-finish-load", send);
43+
else send();
44+
});
3745

3846
app.whenReady().then(() => {
3947
app.setAppUserModelId("dev.labloom.app");

‎main/knowledge/changes.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ export class EditChanges {
2929
readonly seeds = new Map<string, Target>();
3030
readonly dependencies = new Set<string>();
3131
readonly touches = new Set<string>();
32+
removesNotice = false;
3233
private readonly links = new Map<string, { source: Target; field: string; targets: LinkTarget[] }>();
3334
private readonly containers = new Map<string, { source: Target; before: string[]; after: string[]; added: string[] }>();
3435
private readonly ownersCache = new Map<string, string[]>();
@@ -161,6 +162,9 @@ export class EditChanges {
161162
if (id === "deleted" || id === "recycle_reason" || id === "recycled_at") throw new LabloomError({ kind: "attribute-readonly" });
162163
const before = this.readValue(pageId, id);
163164
if (same(before, value)) return;
165+
if (!value && !this.removesNotice && isTimeType(def.type)) {
166+
this.removesNotice = !!data.statement("SELECT 1 FROM timers WHERE page_id=? AND attr_id=? AND fired_at IS NOT NULL LIMIT 1").get(pageId, id);
167+
}
164168
if (id === "paper_annotations") this.highlightPages.add(pageId);
165169
if (isTimeType(def.type) || def.type === "status" || ["feed_url", "feed_status", "feed_refresh"].includes(id)) {
166170
const fields = this.schedules.get(pageId) ?? new Set<string>();

‎main/knowledge/commit.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,8 @@ export function run<T>(options: Options, action: (context: Context) => T): T {
9292
AND page_id IN (SELECT value FROM json_each(?)) LIMIT 1`).get(workspace.seconds(), JSON.stringify(status.restored))) events.feedDue();
9393
});
9494
}
95-
for (const [id, fields] of schedules) timers.recalculate(id, fields);
95+
for (const [id, fields] of schedules) if (timers.recalculate(id, fields)) context.change({ notices: true });
96+
if (plan.removesNotice) context.change({ notices: true });
9697
if (options.history && pageId) captures.push({ source: options.history, page: pageId, rows, dependencies: plan.dependencies, replay: options.replay });
9798
context.change(result);
9899
return result;

‎main/knowledge/records.ts‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,15 @@ import { libraryText, search } from "../../shared/attrs/format";
55
import { attributeTargetKind, decodeValue, emptyValue, encodeValue, nullable, record, validUUID } from "../../shared/attrs/values";
66
import { blockText, payload, validateBlock, validTarget } from "../../shared/content/blocks";
77
import { matchRanges } from "../../shared/content/matches";
8-
import { isTimeType, resolveTimeZone } from "../../shared/content/time";
8+
import { isTimeType, resolveTimeZone, validTimeSeconds } from "../../shared/content/time";
99
import { LabloomError } from "../../shared/failure";
1010
import { type AttributeDefinition, type AttributeValue } from "../../shared/types/attributes";
1111
import { pageKinds, type Backlink, type ContentBlock, type LinkTarget, type PageKind, type PageList, type PageObjects, type PageQuery, type PageRecord, type PageSummary, type PageSearchResult, type ResolvedTarget, type Target } from "../../shared/types/content";
1212
import { type blocks, type pages } from "../storage/tables";
1313
import * as workspace from "../workspace-state";
1414

1515
import { overviewBatchSize, type OverviewIndex, type OverviewPage, type OverviewQuery } from "../../shared/workspace/overview";
16+
import type { CalendarPage, CalendarQuery } from "../../shared/workspace/calendar";
1617
import { libraryBatchSize, type LibraryIndex, type LibraryQuery } from "../../shared/workspace/library";
1718
import { createI18n, type Translate } from "../../shared/i18n";
1819

@@ -520,6 +521,28 @@ export function overviewRows(ids: string[], date?: string): OverviewPage[] {
520521
return rows.map(row => ({ ...row, pinned: !!row.pinned }));
521522
}
522523

524+
export function calendarRows(query: CalendarQuery): CalendarPage[] {
525+
workspace.requireWorkspace();
526+
if (!validTimeSeconds("day", query.from) || !validTimeSeconds("day", query.to) || query.from >= query.to || definition(query.date)?.type !== "day") return [];
527+
const start = query.start && definition(query.start)?.type === "minute" ? query.start : null;
528+
const status = query.status && definition(query.status)?.type === "status" ? query.status : null;
529+
// The initial scan starts at the indexed date range. Changes start at the affected page IDs.
530+
const range = query.ids ? "json_each(@ids) j CROSS JOIN page_attrs d ON d.page_id=j.value" : "page_attrs d INDEXED BY page_attrs_by_value";
531+
const result = statement(`SELECT p.id,knowledge_text(b.type,b.content) AS title,d.value AS date,
532+
s.value AS start,st.value AS status,st.page_id IS NOT NULL AS hasStatus,f.value AS pinned
533+
FROM ${range}
534+
CROSS JOIN pages p ON p.id=d.page_id
535+
CROSS JOIN blocks b ON b.id=p.title_block_id
536+
CROSS JOIN page_attrs r ON r.page_id=p.id AND r.attr_id='deleted' AND r.value=0
537+
LEFT JOIN page_attrs s ON s.page_id=p.id AND s.attr_id=@start
538+
LEFT JOIN page_attrs st ON st.page_id=p.id AND st.attr_id=@status
539+
LEFT JOIN page_attrs f ON f.page_id=p.id AND f.attr_id='pinned'
540+
WHERE d.attr_id=@date AND d.value>=@from AND d.value<@to AND typeof(d.value)='integer'`).all({
541+
date: query.date, from: query.from, to: query.to, start, status, ...(query.ids ? { ids: JSON.stringify(query.ids) } : {})
542+
}) as (Omit<CalendarPage, "hasStatus" | "pinned"> & { hasStatus: number; pinned: number | null })[];
543+
return result.map(page => ({ ...page, hasStatus: !!page.hasStatus, pinned: !!page.pinned }));
544+
}
545+
523546
export function listUpdates(query: PageQuery, unchanged: string[], labelColumns?: string[]): PageList & { order: string[]; names?: Record<string, string> } {
524547
workspace.requireWorkspace();
525548
if (!Array.isArray(unchanged) || !unchanged.every(validUUID)) throw new LabloomError({ kind: "page-invalid-ids" });

‎main/knowledge/timer-state.ts‎

Lines changed: 41 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
import { isTimeType, resolveTimeZone } from "../../shared/content/time";
1+
import { isTimeType, resolveTimeZone, type TimePrecision } from "../../shared/content/time";
22
import { reminderDue } from "../../shared/content/timers";
33
import { LabloomError } from "../../shared/failure";
4-
import { type Notice } from "../../shared/types/knowledge";
4+
import type { AttributeDefinition } from "../../shared/types/attributes";
5+
import { type Notice, type NoticeKey } from "../../shared/types/knowledge";
56
import { reconcileFeedTimer } from "../feed/schedule";
67
import * as workspace from "../workspace-state";
78
import * as attributes from "./attributes";
@@ -42,27 +43,33 @@ export function completed(pageId: string): boolean {
4243
WHERE v.page_id=? AND a.type='status' AND o.value->>'$.id'=v.value AND o.value->>'$.group'='complete' LIMIT 1`).get(pageId);
4344
}
4445

45-
export function recalculate(pageId: string, fields?: string[], leadOnly?: number): void {
46+
export function recalculate(pageId: string, fields?: string[], leadOnly?: number): boolean {
4647
const all = !fields || fields.includes("deleted") || fields.some(id => data.statement("SELECT 1 FROM attrs_meta WHERE id=? AND type='status'").get(id));
4748
const feedChange = fields?.some(id => ["feed_url", "feed_status", "feed_refresh", "deleted"].includes(id));
4849
const rows = data.statement(`SELECT ${columns} FROM timers WHERE page_id=?` + (all ? "" : " AND attr_id IN (SELECT value FROM json_each(?))")).all(...(all ? [pageId] : [pageId, JSON.stringify(fields)])) as TimerRow[];
49-
if (!rows.length && !feedChange) return;
50+
if (!rows.length && !feedChange) return false;
5051
const page = { ...data.header(pageId), attributes: data.valuesFor([pageId]).get(pageId)! };
5152
const muted = page.attributes.deleted || completed(pageId);
53+
let noticesChanged = false;
5254
for (const row of rows) {
5355
const definition = attributes.definition(row.attrId);
5456
if (!isTimeType(definition.type)) {
55-
if (row.attrId !== "feed_refresh" || page.kind !== "feed" || definition.type !== "recurrence") data.statement("DELETE FROM timers WHERE page_id=? AND attr_id=?").run(pageId, row.attrId);
57+
if (row.attrId !== "feed_refresh" || page.kind !== "feed" || definition.type !== "recurrence") {
58+
data.statement("DELETE FROM timers WHERE page_id=? AND attr_id=?").run(pageId, row.attrId);
59+
noticesChanged ||= row.firedAt !== null;
60+
}
5661
continue;
5762
}
5863
if (leadOnly !== undefined && row.leadSeconds !== leadOnly) continue;
5964
const due = muted ? null
6065
: reminderDue(definition.type, page.attributes[row.attrId] as number | null, row.leadSeconds, resolveTimeZone(workspace.timeZone()));
6166
data.statement("UPDATE timers SET due_at=?,fired_at=NULL,seen=0 WHERE page_id=? AND attr_id=? AND lead_seconds=?")
6267
.run(due !== null && due > now() ? due : null, pageId, row.attrId, row.leadSeconds);
68+
noticesChanged ||= row.firedAt !== null;
6369
}
6470
if (page.kind === "feed" && fields && feedChange) reconcileFeedTimer(workspace.database(), pageId, page.attributes, now(),
6571
fields.some(id => id === "feed_url" || id === "feed_status"), fields.includes("deleted") && !page.attributes.deleted);
72+
return noticesChanged;
6673
}
6774

6875
export function recalculateAll(): void {
@@ -72,20 +79,40 @@ export function recalculateAll(): void {
7279
}
7380

7481
export function notices(): Notice[] {
75-
76-
return (data.statement(`SELECT t.${columns.replaceAll(",", ",t.")} FROM timers t JOIN page_attrs d ON d.page_id=t.page_id AND d.attr_id='deleted'
77-
WHERE t.fired_at IS NOT NULL AND d.value=0 ORDER BY t.fired_at DESC,t.page_id,t.attr_id,t.lead_seconds`).all() as TimerRow[]).map(row => notice(row));
82+
const rows = data.statement(`SELECT t.page_id AS pageId,t.attr_id AS attrId,t.lead_seconds AS leadSeconds,
83+
t.fired_at AS firedAt,t.seen,knowledge_text(b.type,b.content) AS title,
84+
coalesce(a.name,a.id) AS attrName,a.type AS attrType,v.value AS attrValue
85+
FROM timers t JOIN page_attrs d ON d.page_id=t.page_id AND d.attr_id='deleted' AND d.value=0
86+
JOIN pages p ON p.id=t.page_id JOIN blocks b ON b.id=p.title_block_id
87+
JOIN attrs_meta a ON a.id=t.attr_id JOIN page_attrs v ON v.page_id=t.page_id AND v.attr_id=t.attr_id
88+
WHERE t.fired_at IS NOT NULL ORDER BY t.fired_at DESC,t.page_id,t.attr_id,t.lead_seconds`).all() as (Omit<Notice, "seen"> & { seen: number })[];
89+
return rows.filter(row => isTimeType(row.attrType)).map(row => ({ ...row, seen: !!row.seen }));
7890
}
7991

80-
export function notice(row: TimerRow): Notice {
92+
export function notice(row: TimerRow, definition: AttributeDefinition & { type: TimePrecision }, value: number | null): Notice {
8193
return {
82-
pageId: row.pageId, attrId: row.attrId, leadSeconds: row.leadSeconds, title: data.title(row.pageId),
83-
attrName: attributes.definition(row.attrId).name, firedAt: row.firedAt!, seen: !!row.seen
94+
pageId: row.pageId, attrId: row.attrId, leadSeconds: row.leadSeconds, title: data.title(row.pageId, ""),
95+
attrName: definition.name, attrType: definition.type, attrValue: value, firedAt: row.firedAt!, seen: !!row.seen
8496
};
8597
}
8698

87-
export function read(pageId: string, attrId: string, leadSeconds: number): void {
88-
if (!Number.isSafeInteger(leadSeconds) || leadSeconds < 0) throw new LabloomError({ kind: "timer-invalid-notice" });
99+
export function unreadCount(): number {
100+
return Number(data.statement(`SELECT count(*) FROM timers t JOIN page_attrs d ON d.page_id=t.page_id AND d.attr_id='deleted' AND d.value=0
101+
WHERE t.fired_at IS NOT NULL AND t.seen=0`).pluck().get());
102+
}
103+
104+
export function updateNotice(action: "read" | "unread" | "clear", { pageId, attrId, leadSeconds, firedAt }: Omit<NoticeKey, "firedAt"> & { firedAt?: number }): number {
105+
if (!Number.isSafeInteger(leadSeconds) || leadSeconds < 0 || firedAt !== undefined && !Number.isSafeInteger(firedAt)) {
106+
throw new LabloomError({ kind: "timer-invalid-notice" });
107+
}
89108
data.writable(pageId);
90-
data.statement("UPDATE timers SET seen=1 WHERE page_id=? AND attr_id=? AND lead_seconds=?").run(pageId, attrId, leadSeconds);
109+
const writes = { read: "seen=1", unread: "seen=0", clear: "fired_at=NULL,seen=0" };
110+
return data.statement(`UPDATE timers SET ${writes[action]} WHERE page_id=? AND attr_id=? AND lead_seconds=?
111+
AND fired_at IS NOT NULL AND (? IS NULL OR fired_at=?)`).run(pageId, attrId, leadSeconds, firedAt ?? null, firedAt ?? null).changes;
112+
}
113+
114+
export function updateAllNotices(clear: boolean): number {
115+
return clear
116+
? data.statement("UPDATE timers SET fired_at=NULL,seen=0 WHERE fired_at IS NOT NULL").run().changes
117+
: data.statement("UPDATE timers SET seen=1 WHERE fired_at IS NOT NULL AND seen=0").run().changes;
91118
}

0 commit comments

Comments
 (0)