Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion configs/components.preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { defineConfig } from "vite";
export default defineConfig({
root: resolve("renderer/preview/components"),
worker: { format: "es" },
optimizeDeps: { entries: ["index.html", "../../components/Editor/code-worker.ts"] },
optimizeDeps: { entries: ["index.html", "../../components/Editor/code-worker.ts"], exclude: ["svelte/elements"] },
plugins: [svelte({ configFile: resolve("configs/svelte.config.js") })],
server: { host: "127.0.0.1", port: 15175, strictPort: true }
});
55 changes: 50 additions & 5 deletions locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,7 @@
"group3": "Focus Third Editor Group",
"about": "About Labloom",
"devtools": "Developer Tools",
"showNotices": "Show notifications",
"blockMenu": "Block menu",
"toggleProperties": "Toggle properties panel"
},
Expand Down Expand Up @@ -501,7 +502,6 @@
"resizeGroup": "Resize Editor Group",
"trashView": "Recycle Bin",
"pinnedView": "Pinned Pages",
"calendarView": "Research Calendar",
"feedView": "Feed Activity",
"targetDeleted": "Target has been deleted"
},
Expand Down Expand Up @@ -630,7 +630,55 @@
"feed_last_modified": "Last-Modified"
},
"notice": {
"reminderTitle": "Labloom reminder"
"reminderTitle": "Labloom reminder",
"title": "Notifications",
"unreadCount": "Show notifications ({{count}} unread)",
"readAll": "Mark all as read",
"clearAll": "Clear all",
"markRead": "Mark as read",
"markUnread": "Mark as unread",
"clear": "Clear",
"empty": "No notifications"
},
"datePicker": {
"previous": "Previous page",
"next": "Next page",
"now": "Now",
"empty": "Empty",
"clock": "Time of day",
"clear": "Clear",
"format": "Use the format {{format}}.",
"weekdays": {
"monday": "Mon",
"tuesday": "Tue",
"wednesday": "Wed",
"thursday": "Thu",
"friday": "Fri",
"saturday": "Sat",
"sunday": "Sun"
},
"examples": {
"title": "Date picker",
"precision": "Precision",
"filled": "With value",
"readonly": "Read-only",
"clock": "Time options",
"invalid": "Invalid input"
}
},
"calendar": {
"previousMonth": "Previous month",
"nextMonth": "Next month",
"today": "Today",
"chooseDate": "Choose date property",
"chooseStart": "Choose start time property",
"chooseStatus": "Choose status property",
"missingDate": "Date property not found",
"agendaWidth": "Day list width",
"remaining": "{{count}} more",
"noPages": "No pages",
"complete": "Mark complete",
"reopen": "Reopen"
},
"block": {
"title": "Page title",
Expand Down Expand Up @@ -683,8 +731,6 @@
"openPage": "Open page",
"removeItem": "Remove {{name}}",
"json": "JSON value",
"hour": "Hour",
"year": "Four-digit year",
"addTag": "Add tag…",
"createTag": "Create tag {{name}}",
"files": "Files for {{name}}",
Expand All @@ -701,7 +747,6 @@
"weekBefore": "1 week before",
"morning": "At 9:00 that day",
"loadingFile": "Loading file…",
"yearHint": "YYYY",
"repeatPeriod": "Every {{period}}",
"enabled": "Enabled",
"paused": "Paused",
Expand Down
55 changes: 50 additions & 5 deletions locales/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,7 @@
"group3": "聚焦第3标签组",
"about": "关于知织",
"devtools": "开发者工具",
"showNotices": "显示通知",
"blockMenu": "块菜单",
"toggleProperties": "切换属性面板"
},
Expand Down Expand Up @@ -501,7 +502,6 @@
"resizeGroup": "调整标签组大小",
"trashView": "回收站",
"pinnedView": "已固定",
"calendarView": "研究日历",
"feedView": "订阅动态",
"targetDeleted": "目标已删除"
},
Expand Down Expand Up @@ -630,7 +630,55 @@
"feed_last_modified": "Last-Modified"
},
"notice": {
"reminderTitle": "知织提醒"
"reminderTitle": "知织提醒",
"title": "通知",
"unreadCount": "显示通知({{count}}条未读)",
"readAll": "全部标为已读",
"clearAll": "全部清除",
"markRead": "标为已读",
"markUnread": "标为未读",
"clear": "清除",
"empty": "没有通知"
},
"datePicker": {
"previous": "上一页",
"next": "下一页",
"now": "现在",
"empty": "空",
"clock": "钟点",
"clear": "清除",
"format": "请输入 {{format}} 格式的值。",
"weekdays": {
"monday": "一",
"tuesday": "二",
"wednesday": "三",
"thursday": "四",
"friday": "五",
"saturday": "六",
"sunday": "日"
},
"examples": {
"title": "日期选择器",
"precision": "精度",
"filled": "有值",
"readonly": "只读",
"clock": "钟点列",
"invalid": "输入错误"
}
},
"calendar": {
"previousMonth": "上个月",
"nextMonth": "下个月",
"today": "今天",
"chooseDate": "选择日期属性",
"chooseStart": "选择开始时间属性",
"chooseStatus": "选择状态属性",
"missingDate": "找不到日期属性",
"agendaWidth": "当天列表宽度",
"remaining": "还有 {{count}} 条",
"noPages": "没有页面",
"complete": "标为完成",
"reopen": "重新打开"
},
"block": {
"title": "标题",
Expand Down Expand Up @@ -683,8 +731,6 @@
"openPage": "打开页面",
"removeItem": "移除{{name}}",
"json": "JSON 值",
"hour": "小时",
"year": "四位年份",
"addTag": "添加标签…",
"createTag": "新建标签 {{name}}",
"files": "{{name}}文件列表",
Expand All @@ -701,7 +747,6 @@
"weekBefore": "提前 1 周",
"morning": "当天 9:00",
"loadingFile": "正在读取文件…",
"yearHint": "YYYY",
"repeatPeriod": "每{{period}}",
"enabled": "启用",
"paused": "暂停",
Expand Down
10 changes: 9 additions & 1 deletion main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import * as settingsEffects from "./settings/effects";
import * as lifecycle from "./lifecycle";
import * as windows from "./ui/window";
import * as reminders from "./ui/reminders";
import { openReminderPage } from "../shared/timers/ipc";

// Set both paths before ready, so development also isolates Chromium state.
const dataPath = app.isPackaged
Expand All @@ -33,7 +34,14 @@ else {
settingsEffects.initialize();
lifecycle.initialize();
session.configureNetwork((input, init) => net.fetch(input instanceof URL ? input.toString() : input, init));
reminders.initialize();
reminders.initialize(pageId => {
const contents = windows.show(applicationLog).webContents;
const send = (): void => {
if (!contents.isDestroyed()) contents.send(openReminderPage, pageId);
};
if (contents.isLoadingMainFrame()) contents.once("did-finish-load", send);
else send();
});

app.whenReady().then(() => {
app.setAppUserModelId("dev.labloom.app");
Expand Down
4 changes: 4 additions & 0 deletions main/knowledge/changes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export class EditChanges {
readonly seeds = new Map<string, Target>();
readonly dependencies = new Set<string>();
readonly touches = new Set<string>();
removesNotice = false;
private readonly links = new Map<string, { source: Target; field: string; targets: LinkTarget[] }>();
private readonly containers = new Map<string, { source: Target; before: string[]; after: string[]; added: string[] }>();
private readonly ownersCache = new Map<string, string[]>();
Expand Down Expand Up @@ -161,6 +162,9 @@ export class EditChanges {
if (id === "deleted" || id === "recycle_reason" || id === "recycled_at") throw new LabloomError({ kind: "attribute-readonly" });
const before = this.readValue(pageId, id);
if (same(before, value)) return;
if (!value && !this.removesNotice && isTimeType(def.type)) {
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);
}
if (id === "paper_annotations") this.highlightPages.add(pageId);
if (isTimeType(def.type) || def.type === "status" || ["feed_url", "feed_status", "feed_refresh"].includes(id)) {
const fields = this.schedules.get(pageId) ?? new Set<string>();
Expand Down
3 changes: 2 additions & 1 deletion main/knowledge/commit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,8 @@ export function run<T>(options: Options, action: (context: Context) => T): T {
AND page_id IN (SELECT value FROM json_each(?)) LIMIT 1`).get(workspace.seconds(), JSON.stringify(status.restored))) events.feedDue();
});
}
for (const [id, fields] of schedules) timers.recalculate(id, fields);
for (const [id, fields] of schedules) if (timers.recalculate(id, fields)) context.change({ notices: true });
if (plan.removesNotice) context.change({ notices: true });
if (options.history && pageId) captures.push({ source: options.history, page: pageId, rows, dependencies: plan.dependencies, replay: options.replay });
context.change(result);
return result;
Expand Down
25 changes: 24 additions & 1 deletion main/knowledge/records.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ import { libraryText, search } from "../../shared/attrs/format";
import { attributeTargetKind, decodeValue, emptyValue, encodeValue, nullable, record, validUUID } from "../../shared/attrs/values";
import { blockText, payload, validateBlock, validTarget } from "../../shared/content/blocks";
import { matchRanges } from "../../shared/content/matches";
import { isTimeType, resolveTimeZone } from "../../shared/content/time";
import { isTimeType, resolveTimeZone, validTimeSeconds } from "../../shared/content/time";
import { LabloomError } from "../../shared/failure";
import { type AttributeDefinition, type AttributeValue } from "../../shared/types/attributes";
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";
import { type blocks, type pages } from "../storage/tables";
import * as workspace from "../workspace-state";

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

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

export function calendarRows(query: CalendarQuery): CalendarPage[] {
workspace.requireWorkspace();
if (!validTimeSeconds("day", query.from) || !validTimeSeconds("day", query.to) || query.from >= query.to || definition(query.date)?.type !== "day") return [];
const start = query.start && definition(query.start)?.type === "minute" ? query.start : null;
const status = query.status && definition(query.status)?.type === "status" ? query.status : null;
// The initial scan starts at the indexed date range. Changes start at the affected page IDs.
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";
const result = statement(`SELECT p.id,knowledge_text(b.type,b.content) AS title,d.value AS date,
s.value AS start,st.value AS status,st.page_id IS NOT NULL AS hasStatus,f.value AS pinned
FROM ${range}
CROSS JOIN pages p ON p.id=d.page_id
CROSS JOIN blocks b ON b.id=p.title_block_id
CROSS JOIN page_attrs r ON r.page_id=p.id AND r.attr_id='deleted' AND r.value=0
LEFT JOIN page_attrs s ON s.page_id=p.id AND s.attr_id=@start
LEFT JOIN page_attrs st ON st.page_id=p.id AND st.attr_id=@status
LEFT JOIN page_attrs f ON f.page_id=p.id AND f.attr_id='pinned'
WHERE d.attr_id=@date AND d.value>=@from AND d.value<@to AND typeof(d.value)='integer'`).all({
date: query.date, from: query.from, to: query.to, start, status, ...(query.ids ? { ids: JSON.stringify(query.ids) } : {})
}) as (Omit<CalendarPage, "hasStatus" | "pinned"> & { hasStatus: number; pinned: number | null })[];
return result.map(page => ({ ...page, hasStatus: !!page.hasStatus, pinned: !!page.pinned }));
}

export function listUpdates(query: PageQuery, unchanged: string[], labelColumns?: string[]): PageList & { order: string[]; names?: Record<string, string> } {
workspace.requireWorkspace();
if (!Array.isArray(unchanged) || !unchanged.every(validUUID)) throw new LabloomError({ kind: "page-invalid-ids" });
Expand Down
55 changes: 41 additions & 14 deletions main/knowledge/timer-state.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { isTimeType, resolveTimeZone } from "../../shared/content/time";
import { isTimeType, resolveTimeZone, type TimePrecision } from "../../shared/content/time";
import { reminderDue } from "../../shared/content/timers";
import { LabloomError } from "../../shared/failure";
import { type Notice } from "../../shared/types/knowledge";
import type { AttributeDefinition } from "../../shared/types/attributes";
import { type Notice, type NoticeKey } from "../../shared/types/knowledge";
import { reconcileFeedTimer } from "../feed/schedule";
import * as workspace from "../workspace-state";
import * as attributes from "./attributes";
Expand Down Expand Up @@ -42,27 +43,33 @@ export function completed(pageId: string): boolean {
WHERE v.page_id=? AND a.type='status' AND o.value->>'$.id'=v.value AND o.value->>'$.group'='complete' LIMIT 1`).get(pageId);
}

export function recalculate(pageId: string, fields?: string[], leadOnly?: number): void {
export function recalculate(pageId: string, fields?: string[], leadOnly?: number): boolean {
const all = !fields || fields.includes("deleted") || fields.some(id => data.statement("SELECT 1 FROM attrs_meta WHERE id=? AND type='status'").get(id));
const feedChange = fields?.some(id => ["feed_url", "feed_status", "feed_refresh", "deleted"].includes(id));
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[];
if (!rows.length && !feedChange) return;
if (!rows.length && !feedChange) return false;
const page = { ...data.header(pageId), attributes: data.valuesFor([pageId]).get(pageId)! };
const muted = page.attributes.deleted || completed(pageId);
let noticesChanged = false;
for (const row of rows) {
const definition = attributes.definition(row.attrId);
if (!isTimeType(definition.type)) {
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);
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);
noticesChanged ||= row.firedAt !== null;
}
continue;
}
if (leadOnly !== undefined && row.leadSeconds !== leadOnly) continue;
const due = muted ? null
: reminderDue(definition.type, page.attributes[row.attrId] as number | null, row.leadSeconds, resolveTimeZone(workspace.timeZone()));
data.statement("UPDATE timers SET due_at=?,fired_at=NULL,seen=0 WHERE page_id=? AND attr_id=? AND lead_seconds=?")
.run(due !== null && due > now() ? due : null, pageId, row.attrId, row.leadSeconds);
noticesChanged ||= row.firedAt !== null;
}
if (page.kind === "feed" && fields && feedChange) reconcileFeedTimer(workspace.database(), pageId, page.attributes, now(),
fields.some(id => id === "feed_url" || id === "feed_status"), fields.includes("deleted") && !page.attributes.deleted);
return noticesChanged;
}

export function recalculateAll(): void {
Expand All @@ -72,20 +79,40 @@ export function recalculateAll(): void {
}

export function notices(): Notice[] {

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'
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));
const rows = data.statement(`SELECT t.page_id AS pageId,t.attr_id AS attrId,t.lead_seconds AS leadSeconds,
t.fired_at AS firedAt,t.seen,knowledge_text(b.type,b.content) AS title,
coalesce(a.name,a.id) AS attrName,a.type AS attrType,v.value AS attrValue
FROM timers t JOIN page_attrs d ON d.page_id=t.page_id AND d.attr_id='deleted' AND d.value=0
JOIN pages p ON p.id=t.page_id JOIN blocks b ON b.id=p.title_block_id
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
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 })[];
return rows.filter(row => isTimeType(row.attrType)).map(row => ({ ...row, seen: !!row.seen }));
}

export function notice(row: TimerRow): Notice {
export function notice(row: TimerRow, definition: AttributeDefinition & { type: TimePrecision }, value: number | null): Notice {
return {
pageId: row.pageId, attrId: row.attrId, leadSeconds: row.leadSeconds, title: data.title(row.pageId),
attrName: attributes.definition(row.attrId).name, firedAt: row.firedAt!, seen: !!row.seen
pageId: row.pageId, attrId: row.attrId, leadSeconds: row.leadSeconds, title: data.title(row.pageId, ""),
attrName: definition.name, attrType: definition.type, attrValue: value, firedAt: row.firedAt!, seen: !!row.seen
};
}

export function read(pageId: string, attrId: string, leadSeconds: number): void {
if (!Number.isSafeInteger(leadSeconds) || leadSeconds < 0) throw new LabloomError({ kind: "timer-invalid-notice" });
export function unreadCount(): number {
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
WHERE t.fired_at IS NOT NULL AND t.seen=0`).pluck().get());
}

export function updateNotice(action: "read" | "unread" | "clear", { pageId, attrId, leadSeconds, firedAt }: Omit<NoticeKey, "firedAt"> & { firedAt?: number }): number {
if (!Number.isSafeInteger(leadSeconds) || leadSeconds < 0 || firedAt !== undefined && !Number.isSafeInteger(firedAt)) {
throw new LabloomError({ kind: "timer-invalid-notice" });
}
data.writable(pageId);
data.statement("UPDATE timers SET seen=1 WHERE page_id=? AND attr_id=? AND lead_seconds=?").run(pageId, attrId, leadSeconds);
const writes = { read: "seen=1", unread: "seen=0", clear: "fired_at=NULL,seen=0" };
return data.statement(`UPDATE timers SET ${writes[action]} WHERE page_id=? AND attr_id=? AND lead_seconds=?
AND fired_at IS NOT NULL AND (? IS NULL OR fired_at=?)`).run(pageId, attrId, leadSeconds, firedAt ?? null, firedAt ?? null).changes;
}

export function updateAllNotices(clear: boolean): number {
return clear
? data.statement("UPDATE timers SET fired_at=NULL,seen=0 WHERE fired_at IS NOT NULL").run().changes
: data.statement("UPDATE timers SET seen=1 WHERE fired_at IS NOT NULL AND seen=0").run().changes;
}
Loading
Loading