diff --git a/locales/en.json b/locales/en.json index 53d8e94..94be5df 100644 --- a/locales/en.json +++ b/locales/en.json @@ -416,6 +416,7 @@ "overview": "Overview", "feed": "Feeds", "library": "Knowledge Base", + "trash": "Recycle Bin", "papers": "Paper Library", "calendar": "Calendar", "attributes": "Manage Attributes", @@ -599,6 +600,90 @@ "page-fit": "Fit page" } }, + "table": { + "sort": "Sort", + "group": "Group", + "ungroup": "Remove grouping", + "field": "Field", + "operator": "Operator", + "value": "Value", + "searchOptions": "Search options", + "addCondition": "Add condition", + "removeCondition": "Remove condition", + "addValue": "Add value", + "removeValue": "Remove value", + "direction": "Direction", + "ascending": "Ascending", + "descending": "Descending", + "sortLevel": "Sort level {{level}}", + "moveSort": "Reorder sort level", + "addSort": "Add sort", + "removeSort": "Remove sort", + "granularity": "Date granularity", + "granularities": { + "day": "Day", + "week": "Week", + "month": "Month", + "year": "Year" + }, + "noGroupValue": "No {{name}}", + "openTrash": "Open Recycle Bin", + "editTitle": "Edit title", + "valueSeparator": ", ", + "dateMode": "Date mode", + "absolute": "Absolute", + "relativeMode": "Relative", + "days": "Days", + "from": "Start", + "to": "End", + "operators": { + "contains": "Contains", + "not-contains": "Does not contain", + "equals": "Is", + "not-equals": "Is not", + "numberEquals": "=", + "numberNotEquals": "≠", + "empty": "Is empty", + "not-empty": "Is not empty", + "greater": ">", + "greater-or-equal": "≥", + "less": "<", + "less-or-equal": "≤", + "in": "Is any of", + "not-in": "Is none of", + "any": "Contains any of", + "all": "Contains all of", + "none": "Contains none of", + "before": "Before", + "after": "After", + "on-or-after": "On or after", + "on-or-before": "On or before", + "between": "Between", + "incomplete": "Is incomplete", + "complete": "Is complete" + }, + "relative": { + "today": "Today", + "yesterday": "Yesterday", + "tomorrow": "Tomorrow", + "this-week": "This week", + "last-week": "Last week", + "next-week": "Next week", + "this-month": "This month", + "last-month": "Last month", + "next-month": "Next month", + "past-days": "Past {{count}} days", + "next-days": "Next {{count}} days", + "past-days_one": "Past {{count}} day", + "past-days_other": "Past {{count}} days", + "next-days_one": "Next {{count}} day", + "next-days_other": "Next {{count}} days" + }, + "relativeOptions": { + "past-days": "Past N days", + "next-days": "Next N days" + } + }, "library": { "scope": "Scope", "all": "All Pages", diff --git a/locales/zh-CN.json b/locales/zh-CN.json index 423c05f..73605e9 100644 --- a/locales/zh-CN.json +++ b/locales/zh-CN.json @@ -416,6 +416,7 @@ "overview": "总览", "feed": "订阅", "library": "知识库", + "trash": "回收站", "papers": "文献库", "calendar": "日历", "attributes": "属性管理", @@ -599,6 +600,90 @@ "page-fit": "适合页面" } }, + "table": { + "sort": "排序", + "group": "分组", + "ungroup": "取消分组", + "field": "字段", + "operator": "运算符", + "value": "值", + "searchOptions": "搜索选项", + "addCondition": "添加条件", + "removeCondition": "删除条件", + "addValue": "添加值", + "removeValue": "删除值", + "direction": "方向", + "ascending": "升序", + "descending": "降序", + "sortLevel": "第{{level}}级排序", + "moveSort": "拖动调整排序顺序", + "addSort": "添加排序", + "removeSort": "删除排序", + "granularity": "时间粒度", + "granularities": { + "day": "日", + "week": "周", + "month": "月", + "year": "年" + }, + "noGroupValue": "无({{name}})", + "openTrash": "打开回收站", + "editTitle": "编辑标题", + "valueSeparator": "、", + "dateMode": "日期模式", + "absolute": "绝对日期", + "relativeMode": "相对日期", + "days": "天数", + "from": "起始值", + "to": "结束值", + "operators": { + "contains": "包含", + "not-contains": "不包含", + "equals": "是", + "not-equals": "不是", + "numberEquals": "=", + "numberNotEquals": "≠", + "empty": "为空", + "not-empty": "不为空", + "greater": ">", + "greater-or-equal": "≥", + "less": "<", + "less-or-equal": "≤", + "in": "是其中之一", + "not-in": "不是其中任何一个", + "any": "包含其中之一", + "all": "全部包含", + "none": "不包含其中任何一个", + "before": "早于", + "after": "晚于", + "on-or-after": "不早于", + "on-or-before": "不晚于", + "between": "介于", + "incomplete": "属于未完成", + "complete": "属于已完成" + }, + "relative": { + "today": "今天", + "yesterday": "昨天", + "tomorrow": "明天", + "this-week": "本周", + "last-week": "上周", + "next-week": "下周", + "this-month": "本月", + "last-month": "上月", + "next-month": "下月", + "past-days": "过去{{count}}天", + "next-days": "未来{{count}}天", + "past-days_one": "过去{{count}}天", + "next-days_one": "未来{{count}}天", + "past-days_other": "过去{{count}}天", + "next-days_other": "未来{{count}}天" + }, + "relativeOptions": { + "past-days": "过去N天", + "next-days": "未来N天" + } + }, "library": { "scope": "范围", "all": "全部页面", diff --git a/main/knowledge/edits.ts b/main/knowledge/edits.ts index 898ab9b..50f6066 100644 --- a/main/knowledge/edits.ts +++ b/main/knowledge/edits.ts @@ -28,11 +28,22 @@ function putBlock(block: ContentBlock): void { plan.putBlock(block); plan.persist(); } -export function create(source: HistorySource, title = "", initial: Record = {}, parentId?: string, kind: "editable" | "paper" = "editable"): PageRecord { +export function validateInitial(initial: Record): void { workspace.requireWorkspace(); 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" }); - return createPage(kind, title, initial, parentId, source); +} + +type CreationIdentity = { id: string; writeId: string }; +export function create(source: HistorySource, title = "", initial: Record = {}, parentId?: string, kind: PageKind = "editable", + identity?: CreationIdentity): PageRecord { + validateInitial(initial); + return createPage(kind, title, kind === "annotation" && !parentId ? { independent: true, ...initial } : initial, parentId, source, identity); +} + +export function rename(pageId: string, title: string, source: HistorySource, confirmation?: string): CommitResult { + const { titleBlockId } = data.writable(pageId); + return commitEdit({ pageId, batch: 0, blocks: [{ id: titleBlockId, type: "title", payload: payload("title", title), children: [] }] }, source, confirmation); } function planEdit(input: EditCommit): EditChanges { if (!record(input) || !Number.isSafeInteger(input.batch) || input.batch < 0 || !Array.isArray(input.blocks) || !record(input.attributes ?? {}) || @@ -301,18 +312,20 @@ function createPageRows(plan: EditChanges, id: string, kind: PageKind, title: st return [titleId, ...children]; } -export function createPage(kind: PageKind = "editable", title = "", initial: Record = {}, parentId?: string, history?: HistorySource): PageRecord { +export function createPage(kind: PageKind = "editable", title = "", initial: Record = {}, parentId?: string, + history?: HistorySource, identity?: CreationIdentity): PageRecord { workspace.requireWorkspace(); - if (!pageKinds.includes(kind) || typeof title !== "string" || !record(initial)) throw new LabloomError({ kind: "page-invalid-create" }); + if (!pageKinds.includes(kind) || typeof title !== "string" || !record(initial) || identity && !validUUID(identity.id)) + throw new LabloomError({ kind: "page-invalid-create" }); const changed = { pages: [] as string[], blocks: [] as string[] }; - const page = commit.run({ history }, context => { + const page = commit.run({ history, writeId: identity?.writeId }, context => { if (parentId) data.writable(parentId); if (kind === "annotation" && initial.annotation_file != null) { if (!parentId || data.header(parentId).kind !== "paper") throw new LabloomError({ kind: "annotation-paper-required" }); const files = data.get(parentId).attributes.paper_files as string[]; if (!files.includes(String(initial.annotation_file))) throw new LabloomError({ kind: "paper-file-removed" }); } - const id = randomUUID(), plan = new EditChanges(); + const id = identity?.id ?? randomUUID(), plan = new EditChanges(); const created = createPageRows(plan, id, kind, title, parentId ? { ...initial, independent: false } : initial); if (parentId && kind === "annotation") { if (data.header(parentId).kind !== "paper") throw new LabloomError({ kind: "annotation-paper-required" }); diff --git a/main/knowledge/papers.ts b/main/knowledge/papers.ts index bbd69a1..2bf4403 100644 --- a/main/knowledge/papers.ts +++ b/main/knowledge/papers.ts @@ -194,7 +194,7 @@ export function attachImported(ids: string[], pageId: string, attributeId: strin }); } -export function importPrepared(ids: string[], source?: HistorySource, pageId?: string): string[] { +export function importPrepared(ids: string[], source?: HistorySource, pageId?: string, initial: Record = {}): string[] { workspace.requireWorkspace(); if (!ids.length) return []; if (pageId) { @@ -204,8 +204,9 @@ export function importPrepared(ids: string[], source?: HistorySource, pageId?: s } const files = requiredFiles(ids); if (files.some(file => file.mediaType !== "application/pdf")) throw new LabloomError({ kind: "import-pdf-only" }); + edits.validateInitial(initial); return files.map(file => edits.createPage("paper", basename(file.originalName, extname(file.originalName)), { - paper_files: [file.id], source_snapshot: { originalName: file.originalName } + ...initial, paper_files: [file.id], source_snapshot: { originalName: file.originalName } }, undefined, source).id); } diff --git a/main/knowledge/query.ts b/main/knowledge/query.ts new file mode 100644 index 0000000..fffa97d --- /dev/null +++ b/main/knowledge/query.ts @@ -0,0 +1,337 @@ +import { libraryText } from "../../shared/attrs/format"; +import { attributeTargetKind, decodeValue, emptyValue, encodeValue } from "../../shared/attrs/values"; +import { isTimeType, resolveTimeZone, secondsToDay, type TimePrecision } from "../../shared/content/time"; +import { createI18n, type Translate } from "../../shared/i18n"; +import type { Language } from "../../shared/locale"; +import type { AttributeDefinition, AttributeValue } from "../../shared/types/attributes"; +import { pageKinds, type PageKind } from "../../shared/types/content"; +import { conditionReady, groupGranularity, repairViewQuery, type GroupValue, type QueryDate, type QueryOperator, + type QueryValue, type ViewCondition, type ViewGroup, type ViewSort } from "../../shared/workspace/query"; +import { dateBounds, dateGroup } from "../../shared/workspace/query-time"; +import { repairPaperQuery, tableBatchSize, type QueryGroup, type TableViewType, type TrashLookup, type ViewLookup, type ViewResult } from "../../shared/workspace/table"; +import * as workspace from "../workspace-state"; +import { definitions } from "./attributes"; +import { subscribe } from "./events"; +import { statement, summariesForIds, summaryNames, targetNames, viewSearch } from "./records"; + +type Stored = string | number | null; +type Operand = Exclude; +type Clause = { test: string; params: Stored[] }; +type Row = { id: string; kind: PageKind; title: string; modified: number }; +type QueryContext = { zone: string; now: number; language: Language; compare: Intl.Collator["compare"]; t: Translate }; +type Definitions = ReadonlyMap; +type Values = Map>; +type Lookup = Omit & { type: TableViewType | "trash" }; +type Projection = { + criteria: string; + rows: Map; + values: Values; + dirty: Set; + targetsChanged: boolean; + search?: { term: string; ids: string[] }; +}; + +const locale = createI18n("zh-CN"); +const title = "knowledge_text(b.type,b.content)"; +const withTitle = " CROSS JOIN blocks b ON b.id=p.title_block_id"; +const withModified = " CROSS JOIN page_attrs m ON m.page_id=p.id AND m.attr_id='modified_at'"; +const reverse: Partial> = { + "not-contains": "contains", "not-equals": "equals", "not-in": "in", none: "any", empty: "not-empty" +}; +const comparisons: Partial> = { greater: ">", "greater-or-equal": ">=", less: "<", "less-or-equal": "<=" }; +const scans = new Set(["contains", "not-contains", "any", "all", "none"]); + +// One projection per mounted table. The workspace session releases all of them on close. +const projections = new Map(); +subscribe(event => { + if (event.type !== "knowledge" || !projections.size) return; + const { change } = event; + if (change.definition) { + projections.clear(); + return; + } + const affected = [...(change.summaryPages ?? change.pages), ...(change.recycledPages ?? []), ...(change.purged ?? [])]; + for (const projection of projections.values()) { + for (const id of affected) projection.dirty.add(id); + projection.search = undefined; + projection.targetsChanged ||= !!(change.titlePages?.length || change.purged?.length); + } +}); + +function timeTest(operator: QueryOperator, precision: TimePrecision, values: Operand[], { zone, now }: QueryContext): Clause { + const ranges = (values as QueryDate[]).map(value => dateBounds(value, precision, zone, now)); + const min = (i: 0 | 1): number => ranges.reduce((result, range) => Math.min(result, range[i]), Infinity); + const max = (i: 0 | 1): number => ranges.reduce((result, range) => Math.max(result, range[i]), -Infinity); + switch (operator) { + case "before": return { test: "a.value < ?", params: [max(0)] }; + case "after": return { test: "a.value >= ?", params: [min(1)] }; + case "on-or-after": return { test: "a.value >= ?", params: [min(0)] }; + case "on-or-before": return { test: "a.value < ?", params: [max(1)] }; + case "between": return { test: "a.value >= ? AND a.value < ?", params: [min(0), max(1)] }; + default: return ranges.length === 1 ? { test: "a.value >= ? AND a.value < ?", params: [...ranges[0]] } + : { test: "EXISTS (SELECT 1 FROM json_each(?) q WHERE a.value >= q.value ->> 0 AND a.value < q.value ->> 1)", params: [JSON.stringify(ranges)] }; + } +} + +function valueTest(operator: QueryOperator, expr: string, values: Operand[], def: AttributeDefinition | undefined, context: QueryContext): Clause { + switch (operator) { + case "not-empty": return { test: expr + " IS NOT ?", params: [def ? encodeValue(def, emptyValue(def.type)) : ""] }; + case "contains": { + const terms = (values as string[]).map(value => value.trim().toLocaleLowerCase()).filter(Boolean); + if (terms.length === 1) return { test: "instr(knowledge_lower(" + expr + "),?)>0", params: terms }; + return { test: "EXISTS (SELECT 1 FROM json_each(?) q WHERE instr(knowledge_lower(" + expr + "),q.value)>0)", params: [JSON.stringify(terms)] }; + } + case "any": case "all": { + const items = "SELECT value FROM json_each(" + expr + ")"; + if (values.length === 1) return { test: "? IN (" + items + ")", params: [values[0] as string] }; + const belongs = operator === "all" ? "NOT EXISTS" : "EXISTS"; + const membership = operator === "all" ? "NOT IN" : "IN"; + return { test: belongs + " (SELECT 1 FROM json_each(?) q WHERE q.value " + membership + " (" + items + "))", params: [JSON.stringify(values)] }; + } + case "complete": case "incomplete": { + const options = def?.metadata.options?.filter(option => option.group === operator).map(option => option.id) ?? []; + return { test: expr + " IN (SELECT value FROM json_each(?))", params: [JSON.stringify(options)] }; + } + } + if (def && isTimeType(def.type)) return timeTest(operator, def.type, values, context); + const cmp = comparisons[operator]; + if (cmp) { + const aggregate = cmp.startsWith(">") ? Math.min : Math.max; + return { test: expr + " " + cmp + " ?", params: [(values as number[]).reduce((a, b) => aggregate(a, b))] }; + } + const encoded = def?.type === "boolean" ? values.map(Number) : values; + return encoded.length === 1 ? { test: expr + " = ?", params: [encoded[0] as Stored] } + : { test: expr + " IN (SELECT value FROM json_each(?))", params: [JSON.stringify(encoded)] }; +} + +function conditionClause(condition: ViewCondition, defs: Definitions, context: QueryContext, byId: boolean): Clause { + const { field, operator } = condition; + const values = condition.values.filter((value): value is Operand => value !== null); + if (values.some(value => typeof value === "object" && value.kind === "current-page")) return { test: "0", params: [] }; + const def = field.kind === "attribute" ? defs.get(field.id) : undefined; + const reversed = reverse[operator], expr = def ? "a.value" : field.kind === "title" ? title : "p.kind"; + const clause = valueTest(reversed ?? operator, expr, values, def, context); + if (def) { + const test = byId ? (reversed ? "NOT EXISTS" : "EXISTS") + " (SELECT 1 FROM page_attrs a WHERE a.page_id=p.id AND " + : "p.id " + (reversed ? "NOT IN" : "IN") + " (SELECT a.page_id FROM page_attrs a WHERE "; + return { test: test + "a.attr_id=? AND " + clause.test + ")", params: [def.id, ...clause.params] }; + } + return reversed ? { ...clause, test: "NOT (" + clause.test + ")" } : clause; +} + +function readRows(conditions: ViewCondition[], defs: Definitions, context: QueryContext, type: Lookup["type"], candidateIds?: string[]): Row[] { + if (candidateIds?.length === 0) return []; + const clauses = conditions.toSorted((a, b) => Number(scans.has(a.operator)) - Number(scans.has(b.operator))) + .map(condition => ({ ...conditionClause(condition, defs, context, !!candidateIds || conditions.length > 1 && scans.has(condition.operator)), + title: condition.field.kind === "title" })); + const scope = (type === "papers" ? "p.kind='paper' AND " : "") + + "EXISTS (SELECT 1 FROM page_attrs d WHERE d.page_id=p.id AND d.attr_id='deleted' AND d.value=" + Number(type === "trash") + ")"; + const source = (prior?: string[]): string => prior ? " FROM json_each(?) j CROSS JOIN pages p ON p.id=j.value" : " FROM pages p"; + const select = (part: typeof clauses, prior?: string[]): [string, Stored[]] => [ + "SELECT p.id" + source(prior) + (part.some(clause => clause.title) ? withTitle : "") + " WHERE " + + [...part.map(clause => clause.test), scope].join(" AND "), + [...(prior ? [JSON.stringify(prior)] : []), ...part.flatMap(clause => clause.params)] + ]; + let matches = candidateIds; + // Break up long expressions to stay within SQLite's expression-tree depth. + const chunk = 32; + let start = 0; + for (; start + chunk < clauses.length; start += chunk) { + const [sql, params] = select(clauses.slice(start, start + chunk), matches); + matches = statement(sql).pluck().all(...params) as string[]; + if (!matches.length) return []; + } + const columns = "SELECT p.id,p.kind," + title + " AS title,m.value AS modified"; + if (start === clauses.length) return statement(columns + source(matches) + withTitle + withModified + " WHERE " + scope) + .all(...(matches ? [JSON.stringify(matches)] : [])) as Row[]; + // Resolve membership through attribute indexes before decoding any selected titles. + const [sql, params] = select(clauses.slice(start), matches); + return statement("WITH candidates AS MATERIALIZED (" + sql + ") " + columns + + " FROM candidates c CROSS JOIN pages p ON p.id=c.id" + withTitle + withModified).all(...params) as Row[]; +} + +function readValues(ids: string[], attrs: string[], into: Values): void { + if (!ids.length || !attrs.length) return; + const raw = statement("SELECT a.page_id AS id,a.attr_id AS attr,a.value FROM json_each(?) j CROSS JOIN page_attrs a ON a.page_id=j.value" + + " WHERE a.attr_id IN (SELECT value FROM json_each(?))").all(JSON.stringify(ids), JSON.stringify(attrs)) as { id: string; attr: string; value: Stored }[]; + for (const { id, attr, value } of raw) into.get(attr)!.set(id, value); +} + +function sortKey({ field }: ViewSort, defs: Definitions, values: Values, context: QueryContext): (row: Row) => string | number | null { + if (field.kind === "title") return row => row.title || null; + if (field.kind === "page-type") { + const labels = Object.fromEntries(pageKinds.map(kind => [kind, context.t(`library.${kind}`)])); + return row => labels[row.kind]; + } + if (field.id === "modified_at") return row => row.modified; + const def = defs.get(field.id)!, stored = values.get(field.id); + if (!stored) return () => null; + if (def.type === "number" || isTimeType(def.type)) return row => stored.get(row.id) as number | null ?? null; + if (def.type === "string" || def.type === "url") return row => stored.get(row.id) as string | null || null; + const decoded = new Map(); + for (const raw of stored.values()) if (raw !== null && !decoded.has(raw)) decoded.set(raw, decodeValue(def, raw)); + const names = attributeTargetKind(def.type) ? targetNames([...decoded.values()].map(value => [def, value])) : {}; + const labels = new Map([...decoded].map(([raw, value]) => [raw, libraryText(def, value, context.language, context.zone, context.t, names)])); + return row => labels.get(stored.get(row.id) ?? null) || null; +} + +function compareKeys(x: string | number | null, y: string | number | null, direction: ViewSort["direction"], compare: Intl.Collator["compare"]): number { + if (x === null || y === null) return x === y ? 0 : x === null ? 1 : -1; + const diff = typeof x === "number" && typeof y === "number" ? x - y : compare(String(x), String(y)); + return direction === "asc" ? diff : -diff; +} + +function sortRows(rows: Row[], sorts: ViewSort[], defs: Definitions, values: Values, context: QueryContext): void { + const keys = sorts.map(sort => sortKey(sort, defs, values, context)); + rows.sort((a, b) => { + for (let i = 0; i < keys.length; i++) { + const diff = compareKeys(keys[i](a), keys[i](b), sorts[i].direction, context.compare); + if (diff) return diff; + } + return b.modified - a.modified || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0); + }); +} + +function grouped(rows: Row[], group: ViewGroup, defs: Definitions, values: Values, context: QueryContext, names: Record): { rows: Row[]; groups: QueryGroup[] } { + const { field, granularity } = group; + const def = field.kind === "attribute" ? defs.get(field.id) : undefined; + const options = def?.metadata.options?.slice() ?? []; + if (def?.type === "status") options.sort((a, b) => Number(a.group === "complete") - Number(b.group === "complete")); + const order: readonly GroupValue[] = field.kind === "page-type" ? pageKinds : def?.type === "boolean" ? [true, false] : options.map(option => option.id); + const ranks = new Map(order.map((value, i) => [value, i])); + const groups = new Map(options.map(option => [option.id, []])); + const stored = def && values.get(def.id), keys = new Map(); + function groupKeys(row: Row): GroupValue[] { + if (field.kind === "page-type") return [row.kind]; + const raw = stored?.get(row.id); + if (!def || raw == null) return [null]; + const cached = keys.get(raw); + if (cached) return cached; + const value = decodeValue(def, raw) as Exclude | GroupValue[]; + const result = isTimeType(def.type) ? [dateGroup(value as number, def.type, groupGranularity(def.type, granularity), context.zone)] + : Array.isArray(value) ? value.length ? value : [null] : [value]; + keys.set(raw, result); + return result; + } + for (const row of rows) for (const value of groupKeys(row)) { + let members = groups.get(value); + if (!members) groups.set(value, members = []); + members.push(row); + } + if (def?.type === "page-link" || def?.type === "page-links") { + const ids = [...groups.keys()].filter((value): value is string => typeof value === "string"); + Object.assign(names, targetNames([[def, ids]])); + } + const ordered = [...groups].sort(([a], [b]) => { + if (a === null || b === null) return a === b ? 0 : a === null ? 1 : -1; + const rankA = ranks.get(a), rankB = ranks.get(b); + if (rankA !== undefined && rankB !== undefined) return rankA - rankB; + if (typeof a === "number" && typeof b === "number") return a - b; + const x = String(a), y = String(b); + return context.compare(names[x] ?? x, names[y] ?? y) || (x < y ? -1 : x > y ? 1 : 0); + }); + let start = 0; + const bounds = ordered.map(([value, members]) => { + const item = { value, start, count: members.length }; + start += members.length; + return item; + }); + return { rows: ordered.flatMap(([, members]) => members), groups: bounds }; +} + +function matchingRows(projection: Projection, keyword: string | undefined, scoped: boolean, zone: string): Row[] { + const term = keyword?.trim().toLocaleLowerCase(); + if (!term || !projection.rows.size) return [...projection.rows.values()]; + const { search } = projection; + if (search?.term !== term) { + // A page matching a longer substring also had to match the shorter one. + const candidates = search && term.includes(search.term) ? search.ids : scoped ? [...projection.rows.keys()] : undefined; + const plan = viewSearch(term, zone, candidates)!; + const ids = candidates?.length === 0 ? [] : (statement(plan.cte + "SELECT id FROM matches").pluck().all(plan.params) as string[]) + .filter(id => projection.rows.has(id)); + projection.search = { term, ids }; + } + return projection.search!.ids.map(id => projection.rows.get(id)!); +} + +function lookup(input: Lookup, columns?: string[]): ViewResult { + const { type } = input; + const zone = resolveTimeZone(workspace.timeZone()), { language } = input; + const context: QueryContext = { zone, now: workspace.seconds(), language, + compare: new Intl.Collator(language === "zh-CN" ? "zh-CN-u-co-pinyin" : language, { numeric: true }).compare, + t: (key, options) => locale.t(key, { ...options, lng: language }) }; + const defs = new Map(definitions().map(def => [def.id, type === "trash" && def.id === "recycled_at" ? { ...def, hidden: false } : def])); + const query = repairViewQuery(type === "papers" ? repairPaperQuery(input.query) : input.query, defs); + const conditions = query.conditions.filter(conditionReady); + const criteria = JSON.stringify([type, conditions, language, zone, secondsToDay(context.now, zone)]); + let projection = input.session ? projections.get(input.session) : undefined; + let known: Set | undefined; + const attrs = new Set(query.sort.flatMap(({ field }) => field.kind === "attribute" && field.id !== "modified_at" ? [field.id] : [])); + if (query.group?.field.kind === "attribute") attrs.add(query.group.field.id); + if (projection?.criteria === criteria) { + const { rows, values, dirty } = projection; + if (input.known && !projection.targetsChanged) known = new Set(input.known.filter(id => !dirty.has(id))); + for (const attr of values.keys()) if (!attrs.has(attr)) values.delete(attr); + if (dirty.size) { + const updated = readRows(conditions, defs, context, type, [...dirty]); + for (const field of values.values()) for (const id of dirty) field.delete(id); + readValues(updated.map(row => row.id), [...values.keys()], values); + for (const id of dirty) rows.delete(id); + for (const row of updated) rows.set(row.id, row); + } + } + else { + const rows = new Map(readRows(conditions, defs, context, type).map(row => [row.id, row])); + projection = { criteria, rows, values: new Map(), dirty: new Set(), targetsChanged: false }; + } + const rows = matchingRows(projection, input.keyword, type === "papers" || conditions.length > 0, zone); + const { values } = projection, missing = [...attrs].filter(id => !values.has(id)); + if (missing.length) { + const fields = new Map(missing.map(id => [id, new Map()])); + readValues(input.session ? [...projection.rows.keys()] : rows.map(row => row.id), missing, fields); + for (const [id, field] of fields) values.set(id, field); + } + sortRows(rows, query.sort, defs, values, context); + const links: [AttributeDefinition, AttributeValue][] = []; + for (const condition of query.conditions) if (condition.field.kind === "attribute") { + const def = defs.get(condition.field.id); + if (def && attributeTargetKind(def.type) === "page") links.push([def, condition.values.filter(value => typeof value === "string")]); + } + const names = targetNames(links); + const buckets = query.group && grouped(rows, query.group, defs, values, context, names); + const ordered = buckets ? buckets.rows : rows; + const groups = buckets ? buckets.groups : undefined; + const result: ViewResult = { ids: ordered.map(row => row.id), titles: ordered.map(row => row.title), ...(groups ? { groups } : {}) }; + if (columns?.length && ordered.length) { + const first = new Set(), collapsed = new Set(query.group?.collapsed); + for (const { start, count, value } of groups ?? [{ start: 0, count: ordered.length, value: null }]) { + if (collapsed.has(value)) continue; + for (let i = start; i < start + count && first.size < tableBatchSize; i++) first.add(ordered[i].id); + if (first.size >= tableBatchSize) break; + } + const initial = summariesForIds([...first].filter(id => !known?.has(id))); + Object.assign(names, summaryNames(initial, columns)); + result.initial = initial; + } + if (Object.keys(names).length) result.names = names; + projection.dirty.clear(); + projection.targetsChanged = false; + if (input.session) projections.set(input.session, projection); + return result; +} + +export function viewIndex(input: ViewLookup, columns?: string[]): ViewResult { + return lookup(input, columns); +} + +export function releaseView(session: string): void { + projections.delete(session); +} + +export function release(): void { + projections.clear(); +} + +export function trashIndex({ sort, ...input }: TrashLookup, columns?: string[]): ViewResult { + return lookup({ ...input, type: "trash", query: { sort, conditions: [] } }, columns); +} \ No newline at end of file diff --git a/main/knowledge/records.ts b/main/knowledge/records.ts index 021a480..43cff0b 100644 --- a/main/knowledge/records.ts +++ b/main/knowledge/records.ts @@ -1,12 +1,12 @@ import type Database from "better-sqlite3"; import { resolveAttributeDefinition } from "../../shared/attrs/definitions"; import { unsearchableBuiltinValues } from "../../shared/attrs/builtins"; -import { libraryText, search } from "../../shared/attrs/format"; +import { 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 type { MediaFile } from "../../shared/content/media"; -import { isTimeType, resolveTimeZone, validTimeSeconds } from "../../shared/content/time"; +import { 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"; @@ -16,8 +16,6 @@ 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"; export type BlockRow = typeof blocks.$inferSelect; type PageRow = typeof pages.$inferSelect; @@ -237,10 +235,11 @@ export function bodyExcerpts(rows: { id: string; children: string[] }[]): Map "'" + id + "'").join(","); // Format each distinct value once, then use page_attrs_by_value to find its pages. const attributeHits = `distinct_values AS MATERIALIZED ( SELECT attr_id, value FROM page_attrs WHERE attr_id IN ( - SELECT id FROM attrs_meta WHERE id NOT IN (${unsearchableBuiltinValues.map(id => "'" + id + "'").join(",")}) + SELECT id FROM attrs_meta WHERE id NOT IN (${unsearchableIds}) ) AND value IS NOT NULL GROUP BY attr_id, value ), matched_values AS MATERIALIZED ( SELECT v.attr_id, v.value FROM distinct_values v JOIN attrs_meta a ON a.id=v.attr_id @@ -277,6 +276,36 @@ const searchMatches = `WITH RECURSIVE ${blockHits}, ${attributeHits}, matches(id SELECT id FROM owners WHERE kind='page' UNION SELECT id FROM attribute_hits ) `; +const scopedSearchMatches = `WITH RECURSIVE candidates(id) AS MATERIALIZED (SELECT value FROM json_each(@candidates)), +visible_blocks(id) AS ( + SELECT r.block_id FROM candidates c CROSS JOIN sync_refs r ON r.container_kind='page' AND r.container_id=c.id + UNION SELECT r.block_id FROM visible_blocks b CROSS JOIN sync_refs r ON r.container_kind='block' AND r.container_id=b.id +), block_hits(id) AS ( + SELECT b.id FROM visible_blocks i CROSS JOIN blocks b ON b.id=i.id + WHERE instr(knowledge_lower(knowledge_text(b.type,b.content)), @keyword)>0 + OR (b.type IN ('image','video','file') AND b.content ->> '$.media.fileId' IS NULL + AND instr(knowledge_lower(coalesce(b.content ->> '$.media.name','')), @keyword)>0) + UNION SELECT l.source_id FROM visible_blocks i CROSS JOIN link_refs l ON l.source_kind='block' AND l.source_id=i.id + JOIN attachments f ON f.id=l.target_id WHERE l.target_kind='file' AND instr(knowledge_lower(f.original_name), @keyword)>0 +), owners(kind,id) AS ( + SELECT 'block',id FROM block_hits + UNION SELECT u.container_kind,u.container_id FROM owners o JOIN sync_refs u ON u.block_id=o.id WHERE o.kind='block' +), matches(id) AS ( + SELECT id FROM owners WHERE kind='page' + UNION SELECT c.id FROM candidates c WHERE EXISTS ( + SELECT 1 FROM page_attrs v JOIN attrs_meta a ON a.id=v.attr_id + WHERE v.page_id=c.id AND v.value IS NOT NULL AND v.attr_id NOT IN (${unsearchableIds}) + AND instr(knowledge_lower(${attributeText()}), @keyword)>0 + ) +) `; + +export function viewSearch(keyword: string | undefined, zone: string, candidates?: string[]): { cte: string; params: Record } | undefined { + const term = keyword?.trim().toLocaleLowerCase(); + if (!term) return undefined; + return candidates ? { cte: scopedSearchMatches, params: { keyword: term, zone, candidates: JSON.stringify(candidates) } } + : { cte: searchMatches, params: { keyword: term, zone } }; +} + function listFilter(query: Omit, bindings: Record = {}): { from: string; filter: string; cte: string; params: unknown[]; keyword?: string } | null { const where = ["d.value = ?"], params: unknown[] = [Number(!!query.deleted)]; if (query.ids !== undefined) { @@ -338,14 +367,16 @@ function listRows(query: PageQuery): { selected: ListRow[]; total: number } { " JOIN page_attrs s ON s.page_id=p.id AND s.attr_id='" + (query.sort === "created" ? "created_at" : "modified_at") + "'"; // Materialize keyword hits once. The window count precedes pagination. const count = keyword ? ", count(*) OVER() AS total" : ""; - const dateOrdered = query.hasValue === undefined && !query.ids && !keyword && query.pinned === undefined && !query.tags?.length && !Object.keys(query.attributes ?? {}).length && query.sort !== "title"; + const dateOrdered = query.hasValue === undefined && !query.ids && !keyword && query.pinned === undefined && !query.tags?.length && query.sort !== "title"; const dateId = query.sort === "created" ? "created_at" : "modified_at"; const selected = (dateOrdered ? statement(`SELECT p.id, p.kind, p.title_block_id AS titleBlockId, p.children FROM page_attrs s INDEXED BY page_attrs_order CROSS JOIN pages p ON p.id=s.page_id AND s.attr_id=? - JOIN page_attrs d ON d.page_id=p.id AND d.attr_id='deleted'${filter} ORDER BY s.value DESC,s.page_id LIMIT ? OFFSET ?`).all(dateId, ...params, limit, offset) + CROSS JOIN page_attrs d ON d.page_id=p.id AND d.attr_id='deleted'${filter} ORDER BY s.value DESC,s.page_id LIMIT ? OFFSET ?`).all(dateId, ...params, limit, offset) : statement(cte + "SELECT p.id, p.kind, p.title_block_id AS titleBlockId, p.children" + count + from + join + filter + " ORDER BY " + order + ", p.id LIMIT ? OFFSET ?").all(...params, limit, offset)) as ListRow[]; - const total = dateOrdered && !query.kind ? statement("SELECT count(*) FROM page_attrs WHERE attr_id='deleted' AND value=?").pluck().get(Number(!!query.deleted)) as number : selected[0]?.total ?? (keyword && !offset ? 0 : statement(cte + "SELECT count(*)" + from + filter).pluck().get(...params) as number); + const total = dateOrdered && !query.kind && !Object.keys(query.attributes ?? {}).length + ? statement("SELECT count(*) FROM page_attrs WHERE attr_id='deleted' AND value=?").pluck().get(Number(!!query.deleted)) as number + : selected[0]?.total ?? (keyword && !offset ? 0 : statement(cte + "SELECT count(*)" + from + filter).pluck().get(...params) as number); return { selected, total }; } @@ -427,7 +458,7 @@ function matchSnippet(text: string, keyword: string): string { return (start ? "…" : "") + text.slice(start, end) + (end < text.length ? "…" : ""); } -function targetNames(entries: Iterable<[AttributeDefinition, AttributeValue]>): Record { +export function targetNames(entries: Iterable<[AttributeDefinition, AttributeValue]>): Record { const pages = new Set(), files = new Set(); for (const [def, value] of entries) { const kind = attributeTargetKind(def.type); @@ -447,65 +478,14 @@ function targetNames(entries: Iterable<[AttributeDefinition, AttributeValue]>): return names; } -const libraryLocale = createI18n("zh-CN"); -function orderedLibraryRows(query: LibraryQuery): { id: string; title: string }[] { - const { column, direction } = query.sort, def = definition(column); - const sortAttr = def && !def.hidden && column !== "modified_at"; - const parts = listFilter(query, sortAttr ? { column } : {}); - if (!parts) return []; - const { from, filter, cte, params } = parts; - const source = from + " JOIN blocks b ON b.id=p.title_block_id JOIN page_attrs m ON m.page_id=p.id AND m.attr_id='modified_at'" + - (sortAttr ? " LEFT JOIN page_attrs s ON s.page_id=p.id AND s.attr_id=@column" : "") + filter; - const valueColumn = sortAttr ? "s.value" : "m.value"; - if (column !== "title" && column !== "kind" && (!def || def.hidden || isTimeType(def.type) || def.type === "number")) { - const order = valueColumn + (direction === "asc" ? " ASC" : " DESC") + " NULLS LAST" + (sortAttr ? ", m.value DESC" : "") + ", p.id"; - return statement(cte + "SELECT p.id,knowledge_text(b.type,b.content) AS title" + source + " ORDER BY " + order).all(...params) as { id: string; title: string }[]; - } - const zone = resolveTimeZone(workspace.timeZone()); - const t: Translate = (key, options) => libraryLocale.t(key, { ...options, lng: query.language }); - const collator = new Intl.Collator(query.language === "zh-CN" ? "zh-CN-u-co-pinyin" : query.language, { numeric: true }); - const rows = statement(cte + "SELECT p.id, p.kind, knowledge_text(b.type,b.content) AS title, m.value AS modified, " + valueColumn + " AS value" + source).all(...params) as { - id: string; kind: PageKind; title: string; modified: number; value: unknown; key?: string | null; - }[]; - const kindLabels = Object.fromEntries(pageKinds.map(kind => [kind, t(`library.${kind}`)])); - const decoded = new Map(); - if (sortAttr) for (const row of rows) { - if (row.value != null && !decoded.has(row.value)) decoded.set(row.value, decodeValue(def, row.value)); - } - const names = def && attributeTargetKind(def.type) ? targetNames(Array.from(decoded.values(), v => [def, v])) : {}; - const labels = new Map(Array.from(decoded, ([raw, value]) => [raw, libraryText(def!, value, query.language, zone, t, names)])); - for (const row of rows) { - if (column === "title") row.key = row.title || null; - else if (column === "kind") row.key = kindLabels[row.kind]; - else row.key = labels.get(row.value) || null; - } - const sign = direction === "desc" ? -1 : 1; - rows.sort((a, b) => { - const x = a.key, y = b.key; - if ((x == null) !== (y == null)) return x == null ? 1 : -1; - const diff = x != null && y != null ? collator.compare(x, y) : 0; - return sign * diff || b.modified - a.modified || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0); - }); - return rows; -} - -export function libraryIndex(query: LibraryQuery, initialColumns?: string[]): LibraryIndex & { initial?: PageSummary[] } { - const rows = orderedLibraryRows(query); - const filterLinks: [AttributeDefinition, AttributeValue][] = []; - for (const [id, value] of Object.entries(query.attributes ?? {})) { - const attr = definition(id); - if (attr && attributeTargetKind(attr.type)) filterLinks.push([attr, value]); - } - const index = { ids: rows.map(row => row.id), titles: rows.map(row => row.title), ...(filterLinks.length ? { names: targetNames(filterLinks) } : {}) }; - if (!initialColumns || !index.ids.length) return index; - // These IDs have already been filtered and ordered. Read just their headers for the first viewport. +export function summariesForIds(ids: string[]): PageSummary[] { + if (!ids.length) return []; const heads = statement(`SELECT p.id,p.kind,p.title_block_id AS titleBlockId,p.children FROM json_each(?) j - CROSS JOIN pages p ON p.id=j.value ORDER BY j.key`).all(JSON.stringify(index.ids.slice(0, libraryBatchSize))) as ListRow[]; - const initial = summaries(heads); - return { ...index, initial, names: { ...index.names, ...summaryNames(initial, initialColumns) } }; + CROSS JOIN pages p ON p.id=j.value ORDER BY j.key`).all(JSON.stringify(ids)) as ListRow[]; + return summaries(heads); } -function summaryNames(items: PageSummary[], columns?: string[]): Record | undefined { +export function summaryNames(items: PageSummary[], columns?: string[]): Record | undefined { const links = columns?.map(definition).filter(def => def && attributeTargetKind(def.type)) as AttributeDefinition[] | undefined; return links?.length ? targetNames(items.flatMap(row => links.map((def): [AttributeDefinition, AttributeValue] => [def, row.attributes[def.id]]))) : undefined; } diff --git a/main/pages/ipc.ts b/main/pages/ipc.ts index ce95123..24d5ede 100644 --- a/main/pages/ipc.ts +++ b/main/pages/ipc.ts @@ -3,6 +3,7 @@ import typia from "typia"; import { pagesChannels, pagesChanged, type PagesAPI } from "../../shared/pages/ipc"; import { invalid, register, route, type Routes } from "../ipc"; import * as records from "../knowledge/records"; +import { releaseView, trashIndex, viewIndex } from "../knowledge/query"; import * as picker from "../knowledge/block-list"; import * as edits from "../knowledge/edits"; import * as papers from "../knowledge/papers"; @@ -14,7 +15,9 @@ type Args = Parameters; export const routes = { list: route(typia.createAssert>(invalid), records.list), search: route(typia.createAssert>(invalid), records.searchPages), - libraryIndex: route(typia.createAssert>(invalid), records.libraryIndex), + viewIndex: route(typia.createAssert>(invalid), viewIndex), + releaseView: route(typia.createAssert>(invalid), releaseView), + trashIndex: route(typia.createAssert>(invalid), trashIndex), listUpdates: route(typia.createAssert>(invalid), records.listUpdates), blockList: route(typia.createAssert>(invalid), picker.blockList), overviewIndex: route(typia.createAssert>(invalid), records.overviewIndex), @@ -24,6 +27,7 @@ export const routes = { readObjects: route(typia.createAssert>(invalid), records.readObjects), syncBlocks: route(typia.createAssert>(invalid), edits.syncBlocks), create: route(typia.createAssert>(invalid), edits.create), + rename: route(typia.createAssert>(invalid), edits.rename), commitEdit: route(typia.createAssert>(invalid), edits.commitEdit), deleteBlock: route(typia.createAssert>(invalid), edits.deleteBlock), place: route(typia.createAssert>(invalid), edits.place), diff --git a/main/session.ts b/main/session.ts index 159370e..c1661e8 100644 --- a/main/session.ts +++ b/main/session.ts @@ -5,6 +5,7 @@ import { createWorkspace, openWorkspace, closeWorkspace, type OpenWorkspace } fr import { fetchFeed } from "./feed/parser"; import * as state from "./workspace-state"; import * as records from "./knowledge/records"; +import * as query from "./knowledge/query"; import * as history from "./knowledge/history-state"; import * as attachments from "./attachments/service"; import * as papers from "./knowledge/papers"; @@ -61,6 +62,7 @@ export function close(): void { commit.release(); history.release(); workspaceSettings.release(); + query.release(); records.release(); if (workspace) closeWorkspace(workspace); } \ No newline at end of file diff --git a/renderer/components/Knowledge/AttributeInput.svelte b/renderer/components/Knowledge/AttributeInput.svelte index 25d70ea..f921ba6 100644 --- a/renderer/components/Knowledge/AttributeInput.svelte +++ b/renderer/components/Knowledge/AttributeInput.svelte @@ -1,9 +1,9 @@ -
+
{#if definition.type === "file" || definition.type === "files"} - + {:else if isTimeType(definition.type)} + readonly={disabled || !!definition.readonly} {initiallyOpen} {onchange} /> {:else if definition.readonly || disabled} {#if (definition.type === "page-link" || definition.type === "page-links") && !empty} {#each (Array.isArray(value) ? value : [value]) as id (id)} @@ -21,7 +21,7 @@ {:else if definition.type === "boolean"} {:else if definition.type === "select" || definition.type === "status"} - ({ value: type, label: t(`library.${type}`) }))]} - onchange={type => change({ pageType: type ? { kind: "page-type", type: type as PageKind } : undefined })} /> - {/if} - {t("attributeName.tags")} - -
- {#each options.filter(o => o.name.toLocaleLowerCase().includes(search.trim().toLocaleLowerCase())) as option (option.id)} - { - change({ tags: checked ? [...params.tags, option.id] : params.tags.filter(id => id !== option.id) }); - }} /> - {/each} -
- {t("library.property")} - { - jump(event.data); event.currentTarget.value = ""; - }} - oninput={event => { - if (!(event instanceof InputEvent && event.isComposing)) event.currentTarget.value = ""; - }} /> - - - - {#each visible as id, n (id)} - {@const row = rows.get(id)} -
{ - ime.focus({ preventScroll: true }); choose(start + n, event.shiftKey, event.ctrlKey); - }} onkeydown={keys} - ondblclick={event => onopen([id], event.ctrlKey)} oncontextmenu={event => { - event.preventDefault(); context(start + n, event.clientX, event.clientY); - }}> - {#each columns as column (column.id)} - - {#if column.id === "title" && row}{/if} - {row ? cell(row, column.id) : column.id === "title" ? index.titles[start + n] : ""} - - {/each} -
- {/each} - - {#if !index.ids.length}
{t(pending ? "library.loading" : "library.empty")}
{/if} -
- ime?.focus({ preventScroll: true })} /> -{#if tip}{/if} - - \ No newline at end of file diff --git a/renderer/components/Knowledge/LibraryInfo.svelte b/renderer/components/Knowledge/LibraryInfo.svelte index 1dc3198..8320753 100644 --- a/renderer/components/Knowledge/LibraryInfo.svelte +++ b/renderer/components/Knowledge/LibraryInfo.svelte @@ -9,19 +9,19 @@ import Properties from "./Properties.svelte"; import FileInput from "./FileInput.svelte"; - let { tabId, pageId }: { tabId: string; pageId: string } = $props(); + let { tabId, pageId, readonly = false }: { tabId: string; pageId: string; readonly?: boolean } = $props(); const inspection = untrack(() => inspectPage(tabId, pageId)), current = inspection.current; onDestroy(inspection.release); const page = $derived(current.state.page); const attachments = $derived(current.state.definitions.find(def => def.id === "paper_files")); - const locked = $derived(current.state.loading || !!page?.attributes.deleted); + const locked = $derived(readonly || current.state.loading || !!page?.attributes.deleted);
{#if current.state.error}
{message(current.state.error)}
{:else if page} - link.sourceFields?.includes("paper_annotations"))} onattr={current.attr} ondetach={current.detach} /> {#if page.kind === "paper"} @@ -30,7 +30,7 @@ openPaperPDF={fileId => openPage(pageId, { duplicate: true, fileId })} onchange={value => current.attr("paper_files", value)} /> {/if}

{t("attributeName.paper_abstract")}

- {#if page.attributes.deleted}
{page.attributes.paper_abstract}
+ {#if readonly || page.attributes.deleted}
{page.attributes.paper_abstract}
{:else} current.attr("paper_abstract", value)} />{/if}
diff --git a/renderer/components/Knowledge/LibraryToolbar.svelte b/renderer/components/Knowledge/LibraryToolbar.svelte deleted file mode 100644 index 1de8977..0000000 --- a/renderer/components/Knowledge/LibraryToolbar.svelte +++ /dev/null @@ -1,41 +0,0 @@ - - -
-
- - {#snippet trigger({ props })}{/snippet} - {@render filters()} - - {#if scope === "trash"} - - {:else} - - - {/if} - - - \ No newline at end of file diff --git a/renderer/components/Knowledge/PageInformation.svelte b/renderer/components/Knowledge/PageInformation.svelte index 1cbd329..d4d73d8 100644 --- a/renderer/components/Knowledge/PageInformation.svelte +++ b/renderer/components/Knowledge/PageInformation.svelte @@ -10,7 +10,7 @@ import { inspectPage } from "./page-sessions"; import { knowledgeState } from "./feedback.svelte"; - let { tabId, pageId }: { tabId: string; pageId: string } = $props(); + let { tabId, pageId, readonly = false }: { tabId: string; pageId: string; readonly?: boolean } = $props(); const inspection = untrack(() => inspectPage(tabId, pageId)), current = inspection.current; onDestroy(inspection.release); const page = $derived(current.state.page); @@ -25,7 +25,7 @@ }); function rename(value: string): void { draft = undefined; - if (!title || page?.attributes.deleted || value === blockText(title)) return; + if (!title || readonly || page?.attributes.deleted || value === blockText(title)) return; current.stage({ blocks: [{ ...title, payload: payload("title", value) }] }); void current.flush().then(saved => { if (!saved && current.state.error) knowledgeState.error = current.state.error; @@ -37,12 +37,12 @@ {#if page?.kind === "paper" && title}
{ + inputProps={{ readonly: readonly || !!page.attributes.deleted, onkeydown: event => { if (event.key === "Enter" && !isComposingKey(event)) event.currentTarget.blur(); } }} disabled={current.state.loading} oninput={value => draft = value} onchange={rename} />
{/if} - + {#if page?.kind === "paper" && current.state.backlinks.length} +{/if} + + \ No newline at end of file diff --git a/renderer/components/Knowledge/TableFilters.svelte b/renderer/components/Knowledge/TableFilters.svelte new file mode 100644 index 0000000..954d22d --- /dev/null +++ b/renderer/components/Knowledge/TableFilters.svelte @@ -0,0 +1,77 @@ + + +
+ {#each conditions as condition, i (i)} + {@const field = fieldColumn(condition.field)} + {@const type = fieldType(condition.field, definitions)} + {#if type} +
+ update(i, newCondition(value))} /> + { + jump(event.data); event.currentTarget.value = ""; + }} + oninput={event => { + if (!(event instanceof InputEvent && event.isComposing)) event.currentTarget.value = ""; + }} /> + + + {#if sticky}{/if} + + {#each visible as entry, n (entry.key)} + {@const i = start + n} + {#if entry.kind === "group"} +
+
{@render groupHeader(entry)}
+
+ {:else} + {@const id = entry.id} + {@const row = rows.get(id)} +
{ + const target = event.target as Element; + if (target.closest("[data-cell-editor]")) return; + const column = target.closest("[data-column]")?.dataset.column; + const edit = column && selected.size === 1 && selected.has(id) && !event.shiftKey && !event.ctrlKey && event.detail < 2; + focusGrid(); choose(i, event.shiftKey, event.ctrlKey); + if (edit) onedit?.(entry, column); + }} onkeydown={keys} ondblclick={event => { + if (!(event.target as Element).closest("[data-cell-editor]")) onopen([id], event.ctrlKey); + }} oncontextmenu={event => { + if ((event.target as Element).closest("[data-cell-editor]")) return; + event.preventDefault(); context(i, event.clientX, event.clientY); + }}> + {#each columns as column (column.id)} +
+ {#snippet contents()} + {#if column.id === "title" && row}{/if} + {row ? cell(row, column.id) : column.id === "title" ? entry.title : ""} + {/snippet} + {#if editor}{@render editor(entry, column.id, row, contents)}{:else}{@render contents()}{/if} +
+ {/each} +
+ {/if} + {/each} + + {#if !layout.ids.size && !pending}
{t("library.empty")}
{/if} +
+ { + if (!document.activeElement?.closest("[data-cell-editor]")) focusGrid(); +}} /> +{#if tip}{/if} + + \ No newline at end of file diff --git a/renderer/components/Knowledge/TableGrouping.svelte b/renderer/components/Knowledge/TableGrouping.svelte new file mode 100644 index 0000000..74f9009 --- /dev/null +++ b/renderer/components/Knowledge/TableGrouping.svelte @@ -0,0 +1,41 @@ + + +
+ { + if (!group || fieldColumn(group.field) !== id) onchange({ field: columnField(id), collapsed: [] }); + }} /> + {#if group && granularity} + update(i, { ...item, direction: direction as ViewSort["direction"] })} /> + onchange(sort.filter((_, index) => i !== index))} /> +
+ {/each} + +
+ + \ No newline at end of file diff --git a/renderer/components/Knowledge/TableToolbar.svelte b/renderer/components/Knowledge/TableToolbar.svelte new file mode 100644 index 0000000..2a816cc --- /dev/null +++ b/renderer/components/Knowledge/TableToolbar.svelte @@ -0,0 +1,64 @@ + + +
+ + {#if query && filters} + { + if ((event.target as Element | null)?.closest("[data-table-filter-chip]")) event.preventDefault(); + } }}> + {#snippet trigger({ props })}{/snippet} + {@render filters()} + + {/if} + + {#snippet trigger({ props })}{/snippet} + {@render sorts()} + + {#if query && groups} + + {#snippet trigger({ props })}{/snippet} + {@render groups()} + + {/if} + {#if oncreate}{/if} + {#if onimport}{/if} + {#if onempty}{/if} +
+ + \ No newline at end of file diff --git a/renderer/components/Knowledge/library-import.svelte.ts b/renderer/components/Knowledge/library-import.svelte.ts index 0cba6ef..976132c 100644 --- a/renderer/components/Knowledge/library-import.svelte.ts +++ b/renderer/components/Knowledge/library-import.svelte.ts @@ -1,21 +1,22 @@ import { SvelteMap } from "svelte/reactivity"; import type { HistorySource } from "../../../shared/history/ipc"; +import type { AttributeValue } from "../../../shared/types/attributes"; import { failure, message, t } from "../../i18n.svelte"; import { openDestination, openPage } from "../layout/navigation"; import { knowledgeState } from "./feedback.svelte"; import { write } from "./page-sessions"; export const importedPages = new SvelteMap(); -export async function importPapers(source: HistorySource, options: { tabId?: string; pageId?: string; paths?: string[] } = {}): Promise { - const { tabId, pageId, paths } = options; +type ImportOptions = { pageId?: string; paths?: string[]; initial?: Record }; +export async function importPaperFiles(source: HistorySource, { pageId, paths, initial }: ImportOptions): Promise<{ pages: string[]; failed: boolean }> { const api = window.api, selected = paths ?? await api.attachments.choose("pdf"); - if (!selected.length) return; + if (!selected.length) return { pages: [], failed: false }; const { files, failures } = await api.attachments.stagePaths(selected, !pageId || !paths); const ids = files.map(file => file.id); let pages: string[] = []; if (ids.length) { try { - pages = await write(() => api.papers.importPrepared(ids, source, pageId)); + pages = await write(() => api.papers.importPrepared(ids, source, pageId, initial)); } catch (error) { failures.push(...files.map(file => ({ name: file.originalName, error: failure(error) }))); @@ -25,8 +26,13 @@ export async function importPapers(source: HistorySource, options: { tabId?: str } } if (failures.length) knowledgeState.error = { kind: "import-failed", diagnostic: failures.map(f => f.name + t("dialog.join") + message(f.error)).join("\n") }; - if (!pageId && pages.length) { - if (pages.length === 1 && !failures.length) openPage(pages[0]); - else importedPages.set(tabId ?? openDestination("papers").id, pages); + return { pages, failed: !!failures.length }; +} + +export async function importPapers(source: HistorySource, options: ImportOptions = {}): Promise { + const { pages, failed } = await importPaperFiles(source, options); + if (!options.pageId && pages.length) { + if (pages.length === 1 && !failed) openPage(pages[0]); + else importedPages.set(openDestination("papers").id, pages); } } \ No newline at end of file diff --git a/renderer/components/Knowledge/page-header.ts b/renderer/components/Knowledge/page-header.ts index 4f67270..9a9820f 100644 --- a/renderer/components/Knowledge/page-header.ts +++ b/renderer/components/Knowledge/page-header.ts @@ -9,6 +9,7 @@ import { viewMenu } from "../Tab/view-menu"; import * as feedback from "./feedback.svelte"; import * as sessions from "./page-sessions"; import type { PageSession } from "./page-session.svelte"; +import { openDestination } from "../layout/navigation"; export function toggleProperties(id: TabID, params: ViewParams["page"]): void { const paper = sessions.mountedSession(id, params.page.id)?.state.page?.kind === "paper"; @@ -43,10 +44,11 @@ export function pageHeader(id: TabID, params: ViewParams["page"]): HeaderActions return actions; } -export function toggleLibraryProperties(id: TabID, params: ViewParams["library"]): void { +export function toggleTableProperties(id: TabID, params: ViewParams["library" | "trash"]): void { tabs.setViewParams(id, { ...params, showProperties: params.showProperties === false }); } -export function libraryHeader(id: TabID, params: ViewParams["library"]): HeaderActions { +export function tableHeader(id: TabID, params: ViewParams["library" | "trash"], trash = false): HeaderActions { return { buttons: [{ icon: "layout-sidebar-right", label: i18n.t("editor.properties"), shortcut: shortcuts.commands.toggleProperties.shortcut, - pressed: params.showProperties !== false, onclick: () => toggleLibraryProperties(id, params) }], menu: [] }; + pressed: params.showProperties !== false, onclick: () => toggleTableProperties(id, params) }], + menu: trash ? [] : [{ label: i18n.t("table.openTrash"), icon: "trash", onselect: () => openDestination("trash") }] }; } \ No newline at end of file diff --git a/renderer/components/Knowledge/query-labels.ts b/renderer/components/Knowledge/query-labels.ts new file mode 100644 index 0000000..82e28a1 --- /dev/null +++ b/renderer/components/Knowledge/query-labels.ts @@ -0,0 +1,47 @@ +import { isTimeType, type TimePrecision } from "../../../shared/content/time"; +import { fieldType, needsValue, type QueryOperator, type QueryValue, type RelativeDate, type ViewCondition, type ViewFieldType } from "../../../shared/workspace/query"; +import { fieldColumn } from "../../../shared/workspace/table"; +import type { AttributeDefinition } from "../../../shared/types/attributes"; +import { pageKinds } from "../../../shared/types/content"; +import { t } from "../../i18n.svelte"; +import { pickerValueText } from "../base/date-picker"; +import { propertyOption } from "./attribute-labels"; + +function relativeLabel(value: RelativeDate): string { + return t(`table.relative.${value.period}`, "days" in value ? { count: value.days } : undefined); +} + +export function operatorLabel(operator: QueryOperator, type?: ViewFieldType): string { + if (type === "number" && operator === "equals") return t("table.operators.numberEquals"); + if (type === "number" && operator === "not-equals") return t("table.operators.numberNotEquals"); + return t(`table.operators.${operator}`); +} + +function operandLabel(value: QueryValue, type: ViewFieldType, zone: string, names: Record, definition?: AttributeDefinition): string { + if (value === null) return ""; + if (typeof value === "object") { + if (value.kind === "relative") return relativeLabel(value); + if (value.kind === "absolute") return pickerValueText(type as TimePrecision, value.seconds, zone); + return ""; + } + if (type === "page-type") { + const kind = pageKinds.find(kind => kind === value); + return kind ? t(`library.${kind}`) : ""; + } + if (type === "page-link" || type === "page-links") return names[String(value)] || t("shell.untitled"); + if (type === "boolean") return t(value ? "library.yes" : "library.no"); + const option = definition?.metadata.options?.find(option => option.id === value); + return definition && option ? propertyOption(definition, option) : String(value); +} + +export function conditionLabel(condition: ViewCondition, definitions: ReadonlyMap, + label: (id: string) => string, zone: string, names: Record): string { + const id = fieldColumn(condition.field), type = fieldType(condition.field, definitions); + const operator = operatorLabel(type === "page-type" && condition.operator === "in" && condition.values.length === 1 ? "equals" : condition.operator, type); + const values = type && needsValue(condition.operator) ? condition.values.map(value => operandLabel(value, type, zone, names, definitions.get(id))).filter(Boolean) : []; + return [label(id), operator, values.join(condition.operator === "between" ? " – " : t("table.valueSeparator"))].filter(Boolean).join(" "); +} + +export function isDateField(type: ViewFieldType): type is TimePrecision { + return type !== "title" && type !== "page-type" && isTimeType(type); +} \ No newline at end of file diff --git a/renderer/components/Knowledge/table-rows.ts b/renderer/components/Knowledge/table-rows.ts new file mode 100644 index 0000000..6f7c841 --- /dev/null +++ b/renderer/components/Knowledge/table-rows.ts @@ -0,0 +1,65 @@ +import type { GroupValue } from "../../../shared/workspace/query"; +import type { ViewResult } from "../../../shared/workspace/table"; + +export type RetainedRow = { id: string; title: string; group?: GroupValue }; +export type TablePage = RetainedRow & { kind: "page"; key: string }; +export type TableGroup = { kind: "group"; key: string; value: GroupValue; count: number; collapsed: boolean; at: number; end: number }; +type TableRow = TablePage | TableGroup; +export type TablePosition = { key?: string; id?: string; index: number; offset: number }; + +export type TableRows = { + items: TableRow[]; + ids: Set; + positions: Map; + firstOccurrences: Map; + groups: Map; +}; + +export function tableRows(result: ViewResult, grouped: boolean, collapsed: GroupValue[], retained: RetainedRow[]): TableRows { + const items: TableRow[] = [], ids = new Set(result.ids), positions = new Map(), firstOccurrences = new Map(); + const groups = new Map(); + const retainedIds = new Set(retained.map(row => row.id)); + for (const id of retainedIds) ids.add(id); + function add(page: RetainedRow): void { + const key = "p:" + JSON.stringify(page.group ?? null) + ":" + page.id; + if (!firstOccurrences.has(page.id)) firstOccurrences.set(page.id, items.length); + positions.set(key, items.length); + items.push({ ...page, kind: "page", key }); + } + if (!grouped) { + retained.forEach(add); + result.ids.forEach((id, i) => { + if (!retainedIds.has(id)) add({ id, title: result.titles[i] }); + }); + return { items, ids, positions, firstOccurrences, groups }; + } + const folded = new Set(collapsed), retainedByGroup = new Map(); + for (const row of retained) { + const value = row.group ?? null, entries = retainedByGroup.get(value); + if (entries) entries.push(row); + else retainedByGroup.set(value, [row]); + } + const buckets = result.groups ?? [], bucketValues = new Set(buckets.map(group => group.value)); + const bounds = [...buckets, ...[...retainedByGroup.keys()].filter(value => !bucketValues.has(value)).map(value => ({ value, start: 0, count: 0 }))]; + for (const { value, start, count } of bounds) { + const local = retainedByGroup.get(value) ?? []; + let visible = local.length + count; + if (retainedIds.size) { + for (let i = start; i < start + count; i++) if (retainedIds.has(result.ids[i])) visible--; + } + if (!visible) continue; + const key = "g:" + JSON.stringify(value), at = items.length; + const header: TableGroup = { kind: "group", value, key, count: visible, collapsed: folded.has(value), at, end: at + 1 }; + positions.set(key, at); + groups.set(value, header); + items.push(header); + if (header.collapsed) continue; + local.forEach(row => add({ ...row, group: value })); + for (let i = start; i < start + count; i++) { + const id = result.ids[i]; + if (!retainedIds.has(id)) add({ id, title: result.titles[i], group: value }); + } + header.end = items.length; + } + return { items, ids, positions, firstOccurrences, groups }; +} \ No newline at end of file diff --git a/renderer/components/Tab/Content.svelte b/renderer/components/Tab/Content.svelte index 0ff3c22..79f9903 100644 --- a/renderer/components/Tab/Content.svelte +++ b/renderer/components/Tab/Content.svelte @@ -1,5 +1,5 @@ {#key source.kind === "page" ? source.id : tab.id} - setViewParams(tab.id, params)} /> + setViewParams(tab.id, params)} /> {/key}