diff --git a/locales/en.json b/locales/en.json index 94be5df..22f509d 100644 --- a/locales/en.json +++ b/locales/en.json @@ -157,6 +157,8 @@ "block-invalid-version": "The block content format version is invalid.", "block-invalid-language": "Only code blocks can specify a supported code language.", "block-invalid-media": "The media block contains invalid file or display information.", + "block-invalid-view": "The view block contains invalid settings.", + "board-invalid-move": "These cards can no longer be moved to that column.", "block-invalid-collapse": "The collapsed state is invalid.", "block-invalid-inline": "The rich text node is invalid.", "block-empty-text": "A text node cannot be empty.", @@ -600,6 +602,19 @@ "page-fit": "Fit page" } }, + "viewBlock": { + "table": "Table view", + "board": "Board view", + "calendar": "Calendar view", + "tableTitle": "Table", + "boardTitle": "Board", + "name": "View name", + "openTab": "Open in tab", + "cardProperties": "Card properties", + "resize": "View height", + "ungrouped": "Ungrouped", + "currentPage": "Current page" + }, "table": { "sort": "Sort", "group": "Group", @@ -809,11 +824,15 @@ "calendar": { "previousMonth": "Previous month", "nextMonth": "Next month", + "previousWeek": "Previous week", + "nextWeek": "Next week", + "month": "Month", + "week": "Week", "today": "Today", "chooseDate": "Choose date property", "chooseStart": "Choose start time property", + "chooseEnd": "Choose end time property", "chooseStatus": "Choose status property", - "missingDate": "Date property not found", "agendaWidth": "Day list width", "remaining": "{{count}} more", "noPages": "No pages", @@ -834,6 +853,7 @@ "table": "Table", "hr": "Divider", "blocked_reference": "Linked reference", + "view": "View", "image": "Image", "video": "Video", "file": "File" diff --git a/locales/zh-CN.json b/locales/zh-CN.json index 73605e9..907b221 100644 --- a/locales/zh-CN.json +++ b/locales/zh-CN.json @@ -157,6 +157,8 @@ "block-invalid-version": "块内容的格式版本无效。", "block-invalid-language": "只有代码块可以指定语言,且必须使用支持的代码语言。", "block-invalid-media": "多媒体块的文件或显示数据无效。", + "block-invalid-view": "视图块的设置无效。", + "board-invalid-move": "这些卡片已无法移动到该列。", "block-invalid-collapse": "折叠状态无效。", "block-invalid-inline": "富文本节点无效。", "block-empty-text": "文本节点不能为空。", @@ -600,6 +602,19 @@ "page-fit": "适合页面" } }, + "viewBlock": { + "table": "表格视图", + "board": "看板视图", + "calendar": "日历视图", + "tableTitle": "表格", + "boardTitle": "看板", + "name": "视图名", + "openTab": "在标签页打开", + "cardProperties": "卡片属性", + "resize": "视图高度", + "ungrouped": "未分组", + "currentPage": "当前页面" + }, "table": { "sort": "排序", "group": "分组", @@ -809,11 +824,15 @@ "calendar": { "previousMonth": "上个月", "nextMonth": "下个月", + "previousWeek": "上一周", + "nextWeek": "下一周", + "month": "月", + "week": "周", "today": "今天", "chooseDate": "选择日期属性", "chooseStart": "选择开始时间属性", + "chooseEnd": "选择结束时间属性", "chooseStatus": "选择状态属性", - "missingDate": "找不到日期属性", "agendaWidth": "当天列表宽度", "remaining": "还有 {{count}} 条", "noPages": "没有页面", @@ -834,6 +853,7 @@ "table": "表格", "hr": "分隔线", "blocked_reference": "链接引用", + "view": "视图", "image": "图片", "video": "视频", "file": "文件" diff --git a/main/app/ipc.ts b/main/app/ipc.ts index cbd35cf..88017e3 100644 --- a/main/app/ipc.ts +++ b/main/app/ipc.ts @@ -21,7 +21,8 @@ export function registerAppIPCs(window: BrowserWindow): void { register(contents, appChannels, { openDevTools: route(typia.createAssert>(invalid), () => contents.openDevTools({ mode: "detach" })), setFrameColors: route(typia.createAssert>(invalid), (color, symbolColor) => { - if (process.platform !== "darwin" && !window.isDestroyed()) window.setTitleBarOverlay({ color, symbolColor }); + if (process.platform === "darwin" || window.isDestroyed()) return; + window.setTitleBarOverlay(process.platform === "win32" ? { symbolColor } : { color, symbolColor }); }), editorStarted: route(typia.createAssert>(invalid), () => lifecycle.editorStarted(contents)), beforeQuitResult: route(typia.createAssert>(invalid), (id, blocked) => lifecycle.saveResult(contents, id, blocked)) diff --git a/main/knowledge/board.ts b/main/knowledge/board.ts new file mode 100644 index 0000000..f597729 --- /dev/null +++ b/main/knowledge/board.ts @@ -0,0 +1,73 @@ +import { isBuiltin } from "../../shared/attrs/builtins"; +import { decodeValue, emptyValue, nullable } from "../../shared/attrs/values"; +import { isTimeType, resolveTimeZone, secondsToDay, secondsToMinute, timeToSeconds } from "../../shared/content/time"; +import { LabloomError } from "../../shared/failure"; +import type { AttributeDefinition, AttributeValue } from "../../shared/types/attributes"; +import type { CommitResult } from "../../shared/types/content"; +import type { BoardMove } from "../../shared/workspace/view-block"; +import { canGroup, groupGranularity, type GroupGranularity, type GroupValue } from "../../shared/workspace/query"; +import { dateGroup, groupDateValue } from "../../shared/workspace/query-time"; +import * as workspace from "../workspace-state"; +import { definitions } from "./attributes"; +import { EditChanges } from "./changes"; +import * as commit from "./commit"; +import { statement, viewBlock } from "./records"; + +function movedValue(def: AttributeDefinition, before: AttributeValue, from: GroupValue, to: GroupValue, + zone: string, granularity?: GroupGranularity): AttributeValue | undefined { + if (def.type === "multiselect" || def.type === "page-links") { + const values = Array.isArray(before) ? before : []; + if (from === null ? values.length : !values.includes(from)) return undefined; + const other = values.filter(value => value !== from); + return to === null || other.includes(to) ? other : [...other, to] as AttributeValue; + } + if (isTimeType(def.type)) { + const unit = groupGranularity(def.type, granularity); + const previous = typeof before === "number" ? dateGroup(before, def.type, unit, zone) : null; + if (previous !== from) return undefined; + if (to === null) return null; + if (typeof to !== "number" || dateGroup(groupDateValue(to, def.type, unit, zone), def.type, unit, zone) !== to) throw invalidMove(); + return typeof before === "number" && (def.type === "minute" || def.type === "hour") + ? timeToSeconds("minute", secondsToDay(to) + " " + secondsToMinute(before, zone).slice(-5), zone) + : groupDateValue(to, def.type, unit, zone); + } + if (before !== from) return undefined; + return to === null && nullable(def.type) ? emptyValue(def.type) : to; +} + +function invalidMove(): LabloomError { + return new LabloomError({ kind: "board-invalid-move" }); +} + +export function moveViewCards(input: BoardMove, confirmation?: string, writeId?: string): CommitResult { + const { pageId, blockId, cards, to } = input, source = { kind: "page", id: pageId } as const; + return commit.edit({ history: source, confirmation, writeId }, () => { + const view = viewBlock(pageId, blockId)?.payload.view, group = view?.query.group; + if (view?.type !== "board" || group?.field.kind !== "attribute") throw invalidMove(); + const { id } = group.field, def = definitions().find(def => def.id === id); + if (!def || def.hidden || def.readonly || id === "deleted" || !canGroup(def.type)) throw invalidMove(); + if (to !== null && (def.type === "page-link" || def.type === "page-links") && + (typeof to !== "string" || !statement("SELECT 1 FROM pages WHERE id=?").get(to))) throw invalidMove(); + const zone = resolveTimeZone(workspace.timeZone()), plan = new EditChanges(); + const unique = new Map(cards.map(card => [card.id, card.from])); + const ids = [...unique.keys()].filter(page => unique.get(page) !== to); + const values = statement(`SELECT j.value AS id, a.value, d.value AS deleted FROM json_each(?) j + LEFT JOIN page_attrs d ON d.page_id=j.value AND d.attr_id='deleted' + LEFT JOIN page_attrs a ON a.page_id=j.value AND a.attr_id=?`).all(JSON.stringify(ids), id) as + { id: string; value: string | number | null; deleted: number | null }[]; + for (const { id: page, value: old, deleted } of values) { + const from = unique.get(page)!; + if (deleted !== 0) throw invalidMove(); + const before = old === null ? null : decodeValue(def, old); + const value = movedValue(def, before, from, to, zone, group.granularity); + if (value === undefined || JSON.stringify(value) === JSON.stringify(before)) continue; + if (value === null && !nullable(def.type)) { + if (isBuiltin(id)) throw invalidMove(); + plan.attributes(page, {}, [id]); + } + else plan.attributes(page, { [id]: value }); + plan.touches.add(page); + } + return commit.finish(plan, pageId, 0, { action: input }); + }); +} \ No newline at end of file diff --git a/main/knowledge/edits.ts b/main/knowledge/edits.ts index 50f6066..3d2a40b 100644 --- a/main/knowledge/edits.ts +++ b/main/knowledge/edits.ts @@ -135,7 +135,7 @@ function deletionSubject(block: ContentBlock): string { const names: Record = { title: "标题", paragraph: "段落", heading_1: "一级标题", heading_2: "二级标题", heading_3: "三级标题", unordered_list: "无序列表项", ordered_list: "有序列表项", blockquote: "引言", callout: "提示块", - code: "代码块", table: "表格", hr: "分隔线", blocked_reference: "链接引用", + code: "代码块", table: "表格", hr: "分隔线", blocked_reference: "链接引用", view: "视图", image: "图片", video: "视频", file: "文件" }; const target = block.payload.target; diff --git a/main/knowledge/query.ts b/main/knowledge/query.ts index fffa97d..757e294 100644 --- a/main/knowledge/query.ts +++ b/main/knowledge/query.ts @@ -1,14 +1,16 @@ 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 { isTimeType, resolveTimeZone, secondsToDay, validTimeSeconds, 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, +import { conditionReady, groupGranularity, repairFilterPages, repairViewQuery, resolveCurrentPage, 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 { dateBounds, dateGroup, groupDateValue } from "../../shared/workspace/query-time"; +import { calendarDefinitions, type CalendarLookup, type CalendarPage, type CalendarResult } from "../../shared/workspace/calendar"; +import { calendarDuration, calendarPoint } from "../../shared/workspace/calendar-time"; +import { repairPaperQuery, tableBatchSize, type QueryGroup, type TrashLookup, type ViewLookup, type ViewResult } from "../../shared/workspace/table"; import * as workspace from "../workspace-state"; import { definitions } from "./attributes"; import { subscribe } from "./events"; @@ -21,7 +23,7 @@ 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 Lookup = ViewLookup | Omit & { type: "trash" }; type Projection = { criteria: string; rows: Map; @@ -30,6 +32,7 @@ type Projection = { targetsChanged: boolean; search?: { term: string; ids: string[] }; }; +type CalendarProjection = { criteria: string; rows: Map; dirty: Set }; const locale = createI18n("zh-CN"); const title = "knowledge_text(b.type,b.content)"; @@ -43,11 +46,16 @@ const scans = new Set(["contains", "not-contains", "any", "all", // One projection per mounted table. The workspace session releases all of them on close. const projections = new Map(); +const calendars = new Map(); +let unfilteredUserRows: Row[] | undefined; subscribe(event => { - if (event.type !== "knowledge" || !projections.size) return; + if (event.type !== "knowledge") return; + unfilteredUserRows = undefined; + if (!projections.size && !calendars.size) return; const { change } = event; if (change.definition) { projections.clear(); + calendars.clear(); return; } const affected = [...(change.summaryPages ?? change.pages), ...(change.recycledPages ?? []), ...(change.purged ?? [])]; @@ -56,6 +64,7 @@ subscribe(event => { projection.search = undefined; projection.targetsChanged ||= !!(change.titlePages?.length || change.purged?.length); } + for (const calendar of calendars.values()) for (const id of affected) calendar.dirty.add(id); }); function timeTest(operator: QueryOperator, precision: TimePrecision, values: Operand[], { zone, now }: QueryContext): Clause { @@ -119,6 +128,21 @@ function conditionClause(condition: ViewCondition, defs: Definitions, context: Q return reversed ? { ...clause, test: "NOT (" + clause.test + ")" } : clause; } +function queryContext(language: Language): QueryContext { + return { zone: resolveTimeZone(workspace.timeZone()), 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 }) }; +} + +function missingFilterPages(conditions: ViewCondition[], defs: Definitions): string[] { + const links = new Set(conditions.flatMap(({ field, values }) => { + const def = field.kind === "attribute" && defs.get(field.id); + return def && attributeTargetKind(def.type) === "page" ? values.filter(value => typeof value === "string") : []; + })); + return links.size ? statement("SELECT value FROM json_each(?) j WHERE NOT EXISTS (SELECT 1 FROM pages p WHERE p.id=j.value)") + .pluck().all(JSON.stringify([...links])) as string[] : []; +} + 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))) @@ -192,7 +216,7 @@ function sortRows(rows: Row[], sorts: ViewSort[], defs: Definitions, values: Val }); } -function grouped(rows: Row[], group: ViewGroup, defs: Definitions, values: Values, context: QueryContext, names: Record): { rows: Row[]; groups: QueryGroup[] } { +function grouped(rows: Row[], group: ViewGroup, defs: Definitions, values: Values, context: QueryContext, names: Record, board: boolean): { rows: Row[]; groups: QueryGroup[] } { const { field, granularity } = group; const def = field.kind === "attribute" ? defs.get(field.id) : undefined; const options = def?.metadata.options?.slice() ?? []; @@ -200,6 +224,11 @@ function grouped(rows: Row[], group: ViewGroup, defs: Definitions, values: Value 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, []])); + if (board && def?.type === "boolean") { + groups.set(true, []); + groups.set(false, []); + } + if (board) groups.set(null, []); const stored = def && values.get(def.id), keys = new Map(); function groupKeys(row: Row): GroupValue[] { if (field.kind === "page-type") return [row.kind]; @@ -254,15 +283,15 @@ function matchingRows(projection: Projection, keyword: string | undefined, scope return projection.search!.ids.map(id => projection.rows.get(id)!); } -function lookup(input: Lookup, columns?: string[]): ViewResult { +function lookup(input: Lookup, columns?: string[], visibleGroups?: number): 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 context = queryContext(input.language), { zone, language } = context; 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); + let query = repairViewQuery(type === "papers" ? repairPaperQuery(input.query) : input.query, defs); + const board = type === "user" && !!input.board; + const missingPages = type === "user" ? missingFilterPages(query.conditions, defs) : []; + if (missingPages.length) query = repairFilterPages(query, defs, new Set(missingPages)); + const conditions = (type === "user" ? resolveCurrentPage(query, input.pageId) : 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; @@ -281,7 +310,11 @@ function lookup(input: Lookup, columns?: string[]): ViewResult { } } else { - const rows = new Map(readRows(conditions, defs, context, type).map(row => [row.id, row])); + // User views have independent sessions. Their unfiltered candidate lists can + // share page metadata until a committed change invalidates that snapshot. + const read = type === "user" && !conditions.length ? unfilteredUserRows ??= readRows(conditions, defs, context, type) + : readRows(conditions, defs, context, type); + const rows = new Map(read.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); @@ -298,15 +331,18 @@ function lookup(input: Lookup, columns?: string[]): ViewResult { 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 buckets = query.group && grouped(rows, query.group, defs, values, context, names, board); 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 (missingPages.length) result.missingPages = missingPages; 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 }]) { + const initialGroups = groups ?? [{ start: 0, count: ordered.length, value: null }]; + const limit = board ? Math.ceil(tableBatchSize / (visibleGroups || 1)) : tableBatchSize; + for (const { start, count, value } of board ? initialGroups.slice(0, visibleGroups || 1) : initialGroups) { if (collapsed.has(value)) continue; - for (let i = start; i < start + count && first.size < tableBatchSize; i++) first.add(ordered[i].id); + for (let i = start; i < start + Math.min(count, limit) && first.size < tableBatchSize; i++) first.add(ordered[i].id); if (first.size >= tableBatchSize) break; } const initial = summariesForIds([...first].filter(id => !known?.has(id))); @@ -320,16 +356,145 @@ function lookup(input: Lookup, columns?: string[]): ViewResult { return result; } -export function viewIndex(input: ViewLookup, columns?: string[]): ViewResult { - return lookup(input, columns); +export function viewIndex(input: ViewLookup, columns?: string[], visibleGroups?: number): ViewResult { + return lookup(input, columns, visibleGroups); +} + +type CalendarRange = { date: string; from: number; to: number; start: string | null; end: string | null; status: string | null; duration: number }; +const live = "CROSS JOIN page_attrs r ON r.page_id=p.id AND r.attr_id='deleted' AND r.value=0"; + +function indexedCalendarIds(range: CalendarRange): string[] { + const start = `SELECT d.page_id FROM page_attrs d INDEXED BY page_attrs_by_value + WHERE d.attr_id=@date AND d.value>=@lower AND d.value<@to AND typeof(d.value)='integer'`; + const overlap = ` UNION SELECT d.page_id FROM page_attrs e INDEXED BY page_attrs_by_value + CROSS JOIN page_attrs d ON d.page_id=e.page_id AND d.attr_id=@date + WHERE e.attr_id=@end AND e.value>@from AND typeof(e.value)='integer' AND d.value<@lower AND typeof(d.value)='integer'`; + const { date, from, to, end, duration } = range; + const lower = duration ? from - duration + 1 : from; + return statement(start + (end ? overlap : "")).pluck().all({ date, lower, to, ...(end ? { end, from } : {}) }) as string[]; +} + +function calendarMatches(ids: string[], conditions: ViewCondition[], defs: Definitions, context: QueryContext): string[] { + let matches = ids; + // Each chunk reuses the same condition compiler as the tables. + for (let offset = 0; offset < conditions.length && matches.length; offset += 32) { + const chunk = conditions.slice(offset, offset + 32); + const clauses = chunk.map(condition => conditionClause(condition, defs, context, true)); + const sql = "SELECT p.id FROM json_each(?) j CROSS JOIN pages p ON p.id=j.value " + + (chunk.some(condition => condition.field.kind === "title") ? withTitle : "") + " WHERE " + clauses.map(clause => clause.test).join(" AND "); + matches = statement(sql).pluck().all(JSON.stringify(matches), ...clauses.flatMap(clause => clause.params)) as string[]; + } + return matches; +} + +function narrowCalendarIds(ids: string[], conditions: ViewCondition[], defs: Definitions, context: QueryContext): string[] { + if (conditions.length < 2 || !ids.length) return ids; + let candidates = ids; + for (const condition of conditions) { + if (condition.field.kind !== "attribute" || reverse[condition.operator] || scans.has(condition.operator) || condition.operator === "not-empty") continue; + const def = defs.get(condition.field.id)!; + const values = condition.values.filter((value): value is Operand => value !== null); + if (values.some(value => typeof value === "object" && value.kind === "current-page")) return []; + const { test, params } = valueTest(condition.operator, "a.value", values, def, context); + // Stop the index scan when it cannot improve on the date scan or an earlier condition. + const indexed = statement(`SELECT a.page_id FROM page_attrs a INDEXED BY page_attrs_by_value WHERE a.attr_id=? AND ${test} LIMIT ?`) + .pluck().all(def.id, ...params, candidates.length) as string[]; + if (indexed.length < candidates.length) candidates = indexed; + if (!candidates.length) return []; + } + if (candidates === ids) return ids; + const dates = new Set(ids); + return candidates.filter(id => dates.has(id)); +} + +function readCalendar(range: CalendarRange, conditions: ViewCondition[], defs: Definitions, context: QueryContext, keyword?: string, + changed?: string[]): CalendarPage[] { + const ids = changed ?? narrowCalendarIds(indexedCalendarIds(range), conditions, defs, context); + let matches = calendarMatches(ids, conditions, defs, context); + const plan = matches.length && viewSearch(keyword, context.zone, matches); + if (plan) { + const hits = new Set(statement(plan.cte + "SELECT id FROM matches").pluck().all(plan.params)); + matches = matches.filter(id => hits.has(id)); + } + if (!matches.length) return []; + const rows = statement(`SELECT p.id,${title} AS title,d.value AS date,s.value AS start,e.value AS end, + st.value AS status,st.page_id IS NOT NULL AS hasStatus,f.value AS pinned + FROM json_each(@ids) j CROSS JOIN page_attrs d ON d.page_id=j.value AND d.attr_id=@date + CROSS JOIN pages p ON p.id=d.page_id ${live} ${withTitle} + LEFT JOIN page_attrs s ON s.page_id=p.id AND s.attr_id=@start + LEFT JOIN page_attrs e ON e.page_id=p.id AND e.attr_id=@end + 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 typeof(d.value)='integer' AND d.value<@to AND (d.value>=@from OR @duration>0 AND + CASE WHEN typeof(e.value)='integer' AND e.value>d.value THEN e.value ELSE d.value+@duration END > @from)`) + .all({ ...range, ids: JSON.stringify(matches) }) as (Omit & { hasStatus: number; pinned: number | null })[]; + return rows.map(page => ({ ...page, hasStatus: !!page.hasStatus, pinned: !!page.pinned })); +} + +export function calendarIndex(input: CalendarLookup): CalendarResult { + workspace.requireWorkspace(); + if (!validTimeSeconds("day", input.from) || !validTimeSeconds("day", input.to) || input.from >= input.to) return { rows: [] }; + const context = queryContext(input.language), { zone, now } = context; + const defs = new Map(definitions().map(def => [def.id, def])); + const { date, start, end, status } = calendarDefinitions(input, defs); + let query = repairViewQuery({ conditions: input.conditions, sort: [] }, defs); + const missingPages = missingFilterPages(query.conditions, defs); + query = repairFilterPages(query, defs, new Set(missingPages)); + const labels: [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") labels.push([def, condition.values.filter(value => typeof value === "string")]); + } + if (input.pageId) query = resolveCurrentPage(query, input.pageId); + const conditions = query.conditions.filter(conditionReady); + const result: CalendarResult = { rows: [], ...(missingPages.length ? { missingPages } : {}) }; + if (labels.length) result.names = targetNames(labels); + if (!date) return result; + const timed = date.type === "minute" || date.type === "hour"; + const range: CalendarRange = { date: date.id, start: timed ? null : start?.id ?? null, end: end?.id ?? null, status: status?.id ?? null, + duration: calendarDuration(date.type), + from: timed ? groupDateValue(input.from, date.type, "day", zone) : input.from, + to: timed ? groupDateValue(input.to, date.type, "day", zone) : input.to }; + const keyword = input.keyword?.trim().toLocaleLowerCase(); + const criteria = JSON.stringify([range, conditions, keyword, input.language, zone, secondsToDay(now, zone)]); + let projection = input.session ? calendars.get(input.session) : undefined; + if (projection?.criteria === criteria) { + if (projection.dirty.size) { + const updated = readCalendar(range, conditions, defs, context, keyword, [...projection.dirty]); + for (const id of projection.dirty) projection.rows.delete(id); + for (const page of updated) projection.rows.set(page.id, page); + projection.dirty.clear(); + } + } + else { + const rows = readCalendar(range, conditions, defs, context, keyword); + projection = { criteria, rows: new Map(rows.map(page => [page.id, page])), dirty: new Set() }; + if (input.session) calendars.set(input.session, projection); + } + const starts = new Map(); + function minute(value: number | null): number { + if (value === null) return -1; + let time = starts.get(value); + if (time === undefined) { + time = calendarPoint(value, zone).minute; + starts.set(value, time); + } + return time; + } + result.rows = [...projection.rows.values()].sort((a, b) => a.date - b.date || minute(a.start) - minute(b.start) || + context.compare(a.title, b.title) || a.id.localeCompare(b.id)); + return result; } export function releaseView(session: string): void { projections.delete(session); + calendars.delete(session); } export function release(): void { projections.clear(); + calendars.clear(); + unfilteredUserRows = undefined; } export function trashIndex({ sort, ...input }: TrashLookup, columns?: string[]): ViewResult { diff --git a/main/knowledge/records.ts b/main/knowledge/records.ts index 43cff0b..4e79c5a 100644 --- a/main/knowledge/records.ts +++ b/main/knowledge/records.ts @@ -6,7 +6,7 @@ import { attributeTargetKind, decodeValue, emptyValue, encodeValue, nullable, re import { blockText, payload, validateBlock, validTarget } from "../../shared/content/blocks"; import { matchRanges } from "../../shared/content/matches"; import type { MediaFile } from "../../shared/content/media"; -import { resolveTimeZone, validTimeSeconds } from "../../shared/content/time"; +import { resolveTimeZone } 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"; @@ -15,7 +15,7 @@ import { attachmentPath } from "../storage/files"; 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 { readBlockView } from "../../shared/workspace/view-block"; export type BlockRow = typeof blocks.$inferSelect; type PageRow = typeof pages.$inferSelect; @@ -30,6 +30,7 @@ export function decodeBlock(row: BlockRow): ContentBlock { const body = row.content === null ? payload(type) : JSON.parse(row.content); if (row.content === null && type === "blocked_reference") body.target = null; if (record(body) && body.schemaVersion !== 1) throw new LabloomError({ kind: "block-unsupported-version" }); + if (type === "view" && record(body)) body.view = readBlockView(body.view); const block: ContentBlock = { id: row.id, type, payload: body, children: row.children }; validateBlock(block); return block; @@ -134,6 +135,12 @@ export function readObjects(pageId: string, ids: string[]): PageObjects { return { page, blocks: content, uses: sharedUses(blocks), ...(files.size ? { mediaFiles: mediaFiles(files) } : {}) }; } +export function viewBlock(pageId: string, blockId: string): ContentBlock | null { + if (flags(pageId).deleted || !owners(blockId).includes(pageId)) return null; + const row = blockRow(blockId); + return row?.type === "view" ? decodeBlock(row) : null; +} + export function uses(id: string): Use[] { workspace.requireWorkspace(); return statement("SELECT container_kind AS kind, container_id AS id, slot, position FROM sync_refs WHERE block_id = ?").all(id) as Use[]; @@ -524,28 +531,6 @@ 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 & { 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 } { workspace.requireWorkspace(); if (!Array.isArray(unchanged) || !unchanged.every(validUUID)) throw new LabloomError({ kind: "page-invalid-ids" }); diff --git a/main/pages/ipc.ts b/main/pages/ipc.ts index 24d5ede..d867e5c 100644 --- a/main/pages/ipc.ts +++ b/main/pages/ipc.ts @@ -3,7 +3,8 @@ 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 { calendarIndex, releaseView, trashIndex, viewIndex } from "../knowledge/query"; +import { moveViewCards } from "../knowledge/board"; import * as picker from "../knowledge/block-list"; import * as edits from "../knowledge/edits"; import * as papers from "../knowledge/papers"; @@ -17,12 +18,14 @@ export const routes = { search: route(typia.createAssert>(invalid), records.searchPages), viewIndex: route(typia.createAssert>(invalid), viewIndex), releaseView: route(typia.createAssert>(invalid), releaseView), + viewBlock: route(typia.createAssert>(invalid), records.viewBlock), + moveViewCards: route(typia.createAssert>(invalid), moveViewCards), 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), overviewRows: route(typia.createAssert>(invalid), records.overviewRows), - calendarRows: route(typia.createAssert>(invalid), records.calendarRows), + calendarIndex: route(typia.createAssert>(invalid), calendarIndex), get: route(typia.createAssert>(invalid), papers.get), readObjects: route(typia.createAssert>(invalid), records.readObjects), syncBlocks: route(typia.createAssert>(invalid), edits.syncBlocks), diff --git a/main/ui/window.ts b/main/ui/window.ts index 5441f61..361812a 100644 --- a/main/ui/window.ts +++ b/main/ui/window.ts @@ -19,7 +19,7 @@ export function createWindow(applicationLog: LogFile | null): void { const bounds = settings.get().settings.window; const mainWindow = new BrowserWindow({ ...(process.platform !== "darwin" ? { - titleBarOverlay: { height: 32 } + titleBarOverlay: { height: 32, ...(process.platform === "win32" ? { color: "#00000000" } : {}) } } : {}), width: bounds.width, height: bounds.height, diff --git a/renderer/components/Editor/Editor.svelte b/renderer/components/Editor/Editor.svelte index ee738ba..670a1ba 100644 --- a/renderer/components/Editor/Editor.svelte +++ b/renderer/components/Editor/Editor.svelte @@ -15,7 +15,13 @@ clearPreview(); }}> - {#snippet trigger({ props })}
{/snippet} + {#snippet trigger({ props })}
{ + if (!(event.target as Element).closest(".view-block")) (props.oncontextmenu as (event: MouseEvent) => void)?.(event); + }} + onkeydown={event => { + if (!(event.target as Element).closest(".view-block")) (props.onkeydown as (event: KeyboardEvent) => void)?.(event); + }}>
{/snippet}
{#each bands as rect (rect.y)}
@@ -97,7 +103,7 @@ import { commandLabel, t } from "../../i18n.svelte"; import { isComposingKey, commands, blockShortcuts, webLinkShortcut } from "../../../shared/content/commands"; import { registerEditing, type EditingCommand } from "../layout/commands"; - import { openPage, openTarget } from "../layout/navigation"; + import { openPage, openTarget, openViewBlock } from "../layout/navigation"; import Menu from "../base/Menu.svelte"; import { hasOpenLayer } from "../base/top-layer"; import IconButton from "../base/IconButton.svelte"; @@ -129,6 +135,8 @@ import { backlinkRow, documentLabels, documentViews } from "./document-view.svelte"; import { clipboardRows, copyBlocks, editing, located, remoteEdit, selectionIn, syncInsert } from "./transactions"; import { mediaViews } from "./media-view.svelte"; + import { viewNodes } from "./view-node.svelte"; + import { defaultBlockView } from "../../../shared/workspace/view-block"; import ImageViewer, { type ViewImage } from "./ImageViewer.svelte"; import { clipboardMedia, pasteBlocks, readClipboard, remapClipboardMedia, writeClipboard, type BlockClipboard } from "./clipboard"; import { finishClipboardWebLinks, readClipboardWebLinks, webLinkClipboard } from "./extensions/mark/webLink"; @@ -180,6 +188,7 @@ let pickerPosition = $state<{ x: number; y: number; left: number; right: number; bottom: number }>(); let hoveredReference: HTMLElement | null = null, previewTimer: ReturnType | undefined; let slash = $state.raw(null), suggestionIndex = $state(0); + let insertedView: string | undefined; const suggestions = $derived(slash ? insertItems(slash.query) : []); function caretBounds(): DOMRect { if (!editor || editor.isDestroyed) return new DOMRect(); @@ -206,14 +215,27 @@ pick(item.kind); return; } + const viewType = item.kind === "table-view" ? "table" : item.kind === "board-view" ? "board" : item.kind === "calendar-view" ? "calendar" : undefined; const empty = !loc.node.firstChild!.content.size && (loc.node.childCount === 1 || canNest(item.kind)); const start = empty ? loc.pos : loc.pos + loc.node.nodeSize; - let node = blankBlock(instance.schema, item.kind); + let node = viewType ? instance.schema.nodes.view.create({ view: defaultBlockView(viewType, session.state.definitions) }) + : blankBlock(instance.schema, item.kind as ContentBlockKind); if (empty) { if (node.type.name === "pageBlock") node = node.copy(loc.node.content); node = node.type.create({ ...node.attrs, blockId: loc.node.attrs.blockId, collapsed: loc.node.attrs.collapsed }, node.content); } + if (viewType) { + insertedView = node.attrs.blockId || crypto.randomUUID(); + node = node.type.create({ ...node.attrs, blockId: insertedView }); + session.checkpoint(); + } tr.replaceWith(start, empty ? start + loc.node.nodeSize : start, node); + if (viewType) { + instance.view.dispatch(tr.setSelection(new BlockSelection(tr.doc, start, start)).scrollIntoView()); + session.checkpoint(); + insertedView = undefined; + return; + } instance.view.dispatch(selectionIn(tr, start + (node.isAtom ? node.nodeSize : 2)).scrollIntoView()); instance.view.focus(); } @@ -263,7 +285,7 @@ else document.execCommand(command); } function context(event: MouseEvent): void { - if (!editor || !(event.target instanceof Element) || event.target.closest(".handle")) return; + if (!editor || !(event.target instanceof Element) || event.target.closest(".handle,.view-block")) return; if (editor.view.composing || event.target.closest(".editor-backlinks")) { event.preventDefault(); event.stopPropagation(); return; } @@ -287,7 +309,7 @@ if (places.length > 1) { const parents = places.filter(p => p.node.type.name === "pageBlock" && p.node.childCount > 1); groupFold = { children: !!parents.length, folded: !!parents.length && parents.every(p => p.node.attrs.collapsed), - media: places.some(place => isMediaKind(kindOf(place.node))) }; + media: places.some(place => isMediaKind(kindOf(place.node)) || kindOf(place.node) === "view") }; } } menu = value; @@ -425,7 +447,7 @@ let marquee = $state.raw(null); function marginDown(event: PointerEvent): void { const instance = editor; - if (!instance || event.button !== 0 || gesture || instance.view.composing) return; + if (!instance || event.button !== 0 || gesture || instance.view.composing || (event.target as Element).closest(".view-block")) return; const selected = wholeSelection(instance.state.selection); const block = event.target instanceof Element && event.target.closest("[data-block-id]"); if (event.shiftKey && selected && block && block.dataset.kind !== "title") { @@ -759,7 +781,7 @@ const loc = target(), instance = editor; const places = loc ? selectedBlocks(loc) : []; close(); - if (!instance || !places.length || places.some(place => isMediaKind(kindOf(place.node)))) return; + if (!instance || !places.length || places.some(place => isMediaKind(kindOf(place.node)) || kindOf(place.node) === "view")) return; void perform(async () => { const tr = instance.state.tr; for (const { pos, node } of places.slice().reverse()) { @@ -831,6 +853,13 @@ writable: () => !locked, checkpoint: () => session.checkpoint(), open: openImage + }), viewNodes({ + session, pageId: page.id, readonly: () => readOnly || !!session.state.page?.attributes.deleted, + inserted: id => id === insertedView, + scroller: root.closest(".annotation-content,[data-tabs-content]"), + expand: id => void perform(async () => { + if (await session.flush()) openViewBlock(page.id, id); + }) })); const links = backlinkElement = document.createElement("div"); const backlinks = pageAnchor ? mount(Backlinks, { target: links, props: { @@ -891,6 +920,33 @@ } if (event.key.startsWith("Arrow") && skipFold(_view, event)) return true; const selected = wholeSelection(instance.state.selection); + if (selected?.first === selected?.last && selected && instance.state.doc.nodeAt(selected.first)?.type.name === "view" && + !event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey) { + if (event.key === "Enter") { + _view.nodeDOM(selected.first)?.dispatchEvent(new Event("labloom-focus-view")); + return true; + } + if (event.key.startsWith("Arrow")) { + const forward = event.key === "ArrowDown" || event.key === "ArrowRight"; + const near = adjacent(instance.state.doc, selected.first, forward ? 1 : -1); + if (near !== null && instance.state.doc.nodeAt(near)?.type.name === "view") + _view.dispatch(instance.state.tr.setSelection(new BlockSelection(instance.state.doc, near, near)).scrollIntoView()); + else _view.dispatch(selectionIn(instance.state.tr, near === null ? forward ? instance.state.doc.content.size : 1 : near + 1).scrollIntoView()); + return true; + } + if (event.key.length === 1) return true; + } + if (!selected && !event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey && event.key.startsWith("Arrow")) { + const loc = located(instance.state), forward = event.key === "ArrowDown" || event.key === "ArrowRight"; + const direction = event.key.slice(5).toLowerCase() as "up" | "down" | "left" | "right"; + if (loc && _view.endOfTextblock(direction)) { + const near = loc.node.type.name === "pageTitle" && forward ? loc.node.nodeSize : adjacent(instance.state.doc, loc.pos, forward ? 1 : -1); + if (near !== null && instance.state.doc.nodeAt(near)?.type.name === "view") { + _view.dispatch(instance.state.tr.setSelection(new BlockSelection(instance.state.doc, near, near)).scrollIntoView()); + return true; + } + } + } if (selected) { if (event.ctrlKey && event.key.toLowerCase() === "a" && instance.state.doc.childCount > 1) { const doc = instance.state.doc; @@ -1104,7 +1160,7 @@ if (!readOnly && !page.blocks[page.titleBlockId].payload.inline.length && !page.attributes.deleted && tabState.groups.find(group => group.id === tabState.focusedGroupId)?.activeTabId === tabId) instance.commands.focus("start", { scrollIntoView: false }); function hold(event: Event): void { - if (readOnly || !readingTabs.has(tabId) || page.attributes.deleted) return; + if (readOnly || !readingTabs.has(tabId) || page.attributes.deleted || (event.target as Element)?.closest?.(".view-block")) return; if (event instanceof KeyboardEvent && isComposingKey(event)) return; if (event instanceof MouseEvent) { const at = instance.view.posAtCoords({ left: event.clientX, top: event.clientY }); diff --git a/renderer/components/Editor/InlineView.svelte b/renderer/components/Editor/InlineView.svelte new file mode 100644 index 0000000..b329c8c --- /dev/null +++ b/renderer/components/Editor/InlineView.svelte @@ -0,0 +1,49 @@ +
+
+ {#if block.type === "calendar"} + + {:else} + params = value} + {initialFilter} {onsettings} {onremove} {onexpand} {onexit} {onundo} /> + {/if} + + {#if !readonly} + onpreview()} oncommit={value => (block.type === "calendar" ? calendar : table)?.resizeView(Math.round(value))} /> + {/if} + + + + + \ No newline at end of file diff --git a/renderer/components/Editor/ReferenceCard.svelte b/renderer/components/Editor/ReferenceCard.svelte index b4be9f7..83e0ddb 100644 --- a/renderer/components/Editor/ReferenceCard.svelte +++ b/renderer/components/Editor/ReferenceCard.svelte @@ -4,9 +4,11 @@ {:else if value} - {#if expanded || kind === "page"}
{value.text}
{/if} + {#if !value.block?.payload.view && (expanded || kind === "page")}
{value.text}
{/if} {:else} {t("editor.missingReference")} {/if} diff --git a/renderer/components/Editor/document-view.svelte.ts b/renderer/components/Editor/document-view.svelte.ts index f65fb99..bf59bbc 100644 --- a/renderer/components/Editor/document-view.svelte.ts +++ b/renderer/components/Editor/document-view.svelte.ts @@ -6,7 +6,7 @@ import type { Target } from "../../../shared/types/content"; import { t } from "../../i18n.svelte"; import { codeView } from "./code-view.svelte"; import { syntaxPlugin } from "./code-highlight"; -import { codeBlock, documentExtensions, inlineReference, mediaBlock, referenceBlock } from "./document"; +import { codeBlock, documentExtensions, inlineReference, mediaBlock, referenceBlock, viewBlock } from "./document"; import "./document.css"; // Only the title and the current textblock can show a placeholder. @@ -36,7 +36,8 @@ export function documentLabels(element: HTMLElement): void { }); } -export function documentViews(glyph: Element, mountCard: (element: HTMLElement, target: Target) => () => void, mediaView?: NodeViewRenderer): Extensions { +export function documentViews(glyph: Element, mountCard: (element: HTMLElement, target: Target) => () => void, mediaView?: NodeViewRenderer, + embeddedView?: NodeViewRenderer): Extensions { const label = (): string => t("block.blocked_reference"); const link = inlineReference.configure({ label, nodeView: ({ node }) => { @@ -68,7 +69,7 @@ export function documentViews(glyph: Element, mountCard: (element: HTMLElement, return DecorationSet.create(state.doc, [Decoration.node(at.before(d), at.after(d), { class: "code-active" })]); return null; } } })] }); - const views = [code, card, link, mediaBlock.configure({ nodeView: mediaView ?? null })]; + const views = [code, card, link, mediaBlock.configure({ nodeView: mediaView ?? null }), viewBlock.configure({ nodeView: embeddedView ?? null })]; return [...documentExtensions.map(extension => views.find(view => view.name === extension.name) ?? extension), placeholders, highlighting]; } diff --git a/renderer/components/Editor/document.ts b/renderer/components/Editor/document.ts index ad75b05..db5150c 100644 --- a/renderer/components/Editor/document.ts +++ b/renderer/components/Editor/document.ts @@ -16,6 +16,7 @@ import fgColor from "./extensions/mark/fgColor"; import bgColor from "./extensions/mark/bgColor"; import webLink from "./extensions/mark/webLink"; import { LabloomError } from "../../../shared/failure"; +import { readBlockView } from "../../../shared/workspace/view-block"; const blockAttrs = (): Record => ({ blockId: { default: null, rendered: false }, collapsed: { default: null, rendered: false } }); const domAttrs = (node: DocNode): Record => ({ "data-block-id": node.attrs.blockId, "data-kind": kindOf(node), ...(node.attrs.collapsed ? { "data-folded": "true" } : {}) }); @@ -175,9 +176,21 @@ export const mediaBlock = ExtensionNode.create<{ nodeView: NodeViewRenderer | nu return this.options.nodeView; } }); +export const viewBlock = ExtensionNode.create<{ nodeView: NodeViewRenderer | null }>({ + name: "view", group: "workspaceBlock", atom: true, isolating: true, + addOptions: () => ({ nodeView: null }), + addAttributes: () => ({ ...blockAttrs(), view: { default: null, rendered: false } }), + renderHTML({ node }) { + const view = readBlockView(node.attrs.view); + return ["div", domAttrs(node), view.name || zhCN.viewBlock[view.type]]; + }, + addNodeView() { + return this.options.nodeView; +} +}); export const documentExtensions = [Document.extend({ content: "pageTitle workspaceBlock*" }), title, block, body, codeLine, codeBlock, table, Table.configure({ resizable: false }), TableRow, TableCell.extend({ content: "paragraph+" }), TableHeader.extend({ content: "paragraph+" }), - cellParagraph, atom("hr"), referenceBlock, mediaBlock, inlineReference, Text, HardBreak, bold, italic, underline, strike, code, fgColor, bgColor, webLink]; + cellParagraph, atom("hr"), referenceBlock, mediaBlock, viewBlock, inlineReference, Text, HardBreak, bold, italic, underline, strike, code, fgColor, bgColor, webLink]; export const blankTable = (): RichNode => ({ type: "table", content: Array.from({ length: 2 }, () => ({ type: "tableRow", content: Array.from({ length: 2 }, () => ({ type: "tableCell", content: [{ type: "paragraph", content: [] }] })) })) }); export function blockJSON(b: ContentBlock, children: JSONContent[] = []): JSONContent { @@ -186,6 +199,7 @@ export function blockJSON(b: ContentBlock, children: JSONContent[] = []): JSONCo if (b.type === "title") return { type: "pageTitle", attrs, content: b.payload.inline }; if (b.type === "table") return { type: "pageTable", attrs, content: [b.payload.table ?? blankTable()] }; if (b.type === "hr" || b.type === "blocked_reference") return { type: b.type, attrs: { ...attrs, target: b.payload.target } }; + if (b.type === "view") return { type: "view", attrs: { ...attrs, view: readBlockView(b.payload.view) } }; const body = { type: "blockBody", attrs: bodyAttributes(b.type) ?? undefined, content: b.payload.inline }; if (isMediaKind(b.type)) return { type: "mediaBlock", attrs: { ...attrs, kind: b.type, media: b.payload.media }, content: [body] }; return { type: "pageBlock", attrs: { ...attrs, kind: b.type }, content: [body, ...children] }; @@ -231,6 +245,7 @@ export function blockData(node: DocNode): ContentBlock { else if (node.type.name === "codeBlock") value.inline = codeInline(node); else if (node.type.name === "pageBlock" || node.type.name === "mediaBlock" || type === "title") value.inline = ((type === "title" ? node : node.firstChild!).content.toJSON() ?? []) as InlineNode[]; if (isMediaKind(type)) value.media = node.attrs.media; + if (type === "view") value.view = readBlockView(node.attrs.view); return { id: node.attrs.blockId, type, payload: value, children: childIds(node) }; } export type Location = { node: DocNode; pos: number }; diff --git a/renderer/components/Editor/menus.ts b/renderer/components/Editor/menus.ts index 5b6f910..9c54dde 100644 --- a/renderer/components/Editor/menus.ts +++ b/renderer/components/Editor/menus.ts @@ -10,7 +10,7 @@ type Handle = { kind: ContentBlockKind; shared: boolean; folded: boolean; childr type Action = "row" | "column" | "fold" | "unsync" | "delete" | "caption"; export function block(handle: Handle, convert: (kind: ContentBlockKind) => void, act: (action: Action) => void, pick: (mode: "reference" | "sync") => void, move: (direction: -1 | 1) => void, multiple = false): MenuItem[] { - const items: MenuItem[] = handle.media || isMediaKind(handle.kind) ? [] : [{ label: i18n.t("editor.convert"), items: labels.convertibleKinds.map(kind => ({ + const items: MenuItem[] = handle.media || isMediaKind(handle.kind) || handle.kind === "view" ? [] : [{ label: i18n.t("editor.convert"), items: labels.convertibleKinds.map(kind => ({ icon: icons.blockIcons[kind], label: i18n.t(`block.${kind}`), shortcut: shortcuts.conversionShortcuts[kind], onselect: () => convert(kind) })) }]; if (!multiple && handle.caption) items.push({ label: i18n.t("editor.addCaption"), onselect: () => act("caption") }); diff --git a/renderer/components/Editor/slash.ts b/renderer/components/Editor/slash.ts index d9cc3f1..e70c2a7 100644 --- a/renderer/components/Editor/slash.ts +++ b/renderer/components/Editor/slash.ts @@ -8,7 +8,7 @@ import { blockIcons } from "../Knowledge/labels"; import type { IconName } from "../utils/Icon.svelte"; type Reference = "inline" | "reference" | "sync"; -export type InsertItem = { kind: ContentBlockKind | Reference; label: string; icon: IconName; shortcut?: string; group: number; terms: string }; +export type InsertItem = { kind: Exclude | Reference | "table-view" | "board-view" | "calendar-view"; label: string; icon: IconName; shortcut?: string; group: number; terms: string }; export type Trigger = { from: number; to: number; query: string }; const aliases: Record = { paragraph: "text plain", heading_1: "h1 #", heading_2: "h2 ##", heading_3: "h3 ###", unordered_list: "bullet", ordered_list: "numbered num", blockquote: "quote", hr: "divider div" }; @@ -16,6 +16,9 @@ const aliases: Record = { paragraph: "text plain", heading_1: "h export function insertItems(query: string): InsertItem[] { const rows: InsertItem[] = convertibleKinds.map(kind => ({ kind, label: t(`block.${kind}`), icon: blockIcons[kind], shortcut: conversionShortcuts[kind], terms: en.block[kind] + " " + (aliases[kind] ?? ""), group: 0 })); + rows.push({ kind: "table-view", label: t("viewBlock.table"), icon: "layout", terms: en.viewBlock.table, group: 0 }, + { kind: "board-view", label: t("viewBlock.board"), icon: "project", terms: en.viewBlock.board, group: 0 }, + { kind: "calendar-view", label: t("viewBlock.calendar"), icon: "calendar", terms: en.viewBlock.calendar, group: 0 }); for (const kind of mediaKinds) rows.push({ kind, label: t(`block.${kind}`), icon: blockIcons[kind], terms: en.block[kind], group: 1 }); for (const kind of ["inline", "reference", "sync"] as const) rows.push({ kind, label: t(`insertReference.${kind}`), icon: kind === "sync" ? "sync" : "link-external", terms: en.insertReference[kind], group: 2 }); diff --git a/renderer/components/Editor/view-node.svelte.ts b/renderer/components/Editor/view-node.svelte.ts new file mode 100644 index 0000000..081dd3a --- /dev/null +++ b/renderer/components/Editor/view-node.svelte.ts @@ -0,0 +1,146 @@ +import { mount, unmount } from "svelte"; +import type { NodeViewRenderer } from "@tiptap/core"; +import { readBlockView, viewBlockHeight, type BlockView } from "../../../shared/workspace/view-block"; +import type { PageSession } from "../Knowledge/page-session.svelte"; +import { perform } from "../Knowledge/feedback.svelte"; +import { syncViewOwners } from "../Knowledge/page-sessions"; +import { pendingViewSettings, stageViewSettings } from "../Knowledge/view-block-state"; +import { BlockSelection } from "./block-selection"; +import InlineView from "./InlineView.svelte"; + +export function viewNodes(options: { + session: PageSession; pageId: string; readonly: () => boolean; + inserted: (id: string) => boolean; expand: (id: string) => void; scroller: HTMLElement | null; +}): NodeViewRenderer { + // eslint-disable-next-line svelte/prefer-svelte-reactivity -- The viewport observers own this queue. + const waiting = new Map void>(); + let observer: IntersectionObserver | undefined; + let resize: ResizeObserver | undefined, margin = 0; + function updateViewport(): void { + const height = options.scroller?.clientHeight || window.innerHeight; + if (height === margin && observer) return; + margin = height; + observer?.disconnect(); + observer = new IntersectionObserver(entries => { + for (const entry of entries) if (entry.isIntersecting) waiting.get(entry.target)?.(); + }, { root: options.scroller, rootMargin: `${margin}px 0px` }); + for (const element of waiting.keys()) observer.observe(element); + } + function forget(element: Element): void { + if (!waiting.delete(element)) return; + observer?.unobserve(element); + if (waiting.size) return; + observer?.disconnect(); + resize?.disconnect(); + observer = resize = undefined; + } + return ({ node: initial, view, getPos }) => { + const dom = document.createElement("div"), id = initial.attrs.blockId as string; + const source = { kind: "page", id: options.pageId } as const; + let node = initial, block = $state.raw(readBlockView(initial.attrs.view)), component: ReturnType | undefined; + let first = options.inserted(id), disposed = false; + dom.className = "view-block"; + dom.dataset.kind = "view"; + dom.dataset.blockId = id; + dom.contentEditable = "false"; + function height(preview?: number): void { + dom.style.height = (preview ?? block.height ?? viewBlockHeight) + "px"; + } + height(); + function select(): void { + const pos = getPos(); + if (pos === undefined) return; + view.dispatch(view.state.tr.setSelection(new BlockSelection(view.state.doc, pos, pos))); + view.focus(); + } + function change(next: BlockView): void { + const pos = getPos(); + if (pos === undefined || options.readonly() || view.composing) return; + if (options.session.source.kind !== "page" || options.session.source.id !== options.pageId) { + const previous = options.session.state.page?.blocks[id]; + if (previous) void perform(async () => { + const saving = options.session.action((token, writeId) => window.api.pages.commitEdit({ + pageId: options.pageId, batch: 0, blocks: [{ ...previous, payload: { ...previous.payload, view: next } }] + }, source, token, writeId)); + const finish = stageViewSettings(id, next); + try { + await saving; + await syncViewOwners(id, options.session.tabId); + } + finally { + await finish(); + } + }); + return; + } + options.session.checkpoint(); + view.dispatch(view.state.tr.setNodeAttribute(pos, "view", next)); + options.session.checkpoint(); + const saving = options.session.flush(), finish = stageViewSettings(id, next); + void saving.then(async saved => { + if (saved) await syncViewOwners(id, options.session.tabId); + }).finally(finish); + } + function reveal(): void { + if (disposed || component) return; + forget(dom); + component = mount(InlineView, { target: dom, props: { + tabId: options.session.tabId, pageId: options.pageId, blockId: id, source, + get block() { + return pendingViewSettings(id) ?? block; +}, + get readonly() { + return options.readonly(); +}, + initialFilter: first, initialDefinitions: options.session.state.definitions, + onsettings: change, onexpand: () => options.expand(id), onexit: select, + onundo: direction => void options.session.undo(direction, source), onpreview: height, + onremove: () => { + if (!options.readonly()) void perform(() => options.session.action((token, writeId) => + window.api.pages.deleteBlock({ pageId: options.pageId, blockId: id }, source, token, writeId))); + } + } }); + first = false; + } + function focus(): void { + reveal(); + component?.focusView(); + } + dom.addEventListener("labloom-focus-view", focus); + const frame = requestAnimationFrame(() => { + if (disposed || component) return; + if (first) { + reveal(); + return; + } + waiting.set(dom, reveal); + updateViewport(); + observer!.observe(dom); + if (!resize) { + resize = new ResizeObserver(updateViewport); + resize.observe(options.scroller ?? document.documentElement); + } + }); + return { + dom, + stopEvent: () => true, + ignoreMutation: () => true, + update(next) { + if (next.type !== node.type || next.attrs.blockId !== id) return false; + const changed = next.attrs.view !== node.attrs.view; + node = next; + if (changed) { + block = readBlockView(next.attrs.view); + height(); + } + return true; + }, + destroy() { + disposed = true; + cancelAnimationFrame(frame); + forget(dom); + if (component) void unmount(component); + } + }; + }; +} \ No newline at end of file diff --git a/renderer/components/Knowledge/BoardGrid.svelte b/renderer/components/Knowledge/BoardGrid.svelte new file mode 100644 index 0000000..70345ec --- /dev/null +++ b/renderer/components/Knowledge/BoardGrid.svelte @@ -0,0 +1,402 @@ + + +
{ + if (event.target === root) focusGrid(); + }} onpointerdown={beginDrag} onscroll={onposition} + onlostpointercapture={cancelDrag}> + { + jump(event.data); event.currentTarget.value = ""; + }} + oninput={event => { + if (!(event instanceof InputEvent && event.isComposing)) event.currentTarget.value = ""; + }} /> + {#each groups as group, i (group.key)} + {@const label = groupLabel(group.value)} +
{ + targets.set(group.key, element); return () => targets.delete(group.key); +}}> + + {#if !group.collapsed} + lists.get(group.key), list => { + if (list) lists.set(group.key, list); else lists.delete(group.key); + }} ids={entries[i]} variable selectedItems={selected} {label} empty="" {pending} {onposition} + onrange={(start, end) => onrange(group.at + 1 + start, group.at + 1 + end)}> + {#snippet row(id)} + {@const entry = layout.items[layout.positions.get("p:" + JSON.stringify(group.value) + ":" + id)!] as TablePage} + {@const page = rows.get(id)} +
+ {#snippet contents()} +
+ {#if page}{/if} + {(page?.title ?? entry.title) || t("shell.untitled")} +
+ {/snippet} + {@render editor(entry, "title", page, contents)} + {#if page} + {#each columns as column (column.id)} + {@const value = cell(page, column.id)} + {#if value}
{value}
{/if} + {/each} + {/if} +
+ {/snippet} +
+ {/if} +
+ {/each} + {#if !pending && !layout.ids.size}
{t("calendar.noPages")}
{/if} +
+ + + \ No newline at end of file diff --git a/renderer/components/Knowledge/Calendar.svelte b/renderer/components/Knowledge/Calendar.svelte index f36dc07..7be1285 100644 --- a/renderer/components/Knowledge/Calendar.svelte +++ b/renderer/components/Knowledge/Calendar.svelte @@ -1,263 +1,509 @@ + + -
-
- shift(-1)} /> - shift(1)} /> - -

{heading}

- -
- {#if error} - - {:else if pending} -
{t("library.loading")}
- {:else if definitionsReady && !dateDefinition} -
{t("calendar.missingDate")}
+
+ filterOpen, value => { + filterOpen = value; + if (!value) { + filterFocus = undefined; addFocus = false; +} + }} addConditionFocus={addFocus ? filterId : undefined}> + {#snippet head()} + {#if user} + {#if naming} + naming = false, onkeydown: event => { + if (isComposingKey(event)) return; + if (event.key === "Enter") event.currentTarget.blur(); + if (event.key === keys.cancel) { + event.preventDefault(); event.stopPropagation(); naming = false; focusView(); + } + } }} onchange={name => updateSettings({}, { name: name.trim() || undefined })} /> + {:else} + + {/if} + {/if} + shift(-1)} /> + shift(1)} /> + +

{heading}

+ {/snippet} + {#snippet filters()} + + {/snippet} + {#snippet actions()} + {#if layout !== "timeline"} + + + {/if} + + {/snippet} + {#snippet tail()} + {#if user} + {#if user.onexpand}{/if} + { + if (user && !readonly) user.onsettings(switchBlockView({ ...user.block, query: { ...user.block.query, conditions: query.conditions } }, type, defs.values())); + }), + ...header(), + ...readonly ? [] : [{ label: t("editor.delete"), icon: "trash" as const, onselect: user.onremove }] + ]}> + {#snippet trigger({ props })}{/snippet} + + {/if} + {/snippet} +
+ { + filterFocus = { index }; filterOpen = true; + }} /> + {#if error}{/if} + {#if layout === "month"} + selected = new Set([id])} oncontext={context} + onwidth={agendaWidth => updateSettings({ agendaWidth })} /> + {:else} + scrollPosition = value} /> {/if} -
-
clickCell(event)} ondblclick={event => clickCell(event, true)} - oncontextmenu={event => { - const id = (event.target as Element).closest("[data-calendar-page]")?.dataset.calendarPage; - if (!id) return; - event.preventDefault(); - context(id, event.clientX, event.clientY, false); - }}> -
- {#each weekdays as weekday (weekday)} -
{t(`datePicker.weekdays.${weekday}`)}
- {/each} -
- {#each gridRows as row, index (index)} -
- {#each row as date, column (column)} - {#if date === null} -
- {:else} - {@const text = secondsToDay(date)} - {@const pages = byDay.get(date) ?? empty} - {@const fits = capacity[index]} - {@const visible = pages.length > fits ? Math.max(0, fits - 1) : fits} -
-
-
- {#each pages.slice(0, visible) as page (page.id)} - {@render pageRow(page, false)} - {/each} - {#if pages.length > visible && fits > 0} - - {/if} -
-
- {/if} - {/each} -
- {/each} -
- onparams({ ...params, agendaWidth: Math.max(1, Math.round(width - size)) })} /> -
-
-

{secondsToDay(selected)}

- {agendaIds.length} -
- {}} onopen={open} oncontext={(id, x, y) => context(id, x, y, true)}> - {#snippet row(id)} - {@const page = pageIndex.get(id)} - {#if page}{@render pageRow(page, true)}{/if} - {/snippet} - -
-
- { - if (fromList) list?.focus(); - else grid?.focus({ preventScroll: true }); -}} /> -{#snippet pageRow(page: CalendarPage, inAgenda: boolean)} -
- {#if page.hasStatus} - done(page), () => {}} disabled={!canToggle(page)} - onclick={event => event.stopPropagation()} onchange={() => toggle(page)} /> - {/if} - {#if inAgenda} - {page.title || t("shell.untitled")} - {#if page.start !== null}{secondsToMinute(page.start, zone).slice(-5)}{/if} + layout === "month" ? month?.focus(fromAgenda) : week?.focus()} /> + +{#snippet monthRow(page: CalendarPage, mode: "month" | "agenda", date: number)} + {@render pageRow(page, mode, date, mode === "agenda" && page.start !== null ? calendarPoint(page.start, zone).minute : null)} +{/snippet} +{#snippet weekCard(entry: WeekEntry)} + {@render pageRow(entry.page, layout === "timeline" ? "timeline" : "week", entry.day, entry.time)} +{/snippet} +{#snippet pageRow(page: CalendarPage, mode: "month" | "agenda" | "week" | "timeline", date: number, time: number | null)} +
+ {#if draft?.id === page.id && draft.day === date} + false} + onchange={value => { + if (draft) draft.value = String(value); + }} onfinish={(save, focus) => void finishTitle(save, focus)}> + {#snippet contents()}{/snippet} + {:else} - + {#if page.hasStatus} + done(page), () => {}} disabled={!canToggle(page)} + onclick={event => event.stopPropagation()} onchange={() => toggle(page)} /> + {/if} + {#if time !== null && mode !== "agenda"}{calendarClock(time)}{/if} + {#if mode === "month"} + + {:else} + {page.title || t("shell.untitled")} + {/if} + {#if time !== null && mode === "agenda"}{calendarClock(time)}{/if} {/if}
{/snippet} \ No newline at end of file diff --git a/renderer/components/Knowledge/CalendarMonth.svelte b/renderer/components/Knowledge/CalendarMonth.svelte new file mode 100644 index 0000000..5dfc886 --- /dev/null +++ b/renderer/components/Knowledge/CalendarMonth.svelte @@ -0,0 +1,145 @@ + + +
+
+
+ {#each weekdays as weekday (weekday)}
{t(`datePicker.weekdays.${weekday}`)}
{/each} +
+ {#each rows as week, i (i)} +
+ {#each week as date, column (column)} + {#if date === null} +
+ {:else} + {@const text = secondsToDay(date)} + {@const entries = pages.get(date) ?? empty} + {@const fits = capacity[i]} + {@const visible = entries.length > fits ? Math.max(0, fits - 1) : fits} +
+
+
+ {#each entries.slice(0, visible) as page (page.id)}{@render row(page, "month", date)}{/each} + {#if entries.length > visible && fits > 0} + + {/if} +
+
+ {/if} + {/each} +
+ {/each} +
+ {#if !readonly} + asidePreview = width - size} oncancel={() => asidePreview = undefined} + oncommit={size => onwidth(Math.max(1, Math.round(width - size)))} /> + {/if} +
+

{secondsToDay(selected)}

{ids.length}
+ selectedPages.has(id))} + selectedItems={selectedPages} onrange={() => {}} {onopen} {onmove} oncontext={(id, x, y) => oncontext(id, x, y, true)}> + {#snippet row(id)} + {@const page = pageIndex.get(id)} + {#if page}{@render agendaRow(page)}{/if} + {/snippet} + +
+
+ +{#snippet agendaRow(page: CalendarPage)}{@render row(page, "agenda", selected)}{/snippet} + + \ No newline at end of file diff --git a/renderer/components/Knowledge/CalendarTimedCards.svelte b/renderer/components/Knowledge/CalendarTimedCards.svelte new file mode 100644 index 0000000..b493aec --- /dev/null +++ b/renderer/components/Knowledge/CalendarTimedCards.svelte @@ -0,0 +1,146 @@ + + + + +
+ + \ No newline at end of file diff --git a/renderer/components/Knowledge/CalendarWeek.svelte b/renderer/components/Knowledge/CalendarWeek.svelte new file mode 100644 index 0000000..23cce10 --- /dev/null +++ b/renderer/components/Knowledge/CalendarWeek.svelte @@ -0,0 +1,201 @@ + + +
+
+ {#if timed}{/if} + {#each days as day, i (day)} + {@const date = secondsToDay(day)} +
+ {t(`datePicker.weekdays.${weekdays[i]}`)} +
+ {/each} +
+
+ {#if timed} + + {/if} + {#each days as day, i (day)} +
+ {#if timed && day === selectedDay && selectedMinute !== undefined} + + {/if} + {#if timed && drop?.day === day} + + {/if} + {#if timed} + {@const editId = editing?.day === day ? editing.id : undefined} + {@const entry = editId ? columns[i].find(item => item.page.id === editId) : undefined} + + {#if entry} +
+ {@render card(entry)} +
+ {/if} + {:else} + {#each visible(columns[i], day) as { entry, index } (entry.page.id)} +
+ {@render card(entry)} +
+ {/each} + {/if} + {#if timed && day === today}{/if} +
+ {/each} +
+ + {#if timed}{/if} +
+ + \ No newline at end of file diff --git a/renderer/components/Knowledge/LibraryInfo.svelte b/renderer/components/Knowledge/LibraryInfo.svelte index 8320753..20cc21f 100644 --- a/renderer/components/Knowledge/LibraryInfo.svelte +++ b/renderer/components/Knowledge/LibraryInfo.svelte @@ -1,5 +1,6 @@ -
+
{#if current.state.error}
{message(current.state.error)}
{:else if page} diff --git a/renderer/components/Knowledge/PageInformation.svelte b/renderer/components/Knowledge/PageInformation.svelte index d4d73d8..061d590 100644 --- a/renderer/components/Knowledge/PageInformation.svelte +++ b/renderer/components/Knowledge/PageInformation.svelte @@ -2,6 +2,7 @@ import { onDestroy, onMount, untrack } from "svelte"; import { blockText, payload } from "../../../shared/content/blocks"; import { isComposingKey } from "../../../shared/content/commands"; + import type { HistorySource } from "../../../shared/history/ipc"; import { t } from "../../i18n.svelte"; import Input from "../base/Input.svelte"; import { openPage } from "../layout/navigation"; @@ -10,8 +11,9 @@ import { inspectPage } from "./page-sessions"; import { knowledgeState } from "./feedback.svelte"; - let { tabId, pageId, readonly = false }: { tabId: string; pageId: string; readonly?: boolean } = $props(); - const inspection = untrack(() => inspectPage(tabId, pageId)), current = inspection.current; + let { tabId, pageId, source, readonly = false }: { tabId: string; pageId: string; source?: HistorySource; readonly?: boolean } = $props(); + const inspection = untrack(() => inspectPage(tabId, pageId, source)), current = inspection.current; + const historyPage = $derived(source?.kind === "page" ? source.id : pageId); onDestroy(inspection.release); const page = $derived(current.state.page); const title = $derived(page?.blocks[page.titleBlockId]); @@ -33,7 +35,7 @@ } -
+
{#if page?.kind === "paper" && title}
draft = value} onchange={rename} />
{/if} - + {#if page?.kind === "paper" && current.state.backlinks.length} {/snippet} -
+
{/if} \ No newline at end of file diff --git a/renderer/components/Knowledge/TableFilterValue.svelte b/renderer/components/Knowledge/TableFilterValue.svelte index 53f2059..22daa02 100644 --- a/renderer/components/Knowledge/TableFilterValue.svelte +++ b/renderer/components/Knowledge/TableFilterValue.svelte @@ -15,12 +15,13 @@ import { propertyOption } from "./attribute-labels"; import { isDateField } from "./query-labels"; - let { condition, type, definition, zone, names, onchange }: { condition: ViewCondition; type: ViewFieldType; definition?: AttributeDefinition; - zone: string; names: Record; onchange: (values: QueryValue[]) => void } = $props(); + let { condition, type, definition, zone, names, currentPage = false, onchange }: { condition: ViewCondition; type: ViewFieldType; definition?: AttributeDefinition; + zone: string; names: Record; currentPage?: boolean; onchange: (values: QueryValue[]) => void } = $props(); let picker = $state<{ x: number; y: number; left: number; right: number; bottom: number }>(), composing = false; const choices = $derived(type === "page-type" ? pageKinds.map(kind => ({ value: kind, label: t(`library.${kind}`), icon: kindIcons[kind] })) : (definition?.metadata.options ?? []).map(option => ({ value: option.id, label: definition ? propertyOption(definition, option) : option.name }))); const strings = $derived(condition.values.filter((value): value is string => typeof value === "string")); + const hasCurrent = $derived(condition.values.some(value => value !== null && typeof value === "object" && value.kind === "current-page")); const between = $derived(condition.operator === "between"); const inputs = $derived(between ? [condition.values[0] ?? null, condition.values[1] ?? null] : condition.values.length ? condition.values : [null]); const boolean = $derived([{ value: "true", label: t("library.yes") }, { value: "false", label: t("library.no") }]); @@ -37,7 +38,7 @@ picker = { x: trigger.left, y: trigger.bottom, left: 0, right: document.documentElement.clientWidth, bottom: document.documentElement.clientHeight }; } function addPage(id: string): void { - if (!strings.includes(id)) onchange([...strings, id]); + if (!strings.includes(id)) onchange([...condition.values, id]); picker = undefined; } function guard(event: KeyboardEvent): void { @@ -57,8 +58,14 @@ {#each strings as id (id)} {@const name = names[id] || t("shell.untitled")} {name} onchange(strings.filter(value => value !== id))} /> + onclick={() => onchange(condition.values.filter(value => value !== id))} /> {/each} + {#if hasCurrent} + {t("viewBlock.currentPage")} onchange(strings)} /> + {:else if currentPage} + + {/if} {#if picker} diff --git a/renderer/components/Knowledge/TableFilters.svelte b/renderer/components/Knowledge/TableFilters.svelte index 954d22d..17947ed 100644 --- a/renderer/components/Knowledge/TableFilters.svelte +++ b/renderer/components/Knowledge/TableFilters.svelte @@ -12,9 +12,9 @@ import TableFilterValue from "./TableFilterValue.svelte"; import { operatorLabel } from "./query-labels"; - let { conditions, choices, definitions, label, names, zone, focus, onchange }: { conditions: ViewCondition[]; choices: string[]; + let { conditions, choices, definitions, label, names, zone, focus, currentPage, addConditionId, onchange }: { conditions: ViewCondition[]; choices: string[]; definitions: ReadonlyMap; label: (id: string) => string; names: Record; - zone: string; focus?: { index: number }; onchange: (values: ViewCondition[]) => void } = $props(); + zone: string; focus?: { index: number }; currentPage?: boolean; addConditionId?: string; onchange: (values: ViewCondition[]) => void } = $props(); let form: HTMLElement; const selectable = $derived(choices.filter(id => { const type = fieldType(columnField(id), definitions); @@ -54,7 +54,7 @@ onchange={operator => update(i, { ...condition, operator: operator as QueryOperator, values: [] })} />
{#key field + ":" + condition.operator} - update(i, { ...condition, values })} /> {/key}
@@ -62,7 +62,7 @@ {/if} {/each} - + }}>{t("table.ungroup")}{/if} \ No newline at end of file diff --git a/renderer/components/Knowledge/ViewConditions.svelte b/renderer/components/Knowledge/ViewConditions.svelte new file mode 100644 index 0000000..057281e --- /dev/null +++ b/renderer/components/Knowledge/ViewConditions.svelte @@ -0,0 +1,41 @@ + + +{#if conditions.length || total} +
+ {#each conditions as condition, i (i)} + + + {#if !readonly} + onchange(conditions.filter((_, j) => i !== j))} /> + {/if} + + {/each} + {#if total}{t("library.count", { count: total })}{/if} +
+{/if} + + \ No newline at end of file diff --git a/renderer/components/Knowledge/calendar-week.ts b/renderer/components/Knowledge/calendar-week.ts new file mode 100644 index 0000000..bc9ecc5 --- /dev/null +++ b/renderer/components/Knowledge/calendar-week.ts @@ -0,0 +1,55 @@ +import { secondsPerDay } from "../../../shared/content/time"; +import type { CalendarDateType, CalendarPage } from "../../../shared/workspace/calendar"; +import { calendarDuration, calendarPoint } from "../../../shared/workspace/calendar-time"; + +export type WeekEntry = { + page: CalendarPage; day: number; time: number | null; from: number; to: number; + lane: number; lanes: number; last: boolean; +}; + +function placeOverlaps(entries: WeekEntry[]): void { + const ends: number[] = []; + let first = 0, end = -1; + for (let i = 0; i < entries.length; i++) { + const entry = entries[i]; + if (entry.from >= end) { + for (; first < i; first++) entries[first].lanes = ends.length; + ends.length = 0; + end = -1; + } + const free = ends.findIndex(value => value <= entry.from); + entry.lane = free < 0 ? ends.length : free; + ends[entry.lane] = Math.max(entry.to, entry.from + 1); + end = Math.max(end, ends[entry.lane]); + } + for (; first < entries.length; first++) entries[first].lanes = ends.length; +} + +export function calendarWeek(pages: CalendarPage[], days: number[], precision: CalendarDateType, zone: string, + compare: Intl.Collator["compare"]): WeekEntry[][] { + const columns: WeekEntry[][] = days.map(() => []); + const first = days[0]; + for (const page of pages) { + if (precision === "day") { + const time = page.start === null ? null : calendarPoint(page.start, zone).minute; + columns[(page.date - first) / secondsPerDay]?.push({ page, day: page.date, time, from: 0, to: 0, lane: 0, lanes: 1, last: true }); + continue; + } + const start = calendarPoint(page.date, zone); + const end = calendarPoint(page.end !== null && page.end > page.date ? page.end : page.date + calendarDuration(precision), zone); + for (let i = Math.max(0, (start.day - first) / secondsPerDay); i < days.length; i++) { + const day = days[i]; + if (day > end.day || day === end.day && day > start.day && !end.minute) break; + const from = day === start.day ? start.minute : 0; + const to = day === end.day ? end.minute : 1440; + columns[i].push({ page, day, time: start.minute, from, to: Math.max(from, to), lane: 0, lanes: 1, + last: day === end.day || day + secondsPerDay === end.day && !end.minute }); + } + } + for (const column of columns) { + column.sort((a, b) => (precision === "day" ? (a.time ?? -1) - (b.time ?? -1) : a.from - b.from) || + compare(a.page.title, b.page.title) || a.page.id.localeCompare(b.page.id)); + if (precision !== "day") placeOverlaps(column); + } + return columns; +} \ No newline at end of file diff --git a/renderer/components/Knowledge/labels.ts b/renderer/components/Knowledge/labels.ts index e0a0cd7..742cddf 100644 --- a/renderer/components/Knowledge/labels.ts +++ b/renderer/components/Knowledge/labels.ts @@ -4,6 +4,6 @@ export const kindIcons: Record = { editable: "edit", paper: export const blockIcons: Record = { title: "edit", paragraph: "paragraph", heading_1: "heading-1", heading_2: "heading-2", heading_3: "heading-3", unordered_list: "list-unordered", ordered_list: "list-ordered", blockquote: "quote", callout: "info", - code: "code", table: "table", hr: "horizontal-rule", blocked_reference: "link-external", + code: "code", table: "table", hr: "horizontal-rule", blocked_reference: "link-external", view: "table", image: "file-media", video: "play-circle", file: "file" }; \ No newline at end of file diff --git a/renderer/components/Knowledge/page-session.svelte.ts b/renderer/components/Knowledge/page-session.svelte.ts index 4cfe45c..87cef5a 100644 --- a/renderer/components/Knowledge/page-session.svelte.ts +++ b/renderer/components/Knowledge/page-session.svelte.ts @@ -33,7 +33,7 @@ export type PageSession = { review(edit: Fields, rollback: () => void, accept: (saved: boolean) => void, finish: () => void): void; action(commit: SessionCommit): Promise; watchObject(id: string, read: () => Promise, own?: boolean): () => void; - undo(direction: "undo" | "redo"): Promise; composition(active: boolean): void; + undo(direction: "undo" | "redo", historySource?: HistorySource): Promise; composition(active: boolean): void; attr(id: string, value: AttributeValue): void; detach(id: string): void; listen(fn: Listener): () => void; }; type Listener = (ids: string[], whole: boolean) => void; @@ -328,12 +328,12 @@ export function makeSession(tabId: string, pageId: string, source: HistorySource await reread([...changed.pages, ...changed.blocks].filter(id => id === pageId || Object.hasOwn(page.blocks, id))); if (!readingTabs.has(tabId) && !state.page?.attributes.deleted) input.replay(); } - function undo(direction: "undo" | "redo"): Promise { + function undo(direction: "undo" | "redo", historySource: HistorySource = source): Promise { if (readingTabs.has(tabId)) return Promise.resolve(); return perform(() => write(async () => { - const history = await api.history.state(source); + const history = await api.history.state(historySource); if (direction === "undo" ? history.canUndo : history.canRedo) { - const result = await receipts.submit(id => api.history.apply(source, direction, id)); + const result = await receipts.submit(id => api.history.apply(historySource, direction, id)); await rereadAction(result.changed); } })); diff --git a/renderer/components/Knowledge/page-sessions.ts b/renderer/components/Knowledge/page-sessions.ts index c772264..8c71bcc 100644 --- a/renderer/components/Knowledge/page-sessions.ts +++ b/renderer/components/Knowledge/page-sessions.ts @@ -14,7 +14,9 @@ export function mountedSession(tabId: string, pageId: string): PageSession | und return sessions.get(sessionKey(tabId, pageId)); } export function session(tabId: string, pageId: string, source: HistorySource): PageSession { - const key = sessionKey(tabId, pageId); + return sessionFor(sessionKey(tabId, pageId), tabId, pageId, source); +} +function sessionFor(key: string, tabId: string, pageId: string, source: HistorySource): PageSession { let value = sessions.get(key); if (!value) { value = makeSession(tabId, pageId, source, write, () => sessions.delete(key)); @@ -25,8 +27,9 @@ export function session(tabId: string, pageId: string, source: HistorySource): P // An inspector borrows the same page write machinery and releases it after its last edit is saved. const inspections = new Map(); -export function inspectPage(tabId: string, pageId: string): { current: PageSession; release(): void } { - const current = session(tabId, pageId, { kind: "page", id: pageId }); +export function inspectPage(tabId: string, pageId: string, source: HistorySource = { kind: "page", id: pageId }): { current: PageSession; release(): void } { + const key = source.kind === "page" && source.id === pageId ? sessionKey(tabId, pageId) : JSON.stringify([tabId, pageId, source]); + const current = sessionFor(key, tabId, pageId, source); inspections.set(current, (inspections.get(current) ?? 0) + 1); void visits.settled(tabId); return { current, release() { @@ -39,7 +42,7 @@ export function inspectPage(tabId: string, pageId: string): { current: PageSessi const release = (): void => { const tab = tabState.groups.flatMap(group => group.tabs).find(tab => tab.id === tabId); const ownsPage = tab?.view.type === "page" && tab.view.params.page.id === pageId; - if (!ownsPage && !inspections.has(current) && mountedSession(tabId, pageId) === current) current.release(); + if ((!ownsPage || key !== sessionKey(tabId, pageId)) && !inspections.has(current) && sessions.get(key) === current) current.release(); }; if (current.state.dirty || current.state.saving) void trackWrite(current.flush()).then(ok => { if (ok) release(); @@ -51,11 +54,18 @@ export function inspectPage(tabId: string, pageId: string): { current: PageSessi export function syncInspected(ids: string[]): void { if (!inspections.size) return; for (const current of inspections.keys()) { - if (current.source.kind !== "page" || !ids.includes(current.source.id)) continue; - for (const other of sessions.values()) if (other.source.kind === "page" && other.source.id === current.source.id) void visits.settled(other.tabId); + const id = current.state.page?.id; + if (!id || !ids.includes(id)) continue; + for (const other of sessions.values()) if (other.state.page?.id === id) void visits.settled(other.tabId); } } +export async function syncViewOwners(blockId: string, origin: string): Promise { + const visible = new Set(tabState.groups.map(group => group.activeTabId)); + const owners = [...sessions.values()].filter(current => current.tabId !== origin && visible.has(current.tabId) && current.state.page?.blocks[blockId]); + await Promise.all(owners.map(current => visits.settled(current.tabId))); +} + async function flushPages(): Promise { window.dispatchEvent(new Event("workspace-flush")); await Promise.all([...sessions.values()].map(async value => { diff --git a/renderer/components/Knowledge/query-labels.ts b/renderer/components/Knowledge/query-labels.ts index 82e28a1..d016d55 100644 --- a/renderer/components/Knowledge/query-labels.ts +++ b/renderer/components/Knowledge/query-labels.ts @@ -22,7 +22,7 @@ function operandLabel(value: QueryValue, type: ViewFieldType, zone: string, name if (typeof value === "object") { if (value.kind === "relative") return relativeLabel(value); if (value.kind === "absolute") return pickerValueText(type as TimePrecision, value.seconds, zone); - return ""; + return t("viewBlock.currentPage"); } if (type === "page-type") { const kind = pageKinds.find(kind => kind === value); diff --git a/renderer/components/Knowledge/table-rows.ts b/renderer/components/Knowledge/table-rows.ts index 6f7c841..f0c6aa3 100644 --- a/renderer/components/Knowledge/table-rows.ts +++ b/renderer/components/Knowledge/table-rows.ts @@ -15,7 +15,7 @@ export type TableRows = { groups: Map; }; -export function tableRows(result: ViewResult, grouped: boolean, collapsed: GroupValue[], retained: RetainedRow[]): TableRows { +export function tableRows(result: ViewResult, grouped: boolean, collapsed: GroupValue[], retained: RetainedRow[], board = false): 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)); @@ -39,7 +39,7 @@ export function tableRows(result: ViewResult, grouped: boolean, collapsed: Group if (entries) entries.push(row); else retainedByGroup.set(value, [row]); } - const buckets = result.groups ?? [], bucketValues = new Set(buckets.map(group => group.value)); + const buckets = result.groups ?? (board ? [{ value: null, start: 0, count: result.ids.length }] : []), 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) ?? []; @@ -47,13 +47,13 @@ export function tableRows(result: ViewResult, grouped: boolean, collapsed: Group if (retainedIds.size) { for (let i = start; i < start + count; i++) if (retainedIds.has(result.ids[i])) visible--; } - if (!visible) continue; + if (!visible && !board) 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 }; + const header: TableGroup = { kind: "group", value, key, count: visible, collapsed: folded.has(value) && (!board || !local.length), at, end: at + 1 }; positions.set(key, at); groups.set(value, header); items.push(header); - if (header.collapsed) continue; + if (header.collapsed && !board) continue; local.forEach(row => add({ ...row, group: value })); for (let i = start; i < start + count; i++) { const id = result.ids[i]; diff --git a/renderer/components/Knowledge/view-block-state.ts b/renderer/components/Knowledge/view-block-state.ts new file mode 100644 index 0000000..11a53f4 --- /dev/null +++ b/renderer/components/Knowledge/view-block-state.ts @@ -0,0 +1,79 @@ +import { derived, readable, toStore, type Readable } from "svelte/store"; +import { SvelteMap } from "svelte/reactivity"; +import type { ContentBlock } from "../../../shared/types/content"; +import { blockViewTypes, type BlockView } from "../../../shared/workspace/view-block"; +import { pageTitle } from "../Tab/page-titles"; +import { t, failure } from "../../i18n.svelte"; +import { knowledgeState } from "./feedback.svelte"; +import type { IconName } from "../utils/Icon.svelte"; +import type { MenuItem } from "../base/Menu.svelte"; + +export const viewBlockIcons = { table: "layout", board: "project", calendar: "calendar" } as const satisfies Record; + +export function viewBlockTypeItems(type: BlockView["type"], select: (type: BlockView["type"]) => void): MenuItem[] { + return blockViewTypes.map(value => ({ label: t(`viewBlock.${value}`), icon: viewBlockIcons[value], checked: value === type, onselect: () => select(value) })); +} + +type BlockObserver = { blockId: string; store: Readable; refresh: () => Promise }; +const observed = new Map(); +const pending = new SvelteMap(); + +export function pendingViewSettings(blockId: string): BlockView | undefined { + return pending.get(blockId); +} + +export function stageViewSettings(blockId: string, view: BlockView): () => Promise { + pending.set(blockId, view); + return async () => { + if (pending.get(blockId) !== view) return; + try { + await Promise.all([...observed.values()].filter(observer => observer.blockId === blockId).map(observer => observer.refresh())); + } + finally { + if (pending.get(blockId) === view) pending.delete(blockId); + } + }; +} + +export function observeViewBlock(pageId: string, blockId: string): Readable { + const key = pageId + ":" + blockId; + const persisted: Readable = { subscribe(run) { + const existing = observed.get(key); + if (existing) return existing.store.subscribe(run); + const store = readable(undefined, set => { + let revision = 0; + async function refresh(): Promise { + const request = ++revision; + try { + const block = await window.api.pages.viewBlock(pageId, blockId); + if (request === revision) set(block); + } + catch (error) { + if (request === revision) knowledgeState.error = failure(error); + } + } + observed.set(key, { blockId, store, refresh }); + const off = window.api.pages.onChanged(change => { + if (change.blocks.includes(blockId) || (change.summaryPages ?? change.pages).includes(pageId) || + change.purged?.includes(pageId) || change.recycledPages?.includes(pageId)) void refresh(); + }); + void refresh(); + return () => { + revision++; off(); observed.delete(key); +}; + }); + return store.subscribe(run); + } }; + return derived([persisted, toStore(() => pendingViewSettings(blockId))], ([block, view]) => + block && view ? { ...block, payload: { ...block.payload, view } } : block); +} + +export function viewBlockTitle(pageId: string, blockId: string): Readable { + const labels = toStore(() => ({ table: t("viewBlock.tableTitle"), board: t("viewBlock.boardTitle"), calendar: t("command.calendar"), + loading: t("block.view"), missing: t("shell.missing") })); + return derived([observeViewBlock(pageId, blockId), pageTitle(pageId), labels], ([block, page, text]) => { + if (!block) return block === null ? text.missing : text.loading; + const view = block.payload.view!; + return view.name || page + " · " + text[view.type]; + }); +} \ No newline at end of file diff --git a/renderer/components/Tab/GroupHeader.svelte b/renderer/components/Tab/GroupHeader.svelte index 620877c..249ba3b 100644 --- a/renderer/components/Tab/GroupHeader.svelte +++ b/renderer/components/Tab/GroupHeader.svelte @@ -9,7 +9,8 @@ {#each group.tabs as tab (tab.id)} {@const title = fromStore(definitionFor(tab.view.type).title(tab.view.params))} {@const kind = tab.view.type === "page" ? fromStore(pageKind(tab.view.params.page.id)) : null} - { activateTab(tab.id); if (tab.view.type === "page") void focusEditor(tab.id); @@ -28,6 +29,7 @@ import { commandLabel, t } from "../../i18n.svelte"; import { runCommand } from "../layout/commands"; import { pageKind } from "./page-titles"; + import { observeViewBlock, viewBlockIcons } from "../Knowledge/view-block-state"; import type { XYDirection } from "../types"; import { acceptTabDrop, dropTab, focusTabGroup, tabDragType } from "./interactions"; import { tick } from "svelte"; @@ -47,6 +49,7 @@ const header = $derived(focused && current ? definitionFor(current.view.type).header?.(current.id, current.view.params) : undefined); function viewIcon(view: Tab["view"]): IconName { if (view.type === "page") return kindIcons.editable; + if (view.type === "view-block") return "table"; return destinationIcons[view.type]; } async function focusEditor(id: TabID): Promise { diff --git a/renderer/components/Tab/api.ts b/renderer/components/Tab/api.ts index 009e65c..7e8e5de 100644 --- a/renderer/components/Tab/api.ts +++ b/renderer/components/Tab/api.ts @@ -37,6 +37,11 @@ export function setViewParams(tabId: TabID, params: Tab["view"]["params"]): void if (tab) tab.view.params = params; } +export function setTabView(tabId: string, view: Tab["view"]): void { + const tab = tabState.groups.flatMap(group => group.tabs).find(tab => tab.id === tabId); + if (tab) tab.view = view; +} + export function removeTab(id: TabID): boolean { const group = findTabGroup(id); if (!group) return false; diff --git a/renderer/components/Tab/restore.ts b/renderer/components/Tab/restore.ts index 53d47e4..e46cbde 100644 --- a/renderer/components/Tab/restore.ts +++ b/renderer/components/Tab/restore.ts @@ -14,6 +14,7 @@ type StoredGroup = { id: string; tabs: { id: string & tags.MinLength<1>; view: u const isLayout = typia.createIs<{ groups: StoredGroup[]; focusedGroupId: string; layout: Layout }>(); const isView = typia.createEquals(); const isPageLocation = typia.createEquals["params"], "page" | "fileId">>(); +const isBlockLocation = typia.createEquals["params"], "pageId" | "blockId">>(); function validTableLayout(view: Extract): boolean { const { columns } = view.params; @@ -46,6 +47,10 @@ export function restoreTabState(state: unknown): TabState | undefined { const location = { page, ...(fileId === undefined ? {} : { fileId }) }; if (isPageLocation(location)) tabs.push({ id: tab.id, view: { type: "page", params: location } }); } + else if (record(view) && view.type === "view-block" && record(view.params)) { + const { pageId, blockId } = view.params, params = { pageId, blockId }; + if (isBlockLocation(params)) tabs.push({ id: tab.id, view: { type: "view-block", params } }); + } else if (record(view) && view.type === "overview") tabs.push({ id: tab.id, view: { type: "overview", params: { status: defaultOverviewStatus, date: defaultOverviewDate } } }); diff --git a/renderer/components/Tab/views.ts b/renderer/components/Tab/views.ts index 7391147..cd9e54d 100644 --- a/renderer/components/Tab/views.ts +++ b/renderer/components/Tab/views.ts @@ -4,6 +4,8 @@ import { type ViewParams } from "../../../shared/workspace/views"; import { workspaceHistory, type HistorySource } from "../../../shared/history/ipc"; import Standalone from "./Standalone.svelte"; import PageView from "../Knowledge/PageView.svelte"; +import ViewBlockTab from "../Knowledge/ViewBlockTab.svelte"; +import { viewBlockTitle } from "../Knowledge/view-block-state"; import Table from "../Knowledge/Table.svelte"; import Calendar from "../Knowledge/Calendar.svelte"; import AttributeManagement from "../Knowledge/AttributeManagement.svelte"; @@ -39,6 +41,7 @@ const named = (key: Parameters[0]) => () => toStore(() => t(key)); const standalone = (screen: Component): Component<{ tabId: string }> => (anchor, { tabId }) => Standalone(anchor, { tabId, screen }); const views: { [K in keyof ViewParams]: Definition } = { page: { component: PageView, header: pageHeader, title: p => pageTitle(p.page.id), history: p => ({ kind: "page", id: p.page.id }), keepMounted: true }, + "view-block": { component: ViewBlockTab, title: p => viewBlockTitle(p.pageId, p.blockId), history: p => ({ kind: "page", id: p.pageId }), keepMounted: true }, library: { component: Table, header: tableHeader, title: named("command.library"), history: workspace, keepMounted: true }, papers: { component: Table, header: tableHeader, title: named("command.papers"), history: workspace, keepMounted: true }, trash: { component: Table, header: (id, params) => tableHeader(id, params, true), title: named("shell.trashView"), history: workspace, keepMounted: true }, diff --git a/renderer/components/base/Checkbox.svelte b/renderer/components/base/Checkbox.svelte index f82feb3..b24876e 100644 --- a/renderer/components/base/Checkbox.svelte +++ b/renderer/components/base/Checkbox.svelte @@ -1,25 +1,43 @@ + + - pointerFocus = true} - onkeydown={() => pointerFocus = false} onblur={() => pointerFocus = false}> - - {#if indeterminate || checked}{/if} - - {#if !hideLabel}{label}{/if} - \ No newline at end of file +{#if native && hideLabel && !indeterminate} + { + const value = event.currentTarget.checked; + checked = value; + event.currentTarget.checked = checked; + onchange?.(value); + }} /> +{:else} + pointerFocus = true} + onkeydown={() => pointerFocus = false} onblur={() => pointerFocus = false}> + + {#if indeterminate || checked}{/if} + + {#if !hideLabel}{label}{/if} + +{/if} \ No newline at end of file diff --git a/renderer/components/base/VirtualList.svelte b/renderer/components/base/VirtualList.svelte index 0438702..ace54cd 100644 --- a/renderer/components/base/VirtualList.svelte +++ b/renderer/components/base/VirtualList.svelte @@ -3,15 +3,18 @@ -
release()} oncontextmenu={context} onpointerover={inspect} onpointerleave={hideTip} style:--list-row-height={`calc(${lines} * var(--ui-row-height))`}> - + {#each visible as id, i (id)} -
{@render row(id)}
{/each} - - {#if !ids.length}
{pending ? t("library.loading") : empty}
{/if} + + {#if !ids.length && empty}
{pending ? t("library.loading") : empty}
{/if}
{#if tip}{/if} @@ -173,6 +237,8 @@ .metric { position: absolute; pointer-events: none; visibility: hidden; height: var(--list-row-height); } .virtual-row { display: flex; flex-direction: column; justify-content: center; padding-inline: var(--ui-space-3); height: var(--list-row-height); box-sizing: border-box; overflow: hidden; user-select: none; cursor: pointer; } .virtual-row:hover { background: var(--ui-hover); } + .variable { background: var(--ui-surface-clear); } + .variable .virtual-row { height: auto; padding: 0; overflow: visible; min-height: var(--ui-row-height); background: var(--ui-surface-clear); } .virtual-row[aria-selected="true"] { background: var(--ui-selected-inactive); color: var(--ui-text-selected); } .virtual-list:focus .virtual-row[aria-selected="true"] { background: var(--ui-selected); } .empty { color: var(--ui-text-secondary); padding: var(--ui-space-3); font-size: var(--ui-font-small); } diff --git a/renderer/components/base/controls.css b/renderer/components/base/controls.css index 6433a72..8f22a8d 100644 --- a/renderer/components/base/controls.css +++ b/renderer/components/base/controls.css @@ -108,6 +108,8 @@ outline-offset: var(--ui-focus-offset); } .ui-check:disabled .ui-check-mark { background: var(--ui-surface-panel); border-color: var(--ui-border-input); color: var(--ui-text-disabled); } +.ui-check.native-check { appearance: auto; width: var(--ui-icon-normal); height: var(--ui-icon-normal); margin: 0; accent-color: var(--ui-accent); } +.ui-check.native-check:focus-visible { outline: var(--ui-focus-width) solid var(--ui-focus); outline-offset: var(--ui-focus-offset); } .ui-popup { display: block; diff --git a/renderer/components/layout/commands.ts b/renderer/components/layout/commands.ts index fdf0fe2..1c43e07 100644 --- a/renderer/components/layout/commands.ts +++ b/renderer/components/layout/commands.ts @@ -133,8 +133,12 @@ export function runCommand(id: Command): void { else if (id === "newPage") { const view = group.tabs.find(tab => tab.id === group.activeTabId)?.view; const pane = document.querySelector(`[data-tabs-content][data-value="${CSS.escape(group.activeTabId ?? "")}"]`); + const viewBlock = lastFocus?.closest(".library[data-table-view=user]"); + const calendar = lastFocus?.closest(".calendar"); const inGrid = lastFocus?.closest(".library-grid") && pane?.contains(lastFocus); - if (view?.type === "calendar") pane?.querySelector(".calendar-create")?.click(); + if (view?.type === "calendar" || view?.type === "view-block" && pane?.querySelector(".calendar")) pane?.querySelector("[data-calendar-create]")?.click(); + else if (calendar && pane?.contains(calendar)) calendar.querySelector("[data-calendar-create]")?.click(); + else if (viewBlock && pane?.contains(viewBlock)) viewBlock.querySelector("[data-table-create]")?.click(); else if (inGrid && (isTableView(view?.type) || view?.type === "trash")) pane?.querySelector("[data-table-create]")?.click(); else createPage(); } @@ -181,6 +185,7 @@ export function globalShortcut(event: KeyboardEvent): void { const id = shortcutCommand(event); if (!id || (shell.search && id !== "commandPalette" && id !== "search")) return; const target = event.target instanceof Element ? event.target : null; + if (id === "blockMenu" && target?.closest(".view-block")) return; if (id === "blockMenu" && !target?.closest(".tiptap[contenteditable=true]")) return; const historyCommand = id === "undo" || id === "redo"; const inspectorHistory = historyCommand && target?.closest("[data-history-page]"); diff --git a/renderer/components/layout/destinations.ts b/renderer/components/layout/destinations.ts index 62d4e27..05feea6 100644 --- a/renderer/components/layout/destinations.ts +++ b/renderer/components/layout/destinations.ts @@ -1,7 +1,7 @@ import { type ViewParams } from "../../../shared/workspace/views"; import { type IconName } from "../utils/Icon.svelte"; -export type Destination = Exclude; +export type Destination = Exclude; export const destinationIcons = { overview: "home", feed: "rss", library: "library", papers: "book", calendar: "calendar", trash: "trash", settings: "settings-gear", attributes: "settings-gear", about: "home" diff --git a/renderer/components/layout/navigation.ts b/renderer/components/layout/navigation.ts index 41791e6..86d3f09 100644 --- a/renderer/components/layout/navigation.ts +++ b/renderer/components/layout/navigation.ts @@ -63,6 +63,10 @@ export function openDestination(type: Destination): Tab { return openView(destinationViews[type]); } +export function openViewBlock(pageId: string, blockId: string): void { + addTab(tabState.focusedGroupId, { id: getTabID(), view: { type: "view-block", params: { pageId, blockId } } }); +} + export function splitCurrent(groupId: GroupID, direction: "horizontal" | "vertical"): GroupID | null { const group = tabState.groups.find(item => item.id === groupId); const tab = group?.tabs.find(item => item.id === group.activeTabId); diff --git a/renderer/components/utils/Icon.svelte b/renderer/components/utils/Icon.svelte index 773265c..fb13ac2 100644 --- a/renderer/components/utils/Icon.svelte +++ b/renderer/components/utils/Icon.svelte @@ -23,8 +23,8 @@ "add", "agent", "arrow-down", "arrow-left", "arrow-right", "arrow-up", "bell", "bell-dot", "bold", "book", "calendar", "check", "chevron-down", "chevron-left", "chevron-right", "chevron-up", "circle-small-filled", "close", "code", "comment", "copy", "dash", "debug-pause", "edit", "file", "file-media", "file-pdf", "file-text", "file-zip", "folder-opened", "gripper", "home", - "horizontal-rule", "info", "italic", "layout-sidebar-left", "layout-sidebar-right", "library", "link-external", "loading", - "list-ordered", "list-unordered", "ellipsis", "music", "play-circle", "quote", "refresh", "rss", "search", + "horizontal-rule", "info", "italic", "layout", "layout-sidebar-left", "layout-sidebar-right", "library", "link-external", "loading", + "list-ordered", "list-unordered", "ellipsis", "music", "play-circle", "project", "quote", "refresh", "rss", "search", "settings-gear", "split-horizontal", "split-vertical", "strikethrough", "symbol-color", "sync", "table", "trash", "warning", "zoom-in", "zoom-out" ] as const; diff --git a/renderer/components/utils/Resizer.svelte b/renderer/components/utils/Resizer.svelte index 225589b..b0dd276 100644 --- a/renderer/components/utils/Resizer.svelte +++ b/renderer/components/utils/Resizer.svelte @@ -3,7 +3,7 @@ role="separator" aria-label={label} aria-orientation={direction} aria-valuenow={Math.round(origin)} aria-valuemin={min} aria-valuemax={max} tabindex="0" {onkeydown} {onpointerdown} {onpointermove} {onpointerup} - onlostpointercapture={() => dragging = false} onpointercancel={onpointerup} + onlostpointercapture={cancelDrag} onpointercancel={cancelDrag} >