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
8 changes: 4 additions & 4 deletions configs/feed.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -674,8 +674,8 @@ test("a few sources are fetched at a time, and those waiting their turn already
assert.ok(!started.includes("/6"), "the source under test is definitely queued");
if (action === "pause") service.setSourceStatus(ids[6], "pause");
else if (action === "delete") {
const result = service.knowledge.trash([ids[6]], "queue-test");
if (result.status === "confirmation") service.knowledge.trash([ids[6]], "queue-test", result.preview.token);
const result = service.knowledge.trash([ids[6]], "queue-test", { kind: "workspace" });
if (result.status === "confirmation") service.knowledge.trash([ids[6]], "queue-test", { kind: "workspace" }, result.preview.token);
}
else service.knowledge.attributes.write(ids[6], { feed_url: "https://example.org/changed" });
while (releases.length) {
Expand Down Expand Up @@ -803,8 +803,8 @@ test("an item becomes a real paper and only replaces a recycled or missing paper
assert.equal(knowledge.get(current).attributes.source_snapshot.feedURL, "https://rss.arxiv.org/atom/cs.LG");
assert.equal(service.importItem(item.id), current);
for (const state of ["recycled", "missing"]) {
const trash = knowledge.trash([current], "trash");
knowledge.trash([current], "trash", trash.preview.token);
const trash = knowledge.trash([current], "trash", { kind: "workspace" });
knowledge.trash([current], "trash", { kind: "workspace" }, trash.preview.token);
if (state === "missing") {
const preview = purge.purge([current], "purge");
purge.purge([current], "purge", preview.token);
Expand Down
2 changes: 1 addition & 1 deletion main/feed/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ export function getItem(id: string): FeedItemDetail {
function updateSource(id: string, name: string, values: Record<string, AttributeValue>): void {
return commit.run({ sourceTab: "", feed: true, history: false, updateModified: false }, () => {
const page = knowledge.get(id), title = page.blocks[page.titleBlockId];
edits.commitEdit({ pageId: id, tabId: "feed-settings", batch: 0, blocks: name === page.title ? [] : [{ ...title, payload: payload("title", name) }], attributes: values });
edits.commitEdit({ pageId: id, tabId: "feed-settings", batch: 0, blocks: name === page.title ? [] : [{ ...title, payload: payload("title", name) }], attributes: values }, false);
commit.invalidate(["page:" + id, "block:" + page.titleBlockId]);

});
Expand Down
10 changes: 7 additions & 3 deletions main/history/ipc.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
import { type BrowserWindow } from "electron";
import typia from "typia";
import { historyChannels, type HistoryAPI } from "../../shared/history/ipc";
import { historyChannels, historyChanged, type HistoryAPI } from "../../shared/history/ipc";
import { invalid, register, route, type Routes } from "../ipc";
import * as history from "../knowledge/history";
import * as events from "../knowledge/events";

type Args<Key extends keyof typeof historyChannels> = Parameters<HistoryAPI[Key]>;

export const routes = {
state: route(typia.createAssert<Args<"state">>(invalid), history.state),
apply: route(typia.createAssert<Args<"apply">>(invalid), history.apply),
closeTab: route(typia.createAssert<Args<"closeTab">>(invalid), history.close)
apply: route(typia.createAssert<Args<"apply">>(invalid), history.apply)
} satisfies Routes<HistoryAPI>;
export function registerHistoryIPCs(window: BrowserWindow): void {
const contents = window.webContents;
register(contents, historyChannels, routes);
const unsubscribe = events.subscribe(event => {
if (event.type === "history" && !contents.isDestroyed()) contents.send(historyChanged, event.sources);
});
contents.once("destroyed", unsubscribe);
}
33 changes: 19 additions & 14 deletions main/knowledge/commit.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { HistorySource } from "../../shared/history/ipc";
import { type ChangePreview, type CommitResult, type KnowledgeChange } from "../../shared/types/content";
import { withFileCleanup } from "../storage/files";
import * as workspace from "../workspace-state";
Expand All @@ -11,7 +12,8 @@ import * as timers from "./timer-state";

export type Options = {
sourceTab: string;
history?: boolean;
history?: HistorySource | false;
replay?: history.Replay;
updateModified?: boolean;
confirmation?: string;
feed?: boolean;
Expand All @@ -20,14 +22,13 @@ export type Options = {
export type Context = {
change(change: Partial<KnowledgeChange>): void;
after(action: () => void): void;
invalidate(keys: string[], exceptTab?: string): void;
clearHistory(): void;
invalidate(keys: string[], permanent?: boolean): void;
persist(plan: EditChanges, pageId?: string): void;
cleanup(): string[];
skip(): void;
};
let effects: (() => void)[] = [];
const contexts: { options: Options; context: Context; feed: boolean }[] = [];
const contexts: { options: Options; context: Context; captures: history.Capture[]; invalid: history.Invalidation[]; feed: boolean }[] = [];
export function release(): void {
effects = [];
contexts.length = 0;
Expand All @@ -38,14 +39,15 @@ export function current(): Context {
if (!contexts.length) throw new Error("A write requires a commit context");
return contexts[contexts.length - 1].context;
}
export function invalidate(keys: string[], exceptTab?: string): void {
current().invalidate(keys, exceptTab);
export function invalidate(keys: string[]): void {
current().invalidate(keys);
}
export function run<T>(options: Options, action: (context: Context) => T): T {
const session = workspace.requireWorkspace(), start = effects.length;
let cleanup: (() => string[]) | undefined;
const write = (): T => session.database.transaction(() => {
const changed: KnowledgeChange = { sourceTab: options.sourceTab, pages: [], blocks: [] };
const captures: history.Capture[] = [], invalid: history.Invalidation[] = [];
let publish = true;
const context: Context = {
change(change) {
Expand All @@ -57,17 +59,14 @@ export function run<T>(options: Options, action: (context: Context) => T): T {
after(action) {
effects.push(action);
},
invalidate(keys, exceptTab) {
effects.push(() => history.invalidate(keys, exceptTab));
},
clearHistory() {
effects.push(() => history.clear());
invalidate(keys, permanent = false) {
invalid.push({ keys, permanent });
},
persist(plan, pageId) {
if (options.updateModified === false) plan.touches.clear();
plan.persist();
for (const change of plan.timerChanges()) timers.recalculate(change.pageId, change.fields);
if (options.history && pageId) effects.push(() => history.capture(options.sourceTab, pageId, plan.rows));
if (options.history && pageId) captures.push({ source: options.history, page: pageId, rows: plan.rows, replay: options.replay });
context.change(plan.changed());
},
cleanup() {
Expand All @@ -79,7 +78,7 @@ export function run<T>(options: Options, action: (context: Context) => T): T {
publish = false;
}
};
const scope = { options, context, feed: !!options.feed };
const scope = { options, context, captures, invalid, feed: !!options.feed };
contexts.push(scope);
try {
const result = action(context);
Expand All @@ -88,9 +87,15 @@ export function run<T>(options: Options, action: (context: Context) => T): T {
const parent = contexts[contexts.length - 2];
if (parent) {
parent.context.change(changed);
parent.captures.push(...captures);
parent.invalid.push(...invalid);
parent.feed ||= scope.feed;
}
else effects.push(() => events.publish(changed, scope.feed));
else effects.push(() => {
const change = events.expand(changed);
history.finish(captures, invalid, change.summaryPages ?? change.pages);
events.publish(change, scope.feed);
});
}
return result;
}
Expand Down
34 changes: 19 additions & 15 deletions main/knowledge/edits.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { HistoryOrigin, HistorySource } from "../../shared/history/ipc";
import { randomUUID } from "node:crypto";
import { attributeTargets, decodeValue, record, validUUID } from "../../shared/attrs/values";
import { blockText, payload, references, validateBlock } from "../../shared/content/blocks";
Expand All @@ -21,10 +22,10 @@ class DefinitionRollback extends Error {
super("definition preview");
}
}
function transact(tabId: string, action: () => CommitResult, confirmation?: string): CommitResult {
function transact(tabId: string, source: HistorySource | false, action: () => CommitResult, confirmation?: string): CommitResult {
workspace.requireWorkspace();
checkTab(tabId);
return commit.run({ sourceTab: tabId, history: true, confirmation }, action);
return commit.run({ sourceTab: tabId, history: source, confirmation }, action);
}
function putBlock(block: ContentBlock): void {
const plan = new EditChanges();
Expand All @@ -36,7 +37,7 @@ export function create(kind: PageKind = "editable", title = "", initial: Record<
if (!record(initial)) throw new LabloomError({ kind: "page-invalid-attributes" });
for (const id of Object.keys(initial)) if (attributes.definition(id).readonly || id === "deleted") throw new LabloomError({ kind: "page-create-readonly" });
if (kind === "annotation") throw new LabloomError({ kind: "annotation-selection-required" });
return createPage(kind, title, initial, parentId, tabId);
return insertPage(kind, title, initial, parentId, tabId, false);
}
function writable(id: string): ReturnType<typeof data["header"]> {
const page = data.header(id);
Expand Down Expand Up @@ -83,9 +84,9 @@ export function previewEdit(input: EditCommit): ChangePreview | null {
return workspace.native().transaction(() => commit.preview(planEdit(input), input))();
}

export function commitEdit(input: EditCommit, confirmation?: string): CommitResult {
export function commitEdit(input: EditCommit, source: HistorySource | false, confirmation?: string): CommitResult {
workspace.requireWorkspace();
return transact(input?.tabId, () => {
return transact(input?.tabId, source, () => {
const plan = planEdit(input);
return commit.finish(plan, input.pageId, input.batch, commit.preview(plan, input));
}, confirmation);
Expand Down Expand Up @@ -129,9 +130,9 @@ function deletionSubject(block: ContentBlock): string {
return excerpt ? `“${excerpt}”` : names[block.type];
}

export function deleteBlock(input: BlockDeletion, confirmation?: string): CommitResult {
export function deleteBlock(input: BlockDeletion, source: HistorySource, confirmation?: string): CommitResult {
workspace.requireWorkspace();
return transact(input?.tabId, () => {
return transact(input?.tabId, source, () => {
const { pageId, blockId } = input;
writable(pageId);
const plan = new EditChanges(), block = plan.block(blockId), pages = data.owners(blockId);
Expand All @@ -147,9 +148,9 @@ export function deleteBlock(input: BlockDeletion, confirmation?: string): Commit
}, confirmation);
}

export function place(input: Placement, confirmation?: string): CommitResult {
export function place(input: Placement, source: HistorySource, confirmation?: string): CommitResult {
workspace.requireWorkspace();
return transact(input?.tabId, () => {
return transact(input?.tabId, source, () => {
const { position, action } = input;
if (!record(position) || !Number.isSafeInteger(position.index) || position.index < 0 || !validUUID(position.blockId)) throw new LabloomError({ kind: "block-invalid-position" });
const { pageId, containerId, index } = position;
Expand Down Expand Up @@ -213,9 +214,9 @@ function selectPages(ids: string[]): string[] {
return [...new Set(ids)];
}

export function trash(ids: string[], tabId: string, confirmation?: string): CommitResult {
export function trash(ids: string[], tabId: string, source: HistorySource, confirmation?: string): CommitResult {
workspace.requireWorkspace();
return transact(tabId, () => {
return transact(tabId, source, () => {
const selected = selectPages(ids), plan = new EditChanges();
for (const id of selected) {
plan.attributes(id, { deleted: true, recycle_reason: "manual_delete", recycled_at: nowSeconds() }, [], true);
Expand All @@ -225,9 +226,9 @@ export function trash(ids: string[], tabId: string, confirmation?: string): Comm
}, confirmation);
}

export function restore(ids: string[], tabId: string): CommitResult {
export function restore(ids: string[], tabId: string, source: HistorySource): CommitResult {
workspace.requireWorkspace();
return transact(tabId, () => {
return transact(tabId, source, () => {
const selected = selectPages(ids), plan = new EditChanges();
for (const id of selected) {
plan.attributes(id, { deleted: false, recycle_reason: null, recycled_at: null }, [], true);
Expand All @@ -238,11 +239,14 @@ export function restore(ids: string[], tabId: string): CommitResult {
});
}

export function createPage(kind: PageKind = "editable", title = "", initial: Record<string, AttributeValue> = {}, parentId?: string, tabId = ""): PageRecord {
export function createPage(kind: PageKind = "editable", title = "", initial: Record<string, AttributeValue> = {}, parentId?: string, origin?: HistoryOrigin): PageRecord {
return insertPage(kind, title, initial, parentId, origin?.tabId ?? "", kind === "annotation" && parentId && origin ? origin.source : false);
}
function insertPage(kind: PageKind, title: string, initial: Record<string, AttributeValue>, parentId: string | undefined, tabId: string, history: HistorySource | false): PageRecord {
workspace.requireWorkspace();
if (!pageKinds.includes(kind) || typeof title !== "string" || !record(initial)) throw new LabloomError({ kind: "page-invalid-create" });
const changed = { pages: [] as string[], blocks: [] as string[] };
const page = commit.run({ sourceTab: tabId, history: !!parentId && kind === "annotation" && !!tabId }, context => {
const page = commit.run({ sourceTab: tabId, history }, context => {
if (parentId) writable(parentId);
if (kind === "annotation" && initial.annotation_file != null) {
if (!parentId || data.header(parentId).kind !== "paper") throw new LabloomError({ kind: "annotation-paper-required" });
Expand Down
10 changes: 9 additions & 1 deletion main/knowledge/events.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import type { HistorySource } from "../../shared/history/ipc";
import { type KnowledgeChange, type PageKind } from "../../shared/types/content";
import { type Notice } from "../../shared/types/knowledge";
import * as workspace from "../workspace-state";
import * as data from "./records";

export type Event =
| { type: "history"; sources: HistorySource[] }
| { type: "knowledge"; change: KnowledgeChange }
| { type: "feed" }
| { type: "reminder"; notice: Notice; body: string };
Expand All @@ -19,7 +21,7 @@ function emit(event: Event): void {
for (const listener of listeners) listener(event);
}
/** Every writer uses the same owner expansion and page-kind calculation. */
export function publish(input: KnowledgeChange, feed = false): void {
export function expand(input: KnowledgeChange): KnowledgeChange {
workspace.requireWorkspace();
const change = { ...input };
if (change.blocks.length) {
Expand All @@ -34,6 +36,12 @@ export function publish(input: KnowledgeChange, feed = false): void {
const rows = data.statement("SELECT id,kind FROM pages WHERE id IN (SELECT value FROM json_each(?))").all(JSON.stringify(pages)) as { id: string; kind: PageKind }[];
change.kinds = Object.fromEntries(rows.map(row => [row.id, row.kind]));
}
return change;
}
export function historyChanged(sources: HistorySource[]): void {
if (sources.length) emit({ type: "history", sources });
}
export function publish(change: KnowledgeChange, feed: boolean): void {
emit({ type: "knowledge", change });
if (feed || Object.values(change.kinds ?? {}).includes("feed") || change.purged?.length) emit({ type: "feed" });
}
Expand Down
Loading
Loading