From d5d405cee3a680b894ea915748e0b95497c56ea8 Mon Sep 17 00:00:00 2001 From: taekchef Date: Fri, 17 Jul 2026 04:49:20 +0800 Subject: [PATCH 1/4] docs: define course drawer and relation workbench --- Docs/course-library-architecture.md | 53 +++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Docs/course-library-architecture.md diff --git a/Docs/course-library-architecture.md b/Docs/course-library-architecture.md new file mode 100644 index 000000000..21570c60e --- /dev/null +++ b/Docs/course-library-architecture.md @@ -0,0 +1,53 @@ +# 课程抽屉与关系台实现说明 + +## 目标 + +- 沉浸学习时,用临时课程抽屉完成低频的课程、资料和笔记切换,不挤压或重建 DOC / CHAT / NOTES。 +- 进入管理关系后,用开放关系纸面查看和编辑资料与笔记的长期多对多关系。 +- 数据很多时先看课程汇总束,聚焦一门课程后再展开文件与一跳笔记。 + +## 数据边界 + +- `Course` 是真实课程实体,不再把全部导入资料假装成一门课程。 +- `CourseItemMembership` 保存课程与资料、笔记的归属;同一项目可以属于多门课程。 +- `NoteSourceLink` 继续只表示笔记与资料的长期关系,不承担课程归属、当前打开状态或 Agent 查询范围。 +- 现有未归属项目进入“未归属”虚拟组,不自动伪造课程。 +- 课程文件夹导入时,每个根文件夹创建或复用一门课程,并把本次导入项目加入该课程。 +- 学习会话第一版继续放在“学习记录”;不把会话直接画成资料—笔记关系带。 + +## 界面边界 + +### 小抽屉 + +- 复用课程目录入口,但改为覆盖在稳定工作区上方的临时抽屉。 +- 根层只显示课程、独立资料、全部笔记和“管理关系”。 +- 进入课程后只深入一层,显示课程资料与课程笔记。 +- 打开资料或笔记不重建稳定面板;抽屉可继续停留,点击遮罩或再次点击入口关闭。 + +### 大关系台 + +- 使用一张连续纸面,不使用左右硬侧边栏。 +- 文件和笔记是独立节点;关系带直接连接节点。 +- 单条关系等宽;汇总束宽只表示真实关系数量。 +- 选中一端时,关联节点和关系带一起显影,其余内容退入纸雾。 +- 查看模式不显示连接把手;管理模式悬停节点后才显示把手,并支持建立或删除关系。 +- 高密度时默认按课程汇总;聚焦课程后只展开该课程和一跳关系。 + +## 共享文件占用 + +本任务计划占用以下共享核心文件: + +- `Sources/WeiBei/Stores/WorkspaceStore.swift`:课程实体、归属、导入和打开动作。 +- `Sources/WeiBei/Views/ContentView.swift`:在稳定面板树上方挂载临时课程抽屉。 +- `Sources/WeiBei/Views/CourseWorkspaceView.swift`:关系台入口、筛选和聚焦状态。 +- `Sources/WeiBeiSelfCheck/main.swift`:数据迁移、抽屉挂载和关系台结构自检。 + +预计释放条件:课程数据可向后兼容保存;小抽屉不重建稳定面板;关系台可查看、建立和删除真实关系;构建、自检和隔离数据真实窗口验收完成。 + +## 验收 + +- 旧 `workspace.json` 可直接打开,原资料、笔记、关系和学习会话不丢失。 +- 打开、关闭抽屉以及在抽屉中切换资料或笔记时,DOC / CHAT / NOTES 连续性不变。 +- 关系台在几十个节点、几百条关系下仍可聚焦和筛选,不渲染无关系的组合。 +- 拖拽成功后只保存一次;取消拖拽不写盘。 +- 使用隔离演示数据完成真实窗口截图,不触碰用户正在使用的课程数据。 From be04a063eb5b6f76937be2e1ce556b6d98b31d19 Mon Sep 17 00:00:00 2001 From: taekchef Date: Fri, 17 Jul 2026 05:48:19 +0800 Subject: [PATCH 2/4] feat: add course drawer and relation workbench --- Docs/course-library-architecture.md | 21 +- Sources/WeiBei/Stores/WorkspaceStore.swift | 386 ++++++++- Sources/WeiBei/Views/ContentView.swift | 109 +-- .../Views/CourseImmersiveDrawerView.swift | 17 + .../Views/CourseRelationGraphModel.swift | 399 +++++++++ .../Views/CourseRelationPaperView.swift | 809 ++++++++++++++++++ .../WeiBei/Views/CourseRelationsView.swift | 464 +--------- .../WeiBei/Views/CourseWorkspaceView.swift | 2 +- Sources/WeiBei/Views/SidebarView.swift | 295 ++++++- Sources/WeiBeiCore/CourseLibraryModels.swift | 117 +++ Sources/WeiBeiCore/WorkspaceModels.swift | 39 +- Sources/WeiBeiSelfCheck/main.swift | 96 ++- 12 files changed, 2164 insertions(+), 590 deletions(-) create mode 100644 Sources/WeiBei/Views/CourseImmersiveDrawerView.swift create mode 100644 Sources/WeiBei/Views/CourseRelationGraphModel.swift create mode 100644 Sources/WeiBei/Views/CourseRelationPaperView.swift create mode 100644 Sources/WeiBeiCore/CourseLibraryModels.swift diff --git a/Docs/course-library-architecture.md b/Docs/course-library-architecture.md index 21570c60e..98c1482a3 100644 --- a/Docs/course-library-architecture.md +++ b/Docs/course-library-architecture.md @@ -4,7 +4,7 @@ - 沉浸学习时,用临时课程抽屉完成低频的课程、资料和笔记切换,不挤压或重建 DOC / CHAT / NOTES。 - 进入管理关系后,用开放关系纸面查看和编辑资料与笔记的长期多对多关系。 -- 数据很多时先看课程汇总束,聚焦一门课程后再展开文件与一跳笔记。 +- 数据很多时先按课程、未归属或未关联范围收窄;搜索和聚焦始终保留命中节点与一跳关系。 ## 数据边界 @@ -19,19 +19,19 @@ ### 小抽屉 -- 复用课程目录入口,但改为覆盖在稳定工作区上方的临时抽屉。 -- 根层只显示课程、独立资料、全部笔记和“管理关系”。 +- 直接复用原课程目录的标题、搜索框、行样式与纸面质感,只把打开方式改为覆盖在稳定工作区上方、宽度保持原来约 292pt 的临时抽屉。 +- 根层显示课程、独立资料、全部笔记和原有内置示例;课程首页继续作为关系管理入口。 - 进入课程后只深入一层,显示课程资料与课程笔记。 -- 打开资料或笔记不重建稳定面板;抽屉可继续停留,点击遮罩或再次点击入口关闭。 +- 打开资料或笔记不重建稳定面板,并立即收起抽屉;点击遮罩、按下 Esc 或再次点击入口也可关闭。 ### 大关系台 - 使用一张连续纸面,不使用左右硬侧边栏。 - 文件和笔记是独立节点;关系带直接连接节点。 -- 单条关系等宽;汇总束宽只表示真实关系数量。 +- 单条关系以克制的低亮度带状曲线呈现,并叠加纸雾;不伪造汇总关系。 - 选中一端时,关联节点和关系带一起显影,其余内容退入纸雾。 - 查看模式不显示连接把手;管理模式悬停节点后才显示把手,并支持建立或删除关系。 -- 高密度时默认按课程汇总;聚焦课程后只展开该课程和一跳关系。 +- 可切换课程、全部、未归属和未关联范围;高密度时优先保留选中项、搜索命中项、一跳节点和高关系节点,并明确显示隐藏数量。 ## 共享文件占用 @@ -48,6 +48,13 @@ - 旧 `workspace.json` 可直接打开,原资料、笔记、关系和学习会话不丢失。 - 打开、关闭抽屉以及在抽屉中切换资料或笔记时,DOC / CHAT / NOTES 连续性不变。 -- 关系台在几十个节点、几百条关系下仍可聚焦和筛选,不渲染无关系的组合。 +- 关系台在高密度数据下仍可聚焦和筛选,不渲染不存在的关系组合。 - 拖拽成功后只保存一次;取消拖拽不写盘。 - 使用隔离演示数据完成真实窗口截图,不触碰用户正在使用的课程数据。 + +## 已完成验证 + +- 兼容 macOS 15.4 SDK 的完整构建通过。 +- `WeiBeiSelfCheck` 完整自检通过,覆盖旧数据兼容、多课程归属、抽屉挂载和关系台聚焦逻辑。 +- 隔离工作区课程流程验证通过:资料与笔记跳转、重启后持久化、稳定面板不重建均通过。 +- 已用隔离演示数据完成原样式课程抽屉和 20 节点、17 关系的真实窗口截图。 diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index 6a2c74a8a..36543adae 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -171,6 +171,13 @@ final class WorkspaceStore: ObservableObject { @Published var importedItems: [StudyItem] = [] @Published var selectedItemID: String? @Published var activeNotebookItemID: String? + @Published private(set) var courses: [Course] = [] + @Published private(set) var courseItemMemberships: [CourseItemMembership] = [] { + didSet { + courseMembershipIndex = CourseItemMemberships(values: courseItemMemberships) + } + } + @Published private(set) var activeCourseID: UUID? @Published var noteText = "" @Published var agentDraft = "" @Published var messages: [AgentMessage] = [] @@ -190,7 +197,7 @@ final class WorkspaceStore: ObservableObject { @Published private(set) var learningMemoryRevision: UInt64 = 0 @Published private(set) var studySessions: [StudySession] = [] @Published private(set) var activeStudySessionID: UUID? - @Published var showLibrary = true + @Published var showLibrary = false @Published var showReader = true @Published var showAgent = true @Published var showNotes = true @@ -279,6 +286,7 @@ final class WorkspaceStore: ObservableObject { private let studyProgressSaveDelay: UInt64 = 900_000_000 private var noteSourceLinksMigrationVersion = 0 private var noteSourceRelationIndex = NoteSourceRelationIndex(links: []) + private var courseMembershipIndex = CourseItemMemberships() private var courseWorkspaceReturnFocus: PaneFocus? var showRightPane: Bool { @@ -397,6 +405,7 @@ final class WorkspaceStore: ObservableObject { } let migratedStudyLocationTitles = refreshStudyLocationReferenceTitles() let sanitizedNoteSourceLinks = sanitizeNoteSourceLinks() + let sanitizedCourseLibrary = sanitizeCourseLibrary() courseDocumentSearchIndex.synchronize(allItems) ensureActiveStudySession() let savedInitializationChanges: Bool @@ -408,7 +417,8 @@ final class WorkspaceStore: ObservableObject { || recoveredPendingNotebookRename || migratedImportedItemIdentities || migratedStudyLocationTitles - || sanitizedNoteSourceLinks { + || sanitizedNoteSourceLinks + || sanitizedCourseLibrary { savedInitializationChanges = save() } else { savedInitializationChanges = true @@ -437,6 +447,114 @@ final class WorkspaceStore: ObservableObject { importedItems.filter(\.isNotebookNote) } + var activeCourse: Course? { + guard let activeCourseID else { return nil } + return courses.first { $0.id == activeCourseID } + } + + func course(withID courseID: UUID) -> Course? { + courses.first { $0.id == courseID } + } + + func courseItems(in courseID: UUID) -> [StudyItem] { + let itemIDs = Set(courseMembershipIndex.itemIDs(in: courseID)) + return importedItems.filter { itemIDs.contains($0.id) } + } + + func courseMaterials(in courseID: UUID) -> [StudyItem] { + courseItems(in: courseID).filter { !$0.isNotebookNote } + } + + func courseNotes(in courseID: UUID) -> [StudyItem] { + courseItems(in: courseID).filter(\.isNotebookNote) + } + + func courseIDs(for itemID: String) -> [UUID] { + courseMembershipIndex.courseIDs(for: itemID) + } + + var unassignedCourseMaterials: [StudyItem] { + courseMaterials.filter { courseMembershipIndex.courseIDs(for: $0.id).isEmpty } + } + + var unassignedCourseNotes: [StudyItem] { + courseNotebookItems.filter { courseMembershipIndex.courseIDs(for: $0.id).isEmpty } + } + + func activateCourse(_ id: UUID?) { + let resolvedID = id.flatMap { candidate in + courses.contains(where: { $0.id == candidate }) ? candidate : nil + } + guard activeCourseID != resolvedID else { return } + activeCourseID = resolvedID + save() + } + + @discardableResult + func createCourse(title rawTitle: String) -> UUID? { + let title = rawTitle.trimmingCharacters(in: .whitespacesAndNewlines) + guard !title.isEmpty else { return nil } + let course = Course( + title: title, + colorIndex: nextCourseColorIndex() + ) + courses.append(course) + activeCourseID = course.id + save() + return course.id + } + + func renameCourse(_ courseID: UUID, title rawTitle: String) { + let title = rawTitle.trimmingCharacters(in: .whitespacesAndNewlines) + guard !title.isEmpty, + let index = courses.firstIndex(where: { $0.id == courseID }), + courses[index].title != title else { return } + courses[index].title = title + courses[index].updatedAt = Date() + save() + } + + func deleteCourse(_ courseID: UUID) { + guard courses.contains(where: { $0.id == courseID }) else { return } + courses.removeAll { $0.id == courseID } + var memberships = courseMembershipIndex + memberships.removeCourse(courseID) + courseItemMemberships = memberships.values + if activeCourseID == courseID { + activeCourseID = courses.first?.id + } + save() + } + + func setCourseIDs(_ courseIDs: Set, for itemID: String) { + guard importedItems.contains(where: { $0.id == itemID }) else { return } + let validCourseIDs = Set(courses.map(\.id)) + var memberships = courseMembershipIndex + memberships.replaceCourses(for: itemID, courseIDs: courseIDs.intersection(validCourseIDs)) + guard memberships.values != courseItemMemberships else { return } + courseItemMemberships = memberships.values + save() + } + + func assignItemIDs(_ itemIDs: Set, to courseID: UUID) { + guard courses.contains(where: { $0.id == courseID }) else { return } + let validItemIDs = Set(importedItems.map(\.id)) + var memberships = courseMembershipIndex + memberships.assign(itemIDs: itemIDs.intersection(validItemIDs), to: courseID) + guard memberships.values != courseItemMemberships else { return } + courseItemMemberships = memberships.values + activeCourseID = courseID + save() + } + + func relationCount(in courseID: UUID) -> Int { + let materialIDs = Set(courseMaterials(in: courseID).map(\.id)) + let noteIDs = Set(courseNotes(in: courseID).map(\.id)) + return noteSourceLinks.lazy.filter { + materialIDs.contains($0.sourceItemID) && noteIDs.contains($0.noteItemID) + }.count + } + var recentCourseSessions: [StudySession] { orderedStudySessions.filter { !$0.messages.isEmpty } } @@ -1070,6 +1188,9 @@ final class WorkspaceStore: ObservableObject { persistCurrentNote() notebookCreationDraft = nil notebookRenameDraft = nil + if let itemID { + alignActiveCourse(with: itemID) + } if let itemID, let item = allItems.first(where: { $0.id == itemID && $0.isNotebookNote }) { activeNotebookItemID = item.id @@ -1114,6 +1235,13 @@ final class WorkspaceStore: ObservableObject { save() } + private func alignActiveCourse(with itemID: String) { + let containingCourseIDs = courseMembershipIndex.courseIDs(for: itemID) + guard !containingCourseIDs.isEmpty else { return } + if let activeCourseID, containingCourseIDs.contains(activeCourseID) { return } + activeCourseID = containingCourseIDs.first + } + func setLinkedSourceIDsForActiveNote(_ sourceItemIDs: Set) { guard let noteItemID = activeNotebookItemID else { return } setLinkedSourceIDs(sourceItemIDs, for: noteItemID) @@ -1174,6 +1302,7 @@ final class WorkspaceStore: ObservableObject { func openCourseMaterial(_ itemID: String) { guard courseMaterials.contains(where: { $0.id == itemID }) else { return } dismissCourseWorkspace(restoringFocus: false) + showLibrary = false select(itemID: itemID) if layout == .immersiveWriting || layout == .immersiveConversation { setLayout(.immersiveReading) @@ -1187,6 +1316,7 @@ final class WorkspaceStore: ObservableObject { func openCourseNote(_ itemID: String) { guard courseNotebookItems.contains(where: { $0.id == itemID }) else { return } dismissCourseWorkspace(restoringFocus: false) + showLibrary = false select(itemID: itemID) } @@ -1194,6 +1324,7 @@ final class WorkspaceStore: ObservableObject { guard studySessions.contains(where: { $0.id == sessionID && !$0.messages.isEmpty }) else { return } activateStudySession(sessionID) dismissCourseWorkspace(restoringFocus: false) + showLibrary = false setLayout(.immersiveConversation) } @@ -1370,21 +1501,17 @@ final class WorkspaceStore: ObservableObject { } func toggleLibrary() { - recordNavigationPoint() showLibrary.toggle() clearUnpinnedFloatingSelection() focus(showLibrary ? .library : .reader) - save() } func revealLibrary() { if !showLibrary { - recordNavigationPoint() clearUnpinnedFloatingSelection() } showLibrary = true focus(.library) - save() } func toggleReader() { @@ -2287,7 +2414,7 @@ final class WorkspaceStore: ObservableObject { let draft = makeCourseFolderImportDraft(rootURLs: panel.urls) guard !draft.markdownFiles.isEmpty else { - _ = importFiles(panel.urls, selectsFirstImportedItem: false) + importCourseFolder(draft, notePaths: []) courseFolderImportDraft = nil return } @@ -2301,6 +2428,49 @@ final class WorkspaceStore: ObservableObject { markdownNotePaths: notePaths, reclassifiesExistingMarkdown: true ) + + var memberships = courseMembershipIndex + var selectedCourseID: UUID? + for rootURL in draft.rootURLs { + let standardizedRoot = rootURL.standardizedFileURL + let itemIDs = Set(importedItems.compactMap { item -> String? in + guard let itemURL = item.url?.standardizedFileURL, + Self.isFileURL(itemURL, inside: standardizedRoot) else { return nil } + return item.id + }) + guard !itemIDs.isEmpty else { continue } + let courseID = ensureCourse(forImportRoot: standardizedRoot) + memberships.assign(itemIDs: itemIDs, to: courseID) + selectedCourseID = selectedCourseID ?? courseID + } + courseItemMemberships = memberships.values + if let selectedCourseID { + activeCourseID = selectedCourseID + } + save() + } + + private func ensureCourse(forImportRoot rootURL: URL) -> UUID { + let rootPath = rootURL.standardizedFileURL.path + if let course = courses.first(where: { $0.sourceRootPath == rootPath }) { + return course.id + } + + let course = Course( + title: rootURL.lastPathComponent.isEmpty + ? ui("未命名课程", "Untitled Course") + : rootURL.lastPathComponent, + colorIndex: nextCourseColorIndex(), + sourceRootPath: rootPath + ) + courses.append(course) + return course.id + } + + nonisolated private static func isFileURL(_ itemURL: URL, inside rootURL: URL) -> Bool { + let rootPath = rootURL.standardizedFileURL.path + let itemPath = itemURL.standardizedFileURL.path + return itemPath == rootPath || itemPath.hasPrefix(rootPath + "/") } @discardableResult @@ -2313,6 +2483,7 @@ final class WorkspaceStore: ObservableObject { linkToActiveNote: false, selectsFirstImportedItem: false, reclassifiesExistingMarkdown: true, + assigningToCourseID: activeCourseID, panelTitle: ui("选择课程资料或文件夹", "Choose course materials or a folder") ) } @@ -2324,6 +2495,7 @@ final class WorkspaceStore: ObservableObject { markdownAsNotes: true, markdownOnly: true, reclassifiesExistingMarkdown: true, + assigningToCourseID: activeCourseID, panelTitle: ui("选择 Markdown 笔记或文件夹", "Choose Markdown notes or a folder") ) } @@ -2338,6 +2510,7 @@ final class WorkspaceStore: ObservableObject { markdownAsNotes: Bool = false, markdownOnly: Bool = false, reclassifiesExistingMarkdown: Bool = false, + assigningToCourseID: UUID? = nil, panelTitle: String? = nil ) { let panel = NSOpenPanel() @@ -2358,6 +2531,17 @@ final class WorkspaceStore: ObservableObject { markdownOnly: markdownOnly, reclassifiesExistingMarkdown: reclassifiesExistingMarkdown ) + if let assigningToCourseID { + let importedPaths = Set(panel.urls + .flatMap(Self.supportedCourseFiles(at:)) + .map { $0.standardizedFileURL.path }) + let importedItemIDs = Set(importedItems.compactMap { item -> String? in + guard let path = item.url?.standardizedFileURL.path, + importedPaths.contains(path) else { return nil } + return item.id + }) + assignItemIDs(importedItemIDs, to: assigningToCourseID) + } if let targetNoteID, targetNoteID == activeNotebookItemID { setLinkedSourceIDsForActiveNote( Set(linkedSourceIDsForActiveNote).union(selectedItems.map(\.id)) @@ -3092,6 +3276,12 @@ final class WorkspaceStore: ObservableObject { } item.importedFileLastKnownPath = url.path importedItems.append(item) + if let activeCourseID, + courses.contains(where: { $0.id == activeCourseID }) { + var memberships = courseMembershipIndex + memberships.assign(itemIDs: [item.id], to: activeCourseID) + courseItemMemberships = memberships.values + } courseDocumentSearchIndex.synchronize(allItems) if let sourceItem { addNoteSourceLink(noteItemID: item.id, sourceItemID: sourceItem.id) @@ -3473,6 +3663,40 @@ final class WorkspaceStore: ObservableObject { return noteSourceLinks != previous } + @discardableResult + private func sanitizeCourseLibrary() -> Bool { + let previousCourses = courses + let previousMemberships = courseItemMemberships + let previousActiveCourseID = activeCourseID + + var seenCourseIDs = Set() + courses = courses.filter { course in + seenCourseIDs.insert(course.id).inserted + && !course.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + var memberships = CourseItemMemberships(values: courseItemMemberships) + _ = memberships.sanitize( + validCourseIDs: Set(courses.map(\.id)), + validItemIDs: Set(importedItems.map(\.id)) + ) + courseItemMemberships = memberships.values + + if let activeCourseID, + !courses.contains(where: { $0.id == activeCourseID }) { + self.activeCourseID = courses.first?.id + } + + return courses != previousCourses + || courseItemMemberships != previousMemberships + || activeCourseID != previousActiveCourseID + } + + private func nextCourseColorIndex() -> Int { + let used = Set(courses.map(\.colorIndex)) + return (0..<8).first(where: { !used.contains($0) }) ?? (courses.count % 8) + } + @discardableResult private func refreshStudyLocationReferenceTitles() -> Bool { var changed = false @@ -4031,21 +4255,12 @@ final class WorkspaceStore: ObservableObject { save() return } - if scenario == "course-workspace-overview-flow" || scenario == "course-workspace-workflow-flow" { + if scenario == "course-workspace-overview-flow" + || scenario == "course-workspace-workflow-flow" + || scenario == "course-index-navigation-flow" { await runCourseWorkspaceVerification(scenario) return } - if scenario == "course-index-navigation-flow" { - layout = .documentAgentNotes - showLibrary = true - showReader = false - showAgent = false - showNotes = false - agentSurface = .hidden - showDailyInspiration = true - save() - return - } if scenario == "pane-toggle-continuity-flow" { await runPaneToggleContinuityVerification() return @@ -4240,6 +4455,28 @@ final class WorkspaceStore: ObservableObject { NoteSourceLink(noteItemID: noteA.id, sourceItemID: materialB.id), NoteSourceLink(noteItemID: noteB.id, sourceItemID: materialB.id), ] + let courseA = Course( + id: UUID(uuidString: "11111111-1111-1111-1111-111111111111")!, + title: "货币金融学", + colorIndex: 0 + ) + let courseB = Course( + id: UUID(uuidString: "22222222-2222-2222-2222-222222222222")!, + title: "经济思想史", + colorIndex: 1 + ) + courses = [courseA, courseB] + var verificationMemberships = CourseItemMemberships() + verificationMemberships.assign( + itemIDs: Set([materialA.id, materialB.id, noteA.id, noteB.id]), + to: courseA.id + ) + verificationMemberships.assign( + itemIDs: Set([materialB.id, materialC.id, noteB.id, noteC.id]), + to: courseB.id + ) + courseItemMemberships = verificationMemberships.values + activeCourseID = courseA.id studyLocationsByItemID = [ materialA.id: StudyLocation( itemID: materialA.id, @@ -4290,6 +4527,28 @@ final class WorkspaceStore: ObservableObject { courseDocumentSearchIndex.synchronize(allItems) save() + if scenario == "course-index-navigation-flow" { + let unassignedURL = fixtureURL("跨课程阅读清单", extension: "txt") + try? "待归类:金融史、政策工具与复习问题。\n".write(to: unassignedURL, atomically: true, encoding: .utf8) + importedItems.append( + StudyItem( + id: "course-material-unassigned", + title: "跨课程阅读清单", + subtitle: unassignedURL.lastPathComponent, + kind: .text, + urlPath: unassignedURL.path, + isSample: false + ) + ) + activeCourseID = nil + showLibrary = true + courseWorkspacePresented = false + courseDocumentSearchIndex.synchronize(allItems) + save() + recordVerificationStage("completed") + return + } + let noteCountBeforeInvalidCreation = courseNotebookItems.count let invalidNoteID = createCourseNotebookNote(title: " ") let invalidNoteCreationPassed = invalidNoteID == nil @@ -4303,7 +4562,10 @@ final class WorkspaceStore: ObservableObject { let requestedPage = Self.environmentValue("WEIBEI_VERIFY_COURSE_PAGE") if requestedPage == "notes" { presentCourseWorkspace(.notes, selecting: noteA.id) - } else if requestedPage == "materials" { + } else if requestedPage == "materials" || requestedPage == "relations-large" { + if requestedPage == "relations-large" { + activeCourseID = nil + } presentCourseWorkspace(.materials, selecting: materialB.id) } else if requestedPage == "sessions" { presentCourseWorkspace(.sessions, selecting: activeSession.id.uuidString) @@ -4346,6 +4608,62 @@ final class WorkspaceStore: ObservableObject { "courseWorkspacePresented": courseWorkspacePresented, ] ) + if requestedPage == "relations-large" { + let courseC = Course( + id: UUID(uuidString: "33333333-3333-3333-3333-333333333333")!, + title: "金融史专题", + colorIndex: 2 + ) + let courseD = Course( + id: UUID(uuidString: "44444444-4444-4444-4444-444444444444")!, + title: "计量练习", + colorIndex: 3 + ) + courses.append(contentsOf: [courseC, courseD]) + + var expandedMemberships = CourseItemMemberships(values: courseItemMemberships) + var expandedRelations = NoteSourceRelations(links: noteSourceLinks) + for index in 1...7 { + let materialURL = fixtureURL("扩展资料 \(index)", extension: "txt") + let noteURL = fixtureURL("扩展笔记 \(index)", extension: "md") + try? "第 \(index) 份课程材料,包含利率、政策与历史线索。\n".write(to: materialURL, atomically: true, encoding: .utf8) + try? "# 扩展笔记 \(index)\n\n## 课程线索\n".write(to: noteURL, atomically: true, encoding: .utf8) + let material = StudyItem( + id: "course-large-material-\(index)", + title: ["债券定价", "通胀预期", "央行沟通", "危机史料", "政策冲击", "回归练习", "期末框架"][index - 1], + subtitle: materialURL.lastPathComponent, + kind: .text, + urlPath: materialURL.path, + isSample: false + ) + let note = StudyItem( + id: "course-large-note-\(index)", + title: ["期限结构札记", "费雪效应", "政策信号", "危机比较", "识别假设", "模型结果", "总复习图谱"][index - 1], + subtitle: noteURL.lastPathComponent, + kind: .markdown, + urlPath: noteURL.path, + isSample: false, + isNotebookNote: true + ) + importedItems.append(contentsOf: [material, note]) + notesByItemID[note.id] = "# \(note.title)\n\n## 课程线索\n" + let primaryCourseID = index <= 3 ? courseC.id : courseD.id + expandedMemberships.assign(itemIDs: Set([material.id, note.id]), to: primaryCourseID) + if index == 3 || index == 4 { + expandedMemberships.assign(itemIDs: Set([material.id, note.id]), to: courseB.id) + } + let nextNoteID = "course-large-note-\(index == 7 ? 1 : index + 1)" + expandedRelations.replaceNotes( + for: material.id, + noteItemIDs: Set([note.id, nextNoteID]) + ) + } + courseItemMemberships = expandedMemberships.values + noteSourceLinks = expandedRelations.links + activeCourseID = nil + courseDocumentSearchIndex.synchronize(allItems) + save() + } recordVerificationStage("completed") return } @@ -4423,6 +4741,9 @@ final class WorkspaceStore: ObservableObject { let persistencePassed = diskRelations.sourceIDs(for: noteA.id) == [materialA.id] && Set(diskRelations.sourceIDs(for: noteC.id)) == Set([materialB.id, materialC.id]) && Set(diskRelations.noteIDs(for: materialB.id)) == Set([noteB.id, noteC.id]) + && Set(diskSnapshot?.courses?.map(\.id) ?? []) == Set([courseA.id, courseB.id]) + && diskSnapshot?.activeCourseID == courseB.id + && diskSnapshot?.courseItemMemberships?.count == courseItemMemberships.count && diskSummary?.explicitLinkCount == 4 && diskSummary?.unlinkedMaterialCount == 0 && diskSummary?.unlinkedNoteCount == 0 @@ -5718,6 +6039,14 @@ final class WorkspaceStore: ObservableObject { if activeNotebookItemID == oldID { activeNotebookItemID = newID } if courseWorkspaceTargetItemID == oldID { courseWorkspaceTargetItemID = newID } + courseItemMemberships = CourseItemMemberships( + values: courseItemMemberships.map { membership in + var copy = membership + if copy.itemID == oldID { copy.itemID = newID } + return copy + } + ).values + noteSourceLinks = NoteSourceRelations( links: noteSourceLinks.map { link in var copy = link @@ -6109,6 +6438,11 @@ final class WorkspaceStore: ObservableObject { noteBackingContentDigestsByItemID = snapshot.noteBackingContentDigestsByItemID ?? [:] selectedItemID = snapshot.selectedItemID activeNotebookItemID = snapshot.activeNotebookItemID + courses = snapshot.courses ?? [] + courseItemMemberships = CourseItemMemberships( + values: snapshot.courseItemMemberships ?? [] + ).values + activeCourseID = snapshot.activeCourseID noteSourceLinks = snapshot.noteSourceLinks ?? [] noteSourceLinksMigrationVersion = snapshot.noteSourceLinksMigrationVersion ?? 0 studyLocationsByItemID = snapshot.studyLocationsByItemID ?? [:] @@ -6130,6 +6464,10 @@ final class WorkspaceStore: ObservableObject { !allItems.contains(where: { $0.id == activeNotebookItemID && $0.isNotebookNote }) { self.activeNotebookItemID = nil } + if let activeCourseID, + !courses.contains(where: { $0.id == activeCourseID }) { + self.activeCourseID = courses.first?.id + } if let modelName = snapshot.modelName { self.modelName = modelName } @@ -6148,9 +6486,6 @@ final class WorkspaceStore: ObservableObject { if let noteRenderMode = snapshot.noteRenderMode { self.noteRenderMode = noteRenderMode.visibleMode } - if let showLibrary = snapshot.showLibrary { - self.showLibrary = showLibrary - } let legacyRightPane = snapshot.showRightPane showReader = snapshot.showReader ?? true showAgent = snapshot.showAgent ?? legacyRightPane ?? true @@ -6202,6 +6537,9 @@ final class WorkspaceStore: ObservableObject { noteBackingContentDigestsByItemID: noteBackingContentDigestsByItemID, selectedItemID: selectedItemID, activeNotebookItemID: activeNotebookItemID, + courses: courses, + courseItemMemberships: courseItemMemberships, + activeCourseID: activeCourseID, noteSourceLinks: noteSourceLinks, noteSourceLinksMigrationVersion: noteSourceLinksMigrationVersion, studyLocationsByItemID: studyLocationsByItemID, @@ -6214,7 +6552,7 @@ final class WorkspaceStore: ObservableObject { threePaneOrder: normalizedThreePaneOrder, agentSurface: agentSurface == .selectionFloat ? .hidden : agentSurface, noteRenderMode: noteRenderMode, - showLibrary: showLibrary, + showLibrary: nil, showReader: showReader, showAgent: showAgent, showNotes: showNotes, diff --git a/Sources/WeiBei/Views/ContentView.swift b/Sources/WeiBei/Views/ContentView.swift index e4195b676..8f87726fe 100644 --- a/Sources/WeiBei/Views/ContentView.swift +++ b/Sources/WeiBei/Views/ContentView.swift @@ -6,9 +6,7 @@ struct ContentView: View { @EnvironmentObject private var store: WorkspaceStore @FocusState private var focusedPane: PaneFocus? @FocusState private var topSearchFocused: Bool - @SceneStorage("libraryPaneWidth") private var libraryPaneWidthStorage: Double = 292 @State private var floatingAgentExpanded = false - @State private var libraryDragStartWidth: CGFloat? @State private var windowIsFullScreen = false var body: some View { @@ -22,25 +20,32 @@ struct ContentView: View { ) ZStack(alignment: .top) { - HStack(spacing: 0) { - if store.showLibrary { - SidebarView() - .frame(width: libraryWidth(in: geometry.size.width)) - .focused($focusedPane, equals: .library) - .transition(WeiBeiTransition.sidePanel) - .zIndex(2) - - libraryResizeHandle(totalWidth: geometry.size.width) - .transition(.opacity) + LayoutContentView() + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(WeiBeiTheme.paper) + .animation(WeiBeiMotion.layout, value: store.layout) + + if store.showLibrary { + ZStack(alignment: .leading) { + WeiBeiTheme.ink.opacity(0.035) + .contentShape(Rectangle()) + .onTapGesture { + withAnimation(WeiBeiMotion.panel) { + store.toggleLibrary() + } + } + + CourseImmersiveDrawerView { + withAnimation(WeiBeiMotion.panel) { + store.toggleLibrary() + } + } + .transition(.move(edge: .leading).combined(with: .opacity)) } - - LayoutContentView() - .frame(maxWidth: .infinity, maxHeight: .infinity) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .transition(.opacity) + .zIndex(35) } - .frame(maxWidth: .infinity, maxHeight: .infinity) - .background(WeiBeiTheme.paper) - .animation(WeiBeiMotion.layout, value: store.showLibrary) - .animation(WeiBeiMotion.layout, value: store.layout) if store.commandPalettePresented { CommandPaletteView() @@ -74,13 +79,19 @@ struct ContentView: View { } } .background { - if !store.courseWorkspacePresented && showsGlobalFloatingAgent { + if !store.courseWorkspacePresented && store.showLibrary { + EscapeKeyBridge { + store.toggleLibrary() + } + } + + if !store.courseWorkspacePresented && !store.showLibrary && showsGlobalFloatingAgent { EscapeKeyBridge { store.dismissFloatingSelectionAgent() } } - if !store.courseWorkspacePresented && store.showReaderSearch { + if !store.courseWorkspacePresented && !store.showLibrary && store.showReaderSearch { EscapeKeyBridge { store.hideReaderSearch() topSearchFocused = false @@ -133,58 +144,6 @@ struct ContentView: View { store.topBarVariant.height } - private func libraryWidth(in totalWidth: CGFloat) -> CGFloat { - min(libraryMaximumWidth(in: totalWidth), max(libraryMinimumWidth, CGFloat(libraryPaneWidthStorage))) - } - - private func libraryMaximumWidth(in totalWidth: CGFloat) -> CGFloat { - max(libraryMinimumWidth, min(430, totalWidth - WeiBeiSplitView.thickness - minimumContentWidthWithLibrary)) - } - - private var libraryMinimumWidth: CGFloat { - 220 - } - - private var minimumContentWidthWithLibrary: CGFloat { - switch store.layout { - case .documentAgentNotes, .documentNotesAgent: - store.showRightPane ? 780 : 560 - case .documentNotesSplit: - store.showRightPane ? 680 : 560 - case .immersiveConversation, .immersiveWriting: - 720 - case .immersiveReading: - 560 - } - } - - private func libraryResizeHandle(totalWidth: CGFloat) -> some View { - Rectangle() - .fill(Color.clear) - .frame(width: WeiBeiSplitView.thickness) - .overlay { - Rectangle() - .fill(WeiBeiTheme.hairline.opacity(0.34)) - .frame(width: 1) - } - .contentShape(Rectangle()) - .gesture( - DragGesture(minimumDistance: 0) - .onChanged { value in - if libraryDragStartWidth == nil { - libraryDragStartWidth = libraryWidth(in: totalWidth) - } - let startWidth = libraryDragStartWidth ?? libraryWidth(in: totalWidth) - let nextWidth = startWidth + value.translation.width - libraryPaneWidthStorage = Double(min(libraryMaximumWidth(in: totalWidth), max(220, nextWidth))) - } - .onEnded { _ in - libraryDragStartWidth = nil - } - ) - .help(store.ui("拖动调整课程目录宽度", "Drag to resize the course index")) - } - } private struct WindowFullScreenReader: NSViewRepresentable { @@ -588,8 +547,8 @@ private struct UnifiedTopBarView: View { @ViewBuilder private var libraryButton: some View { - topIconButton("sidebar.left", help: store.showLibrary ? store.ui("收起课程目录", "Hide course index") : store.ui("打开课程目录", "Show course index"), active: store.showLibrary) { - withAnimation(WeiBeiMotion.layout) { + topIconButton("sidebar.left", help: store.showLibrary ? store.ui("收起课程抽屉", "Hide course drawer") : store.ui("打开课程抽屉", "Show course drawer"), active: store.showLibrary) { + withAnimation(WeiBeiMotion.panel) { store.toggleLibrary() } } diff --git a/Sources/WeiBei/Views/CourseImmersiveDrawerView.swift b/Sources/WeiBei/Views/CourseImmersiveDrawerView.swift new file mode 100644 index 000000000..81633943f --- /dev/null +++ b/Sources/WeiBei/Views/CourseImmersiveDrawerView.swift @@ -0,0 +1,17 @@ +import SwiftUI + +struct CourseImmersiveDrawerView: View { + let dismiss: () -> Void + + var body: some View { + SidebarView() + .frame(width: 292) + .frame(maxHeight: .infinity, alignment: .top) + .overlay(alignment: .trailing) { + Rectangle() + .fill(WeiBeiTheme.hairline.opacity(0.58)) + .frame(width: 1) + } + .accessibilityAction(.escape, dismiss) + } +} diff --git a/Sources/WeiBei/Views/CourseRelationGraphModel.swift b/Sources/WeiBei/Views/CourseRelationGraphModel.swift new file mode 100644 index 000000000..eef643661 --- /dev/null +++ b/Sources/WeiBei/Views/CourseRelationGraphModel.swift @@ -0,0 +1,399 @@ +import Foundation +import SwiftUI +import WeiBeiCore + +enum CourseRelationPaperScope: Equatable, Identifiable { + case course(UUID) + case all + case unassigned + case unlinked + + var id: String { + switch self { + case .course(let id): + return "course-\(id.uuidString)" + case .all: + return "all" + case .unassigned: + return "unassigned" + case .unlinked: + return "unlinked" + } + } +} + +struct CourseRelationGraphItem: Hashable { + enum Kind: String, Hashable { + case material + case note + } + + var itemID: String + var kind: Kind + var title: String + var subtitle: String + var kindLabel: String + var symbolName: String + + var nodeID: String { + "\(kind.rawValue):\(itemID)" + } + + func matches(_ query: String) -> Bool { + guard !query.isEmpty else { return true } + return title.localizedCaseInsensitiveContains(query) + || subtitle.localizedCaseInsensitiveContains(query) + || kindLabel.localizedCaseInsensitiveContains(query) + || itemID.localizedCaseInsensitiveContains(query) + } +} + +struct CourseRelationGraphNode: Identifiable, Hashable { + var item: CourseRelationGraphItem + var relationCount: Int + var isSelected: Bool + var directlyMatchedSearch: Bool + + var id: String { + item.nodeID + } + + var itemID: String { + item.itemID + } + + var kind: CourseRelationGraphItem.Kind { + item.kind + } +} + +struct CourseRelationGraphEdge: Identifiable, Hashable { + var materialID: String + var noteID: String + var count: Int + + var id: String { + "\(materialID)\u{1F}\(noteID)" + } + + var materialNodeID: String { + "\(CourseRelationGraphItem.Kind.material.rawValue):\(materialID)" + } + + var noteNodeID: String { + "\(CourseRelationGraphItem.Kind.note.rawValue):\(noteID)" + } + + func touches(_ nodeID: String) -> Bool { + materialNodeID == nodeID || noteNodeID == nodeID + } +} + +enum CourseRelationGraphProminence { + case focused + case related + case normal + case mist +} + +struct CourseRelationPlacedNode: Identifiable { + var node: CourseRelationGraphNode + var frame: CGRect + + var id: String { + node.id + } +} + +struct CourseRelationPlacedEdge: Identifiable { + var edge: CourseRelationGraphEdge + var from: CGPoint + var to: CGPoint + + var id: String { + edge.id + } +} + +struct CourseRelationGraphLayout { + var nodes: [CourseRelationPlacedNode] + var edges: [CourseRelationPlacedEdge] + var size: CGSize +} + +struct CourseRelationGraphModel { + var materials: [CourseRelationGraphNode] + var notes: [CourseRelationGraphNode] + var edges: [CourseRelationGraphEdge] + var hiddenNodeCount: Int + var totalNodeCount: Int + var totalEdgeCount: Int + var query: String + var selectedNoteID: String? + var selectedMaterialID: String? + + var visibleNodes: [CourseRelationGraphNode] { + materials + notes + } + + var hasContent: Bool { + !visibleNodes.isEmpty + } + + init( + materials rawMaterials: [CourseRelationGraphItem], + notes rawNotes: [CourseRelationGraphItem], + links: [NoteSourceLink], + query: String, + selectedNoteID: String?, + selectedMaterialID: String?, + showsOnlyUnlinked: Bool, + maxVisibleNodes: Int + ) { + let cleanedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines) + self.query = cleanedQuery + self.selectedNoteID = selectedNoteID + self.selectedMaterialID = selectedMaterialID + + let materialIDs = Set(rawMaterials.map(\.itemID)) + let noteIDs = Set(rawNotes.map(\.itemID)) + let groupedLinks = Dictionary( + grouping: links.filter { + materialIDs.contains($0.sourceItemID) + && noteIDs.contains($0.noteItemID) + && $0.sourceItemID != $0.noteItemID + }, + by: { "\($0.sourceItemID)\u{1F}\($0.noteItemID)" } + ) + + let allEdges = groupedLinks.values.compactMap { group -> CourseRelationGraphEdge? in + guard let first = group.first else { return nil } + return CourseRelationGraphEdge( + materialID: first.sourceItemID, + noteID: first.noteItemID, + count: max(1, group.count) + ) + } + .sorted { + if $0.materialID == $1.materialID { return $0.noteID < $1.noteID } + return $0.materialID < $1.materialID + } + + var materialDegree: [String: Int] = [:] + var noteDegree: [String: Int] = [:] + for edge in allEdges { + materialDegree[edge.materialID, default: 0] += edge.count + noteDegree[edge.noteID, default: 0] += edge.count + } + + let matchedMaterialIDs = Set(rawMaterials.filter { $0.matches(cleanedQuery) }.map(\.itemID)) + let matchedNoteIDs = Set(rawNotes.filter { $0.matches(cleanedQuery) }.map(\.itemID)) + var searchNeighborMaterialIDs = matchedMaterialIDs + var searchNeighborNoteIDs = matchedNoteIDs + if !cleanedQuery.isEmpty { + for edge in allEdges { + if matchedMaterialIDs.contains(edge.materialID) { + searchNeighborNoteIDs.insert(edge.noteID) + } + if matchedNoteIDs.contains(edge.noteID) { + searchNeighborMaterialIDs.insert(edge.materialID) + } + } + } + + var candidateMaterials = rawMaterials.filter { item in + if showsOnlyUnlinked, materialDegree[item.itemID, default: 0] > 0 { return false } + guard !cleanedQuery.isEmpty else { return true } + return searchNeighborMaterialIDs.contains(item.itemID) + } + var candidateNotes = rawNotes.filter { item in + if showsOnlyUnlinked, noteDegree[item.itemID, default: 0] > 0 { return false } + guard !cleanedQuery.isEmpty else { return true } + return searchNeighborNoteIDs.contains(item.itemID) + } + + let allCandidateCount = candidateMaterials.count + candidateNotes.count + if allCandidateCount > maxVisibleNodes { + let materialBudget = max(8, Int(Double(maxVisibleNodes) * 0.48)) + let noteBudget = max(8, maxVisibleNodes - materialBudget) + candidateMaterials = Self.prioritizedItems( + candidateMaterials, + relationDegree: materialDegree, + matchedIDs: matchedMaterialIDs, + focusID: selectedMaterialID, + oneHopIDs: Set(allEdges.filter { $0.noteID == selectedNoteID }.map(\.materialID)), + limit: min(materialBudget, candidateMaterials.count) + ) + candidateNotes = Self.prioritizedItems( + candidateNotes, + relationDegree: noteDegree, + matchedIDs: matchedNoteIDs, + focusID: selectedNoteID, + oneHopIDs: Set(allEdges.filter { $0.materialID == selectedMaterialID }.map(\.noteID)), + limit: min(noteBudget, candidateNotes.count) + ) + } + + let visibleMaterialIDs = Set(candidateMaterials.map(\.itemID)) + let visibleNoteIDs = Set(candidateNotes.map(\.itemID)) + let visibleEdges = showsOnlyUnlinked ? [] : allEdges.filter { + visibleMaterialIDs.contains($0.materialID) && visibleNoteIDs.contains($0.noteID) + } + + materials = candidateMaterials.map { + CourseRelationGraphNode( + item: $0, + relationCount: materialDegree[$0.itemID, default: 0], + isSelected: $0.itemID == selectedMaterialID, + directlyMatchedSearch: matchedMaterialIDs.contains($0.itemID) + ) + } + notes = candidateNotes.map { + CourseRelationGraphNode( + item: $0, + relationCount: noteDegree[$0.itemID, default: 0], + isSelected: $0.itemID == selectedNoteID, + directlyMatchedSearch: matchedNoteIDs.contains($0.itemID) + ) + } + edges = visibleEdges + hiddenNodeCount = max(0, allCandidateCount - materials.count - notes.count) + totalNodeCount = allCandidateCount + totalEdgeCount = allEdges.count + } + + func focusNodeID(hoveredNodeID: String?) -> String? { + if let hoveredNodeID, visibleNodes.contains(where: { $0.id == hoveredNodeID }) { + return hoveredNodeID + } + if let selectedMaterialID, + materials.contains(where: { $0.itemID == selectedMaterialID }) { + return "\(CourseRelationGraphItem.Kind.material.rawValue):\(selectedMaterialID)" + } + if let selectedNoteID, + notes.contains(where: { $0.itemID == selectedNoteID }) { + return "\(CourseRelationGraphItem.Kind.note.rawValue):\(selectedNoteID)" + } + return nil + } + + func nodeProminence(_ node: CourseRelationGraphNode, hoveredNodeID: String?) -> CourseRelationGraphProminence { + guard let focusNodeID = focusNodeID(hoveredNodeID: hoveredNodeID) else { + return node.isSelected ? .focused : .normal + } + if node.id == focusNodeID { return .focused } + if edges.contains(where: { $0.touches(focusNodeID) && $0.touches(node.id) }) { + return .related + } + return .mist + } + + func edgeProminence(_ edge: CourseRelationGraphEdge, hoveredNodeID: String?) -> CourseRelationGraphProminence { + guard let focusNodeID = focusNodeID(hoveredNodeID: hoveredNodeID) else { + return .normal + } + return edge.touches(focusNodeID) ? .focused : .mist + } + + func paperSize(forWidth width: CGFloat, compact: Bool) -> CGSize { + if compact { + let rows = max(materials.count + notes.count, 5) + return CGSize(width: max(width, 360), height: max(520, CGFloat(rows) * 74 + 180)) + } + let sideCount = max(materials.count, notes.count, 4) + return CGSize(width: max(width, 860), height: max(620, CGFloat(sideCount) * 92 + 180)) + } + + func layout(in size: CGSize) -> CourseRelationGraphLayout { + let nodeSize = CGSize(width: min(230, max(190, size.width * 0.22)), height: 74) + let top: CGFloat = 92 + let bottom: CGFloat = 86 + let usableHeight = max(1, size.height - top - bottom) + let materialStep = materials.count <= 1 ? 0 : usableHeight / CGFloat(materials.count - 1) + let noteStep = notes.count <= 1 ? 0 : usableHeight / CGFloat(notes.count - 1) + let materialX = min(max(150, size.width * 0.28), size.width * 0.42) + let noteX = max(min(size.width - 150, size.width * 0.72), size.width * 0.58) + + let materialNodes = materials.enumerated().map { index, node in + let wave = CGFloat((index % 3) - 1) * 16 + let y = top + (materials.count <= 1 ? usableHeight * 0.42 : CGFloat(index) * materialStep) + return CourseRelationPlacedNode( + node: node, + frame: CGRect( + x: materialX - nodeSize.width / 2 + wave, + y: y - nodeSize.height / 2, + width: nodeSize.width, + height: nodeSize.height + ) + ) + } + let noteNodes = notes.enumerated().map { index, node in + let wave = CGFloat((index % 3) - 1) * -16 + let y = top + (notes.count <= 1 ? usableHeight * 0.56 : CGFloat(index) * noteStep) + return CourseRelationPlacedNode( + node: node, + frame: CGRect( + x: noteX - nodeSize.width / 2 + wave, + y: y - nodeSize.height / 2, + width: nodeSize.width, + height: nodeSize.height + ) + ) + } + let placedNodes = materialNodes + noteNodes + let framesByID = Dictionary(uniqueKeysWithValues: placedNodes.map { ($0.id, $0.frame) }) + let placedEdges = edges.compactMap { edge -> CourseRelationPlacedEdge? in + guard let materialFrame = framesByID[edge.materialNodeID], + let noteFrame = framesByID[edge.noteNodeID] + else { return nil } + return CourseRelationPlacedEdge( + edge: edge, + from: CGPoint(x: materialFrame.maxX - 6, y: materialFrame.midY), + to: CGPoint(x: noteFrame.minX + 6, y: noteFrame.midY) + ) + } + return CourseRelationGraphLayout(nodes: placedNodes, edges: placedEdges, size: size) + } + + private static func prioritizedItems( + _ items: [CourseRelationGraphItem], + relationDegree: [String: Int], + matchedIDs: Set, + focusID: String?, + oneHopIDs: Set, + limit: Int + ) -> [CourseRelationGraphItem] { + Array(items.sorted { lhs, rhs in + let lhsScore = priority( + lhs, + relationDegree: relationDegree, + matchedIDs: matchedIDs, + focusID: focusID, + oneHopIDs: oneHopIDs + ) + let rhsScore = priority( + rhs, + relationDegree: relationDegree, + matchedIDs: matchedIDs, + focusID: focusID, + oneHopIDs: oneHopIDs + ) + if lhsScore != rhsScore { return lhsScore > rhsScore } + return lhs.title.localizedStandardCompare(rhs.title) == .orderedAscending + }.prefix(limit)) + } + + private static func priority( + _ item: CourseRelationGraphItem, + relationDegree: [String: Int], + matchedIDs: Set, + focusID: String?, + oneHopIDs: Set + ) -> Int { + var score = relationDegree[item.itemID, default: 0] * 12 + if item.itemID == focusID { score += 10_000 } + if oneHopIDs.contains(item.itemID) { score += 5_000 } + if matchedIDs.contains(item.itemID) { score += 2_500 } + return score + } +} diff --git a/Sources/WeiBei/Views/CourseRelationPaperView.swift b/Sources/WeiBei/Views/CourseRelationPaperView.swift new file mode 100644 index 000000000..f907908c6 --- /dev/null +++ b/Sources/WeiBei/Views/CourseRelationPaperView.swift @@ -0,0 +1,809 @@ +import SwiftUI +import WeiBeiCore + +struct CourseRelationPaperView: View { + @EnvironmentObject private var store: WorkspaceStore + @Binding var lens: CourseRelationLens + let search: String + @Binding var selectedNoteID: String? + @Binding var selectedMaterialID: String? + let isCompact: Bool + + @State private var scope: CourseRelationPaperScope? + @State private var mode: CourseRelationPaperMode = .viewing + @State private var hoveredNodeID: String? + @State private var dropTargetNoteID: String? + + private var effectiveScope: CourseRelationPaperScope { + let candidate = scope + ?? store.activeCourseID.map(CourseRelationPaperScope.course) + ?? .all + if case .course(let courseID) = candidate, + !store.courses.contains(where: { $0.id == courseID }) { + return store.activeCourseID.map(CourseRelationPaperScope.course) ?? .all + } + return candidate + } + + private var graphModel: CourseRelationGraphModel { + CourseRelationGraphModel( + materials: scopedMaterials.map { graphItem(for: $0, kind: .material) }, + notes: scopedNotes.map { graphItem(for: $0, kind: .note) }, + links: store.noteSourceLinks, + query: search, + selectedNoteID: selectedNoteID, + selectedMaterialID: selectedMaterialID, + showsOnlyUnlinked: effectiveScope == .unlinked, + maxVisibleNodes: isCompact ? 36 : 72 + ) + } + + private var scopedMaterials: [StudyItem] { + switch effectiveScope { + case .course(let courseID): + return store.courseMaterials(in: courseID) + case .all: + return store.courseMaterials + case .unassigned: + return store.unassignedCourseMaterials + case .unlinked: + return store.courseMaterials + } + } + + private var scopedNotes: [StudyItem] { + switch effectiveScope { + case .course(let courseID): + return store.courseNotes(in: courseID) + case .all: + return store.courseNotebookItems + case .unassigned: + return store.unassignedCourseNotes + case .unlinked: + return store.courseNotebookItems + } + } + + var body: some View { + VStack(spacing: 0) { + header(model: graphModel) + CourseHairline() + GeometryReader { proxy in + if isCompact || proxy.size.width < 660 { + compactPaper(model: graphModel) + } else { + graphPaper(model: graphModel, availableSize: proxy.size) + } + } + } + .background(WeiBeiTheme.paper.opacity(0.94)) + .animation(WeiBeiMotion.hover, value: hoveredNodeID) + .animation(WeiBeiMotion.panel, value: effectiveScope.id) + .animation(WeiBeiMotion.panel, value: mode) + } + + private func header(model: CourseRelationGraphModel) -> some View { + HStack(spacing: 12) { + VStack(alignment: .leading, spacing: 2) { + Text(store.ui("课程关系台", "Course Relations")) + .font(WeiBeiTypography.brandFont(language: store.interfaceLanguage, size: 17, weight: .semibold)) + .foregroundStyle(WeiBeiTheme.ink) + Text(headerDetail(model: model)) + .font(.system(size: 11)) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .lineLimit(1) + } + + Spacer(minLength: 12) + + scopeMenu + + paperModeButton(.viewing) + paperModeButton(.managing) + } + .padding(.horizontal, 20) + .frame(height: 58) + .background(WeiBeiTheme.paperRaised.opacity(0.32)) + } + + private var scopeMenu: some View { + Menu { + Button(store.ui("全部关系", "All relations")) { + setScope(.all) + } + Button(store.ui("未归属课程", "No course")) { + setScope(.unassigned) + } + Button(store.ui("未建立关系", "Unlinked")) { + setScope(.unlinked) + } + Divider() + ForEach(store.courses) { course in + Button(course.title) { + setScope(.course(course.id)) + } + } + } label: { + HStack(spacing: 6) { + Text(scopeTitle(effectiveScope)) + .font(.system(size: 12, weight: .semibold)) + .lineLimit(1) + Image(systemName: "chevron.down") + .font(.system(size: 9, weight: .bold)) + } + .foregroundStyle(WeiBeiTheme.ink) + .padding(.horizontal, 10) + .frame(height: 28) + .background(WeiBeiTheme.paperInset.opacity(0.34), in: Capsule()) + } + .menuStyle(.borderlessButton) + .fixedSize() + } + + private func paperModeButton(_ candidate: CourseRelationPaperMode) -> some View { + Button { + mode = candidate + } label: { + Text(candidate.label(language: store.interfaceLanguage)) + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(mode == candidate ? WeiBeiTheme.cinnabar : WeiBeiTheme.secondaryInk) + .padding(.horizontal, 10) + .frame(height: 28) + .background( + (mode == candidate ? WeiBeiTheme.cinnabarSoft : WeiBeiTheme.paperInset.opacity(0.20)), + in: Capsule() + ) + } + .buttonStyle(.plain) + } + + private func graphPaper(model: CourseRelationGraphModel, availableSize: CGSize) -> some View { + let paperSize = model.paperSize(forWidth: availableSize.width, compact: false) + let layout = model.layout(in: paperSize) + + return ScrollView([.vertical, .horizontal]) { + ZStack(alignment: .topLeading) { + paperBackground(size: paperSize) + + Canvas { context, _ in + for placedEdge in layout.edges { + let prominence = model.edgeProminence(placedEdge.edge, hoveredNodeID: hoveredNodeID) + var path = Path() + path.move(to: placedEdge.from) + let spread = max(120, abs(placedEdge.to.x - placedEdge.from.x) * 0.45) + path.addCurve( + to: placedEdge.to, + control1: CGPoint(x: placedEdge.from.x + spread, y: placedEdge.from.y), + control2: CGPoint(x: placedEdge.to.x - spread, y: placedEdge.to.y) + ) + let width = edgeWidth(placedEdge.edge, prominence: prominence) + context.stroke( + path, + with: .color(edgeHazeColor(for: placedEdge.edge, prominence: prominence)), + style: StrokeStyle( + lineWidth: width + edgeHazeWidth(prominence), + lineCap: .round, + lineJoin: .round + ) + ) + context.stroke( + path, + with: .color(edgeColor(for: placedEdge.edge, prominence: prominence)), + style: StrokeStyle( + lineWidth: width, + lineCap: .round, + lineJoin: .round + ) + ) + } + } + .frame(width: paperSize.width, height: paperSize.height) + .allowsHitTesting(false) + + paperColumnMark(store.ui("课程资料", "MATERIALS")) + .position(x: min(max(150, paperSize.width * 0.28), paperSize.width * 0.42), y: 38) + + paperColumnMark(store.ui("课程笔记", "NOTES")) + .position(x: max(min(paperSize.width - 150, paperSize.width * 0.72), paperSize.width * 0.58), y: 38) + + ForEach(layout.nodes) { placedNode in + paperNode(placedNode.node, model: model) + .frame(width: placedNode.frame.width, height: placedNode.frame.height) + .position(x: placedNode.frame.midX, y: placedNode.frame.midY) + } + + if model.hiddenNodeCount > 0 { + hiddenCountBadge(model.hiddenNodeCount) + .position(x: paperSize.width / 2, y: paperSize.height - 42) + } + + if !model.hasContent { + CourseEmptyState( + title: store.ui("没有匹配内容", "No matching content"), + detail: store.ui("换个筛选或搜索词,再看看这张关系纸面。", "Try another scope or search query."), + systemImage: "point.3.connected.trianglepath.dotted" + ) + .frame(width: min(420, paperSize.width - 80), height: 260) + .position(x: paperSize.width / 2, y: paperSize.height / 2) + } + } + .frame(width: paperSize.width, height: paperSize.height) + } + } + + private func compactPaper(model: CourseRelationGraphModel) -> some View { + ScrollView { + VStack(alignment: .leading, spacing: 18) { + if !model.hasContent { + CourseEmptyState( + title: store.ui("没有匹配关系", "No matching relations"), + detail: store.ui("换个搜索词,或切到全部关系查看。", "Try another query or switch to all relations."), + systemImage: "point.3.connected.trianglepath.dotted" + ) + .frame(maxWidth: .infinity, minHeight: 320) + } else { + compactSection(title: store.ui("资料", "Materials"), nodes: model.materials, model: model) + compactSection(title: store.ui("笔记", "Notes"), nodes: model.notes, model: model) + if model.hiddenNodeCount > 0 { + hiddenCountBadge(model.hiddenNodeCount) + .frame(maxWidth: .infinity) + } + } + } + .padding(18) + } + .background(WeiBeiTheme.paperRaised.opacity(0.18)) + } + + private func compactSection( + title: String, + nodes: [CourseRelationGraphNode], + model: CourseRelationGraphModel + ) -> some View { + VStack(alignment: .leading, spacing: 10) { + Text(title) + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .padding(.horizontal, 4) + + VStack(spacing: 10) { + ForEach(nodes) { node in + paperNode(node, model: model) + .frame(maxWidth: .infinity, minHeight: 72) + } + } + } + } + + private func paperNode( + _ node: CourseRelationGraphNode, + model: CourseRelationGraphModel + ) -> some View { + let prominence = model.nodeProminence(node, hoveredNodeID: hoveredNodeID) + let isDropTarget = node.kind == .note && dropTargetNoteID == node.itemID + let showsHandle = mode == .managing + && node.kind == .material + && hoveredNodeID == node.id + + return CourseRelationPaperNodeView( + node: node, + prominence: prominence, + accent: nodeAccent(for: node), + mode: mode, + showsHandle: showsHandle, + isDropTarget: isDropTarget, + select: { select(node) }, + open: { open(node) }, + hover: { hovering in hoveredNodeID = hovering ? node.id : (hoveredNodeID == node.id ? nil : hoveredNodeID) } + ) + .contextMenu { + relationMenu(for: node) + } + .modifier(CourseRelationDropModifier( + node: node, + enabled: mode == .managing, + dropTargetNoteID: $dropTargetNoteID, + addLink: addLink(materialID:noteID:) + )) + } + + @ViewBuilder + private func relationMenu(for node: CourseRelationGraphNode) -> some View { + Button(node.kind == .material ? store.ui("打开资料", "Open material") : store.ui("打开笔记", "Open note")) { + open(node) + } + if mode == .managing { + Divider() + if node.kind == .material { + let linkedNotes = linkedNoteItems(for: node.itemID) + if linkedNotes.isEmpty { + Text(store.ui("没有可删除关系", "No links to remove")) + } else { + Menu(store.ui("删除已关联笔记", "Remove linked note")) { + ForEach(linkedNotes) { note in + Button(role: .destructive) { + removeLink(noteID: note.id, materialID: node.itemID) + } label: { + Text(store.displayTitle(for: note)) + } + } + } + } + } else { + let linkedMaterials = linkedMaterialItems(for: node.itemID) + if linkedMaterials.isEmpty { + Text(store.ui("没有可删除关系", "No links to remove")) + } else { + Menu(store.ui("删除已关联资料", "Remove linked material")) { + ForEach(linkedMaterials) { material in + Button(role: .destructive) { + removeLink(noteID: node.itemID, materialID: material.id) + } label: { + Text(store.displayTitle(for: material)) + } + } + } + } + } + } + } + + private func paperColumnMark(_ title: String) -> some View { + Text(title) + .font(WeiBeiTypography.englishBrandFont(size: 9.5, weight: .semibold)) + .tracking(1.2) + .foregroundStyle(WeiBeiTheme.tertiaryInk.opacity(0.72)) + } + + private func paperBackground(size: CGSize) -> some View { + ZStack(alignment: .topLeading) { + Rectangle() + .fill(WeiBeiTheme.paperRaised.opacity(0.22)) + Circle() + .fill(WeiBeiTheme.cinnabarSoft.opacity(0.15)) + .frame(width: 480, height: 480) + .blur(radius: 78) + .offset(x: size.width * 0.12, y: -20) + Circle() + .fill(WeiBeiTheme.paperInset.opacity(0.28)) + .frame(width: 560, height: 560) + .blur(radius: 92) + .offset(x: size.width * 0.48, y: size.height * 0.30) + Circle() + .fill(WeiBeiTheme.secondaryInk.opacity(0.025)) + .frame(width: 440, height: 440) + .blur(radius: 84) + .offset(x: size.width * 0.28, y: size.height * 0.56) + VStack { + Spacer() + Rectangle() + .fill( + LinearGradient( + colors: [.clear, WeiBeiTheme.paper.opacity(0.82)], + startPoint: .top, + endPoint: .bottom + ) + ) + .frame(height: 150) + } + } + .frame(width: size.width, height: size.height) + } + + private func hiddenCountBadge(_ count: Int) -> some View { + Text(store.ui("其余 \(count) 项已收起", "\(count) more items hidden")) + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .padding(.horizontal, 12) + .frame(height: 30) + .background(WeiBeiTheme.paper.opacity(0.82), in: Capsule()) + .overlay( + Capsule() + .stroke(WeiBeiTheme.hairline.opacity(0.72), lineWidth: 1) + ) + } + + private func graphItem(for item: StudyItem, kind: CourseRelationGraphItem.Kind) -> CourseRelationGraphItem { + let membershipIDs = Set(store.courseIDs(for: item.id)) + let courseTitles = store.courses + .filter { membershipIDs.contains($0.id) } + .prefix(2) + .map(\.title) + let membershipLabel = courseTitles.isEmpty + ? item.kind.label(language: store.interfaceLanguage) + : courseTitles.joined(separator: " / ") + return CourseRelationGraphItem( + itemID: item.id, + kind: kind, + title: store.displayTitle(for: item), + subtitle: store.displaySubtitle(for: item), + kindLabel: membershipLabel, + symbolName: kind == .note ? "note.text" : item.kind.systemImage + ) + } + + private func headerDetail(model: CourseRelationGraphModel) -> String { + let scopeText = scopeTitle(effectiveScope) + let relationText = store.ui("\(model.edges.count) 条可见关系", "\(model.edges.count) visible links") + let nodeText = store.ui("\(model.visibleNodes.count) 个节点", "\(model.visibleNodes.count) nodes") + let saveText = mode == .managing + ? " · \(store.ui("更改自动保存", "Changes save automatically"))" + : "" + if model.hiddenNodeCount > 0 { + return "\(scopeText) · \(relationText) · \(nodeText) · \(store.ui("其余 \(model.hiddenNodeCount) 项", "\(model.hiddenNodeCount) hidden"))\(saveText)" + } + return "\(scopeText) · \(relationText) · \(nodeText)\(saveText)" + } + + private func scopeTitle(_ scope: CourseRelationPaperScope) -> String { + switch scope { + case .course(let courseID): + return store.courses.first(where: { $0.id == courseID })?.title ?? store.ui("当前课程", "Active course") + case .all: + return store.ui("全部关系", "All relations") + case .unassigned: + return store.ui("未归属课程", "No course") + case .unlinked: + return store.ui("未建立关系", "Unlinked") + } + } + + private func setScope(_ nextScope: CourseRelationPaperScope) { + scope = nextScope + switch nextScope { + case .course(let courseID): + store.activateCourse(courseID) + case .all, .unassigned, .unlinked: + store.activateCourse(nil) + } + } + + private func select(_ node: CourseRelationGraphNode) { + switch node.kind { + case .material: + lens = .materials + selectedMaterialID = node.itemID + selectedNoteID = nil + case .note: + lens = .notes + selectedNoteID = node.itemID + selectedMaterialID = nil + } + } + + private func open(_ node: CourseRelationGraphNode) { + select(node) + switch node.kind { + case .material: + store.openCourseMaterial(node.itemID) + case .note: + store.openCourseNote(node.itemID) + } + } + + private func addLink(materialID: String, noteID: String) { + guard mode == .managing, + scopedMaterials.contains(where: { $0.id == materialID }), + scopedNotes.contains(where: { $0.id == noteID }) + else { return } + var linkedNoteIDs = Set(store.linkedNoteIDs(for: materialID)) + guard linkedNoteIDs.insert(noteID).inserted else { + selectedMaterialID = materialID + selectedNoteID = noteID + return + } + store.setLinkedNoteIDs(linkedNoteIDs, for: materialID) + selectedMaterialID = materialID + selectedNoteID = noteID + } + + private func removeLink(noteID: String, materialID: String) { + var linkedMaterialIDs = Set(store.linkedCourseSourceIDs(for: noteID)) + linkedMaterialIDs.remove(materialID) + store.setLinkedCourseSourceIDs(linkedMaterialIDs, for: noteID) + selectedMaterialID = materialID + selectedNoteID = noteID + } + + private func linkedNoteItems(for materialID: String) -> [StudyItem] { + let ids = Set(store.linkedNoteIDs(for: materialID)) + return store.courseNotebookItems.filter { ids.contains($0.id) } + } + + private func linkedMaterialItems(for noteID: String) -> [StudyItem] { + let ids = Set(store.linkedCourseSourceIDs(for: noteID)) + return store.courseMaterials.filter { ids.contains($0.id) } + } + + private func nodeAccent(for node: CourseRelationGraphNode) -> Color { + if case .course(let courseID) = effectiveScope, + let course = store.course(withID: courseID) { + return courseAccent(colorIndex: course.colorIndex) + } + guard let courseID = store.courseIDs(for: node.itemID).first, + let course = store.course(withID: courseID) + else { + return node.kind == .note ? WeiBeiTheme.cinnabar : WeiBeiTheme.secondaryInk + } + return courseAccent(colorIndex: course.colorIndex) + } + + private func edgeAccent(for edge: CourseRelationGraphEdge) -> Color { + if case .course(let courseID) = effectiveScope, + let course = store.course(withID: courseID) { + return courseAccent(colorIndex: course.colorIndex) + } + let materialCourseIDs = Set(store.courseIDs(for: edge.materialID)) + let noteCourseIDs = Set(store.courseIDs(for: edge.noteID)) + let sharedCourseIDs = materialCourseIDs.intersection(noteCourseIDs) + let courseID = store.courses.first(where: { sharedCourseIDs.contains($0.id) })?.id + ?? store.courses.first(where: { materialCourseIDs.contains($0.id) })?.id + guard let courseID, + let course = store.course(withID: courseID) + else { + return WeiBeiTheme.secondaryInk + } + return courseAccent(colorIndex: course.colorIndex) + } + + private func courseAccent(colorIndex: Int) -> Color { + switch ((colorIndex % 4) + 4) % 4 { + case 0: + return WeiBeiTheme.cinnabar + case 1: + return WeiBeiTheme.moss + case 2: + return WeiBeiTheme.link + default: + return WeiBeiTheme.secondaryInk + } + } + + private func edgeColor( + for edge: CourseRelationGraphEdge, + prominence: CourseRelationGraphProminence + ) -> Color { + let accent = edgeAccent(for: edge) + switch prominence { + case .focused: + return accent.opacity(0.70) + case .related: + return accent.opacity(0.46) + case .normal: + return accent.opacity(0.20) + case .mist: + return accent.opacity(0.040) + } + } + + private func edgeHazeColor( + for edge: CourseRelationGraphEdge, + prominence: CourseRelationGraphProminence + ) -> Color { + let accent = edgeAccent(for: edge) + switch prominence { + case .focused: + return accent.opacity(0.075) + case .related: + return accent.opacity(0.050) + case .normal: + return accent.opacity(0.028) + case .mist: + return accent.opacity(0.012) + } + } + + private func edgeWidth(_ edge: CourseRelationGraphEdge, prominence: CourseRelationGraphProminence) -> CGFloat { + let base = CGFloat(min(9, 4 + max(0, edge.count - 1) * 2)) + switch prominence { + case .focused: + return base + 7 + case .related: + return base + 3 + case .normal: + return base + case .mist: + return max(1.2, base * 0.38) + } + } + + private func edgeHazeWidth(_ prominence: CourseRelationGraphProminence) -> CGFloat { + switch prominence { + case .focused: + return 18 + case .related: + return 13 + case .normal: + return 9 + case .mist: + return 5 + } + } +} + +private enum CourseRelationPaperMode: Equatable { + case viewing + case managing + + func label(language: WeiBeiInterfaceLanguage) -> String { + switch self { + case .viewing: + return language.text("查看", "View") + case .managing: + return language.text("管理", "Manage") + } + } +} + +private struct CourseRelationPaperNodeView: View { + @EnvironmentObject private var store: WorkspaceStore + let node: CourseRelationGraphNode + let prominence: CourseRelationGraphProminence + let accent: Color + let mode: CourseRelationPaperMode + let showsHandle: Bool + let isDropTarget: Bool + let select: () -> Void + let open: () -> Void + let hover: (Bool) -> Void + + var body: some View { + HStack(spacing: 9) { + Capsule() + .fill(markerColor) + .frame(width: prominence == .focused ? 3 : 2, height: 30) + + Button(action: select) { + HStack(spacing: 9) { + Image(systemName: node.item.symbolName) + .font(.system(size: 15, weight: .semibold)) + .foregroundStyle(iconColor) + .frame(width: 20) + + VStack(alignment: .leading, spacing: 4) { + Text(node.item.title) + .font(.system(size: 13.5, weight: .semibold)) + .foregroundStyle(WeiBeiTheme.ink) + .lineLimit(1) + Text(detailText) + .font(.system(size: 11)) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .lineLimit(1) + } + + Spacer(minLength: 6) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + + if showsHandle { + handle + } else { + Button(action: open) { + Image(systemName: "arrow.up.forward") + .font(.system(size: 10.5, weight: .semibold)) + .foregroundStyle(WeiBeiTheme.tertiaryInk) + .frame(width: 22, height: 22) + } + .buttonStyle(.plain) + .opacity(prominence == .mist ? 0.12 : 0.72) + } + } + .padding(.horizontal, 8) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .contentShape(Rectangle()) + .opacity(opacity) + .background(nodeBackground, in: RoundedRectangle(cornerRadius: 11, style: .continuous)) + .overlay(alignment: .bottomLeading) { + Rectangle() + .fill(underlineColor) + .frame(width: prominence == .focused ? 76 : 42, height: isDropTarget ? 2 : 1) + .padding(.leading, 12) + } + .onHover(perform: hover) + } + + private var detailText: String { + let countText = node.relationCount == 0 ? "0" : "\(node.relationCount)" + return "\(node.item.kindLabel) · \(countText)" + } + + private var handle: some View { + HStack(spacing: 5) { + Image(systemName: "smallcircle.filled.circle") + .font(.system(size: 12, weight: .bold)) + Text(store.ui("拖到笔记", "Drag to note")) + .font(.system(size: 10.5, weight: .semibold)) + } + .foregroundStyle(WeiBeiTheme.onCinnabar) + .padding(.horizontal, 8) + .frame(height: 26) + .background(WeiBeiTheme.cinnabar.opacity(0.86), in: Capsule()) + .draggable(node.itemID) + } + + private var iconColor: Color { + prominence == .mist ? WeiBeiTheme.tertiaryInk : accent + } + + private var nodeBackground: Color { + if isDropTarget { return accent.opacity(0.14) } + switch prominence { + case .focused: + return accent.opacity(0.080) + case .related: + return accent.opacity(0.042) + case .normal: + return WeiBeiTheme.paperRaised.opacity(0.10) + case .mist: + return Color.clear + } + } + + private var markerColor: Color { + if isDropTarget { return accent.opacity(0.92) } + switch prominence { + case .focused: + return accent.opacity(0.88) + case .related: + return accent.opacity(0.48) + case .normal: + return WeiBeiTheme.hairline.opacity(0.78) + case .mist: + return WeiBeiTheme.hairline.opacity(0.20) + } + } + + private var underlineColor: Color { + if isDropTarget { return accent.opacity(0.82) } + switch prominence { + case .focused: + return accent.opacity(0.54) + case .related: + return accent.opacity(0.26) + case .normal: + return WeiBeiTheme.hairline.opacity(0.48) + case .mist: + return WeiBeiTheme.hairline.opacity(0.12) + } + } + + private var opacity: Double { + switch prominence { + case .focused: + return 1 + case .related: + return 0.92 + case .normal: + return 0.82 + case .mist: + return 0.28 + } + } +} + +private struct CourseRelationDropModifier: ViewModifier { + let node: CourseRelationGraphNode + let enabled: Bool + @Binding var dropTargetNoteID: String? + let addLink: (String, String) -> Void + + func body(content: Content) -> some View { + if enabled, node.kind == .note { + content.dropDestination( + for: String.self, + action: { materialIDs, _ in + guard let materialID = materialIDs.first else { return false } + addLink(materialID, node.itemID) + return true + }, + isTargeted: { targeted in + dropTargetNoteID = targeted ? node.itemID : nil + } + ) + } else { + content + } + } +} diff --git a/Sources/WeiBei/Views/CourseRelationsView.swift b/Sources/WeiBei/Views/CourseRelationsView.swift index 9fe2e1d6d..c4e6e3a3c 100644 --- a/Sources/WeiBei/Views/CourseRelationsView.swift +++ b/Sources/WeiBei/Views/CourseRelationsView.swift @@ -1,471 +1,19 @@ -import Foundation import SwiftUI -import WeiBeiCore struct CourseRelationsView: View { - @EnvironmentObject private var store: WorkspaceStore @Binding var lens: CourseRelationLens let search: String @Binding var selectedNoteID: String? @Binding var selectedMaterialID: String? let isCompact: Bool - private var filteredNotes: [StudyItem] { - filtered(store.courseNotebookItems) - } - - private var filteredMaterials: [StudyItem] { - filtered(store.courseMaterials) - } - var body: some View { - VStack(spacing: 0) { - HStack(spacing: 12) { - Text(store.ui("查看", "View")) - .font(.system(size: 11, weight: .medium)) - .foregroundStyle(WeiBeiTheme.secondaryInk) - - Menu { - ForEach(CourseRelationLens.allCases) { candidate in - Button(candidate.label(language: store.interfaceLanguage)) { - withAnimation(WeiBeiMotion.panel) { - lens = candidate - } - } - } - } label: { - HStack(spacing: 5) { - Text(lens.label(language: store.interfaceLanguage)) - .font(.system(size: 12, weight: .semibold)) - Image(systemName: "chevron.down") - .font(.system(size: 9, weight: .semibold)) - } - .foregroundStyle(WeiBeiTheme.ink) - } - .menuStyle(.borderlessButton) - .fixedSize() - - Spacer() - - Text(store.ui( - "先查看长期关联,需要调整时再进入管理。", - "Review durable links first. Manage them only when needed." - )) - .font(.system(size: 11)) - .foregroundStyle(WeiBeiTheme.tertiaryInk) - } - .padding(.horizontal, 22) - .frame(height: 40) - .background(WeiBeiTheme.paperRaised.opacity(0.28)) - - CourseHairline() - - if lens == .notes { - relationSplit( - list: noteList, - detail: AnyView(NoteRelationDetail(noteID: resolvedNoteID)) - ) - } else { - relationSplit( - list: materialList, - detail: AnyView(MaterialRelationDetail(materialID: resolvedMaterialID)) - ) - } - } - .onAppear(perform: ensureSelections) - .onChange(of: lens) { _, _ in ensureSelections() } - .onChange(of: store.importedItems) { _, _ in ensureSelections() } - } - - private var resolvedNoteID: String? { - if let selectedNoteID, filteredNotes.contains(where: { $0.id == selectedNoteID }) { - return selectedNoteID - } - return filteredNotes.first?.id - } - - private var resolvedMaterialID: String? { - if let selectedMaterialID, filteredMaterials.contains(where: { $0.id == selectedMaterialID }) { - return selectedMaterialID - } - return filteredMaterials.first?.id - } - - private var noteList: AnyView { - AnyView( - CourseEntityList( - items: filteredNotes, - selectedID: resolvedNoteID, - emptyTitle: store.ui("还没有课程笔记", "No course notes yet"), - emptyDetail: store.ui("点顶部“加入”,新建或导入 Markdown 笔记。", "Use Add above to create or import Markdown notes."), - status: { item in - let count = store.linkedCourseSourceIDs(for: item.id).count - return count == 0 - ? store.ui("尚未关联资料", "No material links") - : store.ui("\(count) 份资料", "\(count) materials") - }, - detail: { item in courseFolderLabel(item, store: store) }, - select: { selectedNoteID = $0 } - ) + CourseRelationPaperView( + lens: $lens, + search: search, + selectedNoteID: $selectedNoteID, + selectedMaterialID: $selectedMaterialID, + isCompact: isCompact ) } - - private var materialList: AnyView { - AnyView( - CourseEntityList( - items: filteredMaterials, - selectedID: resolvedMaterialID, - emptyTitle: store.ui("还没有课程资料", "No course materials yet"), - emptyDetail: store.ui("点顶部“导入”,选择 PDF、HTML、Markdown、文本或文件夹。", "Use Import for PDF, HTML, Markdown, text, or folders."), - status: { item in - let count = store.linkedNoteCount(for: item.id) - return count == 0 - ? store.ui("尚未关联笔记", "No note links") - : store.ui("\(count) 份笔记", "\(count) notes") - }, - detail: { item in - if let location = store.studyLocation(for: item.id) { - return courseLocationLabel(location, store: store) - } - return courseFolderLabel(item, store: store) - }, - select: { selectedMaterialID = $0 } - ) - ) - } - - @ViewBuilder - private func relationSplit(list: AnyView, detail: AnyView) -> some View { - if isCompact { - VStack(spacing: 0) { - list - CourseHairline() - detail.frame(minHeight: 360) - } - } else { - HStack(spacing: 0) { - list - .frame(width: 350) - Rectangle() - .fill(WeiBeiTheme.hairline.opacity(0.72)) - .frame(width: 1) - detail - .frame(maxWidth: .infinity, maxHeight: .infinity) - } - } - } - - private func ensureSelections() { - if selectedNoteID == nil || !store.courseNotebookItems.contains(where: { $0.id == selectedNoteID }) { - selectedNoteID = store.courseNotebookItems.first?.id - } - if selectedMaterialID == nil || !store.courseMaterials.contains(where: { $0.id == selectedMaterialID }) { - selectedMaterialID = store.courseMaterials.first?.id - } - } - - private func filtered(_ items: [StudyItem]) -> [StudyItem] { - let cleaned = search.trimmingCharacters(in: .whitespacesAndNewlines) - guard !cleaned.isEmpty else { return items } - return items.filter { item in - store.displayTitle(for: item).localizedCaseInsensitiveContains(cleaned) - || store.displaySubtitle(for: item).localizedCaseInsensitiveContains(cleaned) - || (item.url?.path.localizedCaseInsensitiveContains(cleaned) == true) - } - } -} - -struct CourseEntityList: View { - @EnvironmentObject private var store: WorkspaceStore - let items: [StudyItem] - let selectedID: String? - let emptyTitle: String - let emptyDetail: String - let status: (StudyItem) -> String - let detail: (StudyItem) -> String - let select: (String) -> Void - - var body: some View { - if items.isEmpty { - CourseEmptyState(title: emptyTitle, detail: emptyDetail, systemImage: "tray") - .frame(maxWidth: .infinity, maxHeight: .infinity) - .padding(24) - } else { - ScrollView { - LazyVStack(spacing: 0) { - ForEach(items) { item in - CourseWorkspaceRow( - icon: item.kind.systemImage, - title: store.displayTitle(for: item), - detail: detail(item), - status: status(item), - selected: item.id == selectedID - ) { - select(item.id) - } - CourseHairline() - } - } - .padding(.vertical, 6) - } - .background(WeiBeiTheme.paperRaised.opacity(0.22)) - } - } -} - -struct NoteRelationDetail: View { - @EnvironmentObject private var store: WorkspaceStore - let noteID: String? - @State private var isManagingLinks = false - - private var note: StudyItem? { - noteID.flatMap(store.item(withID:)) - } - - private var linkedSourceIDs: Set { - Set(noteID.map(store.linkedCourseSourceIDs(for:)) ?? []) - } - - var body: some View { - Group { - if let note, let noteID { - VStack(spacing: 0) { - CourseRelationDetailHeader( - mark: "NOTE", - title: store.displayTitle(for: note), - detail: store.ui( - "\(linkedSourceIDs.count) 份长期关联资料", - "\(linkedSourceIDs.count) linked materials" - ), - manageTitle: isManagingLinks - ? store.ui("完成", "Done") - : store.ui("管理关联", "Manage links"), - manage: { - withAnimation(WeiBeiMotion.reveal) { - isManagingLinks.toggle() - } - }, - openTitle: store.ui("打开笔记", "Open note"), - open: { store.openCourseNote(noteID) } - ) - - CourseHairline() - - ScrollView { - VStack(alignment: .leading, spacing: 20) { - Text(store.ui( - isManagingLinks - ? "选择长期支撑这份笔记的资料。更改会自动保存。" - : "这些资料会长期跟随这份笔记,打开其他文稿不会改变它们。", - isManagingLinks - ? "Choose the materials that support this note. Changes save automatically." - : "These materials stay with this note even when another document is open." - )) - .font(.system(size: 12)) - .foregroundStyle(WeiBeiTheme.secondaryInk) - - if store.courseMaterials.isEmpty { - CourseEmptyState( - title: store.ui("还没有可关联资料", "No materials to link"), - detail: store.ui("点课程首页顶部“导入”添加资料或文件夹。", "Use Import above to add materials or folders."), - systemImage: "books.vertical" - ) - } else if isManagingLinks { - VStack(spacing: 0) { - ForEach(store.courseMaterials) { material in - RelationSelectionRow( - item: material, - checked: linkedSourceIDs.contains(material.id), - detail: courseFolderLabel(material, store: store) - ) { - store.setLinkedCourseSourceIDs( - toggled(material.id, in: linkedSourceIDs), - for: noteID - ) - } - CourseHairline() - } - } - } else if linkedSourceIDs.isEmpty { - CourseEmptyState( - title: store.ui("还没有关联资料", "No linked materials"), - detail: store.ui("需要时点“管理关联”,为这份笔记选择长期资料。", "Use Manage links when this note needs supporting materials."), - systemImage: "link" - ) - } else { - VStack(spacing: 0) { - ForEach(store.courseMaterials.filter { linkedSourceIDs.contains($0.id) }) { material in - CourseLinkedItemRow( - item: material, - detail: courseFolderLabel(material, store: store) - ) - CourseHairline() - } - } - } - } - .padding(24) - .frame(maxWidth: 820, alignment: .leading) - .frame(maxWidth: .infinity, alignment: .topLeading) - } - - if isManagingLinks { - CourseHairline() - relationFooter( - countTitle: store.ui( - "已关联 \(linkedSourceIDs.count) 份资料", - "\(linkedSourceIDs.count) linked materials" - ), - statusTitle: store.ui("更改自动保存", "Changes save automatically"), - errorTitle: store.workspaceSaveError, - retryTitle: store.ui("重试保存", "Retry save"), - retry: { _ = store.retryWorkspaceSave() } - ) - } - } - } else { - CourseEmptyState( - title: store.ui("选择一份笔记", "Select a note"), - detail: store.ui("在左侧选择笔记后,可以查看它的长期资料关系。", "Choose a note to review its material relationships."), - systemImage: "note.text" - ) - .frame(maxWidth: .infinity, maxHeight: .infinity) - } - } - .onChange(of: noteID) { _, _ in isManagingLinks = false } - } - -} - -struct MaterialRelationDetail: View { - @EnvironmentObject private var store: WorkspaceStore - let materialID: String? - @State private var isManagingLinks = false - - private var material: StudyItem? { - materialID.flatMap(store.item(withID:)) - } - - private var linkedNoteIDs: Set { - Set(materialID.map(store.linkedNoteIDs(for:)) ?? []) - } - - var body: some View { - Group { - if let material, let materialID { - VStack(spacing: 0) { - CourseRelationDetailHeader( - mark: courseMaterialMark(material.kind), - title: store.displayTitle(for: material), - detail: materialDetail(material), - manageTitle: isManagingLinks - ? store.ui("完成", "Done") - : store.ui("管理关联", "Manage links"), - manage: { - withAnimation(WeiBeiMotion.reveal) { - isManagingLinks.toggle() - } - }, - openTitle: store.ui("打开资料", "Open material"), - open: { store.openCourseMaterial(materialID) } - ) - - CourseHairline() - - ScrollView { - VStack(alignment: .leading, spacing: 20) { - Text(store.ui( - isManagingLinks - ? "选择会长期使用这份资料的笔记。更改不会切换当前文稿。" - : "这些笔记长期使用这份资料,查看关系不会切换当前文稿。", - isManagingLinks - ? "Choose the notes that use this material. Changes do not switch the open document." - : "These notes use this material. Reviewing links does not switch the open document." - )) - .font(.system(size: 12)) - .foregroundStyle(WeiBeiTheme.secondaryInk) - - if store.courseNotebookItems.isEmpty { - CourseEmptyState( - title: store.ui("还没有课程笔记", "No course notes yet"), - detail: store.ui("先新建或导入笔记,再回来建立关系。", "Create or import a note before linking this material."), - systemImage: "note.text" - ) - } else if isManagingLinks { - VStack(spacing: 0) { - ForEach(store.courseNotebookItems) { note in - RelationSelectionRow( - item: note, - checked: linkedNoteIDs.contains(note.id), - detail: store.ui( - "\(store.linkedCourseSourceIDs(for: note.id).count) 份资料", - "\(store.linkedCourseSourceIDs(for: note.id).count) materials" - ) - ) { - store.setLinkedNoteIDs( - toggled(note.id, in: linkedNoteIDs), - for: materialID - ) - } - CourseHairline() - } - } - } else if linkedNoteIDs.isEmpty { - CourseEmptyState( - title: store.ui("还没有关联笔记", "No linked notes"), - detail: store.ui("需要时点“管理关联”,选择会使用这份资料的笔记。", "Use Manage links when notes should use this material."), - systemImage: "link" - ) - } else { - VStack(spacing: 0) { - ForEach(store.courseNotebookItems.filter { linkedNoteIDs.contains($0.id) }) { note in - CourseLinkedItemRow( - item: note, - detail: store.ui( - "\(store.linkedCourseSourceIDs(for: note.id).count) 份资料", - "\(store.linkedCourseSourceIDs(for: note.id).count) materials" - ) - ) - CourseHairline() - } - } - } - } - .padding(24) - .frame(maxWidth: 820, alignment: .leading) - .frame(maxWidth: .infinity, alignment: .topLeading) - } - - if isManagingLinks { - CourseHairline() - relationFooter( - countTitle: store.ui( - "已关联 \(linkedNoteIDs.count) 份笔记", - "\(linkedNoteIDs.count) linked notes" - ), - statusTitle: store.ui("更改自动保存", "Changes save automatically"), - errorTitle: store.workspaceSaveError, - retryTitle: store.ui("重试保存", "Retry save"), - retry: { _ = store.retryWorkspaceSave() } - ) - } - } - } else { - CourseEmptyState( - title: store.ui("选择一份资料", "Select a material"), - detail: store.ui("在左侧选择资料后,可以查看阅读位置和关联笔记。", "Choose a material to inspect its reading position and note links."), - systemImage: "books.vertical" - ) - .frame(maxWidth: .infinity, maxHeight: .infinity) - } - } - .onChange(of: materialID) { _, _ in isManagingLinks = false } - } - - private func materialDetail(_ material: StudyItem) -> String { - if let location = store.studyLocation(for: material.id) { - return "\(courseLocationLabel(location, store: store)) · \(courseRelativeDate(location.lastStudiedAt, language: store.interfaceLanguage))" - } - return store.ui("尚无阅读位置", "No reading position") - } } diff --git a/Sources/WeiBei/Views/CourseWorkspaceView.swift b/Sources/WeiBei/Views/CourseWorkspaceView.swift index 4ec349979..2c7f72773 100644 --- a/Sources/WeiBei/Views/CourseWorkspaceView.swift +++ b/Sources/WeiBei/Views/CourseWorkspaceView.swift @@ -14,7 +14,7 @@ enum CourseWorkspacePage: String, CaseIterable, Identifiable { case .overview: language.text("概览", "Overview") case .relations: - language.text("课程内容", "Course Content") + language.text("关系台", "Relations") case .records: language.text("学习记录", "Learning Records") } diff --git a/Sources/WeiBei/Views/SidebarView.swift b/Sources/WeiBei/Views/SidebarView.swift index 9b1b93d43..51bccbd9f 100644 --- a/Sources/WeiBei/Views/SidebarView.swift +++ b/Sources/WeiBei/Views/SidebarView.swift @@ -4,6 +4,11 @@ import WeiBeiCore struct SidebarView: View { @EnvironmentObject private var store: WorkspaceStore @FocusState private var librarySearchFocused: Bool + @State private var showsNewCourseSheet = false + @State private var newCourseTitle = "" + @State private var courseToRename: Course? + @State private var renameCourseTitle = "" + @State private var coursePendingDeletion: Course? var body: some View { VStack(spacing: 0) { @@ -28,12 +33,12 @@ struct SidebarView: View { .help(store.ui("打开课程首页", "Open course home")) } Spacer() - Button { store.importFilesFromPanel() } label: { + Button { showsNewCourseSheet = true } label: { Image(systemName: "plus") } .buttonStyle(WeiBeiIconButtonStyle()) - .accessibilityLabel(Text(store.ui("导入资料", "Import material"))) - .help(store.ui("导入资料", "Import material")) + .accessibilityLabel(Text(store.ui("新建课程", "Create course"))) + .help(store.ui("新建课程", "Create course")) } .padding(.horizontal, 16) .padding(.top, 14) @@ -63,9 +68,15 @@ struct SidebarView: View { ScrollView(showsIndicators: false) { LazyVStack(alignment: .leading, spacing: 14) { - sidebarSection(title: store.ui("内置示例", "Built-in Examples"), items: store.sampleItems) - sidebarSection(title: store.ui("课程资料", "Course Materials"), items: importedMaterialItems) - sidebarSection(title: store.ui("课程笔记", "Course Notes"), items: notebookItems) + courseSection + if let activeCourseID = store.activeCourseID { + sidebarSection(title: store.ui("本课资料", "Course Materials"), items: materials(in: activeCourseID)) + sidebarSection(title: store.ui("本课笔记", "Course Notes"), items: notes(in: activeCourseID)) + } else { + sidebarSection(title: store.ui("独立资料", "Unassigned Materials"), items: unassignedMaterials) + sidebarSection(title: store.ui("全部笔记", "All Notes"), items: notebookItems) + } + sidebarSection(title: store.ui("内置示例", "Built-in Examples"), items: sampleItems) } .padding(.horizontal, 10) .padding(.vertical, 10) @@ -86,16 +97,124 @@ struct SidebarView: View { .onAppear { librarySearchFocused = store.focusedPane == .library } + .sheet(isPresented: $showsNewCourseSheet) { + SidebarCourseNameSheet( + heading: store.ui("新建课程", "Create Course"), + detail: store.ui("课程只负责归拢资料与笔记,不会移动原文件。", "Courses organize materials and notes without moving files."), + confirmTitle: store.ui("创建", "Create"), + title: $newCourseTitle, + cancel: closeNewCourseSheet, + confirm: createCourse + ) + .environmentObject(store) + } + .sheet(item: $courseToRename) { course in + SidebarCourseNameSheet( + heading: store.ui("重命名课程", "Rename Course"), + detail: store.ui("只修改显示名称,资料与笔记保持原位。", "Only the display title changes; files stay where they are."), + confirmTitle: store.ui("保存", "Save"), + title: $renameCourseTitle, + cancel: { courseToRename = nil }, + confirm: { renameCourse(course) } + ) + .environmentObject(store) + } + .confirmationDialog( + store.ui("删除课程?", "Delete course?"), + isPresented: Binding( + get: { coursePendingDeletion != nil }, + set: { if !$0 { coursePendingDeletion = nil } } + ), + titleVisibility: .visible, + presenting: coursePendingDeletion + ) { course in + Button(store.ui("删除“\(course.title)”", "Delete “\(course.title)”"), role: .destructive) { + store.deleteCourse(course.id) + coursePendingDeletion = nil + } + Button(store.ui("取消", "Cancel"), role: .cancel) { + coursePendingDeletion = nil + } + } message: { _ in + Text(store.ui("原文件不会删除,只会回到未归属状态。", "Files remain intact and become unassigned.")) + } + } + + private var filteredItemIDs: Set { + Set(store.filteredItems.map(\.id)) } - private var importedMaterialItems: [StudyItem] { - store.filteredItems.filter { !$0.isSample && !$0.isNotebookNote } + private var filteredCourses: [Course] { + let query = store.librarySearch.trimmingCharacters(in: .whitespacesAndNewlines) + guard !query.isEmpty else { return store.courses } + return store.courses.filter { course in + course.title.localizedCaseInsensitiveContains(query) + || store.courseItems(in: course.id).contains { filteredItemIDs.contains($0.id) } + } + } + + private var sampleItems: [StudyItem] { + store.sampleItems.filter { filteredItemIDs.contains($0.id) } + } + + private var unassignedMaterials: [StudyItem] { + store.unassignedCourseMaterials.filter { filteredItemIDs.contains($0.id) } } private var notebookItems: [StudyItem] { store.filteredItems.filter(\.isNotebookNote) } + private func materials(in courseID: UUID) -> [StudyItem] { + store.courseMaterials(in: courseID).filter { filteredItemIDs.contains($0.id) } + } + + private func notes(in courseID: UUID) -> [StudyItem] { + store.courseNotes(in: courseID).filter { filteredItemIDs.contains($0.id) } + } + + private var courseSection: some View { + VStack(alignment: .leading, spacing: 6) { + Text(store.ui("课程", "Courses")) + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(WeiBeiTheme.tertiaryInk) + .padding(.horizontal, 8) + + if filteredCourses.isEmpty { + Text(store.ui("还没有匹配课程", "No matching courses")) + .font(.system(size: 12)) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .padding(.horizontal, 9) + .frame(height: 40) + } else { + ForEach(filteredCourses) { course in + Button { + withAnimation(WeiBeiMotion.panel) { + store.activateCourse(store.activeCourseID == course.id ? nil : course.id) + } + } label: { + SidebarCourseRow( + course: course, + materialCount: store.courseMaterials(in: course.id).count, + noteCount: store.courseNotes(in: course.id).count, + selected: store.activeCourseID == course.id + ) + } + .buttonStyle(.plain) + .contextMenu { + Button(store.ui("重命名课程", "Rename course")) { + renameCourseTitle = course.title + courseToRename = course + } + Button(store.ui("删除课程", "Delete course"), role: .destructive) { + coursePendingDeletion = course + } + } + } + } + } + } + @ViewBuilder private func sidebarSection(title: String, items: [StudyItem]) -> some View { if !items.isEmpty { @@ -112,7 +231,7 @@ struct SidebarView: View { } else { Button { withAnimation(WeiBeiMotion.panel) { - store.select(itemID: item.id) + open(item) } } label: { LibraryRow(item: item, selected: item.isNotebookNote ? store.activeNotebookItemID == item.id : store.selectedItemID == item.id) @@ -124,6 +243,24 @@ struct SidebarView: View { store.promptRenameNotebookNote(itemID: item.id) } } + if !item.isSample, !store.courses.isEmpty { + Menu(store.ui("课程归属", "Course membership")) { + ForEach(store.courses) { course in + let assigned = store.courseIDs(for: item.id).contains(course.id) + Button { + var courseIDs = Set(store.courseIDs(for: item.id)) + if assigned { + courseIDs.remove(course.id) + } else { + courseIDs.insert(course.id) + } + store.setCourseIDs(courseIDs, for: item.id) + } label: { + Label(course.title, systemImage: assigned ? "checkmark" : "circle") + } + } + } + } } .transition(WeiBeiTransition.message) } @@ -131,6 +268,146 @@ struct SidebarView: View { } } } + + private func open(_ item: StudyItem) { + if item.isSample { + store.select(itemID: item.id) + store.showLibrary = false + } else if item.isNotebookNote { + store.openCourseNote(item.id) + } else { + store.openCourseMaterial(item.id) + } + } + + private func closeNewCourseSheet() { + showsNewCourseSheet = false + newCourseTitle = "" + } + + private func createCourse() { + guard let courseID = store.createCourse(title: newCourseTitle) else { return } + store.activateCourse(courseID) + closeNewCourseSheet() + } + + private func renameCourse(_ course: Course) { + store.renameCourse(course.id, title: renameCourseTitle) + courseToRename = nil + renameCourseTitle = "" + } +} + +private struct SidebarCourseRow: View { + @EnvironmentObject private var store: WorkspaceStore + let course: Course + let materialCount: Int + let noteCount: Int + let selected: Bool + @State private var hovering = false + + var body: some View { + HStack(spacing: 10) { + Image(systemName: "book.closed") + .foregroundStyle(accent.opacity(selected || hovering ? 1 : 0.78)) + .frame(width: 18) + .scaleEffect(selected || hovering ? 1.08 : 1) + + VStack(alignment: .leading, spacing: 2) { + Text(course.title) + .lineLimit(1) + .foregroundStyle(WeiBeiTheme.ink) + Text(store.ui("\(materialCount) 份资料 · \(noteCount) 份笔记", "\(materialCount) materials · \(noteCount) notes")) + .font(.caption) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .lineLimit(1) + } + } + .padding(.horizontal, 9) + .frame(height: 48) + .frame(maxWidth: .infinity, alignment: .leading) + .background(rowBackground) + .offset(x: selected || hovering ? 2 : 0) + .clipShape(RoundedRectangle(cornerRadius: 8)) + .overlay(alignment: .leading) { + if selected { + Capsule() + .fill(accent.opacity(0.72)) + .frame(width: 3, height: 24) + .padding(.leading, 2) + } + } + .weibeiHoverLift(active: hovering && !selected, amount: 1) + .onHover { hovering = $0 } + .animation(WeiBeiMotion.micro, value: selected) + .animation(WeiBeiMotion.hover, value: hovering) + } + + private var rowBackground: Color { + if selected { return WeiBeiTheme.paperInset.opacity(0.70) } + if hovering { return WeiBeiTheme.paperInset.opacity(0.30) } + return .clear + } + + private var accent: Color { + switch ((course.colorIndex % 4) + 4) % 4 { + case 0: + return WeiBeiTheme.cinnabar + case 1: + return WeiBeiTheme.moss + case 2: + return WeiBeiTheme.link + default: + return WeiBeiTheme.secondaryInk + } + } +} + +private struct SidebarCourseNameSheet: View { + @EnvironmentObject private var store: WorkspaceStore + let heading: String + let detail: String + let confirmTitle: String + @Binding var title: String + let cancel: () -> Void + let confirm: () -> Void + @FocusState private var titleFocused: Bool + + var body: some View { + VStack(alignment: .leading, spacing: 18) { + VStack(alignment: .leading, spacing: 5) { + Text(heading) + .font(WeiBeiTypography.brandFont(language: store.interfaceLanguage, size: 21, weight: .semibold)) + Text(detail) + .font(.system(size: 12)) + .foregroundStyle(WeiBeiTheme.secondaryInk) + } + + TextField(store.ui("课程名", "Course title"), text: $title) + .textFieldStyle(.plain) + .focused($titleFocused) + .font(.system(size: 13)) + .foregroundColor(WeiBeiTheme.ink) + .weibeiInputSurface(active: titleFocused, height: 32) + .onSubmit(confirm) + + HStack { + Spacer() + Button(store.ui("取消", "Cancel"), action: cancel) + .buttonStyle(WeiBeiTextActionButtonStyle()) + .keyboardShortcut(.cancelAction) + Button(confirmTitle, action: confirm) + .buttonStyle(WeiBeiTextActionButtonStyle(active: true)) + .keyboardShortcut(.defaultAction) + .disabled(title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + } + .padding(22) + .frame(width: 360) + .background(WeiBeiTheme.paper) + .foregroundStyle(WeiBeiTheme.ink) + .onAppear { titleFocused = true } + } } private struct NotebookRenameRow: View { diff --git a/Sources/WeiBeiCore/CourseLibraryModels.swift b/Sources/WeiBeiCore/CourseLibraryModels.swift new file mode 100644 index 000000000..fdc551d21 --- /dev/null +++ b/Sources/WeiBeiCore/CourseLibraryModels.swift @@ -0,0 +1,117 @@ +import Foundation + +public struct Course: Identifiable, Codable, Hashable, Sendable { + public var id: UUID + public var title: String + public var colorIndex: Int + public var sourceRootPath: String? + public var createdAt: Date + public var updatedAt: Date + + public init( + id: UUID = UUID(), + title: String, + colorIndex: Int = 0, + sourceRootPath: String? = nil, + createdAt: Date = Date(), + updatedAt: Date = Date() + ) { + self.id = id + self.title = title + self.colorIndex = colorIndex + self.sourceRootPath = sourceRootPath + self.createdAt = createdAt + self.updatedAt = updatedAt + } +} + +public struct CourseItemMembership: Identifiable, Codable, Hashable, Sendable { + public var id: UUID + public var courseID: UUID + public var itemID: String + public var createdAt: Date + + public init( + id: UUID = UUID(), + courseID: UUID, + itemID: String, + createdAt: Date = Date() + ) { + self.id = id + self.courseID = courseID + self.itemID = itemID + self.createdAt = createdAt + } +} + +public struct CourseItemMemberships: Sendable { + public private(set) var values: [CourseItemMembership] + + public init(values: [CourseItemMembership] = []) { + self.values = Self.normalized(values) + } + + public func courseIDs(for itemID: String) -> [UUID] { + values + .lazy + .filter { $0.itemID == itemID } + .map(\.courseID) + } + + public func itemIDs(in courseID: UUID) -> [String] { + values + .lazy + .filter { $0.courseID == courseID } + .map(\.itemID) + } + + public mutating func assign(itemIDs: Set, to courseID: UUID) { + let existingItemIDs = Set(values.lazy.filter { $0.courseID == courseID }.map(\.itemID)) + for itemID in itemIDs.subtracting(existingItemIDs).sorted() { + values.append(CourseItemMembership(courseID: courseID, itemID: itemID)) + } + values = Self.normalized(values) + } + + public mutating func replaceCourses(for itemID: String, courseIDs: Set) { + let retained = values.filter { $0.itemID != itemID || courseIDs.contains($0.courseID) } + let existingCourseIDs = Set(retained.lazy.filter { $0.itemID == itemID }.map(\.courseID)) + let additions = courseIDs.subtracting(existingCourseIDs).sorted { $0.uuidString < $1.uuidString }.map { + CourseItemMembership(courseID: $0, itemID: itemID) + } + values = Self.normalized(retained + additions) + } + + public mutating func removeCourse(_ courseID: UUID) { + values.removeAll { $0.courseID == courseID } + } + + public mutating func removeItem(_ itemID: String) { + values.removeAll { $0.itemID == itemID } + } + + @discardableResult + public mutating func sanitize(validCourseIDs: Set, validItemIDs: Set) -> Bool { + let next = Self.normalized(values.filter { + validCourseIDs.contains($0.courseID) && validItemIDs.contains($0.itemID) + }) + guard next != values else { return false } + values = next + return true + } + + private static func normalized(_ values: [CourseItemMembership]) -> [CourseItemMembership] { + var oldestByPair: [String: CourseItemMembership] = [:] + for value in values { + let key = "\(value.courseID.uuidString)|\(value.itemID)" + if let existing = oldestByPair[key], existing.createdAt <= value.createdAt { + continue + } + oldestByPair[key] = value + } + return oldestByPair.values.sorted { + if $0.createdAt != $1.createdAt { return $0.createdAt < $1.createdAt } + return $0.id.uuidString < $1.id.uuidString + } + } +} diff --git a/Sources/WeiBeiCore/WorkspaceModels.swift b/Sources/WeiBeiCore/WorkspaceModels.swift index 4ff2be426..a0b72b867 100644 --- a/Sources/WeiBeiCore/WorkspaceModels.swift +++ b/Sources/WeiBeiCore/WorkspaceModels.swift @@ -880,6 +880,9 @@ public struct PersistedWorkspace: Codable { public var noteBackingContentDigestsByItemID: [String: String]? public var selectedItemID: String? public var activeNotebookItemID: String? + public var courses: [Course]? + public var courseItemMemberships: [CourseItemMembership]? + public var activeCourseID: UUID? public var noteSourceLinks: [NoteSourceLink]? public var noteSourceLinksMigrationVersion: Int? public var studyLocationsByItemID: [String: StudyLocation]? @@ -902,13 +905,47 @@ public struct PersistedWorkspace: Codable { public var adaptImportedDocumentColors: Bool? public var interfaceLanguageRaw: String? - public init(importedItems: [StudyItem] = [], notesByItemID: [String: String] = [:], pendingNoteWritesByItemID: [String: PendingNoteWriteState]? = nil, noteBackingContentDigestsByItemID: [String: String]? = nil, selectedItemID: String? = nil, activeNotebookItemID: String? = nil, noteSourceLinks: [NoteSourceLink]? = nil, noteSourceLinksMigrationVersion: Int? = nil, studyLocationsByItemID: [String: StudyLocation]? = nil, learningMemoryEntries: [LearningMemoryEntry]? = nil, learningMemoryRevision: UInt64? = nil, studySessions: [StudySession]? = nil, activeStudySessionID: UUID? = nil, modelName: String? = nil, workspaceLayout: WorkspaceLayout? = nil, threePaneOrder: [WorkspacePaneRole]? = nil, agentSurface: AgentSurface? = nil, noteRenderMode: NoteRenderMode? = nil, showLibrary: Bool? = nil, showReader: Bool? = nil, showAgent: Bool? = nil, showNotes: Bool? = nil, showRightPane: Bool? = nil, showDailyInspiration: Bool? = nil, appearanceModeRaw: String? = nil, adaptImportedDocumentColors: Bool? = nil, interfaceLanguageRaw: String? = nil) { + public init( + importedItems: [StudyItem] = [], + notesByItemID: [String: String] = [:], + pendingNoteWritesByItemID: [String: PendingNoteWriteState]? = nil, + noteBackingContentDigestsByItemID: [String: String]? = nil, + selectedItemID: String? = nil, + activeNotebookItemID: String? = nil, + courses: [Course]? = nil, + courseItemMemberships: [CourseItemMembership]? = nil, + activeCourseID: UUID? = nil, + noteSourceLinks: [NoteSourceLink]? = nil, + noteSourceLinksMigrationVersion: Int? = nil, + studyLocationsByItemID: [String: StudyLocation]? = nil, + learningMemoryEntries: [LearningMemoryEntry]? = nil, + learningMemoryRevision: UInt64? = nil, + studySessions: [StudySession]? = nil, + activeStudySessionID: UUID? = nil, + modelName: String? = nil, + workspaceLayout: WorkspaceLayout? = nil, + threePaneOrder: [WorkspacePaneRole]? = nil, + agentSurface: AgentSurface? = nil, + noteRenderMode: NoteRenderMode? = nil, + showLibrary: Bool? = nil, + showReader: Bool? = nil, + showAgent: Bool? = nil, + showNotes: Bool? = nil, + showRightPane: Bool? = nil, + showDailyInspiration: Bool? = nil, + appearanceModeRaw: String? = nil, + adaptImportedDocumentColors: Bool? = nil, + interfaceLanguageRaw: String? = nil + ) { self.importedItems = importedItems self.notesByItemID = notesByItemID self.pendingNoteWritesByItemID = pendingNoteWritesByItemID self.noteBackingContentDigestsByItemID = noteBackingContentDigestsByItemID self.selectedItemID = selectedItemID self.activeNotebookItemID = activeNotebookItemID + self.courses = courses + self.courseItemMemberships = courseItemMemberships + self.activeCourseID = activeCourseID self.noteSourceLinks = noteSourceLinks self.noteSourceLinksMigrationVersion = noteSourceLinksMigrationVersion self.studyLocationsByItemID = studyLocationsByItemID diff --git a/Sources/WeiBeiSelfCheck/main.swift b/Sources/WeiBeiSelfCheck/main.swift index 3ec52e76a..413d922a4 100644 --- a/Sources/WeiBeiSelfCheck/main.swift +++ b/Sources/WeiBeiSelfCheck/main.swift @@ -1464,8 +1464,11 @@ expect(contentViewSource.contains("dividerFill.setFill()") && contentViewSource.contains("rect.minY + 14") && !contentViewSource.contains("NSColor.clear.setFill()"), "native split divider uses the current paper surface instead of a transparent hard gap") expect(contentViewSource.contains("override func layout()"), "native split applies saved positions after first real layout") -expect(contentViewSource.contains("libraryResizeHandle"), "library pane keeps SwiftUI resize handle") -expect(contentViewSource.contains("minimumContentWidthWithLibrary"), "library leaves readable width for the workspace") +expect(contentViewSource.contains("CourseImmersiveDrawerView") + && contentViewSource.contains("LayoutContentView()") + && contentViewSource.contains("ZStack(alignment: .leading)") + && !contentViewSource.contains("libraryResizeHandle") + && !contentViewSource.contains("minimumContentWidthWithLibrary"), "course drawer temporarily covers the living workspace instead of resizing or rebuilding it") expect(contentViewSource.contains("private let railWidth = ContentRailMetrics.railOnlyWidth") && contentRailSource.contains("static let snapThreshold = ContentRailPolicy.snapThreshold") && contentRailSource.contains("static let readableWidth = ContentRailPolicy.readableWidth") @@ -1486,7 +1489,7 @@ expect(contentViewSource.contains("store.toggleLibrary()") && contentViewSource.contains("sidebar.left") && contentViewSource.contains("private var libraryButton: some View") && contentViewSource.contains("active: store.showLibrary") - && contentViewSource.contains("store.showLibrary ? store.ui(\"收起课程目录\"") + && contentViewSource.contains("store.showLibrary ? store.ui(\"收起课程抽屉\"") && !contentViewSource.contains("恢复课程目录") && !contentViewSource.contains(".opacity(isImmersiveLayout ? 0.45 : 1)"), "immersive top bar keeps a clear stateful library chooser instead of dimming a live control") if let leftControlsStart = contentViewSource.range(of: "private var leftPrimaryControls: some View")?.lowerBound, @@ -1675,9 +1678,15 @@ expect(notesAgentSource.contains("private func refreshSourcePresentation(in text expect(!sidebarSource.contains("commandPalettePresented.toggle()") && !sidebarSource.contains("Label(\"命令\", systemImage: \"command\")"), "sidebar does not duplicate the command palette entry") expect(sidebarSource.contains("ScrollView(showsIndicators: false)"), "sidebar hides the heavy system scroll indicator that reads as a divider") expect(sidebarSource.contains("sidebarSection(title: store.ui(\"内置示例\"") - && sidebarSource.contains("sidebarSection(title: store.ui(\"课程资料\"") - && sidebarSource.contains("sidebarSection(title: store.ui(\"课程笔记\""), "course index separates built-in examples, course materials, and course notes") -expect(sidebarSource.contains("!$0.isSample && !$0.isNotebookNote") && sidebarSource.contains("store.filteredItems.filter(\\.isNotebookNote)"), "sidebar material list excludes notebook notes without hiding notes") + && sidebarSource.contains("courseSection") + && sidebarSource.contains("sidebarSection(title: store.ui(\"本课资料\"") + && sidebarSource.contains("sidebarSection(title: store.ui(\"本课笔记\"") + && sidebarSource.contains("sidebarSection(title: store.ui(\"独立资料\"") + && sidebarSource.contains("sidebarSection(title: store.ui(\"全部笔记\""), "course drawer keeps the original course-index styling while adding course, active-course, unassigned, note, and sample levels") +expect(sidebarSource.contains("store.unassignedCourseMaterials") + && sidebarSource.contains("store.courseMaterials(in: courseID)") + && sidebarSource.contains("store.courseNotes(in: courseID)") + && sidebarSource.contains("store.filteredItems.filter(\\.isNotebookNote)"), "course drawer filters materials and notes by real membership without hiding notebook notes") expect(sidebarSource.contains("item.isNotebookNote ? store.activeNotebookItemID == item.id : store.selectedItemID == item.id"), "sidebar highlights the active notebook note separately from the selected reader material") expect(sidebarSource.contains(".contextMenu") && sidebarSource.contains("Button(store.ui(\"重命名笔记\"") @@ -2287,6 +2296,9 @@ let courseWorkspaceSourceNames = [ "CourseWorkspaceView.swift", "CourseOverviewView.swift", "CourseRelationsView.swift", + "CourseRelationPaperView.swift", + "CourseRelationGraphModel.swift", + "CourseImmersiveDrawerView.swift", "CourseRecordsView.swift", "CourseWorkspaceComponents.swift", ] @@ -2326,6 +2338,15 @@ expect(courseWorkspaceSource.contains("case overview") && courseWorkspaceSource.contains("尚无阅读位置") && !courseWorkspaceSource.contains("已消化") && !courseWorkspaceSource.contains("消化率"), "course workspace exposes overview, relationships, and learning records using only evidence-backed status language") +expect(courseWorkspaceSource.contains("CourseRelationPaperView(") + && courseWorkspaceSource.contains("CourseImmersiveDrawerView") + && courseWorkspaceSource.contains(".frame(width: 292)") + && courseWorkspaceSource.contains("未归属课程") + && courseWorkspaceSource.contains("未建立关系") + && courseWorkspaceSource.contains("showsOnlyUnlinked") + && courseWorkspaceSource.contains("edgeHazeColor") + && courseWorkspaceSource.contains("nodeProminence") + && courseWorkspaceSource.contains("private struct CourseRelationPaperNodeView: View"), "course drawer and relation paper share explicit course membership while keeping course assignment separate from note-material links") expect(courseWorkspaceSource.contains("更改自动保存") && courseWorkspaceSource.contains("showRecords(session.id)") && courseWorkspaceSource.contains("courseMaterialsWithoutReadingPosition.first?.id") @@ -2356,10 +2377,10 @@ expect(workspaceStoreSource.contains("func presentCourseWorkspace(") && sidebarSource.contains("store.presentCourseWorkspace()") && linkedSourcesSource.contains("store.presentCourseWorkspace(.notes"), "course workspace is reachable from top-level commands and note relationships, while explicit open actions own navigation") expect(workspaceStoreSource.contains("scenario == \"course-index-navigation-flow\"") + && workspaceStoreSource.contains("course-material-unassigned") + && workspaceStoreSource.contains("activeCourseID = nil") && workspaceStoreSource.contains("showLibrary = true") - && workspaceStoreSource.contains("showReader = false") - && workspaceStoreSource.contains("showAgent = false") - && workspaceStoreSource.contains("showNotes = false"), "course-index verification owns a quiet real-window state for the unified navigation path") + && workspaceStoreSource.contains("CourseItemMemberships()"), "course-drawer verification uses isolated real courses, shared items, and one genuinely unassigned material") expect(workspaceStoreSource.contains("noteSourceRelationIndex = NoteSourceRelationIndex(links: noteSourceLinks)") && workspaceStoreSource.contains("func linkedNoteCount(for sourceItemID: String)") && workspaceStoreSource.contains("verifyCourseOverlayContinuity(itemID:") @@ -2696,8 +2717,9 @@ if let updateSelectionStart = workspaceStoreSource.range(of: "func updateSelecti expect(false, "updateSelection animation policy source is readable") } expect(workspaceStoreSource.contains("let itemChanged = selectedItemID != itemID") && workspaceStoreSource.contains("clearUnpinnedFloatingSelection(keepContext: false)"), "selecting a different item clears the old selection context") -expect(workspaceStoreSource.contains("func toggleLibrary() {\n recordNavigationPoint()\n showLibrary.toggle()\n clearUnpinnedFloatingSelection()") - && workspaceStoreSource.contains("func toggleRightPane() {\n guard layout.hasCollapsibleRightPane else { return }\n recordNavigationPoint()\n showRightPane.toggle()\n clearUnpinnedFloatingSelection()"), "pane visibility changes record navigation and invalidate stale floating selection anchors") +expect(workspaceStoreSource.contains("func toggleLibrary() {\n showLibrary.toggle()\n clearUnpinnedFloatingSelection()") + && !workspaceStoreSource.contains("func toggleLibrary() {\n recordNavigationPoint()") + && workspaceStoreSource.contains("func toggleRightPane() {\n guard layout.hasCollapsibleRightPane else { return }\n recordNavigationPoint()\n showRightPane.toggle()\n clearUnpinnedFloatingSelection()"), "the transient course drawer stays out of navigation history while durable pane visibility still records navigation") expect(workspaceStoreSource.contains("collapseSelectionFloatIntoConversationIfVisible()\n focusedPane = pane") && workspaceStoreSource.contains("private func collapseSelectionFloatIntoConversationIfVisible()") && workspaceStoreSource.contains("guard isConversationSurfaceVisible, agentSurface == .selectionFloat else { return }") @@ -2708,8 +2730,9 @@ expect(workspaceStoreSource.contains("focus(showRightPane ? rightPaneRevealFocus && workspaceStoreSource.contains("return normalizedThreePaneOrder.last?.focus ?? .notes") && workspaceStoreSource.contains("case .documentNotesAgent, .immersiveConversation:\n return .agent"), "right-pane reveal focuses the visible pane by current role order instead of legacy fixed layout names") expect(workspaceStoreSource.contains("func revealLibrary()") - && workspaceStoreSource.contains("if !showLibrary {\n recordNavigationPoint()\n clearUnpinnedFloatingSelection()\n }") - && workspaceStoreSource.contains("focus(.library)\n save()"), "library reveal uses the shared durable state path") + && workspaceStoreSource.contains("if !showLibrary {\n clearUnpinnedFloatingSelection()\n }") + && workspaceStoreSource.contains("showLibrary = true\n focus(.library)") + && !workspaceStoreSource.contains("focus(.library)\n save()"), "library reveal uses transient in-memory state without writing the workspace") expect(workspaceStoreSource.contains("layout == .immersiveReading || layout == .immersiveWriting") && workspaceStoreSource.contains("agentSurface = .cornerPanel") && !workspaceStoreSource.contains("layout = .immersiveConversation\n showLibrary = false\n showRightPane = true"), "agent focus in immersive layouts opens an overlay instead of switching layout") if let setLayoutStart = workspaceStoreSource.range(of: "func setLayout(_ layout: WorkspaceLayout)")?.lowerBound, let setAgentSurfaceStart = workspaceStoreSource.range(of: "func setAgentSurface")?.lowerBound { @@ -3801,15 +3824,58 @@ expect(courseSummary.materialCount == 3 && courseSummary.studySessionCount == 1 && courseSummary.unresolvedConfusionCount == 2, "course workspace summary reports only durable facts from the imported course") -let persisted = PersistedWorkspace(noteSourceLinks: [oldestLink], noteSourceLinksMigrationVersion: 1, threePaneOrder: [.agent, .reader, .notes], noteRenderMode: .preview, showLibrary: false, showReader: false, showAgent: true, showNotes: false, showRightPane: true, showDailyInspiration: false, adaptImportedDocumentColors: false) +let courseA = Course( + id: UUID(uuidString: "11111111-1111-1111-1111-111111111111")!, + title: "货币金融学", + colorIndex: 0, + sourceRootPath: "/Courses/Money" +) +let courseB = Course( + id: UUID(uuidString: "22222222-2222-2222-2222-222222222222")!, + title: "经济思想史", + colorIndex: 1, + sourceRootPath: "/Courses/History" +) +var courseMemberships = CourseItemMemberships() +courseMemberships.assign(itemIDs: Set(["material-a", "note-a"]), to: courseA.id) +courseMemberships.assign(itemIDs: Set(["material-a", "material-b"]), to: courseB.id) +expect(Set(courseMemberships.courseIDs(for: "material-a")) == Set([courseA.id, courseB.id]) + && Set(courseMemberships.itemIDs(in: courseA.id)) == Set(["material-a", "note-a"]) + && Set(courseMemberships.itemIDs(in: courseB.id)) == Set(["material-a", "material-b"]), "one item can belong to multiple real courses without duplicating the item") +courseMemberships.replaceCourses(for: "note-a", courseIDs: Set([courseB.id])) +expect(courseMemberships.courseIDs(for: "note-a") == [courseB.id] + && !courseMemberships.itemIDs(in: courseA.id).contains("note-a"), "changing course membership removes only the replaced item-course pair") + +let persisted = PersistedWorkspace( + courses: [courseA, courseB], + courseItemMemberships: courseMemberships.values, + activeCourseID: courseB.id, + noteSourceLinks: [oldestLink], + noteSourceLinksMigrationVersion: 1, + threePaneOrder: [.agent, .reader, .notes], + noteRenderMode: .preview, + showLibrary: false, + showReader: false, + showAgent: true, + showNotes: false, + showRightPane: true, + showDailyInspiration: false, + adaptImportedDocumentColors: false +) let restored = try JSONDecoder().decode(PersistedWorkspace.self, from: try JSONEncoder().encode(persisted)) expect(restored.showLibrary == false && restored.showReader == false && restored.showAgent == true && restored.showNotes == false && restored.showRightPane == true, "pane visibility state persists") +expect(restored.courses == [courseA, courseB] + && restored.courseItemMemberships == courseMemberships.values + && restored.activeCourseID == courseB.id, "courses, many-to-many membership, and the active course persist together") expect(restored.showDailyInspiration == false, "daily inspiration can be disabled and restored from workspace persistence") let reenabledInspiration = try JSONDecoder().decode(PersistedWorkspace.self, from: try JSONEncoder().encode(PersistedWorkspace(showDailyInspiration: true))) expect(reenabledInspiration.showDailyInspiration == true, "daily inspiration can be re-enabled and restored from workspace persistence") let legacyWorkspace = try JSONDecoder().decode(PersistedWorkspace.self, from: Data(#"{"importedItems":[],"notesByItemID":{}}"#.utf8)) expect(legacyWorkspace.showDailyInspiration == nil - && workspaceStoreSource.contains("showDailyInspiration = snapshot.showDailyInspiration ?? true"), "workspace snapshots created before daily inspiration remain decodable and default to enabled") + && legacyWorkspace.courses == nil + && legacyWorkspace.courseItemMemberships == nil + && legacyWorkspace.activeCourseID == nil + && workspaceStoreSource.contains("showDailyInspiration = snapshot.showDailyInspiration ?? true"), "older workspace snapshots remain decodable without inventing a fake course") expect(restored.adaptImportedDocumentColors == false && workspaceStoreSource.contains("adaptImportedDocumentColors = snapshot.adaptImportedDocumentColors ?? true") && workspaceStoreSource.contains("adaptImportedDocumentColors: adaptImportedDocumentColors"), "imported-document color adaptation persists while old workspaces default to adapted reading") From 816b0304d8692b1a7a3a8de2a55843d4ffde26b4 Mon Sep 17 00:00:00 2001 From: taekchef Date: Fri, 17 Jul 2026 06:49:35 +0800 Subject: [PATCH 3/4] feat: refine course relations interaction --- Docs/course-library-architecture.md | 15 +- Sources/WeiBei/App/WeiBeiApp.swift | 2 +- Sources/WeiBei/Stores/WorkspaceStore.swift | 10 +- Sources/WeiBei/Views/CommandPaletteView.swift | 2 +- Sources/WeiBei/Views/ContentView.swift | 20 +- .../Views/CourseRelationGraphModel.swift | 49 +- .../Views/CourseRelationPaperView.swift | 601 +++++++++++++++--- .../WeiBei/Views/CourseWorkspaceView.swift | 63 +- Sources/WeiBei/Views/LinkedSourcesView.swift | 2 +- Sources/WeiBei/Views/SidebarView.swift | 333 ++++++---- Sources/WeiBeiSelfCheck/main.swift | 53 +- 11 files changed, 851 insertions(+), 299 deletions(-) diff --git a/Docs/course-library-architecture.md b/Docs/course-library-architecture.md index 98c1482a3..394c3527b 100644 --- a/Docs/course-library-architecture.md +++ b/Docs/course-library-architecture.md @@ -20,17 +20,19 @@ ### 小抽屉 - 直接复用原课程目录的标题、搜索框、行样式与纸面质感,只把打开方式改为覆盖在稳定工作区上方、宽度保持原来约 292pt 的临时抽屉。 -- 根层显示课程、独立资料、全部笔记和原有内置示例;课程首页继续作为关系管理入口。 -- 进入课程后只深入一层,显示课程资料与课程笔记。 +- 根层显示课程、独立资料、独立笔记和原有内置示例;“资料关系台”作为明确的长期关系管理入口。 +- 点击课程后,资料与笔记直接嵌套展开在课程行下方,并用缩进、分组标题和纵向引导线表达父子层级。 - 打开资料或笔记不重建稳定面板,并立即收起抽屉;点击遮罩、按下 Esc 或再次点击入口也可关闭。 ### 大关系台 - 使用一张连续纸面,不使用左右硬侧边栏。 - 文件和笔记是独立节点;关系带直接连接节点。 -- 单条关系以克制的低亮度带状曲线呈现,并叠加纸雾;不伪造汇总关系。 +- 大窗口不再保留含糊的“概览”;它只管理资料与笔记的长期多对多关系,课程归属仍在小抽屉管理。 +- 单条关系以克制的低亮度带状曲线呈现,并叠加纸雾;同一节点的多条关系在端点扇出、汇流,不伪造汇总关系。 - 选中一端时,关联节点和关系带一起显影,其余内容退入纸雾。 -- 查看模式不显示连接把手;管理模式悬停节点后才显示把手,并支持建立或删除关系。 +- 查看模式不显示连接点;管理模式在资料和笔记节点旁显示加号,依次点击两侧加号即可建立关系,同时保留拖拽和删除关系。 +- 纸面支持减号、百分比、加号、适合窗口和触控板捏合缩放;缩放后仍可双向滚动浏览。 - 可切换课程、全部、未归属和未关联范围;高密度时优先保留选中项、搜索命中项、一跳节点和高关系节点,并明确显示隐藏数量。 ## 共享文件占用 @@ -55,6 +57,7 @@ ## 已完成验证 - 兼容 macOS 15.4 SDK 的完整构建通过。 -- `WeiBeiSelfCheck` 完整自检通过,覆盖旧数据兼容、多课程归属、抽屉挂载和关系台聚焦逻辑。 +- `WeiBeiSelfCheck` 完整自检通过,覆盖旧数据兼容、多课程归属、原抽屉动画、树状展开、点击连线、缩放回位和关系带扇出。 - 隔离工作区课程流程验证通过:资料与笔记跳转、重启后持久化、稳定面板不重建均通过。 -- 已用隔离演示数据完成原样式课程抽屉和 20 节点、17 关系的真实窗口截图。 +- 画中画真实操作验证通过:点击“复习问题”与“期末复习笔记”的加号后,可见关系从 17 条准确增加到 18 条,磁盘只新增一条对应关系。 +- 画中画缩放验证通过:从 100% 缩小到 80%,再点“适合”回到 62% 并回到纸面起点;课程抽屉也已真实展开到资料、笔记两层。 diff --git a/Sources/WeiBei/App/WeiBeiApp.swift b/Sources/WeiBei/App/WeiBeiApp.swift index a4545a443..8727701f1 100644 --- a/Sources/WeiBei/App/WeiBeiApp.swift +++ b/Sources/WeiBei/App/WeiBeiApp.swift @@ -97,7 +97,7 @@ struct WeiBeiApp: App { .windowStyle(.hiddenTitleBar) .commands { CommandMenu(store.appDisplayName) { - Button(store.ui("打开课程首页", "Open Course Home")) { store.presentCourseWorkspace() } + Button(store.ui("打开资料关系台", "Open Course Relations")) { store.presentCourseWorkspace() } .keyboardShortcut("0") Divider() diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index 36543adae..c9d4c2a90 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -160,7 +160,7 @@ enum PaneToggleContinuityVerifier { } enum CourseWorkspaceDestination: String, CaseIterable, Sendable { - case overview + case relations case materials case notes case sessions @@ -244,7 +244,7 @@ final class WorkspaceStore: ObservableObject { @Published var interfaceLanguage: WeiBeiInterfaceLanguage = .chinese @Published var topBarVariant: TopBarVariant = TopBarVariant(rawValue: UserDefaults.standard.string(forKey: "topBarVariant") ?? "") ?? .balanced @Published var courseWorkspacePresented = false - @Published private(set) var courseWorkspaceDestination: CourseWorkspaceDestination = .overview + @Published private(set) var courseWorkspaceDestination: CourseWorkspaceDestination = .relations @Published private(set) var courseWorkspaceTargetItemID: String? @Published var courseFolderImportDraft: CourseFolderImportDraft? @Published private var backNavigationStack: [NavigationSnapshot] = [] @@ -1285,7 +1285,7 @@ final class WorkspaceStore: ObservableObject { } func presentCourseWorkspace( - _ destination: CourseWorkspaceDestination = .overview, + _ destination: CourseWorkspaceDestination = .relations, selecting itemID: String? = nil ) { persistCurrentNote() @@ -4570,7 +4570,7 @@ final class WorkspaceStore: ObservableObject { } else if requestedPage == "sessions" { presentCourseWorkspace(.sessions, selecting: activeSession.id.uuidString) } else { - presentCourseWorkspace(.overview) + presentCourseWorkspace(.relations) } writeCourseWorkspaceVerificationReport( name: "course-workspace-overview-report.json", @@ -4679,7 +4679,7 @@ final class WorkspaceStore: ObservableObject { let baselineOrder = threePaneOrder let baselineLocation = selectedItemID.flatMap { studyLocationsByItemID[$0] } PaneToggleContinuityVerifier.beginMeasurement() - presentCourseWorkspace(.overview) + presentCourseWorkspace(.relations) try? await Task.sleep(nanoseconds: 500_000_000) dismissCourseWorkspace() try? await Task.sleep(nanoseconds: 500_000_000) diff --git a/Sources/WeiBei/Views/CommandPaletteView.swift b/Sources/WeiBei/Views/CommandPaletteView.swift index 2c70c8d9d..4646708aa 100644 --- a/Sources/WeiBei/Views/CommandPaletteView.swift +++ b/Sources/WeiBei/Views/CommandPaletteView.swift @@ -10,7 +10,7 @@ struct CommandPaletteView: View { private var commands: [PaletteCommand] { var items = [ - PaletteCommand(title: store.ui("打开课程首页", "Open Course Home"), shortcut: "⌘0", animation: WeiBeiMotion.panel) { store.presentCourseWorkspace() }, + PaletteCommand(title: store.ui("打开资料关系台", "Open Course Relations"), shortcut: "⌘0", animation: WeiBeiMotion.panel) { store.presentCourseWorkspace() }, PaletteCommand(title: store.ui("打开资料", "Open Material"), shortcut: "⌘O") { store.importFilesFromPanel() }, PaletteCommand(title: store.ui("新建空白笔记", "New Blank Note"), shortcut: "⌘N") { store.promptCreateBlankNotebookNote() }, PaletteCommand(title: store.ui("聚焦课程目录", "Focus Course Index"), shortcut: "⌘1", animation: WeiBeiMotion.layout) { store.focus(.library) }, diff --git a/Sources/WeiBei/Views/ContentView.swift b/Sources/WeiBei/Views/ContentView.swift index 8f87726fe..5cc5e10d5 100644 --- a/Sources/WeiBei/Views/ContentView.swift +++ b/Sources/WeiBei/Views/ContentView.swift @@ -25,27 +25,28 @@ struct ContentView: View { .background(WeiBeiTheme.paper) .animation(WeiBeiMotion.layout, value: store.layout) - if store.showLibrary { - ZStack(alignment: .leading) { + ZStack(alignment: .leading) { + if store.showLibrary { WeiBeiTheme.ink.opacity(0.035) .contentShape(Rectangle()) .onTapGesture { - withAnimation(WeiBeiMotion.panel) { + withAnimation(WeiBeiMotion.layout) { store.toggleLibrary() } } + .transition(.opacity) CourseImmersiveDrawerView { - withAnimation(WeiBeiMotion.panel) { + withAnimation(WeiBeiMotion.layout) { store.toggleLibrary() } } - .transition(.move(edge: .leading).combined(with: .opacity)) + .transition(WeiBeiTransition.sidePanel) } - .frame(maxWidth: .infinity, maxHeight: .infinity) - .transition(.opacity) - .zIndex(35) } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .allowsHitTesting(store.showLibrary) + .zIndex(35) if store.commandPalettePresented { CommandPaletteView() @@ -110,6 +111,7 @@ struct ContentView: View { focusedPane = store.focusedPane } .animation(WeiBeiMotion.appearance, value: store.appearanceMode) + .animation(WeiBeiMotion.layout, value: store.showLibrary) .animation(WeiBeiMotion.panel, value: store.courseWorkspacePresented) } @@ -548,7 +550,7 @@ private struct UnifiedTopBarView: View { @ViewBuilder private var libraryButton: some View { topIconButton("sidebar.left", help: store.showLibrary ? store.ui("收起课程抽屉", "Hide course drawer") : store.ui("打开课程抽屉", "Show course drawer"), active: store.showLibrary) { - withAnimation(WeiBeiMotion.panel) { + withAnimation(WeiBeiMotion.layout) { store.toggleLibrary() } } diff --git a/Sources/WeiBei/Views/CourseRelationGraphModel.swift b/Sources/WeiBei/Views/CourseRelationGraphModel.swift index eef643661..e6bbc761b 100644 --- a/Sources/WeiBei/Views/CourseRelationGraphModel.swift +++ b/Sources/WeiBei/Views/CourseRelationGraphModel.swift @@ -89,7 +89,7 @@ struct CourseRelationGraphEdge: Identifiable, Hashable { } } -enum CourseRelationGraphProminence { +enum CourseRelationGraphProminence: Equatable { case focused case related case normal @@ -342,19 +342,62 @@ struct CourseRelationGraphModel { } let placedNodes = materialNodes + noteNodes let framesByID = Dictionary(uniqueKeysWithValues: placedNodes.map { ($0.id, $0.frame) }) + let materialFanOffsets = Self.fanOffsets( + groupedEdges: Dictionary(grouping: edges, by: { $0.materialID }), + oppositeNodeID: { $0.noteNodeID }, + framesByID: framesByID + ) + let noteFanOffsets = Self.fanOffsets( + groupedEdges: Dictionary(grouping: edges, by: { $0.noteID }), + oppositeNodeID: { $0.materialNodeID }, + framesByID: framesByID + ) let placedEdges = edges.compactMap { edge -> CourseRelationPlacedEdge? in guard let materialFrame = framesByID[edge.materialNodeID], let noteFrame = framesByID[edge.noteNodeID] else { return nil } return CourseRelationPlacedEdge( edge: edge, - from: CGPoint(x: materialFrame.maxX - 6, y: materialFrame.midY), - to: CGPoint(x: noteFrame.minX + 6, y: noteFrame.midY) + from: CGPoint( + x: materialFrame.maxX - 2, + y: materialFrame.midY + materialFanOffsets[edge.id, default: 0] + ), + to: CGPoint( + x: noteFrame.minX + 2, + y: noteFrame.midY + noteFanOffsets[edge.id, default: 0] + ) ) } return CourseRelationGraphLayout(nodes: placedNodes, edges: placedEdges, size: size) } + private static func fanOffsets( + groupedEdges: [String: [CourseRelationGraphEdge]], + oppositeNodeID: (CourseRelationGraphEdge) -> String, + framesByID: [String: CGRect] + ) -> [String: CGFloat] { + var offsets: [String: CGFloat] = [:] + for groupedEdge in groupedEdges.values { + let sortedEdges = groupedEdge.sorted { lhs, rhs in + let lhsY = framesByID[oppositeNodeID(lhs)]?.midY ?? 0 + let rhsY = framesByID[oppositeNodeID(rhs)]?.midY ?? 0 + if lhsY == rhsY { return lhs.id < rhs.id } + return lhsY < rhsY + } + guard sortedEdges.count > 1 else { + if let edge = sortedEdges.first { offsets[edge.id] = 0 } + continue + } + let maximumSpan: CGFloat = 40 + let step = min(11, maximumSpan / CGFloat(sortedEdges.count - 1)) + let firstOffset = -step * CGFloat(sortedEdges.count - 1) / 2 + for (index, edge) in sortedEdges.enumerated() { + offsets[edge.id] = firstOffset + CGFloat(index) * step + } + } + return offsets + } + private static func prioritizedItems( _ items: [CourseRelationGraphItem], relationDegree: [String: Int], diff --git a/Sources/WeiBei/Views/CourseRelationPaperView.swift b/Sources/WeiBei/Views/CourseRelationPaperView.swift index f907908c6..36912c1d0 100644 --- a/Sources/WeiBei/Views/CourseRelationPaperView.swift +++ b/Sources/WeiBei/Views/CourseRelationPaperView.swift @@ -13,6 +13,14 @@ struct CourseRelationPaperView: View { @State private var mode: CourseRelationPaperMode = .viewing @State private var hoveredNodeID: String? @State private var dropTargetNoteID: String? + @State private var pendingConnection: CourseRelationConnectionAnchor? + @State private var zoomScale: CGFloat = 1 + @State private var zoomGestureStartScale: CGFloat? + @State private var fitScrollRequest = 0 + + private var minimumZoomScale: CGFloat { 0.2 } + private var maximumZoomScale: CGFloat { 1.6 } + private static let paperOriginID = "course-relation-paper-origin" private var effectiveScope: CourseRelationPaperScope { let candidate = scope @@ -78,21 +86,40 @@ struct CourseRelationPaperView: View { } .background(WeiBeiTheme.paper.opacity(0.94)) .animation(WeiBeiMotion.hover, value: hoveredNodeID) + .animation(WeiBeiMotion.hover, value: pendingConnection) .animation(WeiBeiMotion.panel, value: effectiveScope.id) .animation(WeiBeiMotion.panel, value: mode) + .onChange(of: mode) { _, nextMode in + if nextMode != .managing { pendingConnection = nil } + } + .onChange(of: effectiveScope.id) { _, _ in + pendingConnection = nil + } + .onChange(of: search) { _, _ in + pendingConnection = nil + } } private func header(model: CourseRelationGraphModel) -> some View { HStack(spacing: 12) { - VStack(alignment: .leading, spacing: 2) { - Text(store.ui("课程关系台", "Course Relations")) + VStack(alignment: .leading, spacing: 1) { + Text(store.ui("资料与笔记的长期关联", "Long-term material–note links")) .font(WeiBeiTypography.brandFont(language: store.interfaceLanguage, size: 17, weight: .semibold)) .foregroundStyle(WeiBeiTheme.ink) - Text(headerDetail(model: model)) - .font(.system(size: 11)) + Text(store.ui( + "这里管理资料与笔记的长期关联,不表示当前打开状态。", + "This manages long-term links between materials and notes, not what is currently open." + )) + .font(.system(size: 11, weight: .medium)) .foregroundStyle(WeiBeiTheme.secondaryInk) + .lineLimit(isCompact ? 2 : 1) + .minimumScaleFactor(0.84) + Text(headerDetail(model: model)) + .font(.system(size: 10.5)) + .foregroundStyle(WeiBeiTheme.tertiaryInk) .lineLimit(1) } + .layoutPriority(1) Spacer(minLength: 12) @@ -102,7 +129,7 @@ struct CourseRelationPaperView: View { paperModeButton(.managing) } .padding(.horizontal, 20) - .frame(height: 58) + .frame(height: 72) .background(WeiBeiTheme.paperRaised.opacity(0.32)) } @@ -161,73 +188,284 @@ struct CourseRelationPaperView: View { let paperSize = model.paperSize(forWidth: availableSize.width, compact: false) let layout = model.layout(in: paperSize) - return ScrollView([.vertical, .horizontal]) { - ZStack(alignment: .topLeading) { - paperBackground(size: paperSize) - - Canvas { context, _ in - for placedEdge in layout.edges { - let prominence = model.edgeProminence(placedEdge.edge, hoveredNodeID: hoveredNodeID) - var path = Path() - path.move(to: placedEdge.from) - let spread = max(120, abs(placedEdge.to.x - placedEdge.from.x) * 0.45) - path.addCurve( - to: placedEdge.to, - control1: CGPoint(x: placedEdge.from.x + spread, y: placedEdge.from.y), - control2: CGPoint(x: placedEdge.to.x - spread, y: placedEdge.to.y) - ) - let width = edgeWidth(placedEdge.edge, prominence: prominence) - context.stroke( - path, - with: .color(edgeHazeColor(for: placedEdge.edge, prominence: prominence)), - style: StrokeStyle( - lineWidth: width + edgeHazeWidth(prominence), - lineCap: .round, - lineJoin: .round + return ZStack(alignment: .topTrailing) { + ScrollViewReader { scrollProxy in + ScrollView([.vertical, .horizontal]) { + ZStack(alignment: .topLeading) { + paperBackground(size: paperSize) + + Canvas { context, _ in + for placedEdge in layout.edges { + let prominence = model.edgeProminence(placedEdge.edge, hoveredNodeID: hoveredNodeID) + let path = edgePath(for: placedEdge) + let width = edgeWidth(placedEdge.edge, prominence: prominence) + context.stroke( + path, + with: .color(edgeHazeColor(for: placedEdge.edge, prominence: prominence)), + style: StrokeStyle( + lineWidth: width + edgeHazeWidth(prominence), + lineCap: .round, + lineJoin: .round + ) ) - ) - context.stroke( - path, - with: .color(edgeColor(for: placedEdge.edge, prominence: prominence)), - style: StrokeStyle( - lineWidth: width, - lineCap: .round, - lineJoin: .round + } + + let orderedEdges = layout.edges.sorted { lhs, rhs in + let lhsProminence = model.edgeProminence(lhs.edge, hoveredNodeID: hoveredNodeID) + let rhsProminence = model.edgeProminence(rhs.edge, hoveredNodeID: hoveredNodeID) + let lhsOrder = edgeDrawingOrder(lhsProminence) + let rhsOrder = edgeDrawingOrder(rhsProminence) + if lhsOrder == rhsOrder { return lhs.edge.id < rhs.edge.id } + return lhsOrder < rhsOrder + } + for placedEdge in orderedEdges { + let prominence = model.edgeProminence(placedEdge.edge, hoveredNodeID: hoveredNodeID) + let path = edgePath(for: placedEdge) + let width = edgeWidth(placedEdge.edge, prominence: prominence) + context.stroke( + path, + with: edgeShading( + for: placedEdge.edge, + prominence: prominence, + from: placedEdge.from, + to: placedEdge.to + ), + style: StrokeStyle( + lineWidth: width, + lineCap: .round, + lineJoin: .round + ) ) - ) + if prominence == .focused || prominence == .related { + context.stroke( + path, + with: .color(edgeThreadColor(prominence: prominence)), + style: StrokeStyle( + lineWidth: prominence == .focused ? 1.4 : 0.8, + lineCap: .round, + lineJoin: .round + ) + ) + } + } } - } - .frame(width: paperSize.width, height: paperSize.height) - .allowsHitTesting(false) + .frame(width: paperSize.width, height: paperSize.height) + .allowsHitTesting(false) - paperColumnMark(store.ui("课程资料", "MATERIALS")) - .position(x: min(max(150, paperSize.width * 0.28), paperSize.width * 0.42), y: 38) + paperColumnMark(store.ui("课程资料", "MATERIALS")) + .position(x: min(max(150, paperSize.width * 0.28), paperSize.width * 0.42), y: 38) - paperColumnMark(store.ui("课程笔记", "NOTES")) - .position(x: max(min(paperSize.width - 150, paperSize.width * 0.72), paperSize.width * 0.58), y: 38) + paperColumnMark(store.ui("课程笔记", "NOTES")) + .position(x: max(min(paperSize.width - 150, paperSize.width * 0.72), paperSize.width * 0.58), y: 38) + + ForEach(layout.nodes) { placedNode in + paperNode(placedNode.node, model: model) + .frame(width: placedNode.frame.width, height: placedNode.frame.height) + .position(x: placedNode.frame.midX, y: placedNode.frame.midY) + } + + if model.hiddenNodeCount > 0 { + hiddenCountBadge(model.hiddenNodeCount) + .position(x: paperSize.width / 2, y: paperSize.height - 42) + } - ForEach(layout.nodes) { placedNode in - paperNode(placedNode.node, model: model) - .frame(width: placedNode.frame.width, height: placedNode.frame.height) - .position(x: placedNode.frame.midX, y: placedNode.frame.midY) + if !model.hasContent { + CourseEmptyState( + title: store.ui("没有匹配内容", "No matching content"), + detail: store.ui("换个筛选或搜索词,再看看这张关系纸面。", "Try another scope or search query."), + systemImage: "point.3.connected.trianglepath.dotted" + ) + .frame(width: min(420, paperSize.width - 80), height: 260) + .position(x: paperSize.width / 2, y: paperSize.height / 2) + } + } + .frame(width: paperSize.width, height: paperSize.height) + .scaleEffect(zoomScale, anchor: .topLeading) + .frame( + width: paperSize.width * zoomScale, + height: paperSize.height * zoomScale, + alignment: .topLeading + ) + .id(Self.paperOriginID) } + .simultaneousGesture(magnificationGesture) + .onChange(of: fitScrollRequest) { _, _ in + DispatchQueue.main.async { + withAnimation(WeiBeiMotion.hover) { + scrollProxy.scrollTo(Self.paperOriginID, anchor: .topLeading) + } + } + } + } - if model.hiddenNodeCount > 0 { - hiddenCountBadge(model.hiddenNodeCount) - .position(x: paperSize.width / 2, y: paperSize.height - 42) + zoomControls(paperSize: paperSize, availableSize: availableSize) + .padding(14) + } + } + + private var magnificationGesture: some Gesture { + MagnificationGesture() + .onChanged { magnification in + let startingScale = zoomGestureStartScale ?? zoomScale + if zoomGestureStartScale == nil { + zoomGestureStartScale = zoomScale } + zoomScale = clampedZoomScale(startingScale * magnification) + } + .onEnded { _ in + zoomScale = clampedZoomScale(zoomScale) + zoomGestureStartScale = nil + } + } - if !model.hasContent { - CourseEmptyState( - title: store.ui("没有匹配内容", "No matching content"), - detail: store.ui("换个筛选或搜索词,再看看这张关系纸面。", "Try another scope or search query."), - systemImage: "point.3.connected.trianglepath.dotted" - ) - .frame(width: min(420, paperSize.width - 80), height: 260) - .position(x: paperSize.width / 2, y: paperSize.height / 2) + private func zoomControls(paperSize: CGSize, availableSize: CGSize) -> some View { + HStack(spacing: 0) { + Button { + setZoomScale(zoomScale - 0.1) + } label: { + Image(systemName: "minus") + .font(.system(size: 10.5, weight: .bold)) + .frame(width: 30, height: 28) + } + .buttonStyle(.plain) + .disabled(zoomScale <= minimumZoomScale + 0.001) + .help(store.ui("缩小画布", "Zoom out")) + + zoomControlDivider + + Text("\(Int((zoomScale * 100).rounded()))%") + .font(.system(size: 10.5, weight: .semibold, design: .monospaced)) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .frame(width: 48, height: 28) + .accessibilityLabel(store.ui("当前缩放 \(Int((zoomScale * 100).rounded()))%", "Current zoom \(Int((zoomScale * 100).rounded())) percent")) + + zoomControlDivider + + Button { + setZoomScale(zoomScale + 0.1) + } label: { + Image(systemName: "plus") + .font(.system(size: 10.5, weight: .bold)) + .frame(width: 30, height: 28) + } + .buttonStyle(.plain) + .disabled(zoomScale >= maximumZoomScale - 0.001) + .help(store.ui("放大画布", "Zoom in")) + + zoomControlDivider + + Button { + setZoomScale(fitZoomScale(paperSize: paperSize, availableSize: availableSize)) + fitScrollRequest += 1 + } label: { + HStack(spacing: 4) { + Image(systemName: "arrow.up.left.and.arrow.down.right") + .font(.system(size: 9.5, weight: .semibold)) + Text(store.ui("适合", "Fit")) + .font(.system(size: 10.5, weight: .semibold)) } + .padding(.horizontal, 9) + .frame(height: 28) } - .frame(width: paperSize.width, height: paperSize.height) + .buttonStyle(.plain) + .help(store.ui("完整显示关系画布", "Fit the relationship canvas")) + } + .foregroundStyle(WeiBeiTheme.ink) + .background(WeiBeiTheme.paper.opacity(0.94), in: RoundedRectangle(cornerRadius: 9, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: 9, style: .continuous) + .stroke(WeiBeiTheme.hairline.opacity(0.74), lineWidth: 1) + ) + .shadow(color: WeiBeiTheme.ink.opacity(0.055), radius: 8, y: 3) + } + + private var zoomControlDivider: some View { + Rectangle() + .fill(WeiBeiTheme.hairline.opacity(0.64)) + .frame(width: 1, height: 15) + } + + private func fitZoomScale(paperSize: CGSize, availableSize: CGSize) -> CGFloat { + let horizontalScale = max(1, availableSize.width - 32) / max(1, paperSize.width) + let verticalScale = max(1, availableSize.height - 32) / max(1, paperSize.height) + return clampedZoomScale(min(horizontalScale, verticalScale)) + } + + private func setZoomScale(_ scale: CGFloat) { + withAnimation(WeiBeiMotion.hover) { + zoomScale = clampedZoomScale(scale) + } + } + + private func clampedZoomScale(_ scale: CGFloat) -> CGFloat { + min(maximumZoomScale, max(minimumZoomScale, scale)) + } + + private func edgePath(for placedEdge: CourseRelationPlacedEdge) -> Path { + let from = placedEdge.from + let to = placedEdge.to + let horizontalDistance = max(1, to.x - from.x) + let middle = CGPoint( + x: from.x + horizontalDistance * 0.5, + y: (from.y + to.y) * 0.5 + min(16, max(-16, (to.y - from.y) * 0.035)) + ) + let departure = min(horizontalDistance * 0.40, max(88, horizontalDistance * 0.30)) + let waist = min(horizontalDistance * 0.16, 72) + + var path = Path() + path.move(to: from) + path.addCurve( + to: middle, + control1: CGPoint(x: from.x + departure, y: from.y), + control2: CGPoint(x: middle.x - waist, y: middle.y) + ) + path.addCurve( + to: to, + control1: CGPoint(x: middle.x + waist, y: middle.y), + control2: CGPoint(x: to.x - departure, y: to.y) + ) + return path + } + + private func edgeDrawingOrder(_ prominence: CourseRelationGraphProminence) -> Int { + switch prominence { + case .mist: + return 0 + case .normal: + return 1 + case .related: + return 2 + case .focused: + return 3 + } + } + + private func edgeShading( + for edge: CourseRelationGraphEdge, + prominence: CourseRelationGraphProminence, + from: CGPoint, + to: CGPoint + ) -> GraphicsContext.Shading { + let color = edgeColor(for: edge, prominence: prominence) + return .linearGradient( + Gradient(stops: [ + .init(color: color.opacity(0.76), location: 0), + .init(color: color, location: 0.42), + .init(color: color.opacity(0.82), location: 1), + ]), + startPoint: from, + endPoint: to + ) + } + + private func edgeThreadColor(prominence: CourseRelationGraphProminence) -> Color { + switch prominence { + case .focused: + return WeiBeiTheme.paper.opacity(0.34) + case .related: + return WeiBeiTheme.paper.opacity(0.20) + case .normal, .mist: + return .clear } } @@ -281,19 +519,18 @@ struct CourseRelationPaperView: View { ) -> some View { let prominence = model.nodeProminence(node, hoveredNodeID: hoveredNodeID) let isDropTarget = node.kind == .note && dropTargetNoteID == node.itemID - let showsHandle = mode == .managing - && node.kind == .material - && hoveredNodeID == node.id + let connectorState = mode == .managing ? connectionState(for: node) : nil return CourseRelationPaperNodeView( node: node, prominence: prominence, accent: nodeAccent(for: node), mode: mode, - showsHandle: showsHandle, + connectionState: connectorState, isDropTarget: isDropTarget, select: { select(node) }, open: { open(node) }, + connect: { handleConnectionTap(node) }, hover: { hovering in hoveredNodeID = hovering ? node.id : (hoveredNodeID == node.id ? nil : hoveredNodeID) } ) .contextMenu { @@ -423,6 +660,15 @@ struct CourseRelationPaperView: View { } private func headerDetail(model: CourseRelationGraphModel) -> String { + if let pendingConnection { + let title = model.visibleNodes.first(where: { + $0.itemID == pendingConnection.itemID && $0.kind == pendingConnection.kind + })?.item.title ?? store.ui("当前项目", "Current item") + return store.ui( + "已选「\(title)」· 点另一侧的 + 建立关联,点当前 + 取消", + "Selected “\(title)” · choose + on the other side to link, or choose this + again to cancel" + ) + } let scopeText = scopeTitle(effectiveScope) let relationText = store.ui("\(model.edges.count) 条可见关系", "\(model.edges.count) visible links") let nodeText = store.ui("\(model.visibleNodes.count) 个节点", "\(model.visibleNodes.count) nodes") @@ -481,6 +727,37 @@ struct CourseRelationPaperView: View { } } + private func connectionState(for node: CourseRelationGraphNode) -> CourseRelationConnectionState { + guard let pendingConnection else { return .available } + let anchor = CourseRelationConnectionAnchor(itemID: node.itemID, kind: node.kind) + if pendingConnection == anchor { return .source } + return pendingConnection.kind == node.kind ? .alternate : .target + } + + private func handleConnectionTap(_ node: CourseRelationGraphNode) { + guard mode == .managing else { return } + let anchor = CourseRelationConnectionAnchor(itemID: node.itemID, kind: node.kind) + guard let pendingConnection else { + self.pendingConnection = anchor + select(node) + return + } + if pendingConnection == anchor { + self.pendingConnection = nil + return + } + if pendingConnection.kind == anchor.kind { + self.pendingConnection = anchor + select(node) + return + } + + let materialID = pendingConnection.kind == .material ? pendingConnection.itemID : anchor.itemID + let noteID = pendingConnection.kind == .note ? pendingConnection.itemID : anchor.itemID + addLink(materialID: materialID, noteID: noteID) + self.pendingConnection = nil + } + private func addLink(materialID: String, noteID: String) { guard mode == .managing, scopedMaterials.contains(where: { $0.id == materialID }), @@ -566,13 +843,13 @@ struct CourseRelationPaperView: View { let accent = edgeAccent(for: edge) switch prominence { case .focused: - return accent.opacity(0.70) + return accent.opacity(0.62) case .related: - return accent.opacity(0.46) + return accent.opacity(0.38) case .normal: - return accent.opacity(0.20) + return accent.opacity(0.15) case .mist: - return accent.opacity(0.040) + return accent.opacity(0.028) } } @@ -583,13 +860,13 @@ struct CourseRelationPaperView: View { let accent = edgeAccent(for: edge) switch prominence { case .focused: - return accent.opacity(0.075) + return accent.opacity(0.060) case .related: - return accent.opacity(0.050) + return accent.opacity(0.042) case .normal: - return accent.opacity(0.028) + return accent.opacity(0.026) case .mist: - return accent.opacity(0.012) + return accent.opacity(0.010) } } @@ -597,9 +874,9 @@ struct CourseRelationPaperView: View { let base = CGFloat(min(9, 4 + max(0, edge.count - 1) * 2)) switch prominence { case .focused: - return base + 7 + return base + 6 case .related: - return base + 3 + return base + 2.5 case .normal: return base case .mist: @@ -610,17 +887,29 @@ struct CourseRelationPaperView: View { private func edgeHazeWidth(_ prominence: CourseRelationGraphProminence) -> CGFloat { switch prominence { case .focused: - return 18 + return 22 case .related: - return 13 + return 16 case .normal: - return 9 + return 11 case .mist: - return 5 + return 7 } } } +private struct CourseRelationConnectionAnchor: Equatable { + let itemID: String + let kind: CourseRelationGraphItem.Kind +} + +private enum CourseRelationConnectionState: Equatable { + case available + case alternate + case source + case target +} + private enum CourseRelationPaperMode: Equatable { case viewing case managing @@ -641,14 +930,19 @@ private struct CourseRelationPaperNodeView: View { let prominence: CourseRelationGraphProminence let accent: Color let mode: CourseRelationPaperMode - let showsHandle: Bool + let connectionState: CourseRelationConnectionState? let isDropTarget: Bool let select: () -> Void let open: () -> Void + let connect: () -> Void let hover: (Bool) -> Void var body: some View { - HStack(spacing: 9) { + HStack(spacing: 8) { + if node.kind == .note, let connectionState { + connectionControl(connectionState) + } + Capsule() .fill(markerColor) .frame(width: prominence == .focused ? 3 : 2, height: 30) @@ -676,18 +970,15 @@ private struct CourseRelationPaperNodeView: View { .contentShape(Rectangle()) } .buttonStyle(.plain) - - if showsHandle { - handle - } else { - Button(action: open) { - Image(systemName: "arrow.up.forward") - .font(.system(size: 10.5, weight: .semibold)) - .foregroundStyle(WeiBeiTheme.tertiaryInk) - .frame(width: 22, height: 22) - } - .buttonStyle(.plain) - .opacity(prominence == .mist ? 0.12 : 0.72) + .modifier(CourseRelationNodeDragModifier( + enabled: mode == .managing && node.kind == .material, + itemID: node.itemID + )) + + if node.kind == .material, let connectionState { + connectionControl(connectionState) + } else if mode == .viewing { + openControl } } .padding(.horizontal, 8) @@ -709,18 +1000,100 @@ private struct CourseRelationPaperNodeView: View { return "\(node.item.kindLabel) · \(countText)" } - private var handle: some View { - HStack(spacing: 5) { - Image(systemName: "smallcircle.filled.circle") - .font(.system(size: 12, weight: .bold)) - Text(store.ui("拖到笔记", "Drag to note")) + private var openControl: some View { + Button(action: open) { + Image(systemName: "arrow.up.forward") .font(.system(size: 10.5, weight: .semibold)) + .foregroundStyle(WeiBeiTheme.tertiaryInk) + .frame(width: 22, height: 22) } - .foregroundStyle(WeiBeiTheme.onCinnabar) - .padding(.horizontal, 8) - .frame(height: 26) - .background(WeiBeiTheme.cinnabar.opacity(0.86), in: Capsule()) - .draggable(node.itemID) + .buttonStyle(.plain) + .opacity(prominence == .mist ? 0.12 : 0.72) + } + + @ViewBuilder + private func connectionControl(_ state: CourseRelationConnectionState) -> some View { + connectionButton(state) + } + + private func connectionButton(_ state: CourseRelationConnectionState) -> some View { + Button(action: connect) { + Image(systemName: state == .source ? "xmark" : "plus") + .font(.system(size: 10.5, weight: .bold)) + .foregroundStyle(connectionForeground(state)) + .frame(width: 27, height: 27) + .background(connectionBackground(state), in: Circle()) + .overlay( + Circle() + .stroke(connectionBorder(state), lineWidth: state == .target ? 1.4 : 1) + ) + .contentShape(Circle()) + } + .buttonStyle(.plain) + .accessibilityLabel("\(node.item.title):\(connectionLabel(state))") + .help(connectionHelp(state)) + } + + private func connectionForeground(_ state: CourseRelationConnectionState) -> Color { + switch state { + case .available: + return WeiBeiTheme.secondaryInk + case .alternate: + return WeiBeiTheme.secondaryInk.opacity(0.84) + case .source: + return WeiBeiTheme.onCinnabar + case .target: + return accent + } + } + + private func connectionBackground(_ state: CourseRelationConnectionState) -> Color { + switch state { + case .available: + return WeiBeiTheme.paper.opacity(0.88) + case .alternate: + return WeiBeiTheme.paperInset.opacity(0.34) + case .source: + return accent.opacity(0.88) + case .target: + return accent.opacity(0.13) + } + } + + private func connectionBorder(_ state: CourseRelationConnectionState) -> Color { + switch state { + case .available: + return WeiBeiTheme.hairline.opacity(0.82) + case .alternate: + return WeiBeiTheme.hairline.opacity(0.68) + case .source: + return accent.opacity(0.92) + case .target: + return accent.opacity(0.62) + } + } + + private func connectionLabel(_ state: CourseRelationConnectionState) -> String { + switch state { + case .available: + return store.ui("选择为关联起点", "Choose as link start") + case .alternate: + return store.ui("切换为新的关联起点", "Switch to this link start") + case .source: + return store.ui("取消当前关联起点", "Cancel current link start") + case .target: + return store.ui("与当前起点建立关联", "Link with current start") + } + } + + private func connectionHelp(_ state: CourseRelationConnectionState) -> String { + if state == .target { + return connectionLabel(state) + } + if node.kind == .material, state != .source { + return store.ui("点按选择资料;也可拖到笔记", "Choose this material, or drag it onto a note") + } + return connectionLabel(state) } private var iconColor: Color { @@ -729,6 +1102,8 @@ private struct CourseRelationPaperNodeView: View { private var nodeBackground: Color { if isDropTarget { return accent.opacity(0.14) } + if connectionState == .source { return accent.opacity(0.11) } + if connectionState == .target { return accent.opacity(0.055) } switch prominence { case .focused: return accent.opacity(0.080) @@ -743,6 +1118,8 @@ private struct CourseRelationPaperNodeView: View { private var markerColor: Color { if isDropTarget { return accent.opacity(0.92) } + if connectionState == .source { return accent.opacity(0.88) } + if connectionState == .target { return accent.opacity(0.42) } switch prominence { case .focused: return accent.opacity(0.88) @@ -757,6 +1134,8 @@ private struct CourseRelationPaperNodeView: View { private var underlineColor: Color { if isDropTarget { return accent.opacity(0.82) } + if connectionState == .source { return accent.opacity(0.58) } + if connectionState == .target { return accent.opacity(0.30) } switch prominence { case .focused: return accent.opacity(0.54) @@ -770,6 +1149,10 @@ private struct CourseRelationPaperNodeView: View { } private var opacity: Double { + if connectionState == .source { return 1 } + if connectionState == .target { return 0.90 } + if connectionState == .alternate { return 0.72 } + if connectionState == .available { return 0.82 } switch prominence { case .focused: return 1 @@ -783,6 +1166,20 @@ private struct CourseRelationPaperNodeView: View { } } +private struct CourseRelationNodeDragModifier: ViewModifier { + let enabled: Bool + let itemID: String + + @ViewBuilder + func body(content: Content) -> some View { + if enabled { + content.draggable(itemID) + } else { + content + } + } +} + private struct CourseRelationDropModifier: ViewModifier { let node: CourseRelationGraphNode let enabled: Bool diff --git a/Sources/WeiBei/Views/CourseWorkspaceView.swift b/Sources/WeiBei/Views/CourseWorkspaceView.swift index 2c7f72773..937383ec2 100644 --- a/Sources/WeiBei/Views/CourseWorkspaceView.swift +++ b/Sources/WeiBei/Views/CourseWorkspaceView.swift @@ -3,7 +3,6 @@ import SwiftUI import WeiBeiCore enum CourseWorkspacePage: String, CaseIterable, Identifiable { - case overview case relations case records @@ -11,10 +10,8 @@ enum CourseWorkspacePage: String, CaseIterable, Identifiable { func label(language: WeiBeiInterfaceLanguage) -> String { switch self { - case .overview: - language.text("概览", "Overview") case .relations: - language.text("关系台", "Relations") + language.text("资料与笔记", "Materials & Notes") case .records: language.text("学习记录", "Learning Records") } @@ -39,7 +36,7 @@ enum CourseRelationLens: String, CaseIterable, Identifiable { struct CourseWorkspaceView: View { @EnvironmentObject private var store: WorkspaceStore - @State private var page: CourseWorkspacePage = .overview + @State private var page: CourseWorkspacePage = .relations @State private var relationLens: CourseRelationLens = .notes @State private var selectedNoteID: String? @State private var selectedMaterialID: String? @@ -114,28 +111,6 @@ struct CourseWorkspaceView: View { @ViewBuilder private func pageContent(size: CGSize) -> some View { switch page { - case .overview: - CourseOverviewView( - showUnlinkedNotes: { - relationLens = .notes - selectedNoteID = store.courseNotesWithoutSourceLinks.first?.id - page = .relations - }, - showUnlinkedMaterials: { - relationLens = .materials - selectedMaterialID = store.courseMaterialsWithoutNoteLinks.first?.id - page = .relations - }, - showMaterialsWithoutReadingPosition: { - relationLens = .materials - selectedMaterialID = store.courseMaterialsWithoutReadingPosition.first?.id - page = .relations - }, - showRecords: { sessionID in - selectedSessionID = sessionID ?? store.recentCourseSessions.first?.id - page = .records - } - ) case .relations: CourseRelationsView( lens: $relationLens, @@ -173,8 +148,8 @@ struct CourseWorkspaceView: View { private func prepareInitialRoute() { switch store.courseWorkspaceDestination { - case .overview: - page = .overview + case .relations: + page = .relations case .materials: relationLens = .materials selectedMaterialID = store.courseWorkspaceTargetItemID ?? store.courseMaterials.first?.id @@ -210,7 +185,7 @@ private struct CourseNewNoteSheet: View { VStack(alignment: .leading, spacing: 6) { Text(store.ui("新建课程笔记", "New course note")) .font(WeiBeiTypography.brandFont(language: store.interfaceLanguage, size: 20, weight: .semibold)) - Text(store.ui("新笔记会进入课程首页,并保存到本地笔记目录。", "The note will appear in the course home and save locally.")) + Text(store.ui("新笔记会进入当前课程的笔记栏,并保存到本地笔记目录。", "The note will appear in the current course and save locally.")) .font(.system(size: 12)) .foregroundStyle(WeiBeiTheme.secondaryInk) } @@ -416,12 +391,12 @@ struct CourseWorkspaceHeader: View { .contentShape(Rectangle()) } .buttonStyle(.plain) - .accessibilityLabel(Text(store.ui("关闭课程首页并返回工作台", "Close course home"))) + .accessibilityLabel(Text(store.ui("关闭资料关系台并返回工作台", "Close course relations"))) VStack(alignment: .leading, spacing: 0) { - Text(store.ui("课程首页", "Course Home")) + Text(store.ui("资料关系台", "Course Relations")) .font(WeiBeiTypography.brandFont(language: store.interfaceLanguage, size: 20, weight: .semibold)) - Text(store.interfaceLanguage == .chinese ? "COURSE HOME" : "WEIBEI") + Text(store.interfaceLanguage == .chinese ? "MATERIALS × NOTES" : "WEIBEI") .font(WeiBeiTypography.englishBrandFont(size: 8.5, weight: .semibold)) .tracking(0.9) .foregroundStyle(WeiBeiTheme.cinnabar.opacity(0.74)) @@ -468,18 +443,16 @@ struct CourseWorkspaceHeader: View { .help(saveError) } - if page != .overview { - HStack(spacing: 7) { - Image(systemName: "magnifyingglass") - .foregroundStyle(WeiBeiTheme.tertiaryInk) - TextField(searchPrompt, text: $search) - .textFieldStyle(.plain) - .focused(searchFocused) - .font(.system(size: 12)) - } - .weibeiInputSurface(active: searchFocused.wrappedValue, height: 30) - .frame(width: isCompact ? 160 : 220) + HStack(spacing: 7) { + Image(systemName: "magnifyingglass") + .foregroundStyle(WeiBeiTheme.tertiaryInk) + TextField(searchPrompt, text: $search) + .textFieldStyle(.plain) + .focused(searchFocused) + .font(.system(size: 12)) } + .weibeiInputSurface(active: searchFocused.wrappedValue, height: 30) + .frame(width: isCompact ? 160 : 220) Menu { Button(action: importCourseFolder) { @@ -515,8 +488,6 @@ struct CourseWorkspaceHeader: View { private var searchPrompt: String { switch page { - case .overview: - store.ui("搜索课程", "Search course") case .relations: store.ui("搜索课程内容", "Search course content") case .records: diff --git a/Sources/WeiBei/Views/LinkedSourcesView.swift b/Sources/WeiBei/Views/LinkedSourcesView.swift index 598efa29c..fefa35426 100644 --- a/Sources/WeiBei/Views/LinkedSourcesView.swift +++ b/Sources/WeiBei/Views/LinkedSourcesView.swift @@ -126,7 +126,7 @@ struct LinkedSourcesPopover: View { store.presentCourseWorkspace(.notes, selecting: noteItemID) dismiss() } label: { - Label(store.ui("课程首页", "Course Home"), systemImage: "books.vertical") + Label(store.ui("资料关系台", "Course Relations"), systemImage: "books.vertical") } .buttonStyle(WeiBeiTextActionButtonStyle()) diff --git a/Sources/WeiBei/Views/SidebarView.swift b/Sources/WeiBei/Views/SidebarView.swift index 51bccbd9f..b57e532b3 100644 --- a/Sources/WeiBei/Views/SidebarView.swift +++ b/Sources/WeiBei/Views/SidebarView.swift @@ -21,7 +21,7 @@ struct SidebarView: View { store.presentCourseWorkspace() } label: { HStack(spacing: 3) { - Text(store.ui("课程首页", "Course Home")) + Text(store.ui("资料关系台", "Course Relations")) Image(systemName: "chevron.right") .font(.system(size: 8, weight: .bold)) } @@ -29,8 +29,8 @@ struct SidebarView: View { .foregroundStyle(WeiBeiTheme.cinnabar.opacity(0.78)) } .buttonStyle(.plain) - .accessibilityLabel(Text(store.ui("打开课程首页", "Open course home"))) - .help(store.ui("打开课程首页", "Open course home")) + .accessibilityLabel(Text(store.ui("打开资料关系台", "Open course relations"))) + .help(store.ui("打开资料关系台", "Open course relations")) } Spacer() Button { showsNewCourseSheet = true } label: { @@ -69,13 +69,8 @@ struct SidebarView: View { ScrollView(showsIndicators: false) { LazyVStack(alignment: .leading, spacing: 14) { courseSection - if let activeCourseID = store.activeCourseID { - sidebarSection(title: store.ui("本课资料", "Course Materials"), items: materials(in: activeCourseID)) - sidebarSection(title: store.ui("本课笔记", "Course Notes"), items: notes(in: activeCourseID)) - } else { - sidebarSection(title: store.ui("独立资料", "Unassigned Materials"), items: unassignedMaterials) - sidebarSection(title: store.ui("全部笔记", "All Notes"), items: notebookItems) - } + sidebarSection(title: store.ui("独立资料", "Unassigned Materials"), items: unassignedMaterials) + sidebarSection(title: store.ui("独立笔记", "Unassigned Notes"), items: unassignedNotes) sidebarSection(title: store.ui("内置示例", "Built-in Examples"), items: sampleItems) } .padding(.horizontal, 10) @@ -165,6 +160,10 @@ struct SidebarView: View { store.filteredItems.filter(\.isNotebookNote) } + private var unassignedNotes: [StudyItem] { + notebookItems.filter { store.courseIDs(for: $0.id).isEmpty } + } + private func materials(in courseID: UUID) -> [StudyItem] { store.courseMaterials(in: courseID).filter { filteredItemIDs.contains($0.id) } } @@ -188,26 +187,34 @@ struct SidebarView: View { .frame(height: 40) } else { ForEach(filteredCourses) { course in - Button { - withAnimation(WeiBeiMotion.panel) { - store.activateCourse(store.activeCourseID == course.id ? nil : course.id) + VStack(alignment: .leading, spacing: 0) { + Button { + withAnimation(WeiBeiMotion.layout) { + store.activateCourse(store.activeCourseID == course.id ? nil : course.id) + } + } label: { + SidebarCourseRow( + course: course, + materialCount: store.courseMaterials(in: course.id).count, + noteCount: store.courseNotes(in: course.id).count, + expanded: store.activeCourseID == course.id + ) } - } label: { - SidebarCourseRow( - course: course, - materialCount: store.courseMaterials(in: course.id).count, - noteCount: store.courseNotes(in: course.id).count, - selected: store.activeCourseID == course.id - ) - } - .buttonStyle(.plain) - .contextMenu { - Button(store.ui("重命名课程", "Rename course")) { - renameCourseTitle = course.title - courseToRename = course + .buttonStyle(.plain) + .accessibilityHint(Text(store.activeCourseID == course.id ? store.ui("收起课程内容", "Collapse course contents") : store.ui("展开课程内容", "Expand course contents"))) + .contextMenu { + Button(store.ui("重命名课程", "Rename course")) { + renameCourseTitle = course.title + courseToRename = course + } + Button(store.ui("删除课程", "Delete course"), role: .destructive) { + coursePendingDeletion = course + } } - Button(store.ui("删除课程", "Delete course"), role: .destructive) { - coursePendingDeletion = course + + if store.activeCourseID == course.id { + courseContents(for: course) + .transition(.opacity.combined(with: .move(edge: .top))) } } } @@ -215,6 +222,83 @@ struct SidebarView: View { } } + private func courseContents(for course: Course) -> some View { + let accent = sidebarCourseAccent(colorIndex: course.colorIndex) + return HStack(alignment: .top, spacing: 0) { + LinearGradient( + colors: [accent.opacity(0.34), accent.opacity(0.10)], + startPoint: .top, + endPoint: .bottom + ) + .frame(width: 1) + .padding(.leading, 9) + .frame(width: 18) + + VStack(alignment: .leading, spacing: 9) { + courseItemGroup( + title: store.ui("资料", "Materials"), + systemImage: "doc.text", + items: materials(in: course.id), + emptyTitle: store.ui("暂无资料", "No materials"), + accent: accent + ) + courseItemGroup( + title: store.ui("笔记", "Notes"), + systemImage: "note.text", + items: notes(in: course.id), + emptyTitle: store.ui("暂无笔记", "No notes"), + accent: accent + ) + } + } + .padding(.leading, 15) + .padding(.trailing, 2) + .padding(.top, 3) + .padding(.bottom, 9) + } + + private func courseItemGroup( + title: String, + systemImage: String, + items: [StudyItem], + emptyTitle: String, + accent: Color + ) -> some View { + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: 5) { + Image(systemName: systemImage) + .font(.system(size: 9.5, weight: .semibold)) + .foregroundStyle(accent.opacity(0.74)) + Text(title) + .font(.system(size: 10.5, weight: .semibold)) + .foregroundStyle(WeiBeiTheme.secondaryInk) + Spacer(minLength: 4) + Text("\(items.count)") + .font(.system(size: 9.5, weight: .medium, design: .monospaced)) + .foregroundStyle(WeiBeiTheme.tertiaryInk) + } + .frame(height: 18) + .overlay(alignment: .leading) { + Rectangle() + .fill(accent.opacity(0.30)) + .frame(width: 10, height: 1) + .offset(x: -13) + } + + if items.isEmpty { + Text(emptyTitle) + .font(.system(size: 10.5)) + .foregroundStyle(WeiBeiTheme.tertiaryInk.opacity(0.78)) + .padding(.leading, 2) + .frame(height: 26, alignment: .leading) + } else { + ForEach(items) { item in + sidebarItemRow(item, compact: true, accent: accent) + } + } + } + } + @ViewBuilder private func sidebarSection(title: String, items: [StudyItem]) -> some View { if !items.isEmpty { @@ -225,44 +309,55 @@ struct SidebarView: View { .padding(.horizontal, 8) ForEach(items) { item in - if store.notebookRenameDraft?.itemID == item.id { - NotebookRenameRow(item: item, selected: item.isNotebookNote ? store.activeNotebookItemID == item.id : store.selectedItemID == item.id) - .transition(WeiBeiTransition.message) - } else { - Button { - withAnimation(WeiBeiMotion.panel) { - open(item) - } - } label: { - LibraryRow(item: item, selected: item.isNotebookNote ? store.activeNotebookItemID == item.id : store.selectedItemID == item.id) - } - .buttonStyle(.plain) - .contextMenu { - if item.isNotebookNote { - Button(store.ui("重命名笔记", "Rename Note")) { - store.promptRenameNotebookNote(itemID: item.id) - } - } - if !item.isSample, !store.courses.isEmpty { - Menu(store.ui("课程归属", "Course membership")) { - ForEach(store.courses) { course in - let assigned = store.courseIDs(for: item.id).contains(course.id) - Button { - var courseIDs = Set(store.courseIDs(for: item.id)) - if assigned { - courseIDs.remove(course.id) - } else { - courseIDs.insert(course.id) - } - store.setCourseIDs(courseIDs, for: item.id) - } label: { - Label(course.title, systemImage: assigned ? "checkmark" : "circle") - } - } - } - } + sidebarItemRow(item, compact: false, accent: nil) + } + } + } + } + + @ViewBuilder + private func sidebarItemRow(_ item: StudyItem, compact: Bool, accent: Color?) -> some View { + let selected = item.isNotebookNote ? store.activeNotebookItemID == item.id : store.selectedItemID == item.id + if store.notebookRenameDraft?.itemID == item.id { + NotebookRenameRow(item: item, selected: selected, compact: compact, accent: accent ?? WeiBeiTheme.cinnabar) + .transition(WeiBeiTransition.message) + } else { + Button { + withAnimation(WeiBeiMotion.layout) { + open(item) + } + } label: { + LibraryRow(item: item, selected: selected, compact: compact, accent: accent) + } + .buttonStyle(.plain) + .contextMenu { + itemContextMenu(for: item) + } + .transition(WeiBeiTransition.message) + } + } + + @ViewBuilder + private func itemContextMenu(for item: StudyItem) -> some View { + if item.isNotebookNote { + Button(store.ui("重命名笔记", "Rename Note")) { + store.promptRenameNotebookNote(itemID: item.id) + } + } + if !item.isSample, !store.courses.isEmpty { + Menu(store.ui("课程归属", "Course membership")) { + ForEach(store.courses) { course in + let assigned = store.courseIDs(for: item.id).contains(course.id) + Button { + var courseIDs = Set(store.courseIDs(for: item.id)) + if assigned { + courseIDs.remove(course.id) + } else { + courseIDs.insert(course.id) } - .transition(WeiBeiTransition.message) + store.setCourseIDs(courseIDs, for: item.id) + } label: { + Label(course.title, systemImage: assigned ? "checkmark" : "circle") } } } @@ -303,18 +398,19 @@ private struct SidebarCourseRow: View { let course: Course let materialCount: Int let noteCount: Int - let selected: Bool + let expanded: Bool @State private var hovering = false var body: some View { HStack(spacing: 10) { - Image(systemName: "book.closed") - .foregroundStyle(accent.opacity(selected || hovering ? 1 : 0.78)) + Image(systemName: expanded ? "book.closed.fill" : "book.closed") + .foregroundStyle(accent.opacity(expanded || hovering ? 1 : 0.78)) .frame(width: 18) - .scaleEffect(selected || hovering ? 1.08 : 1) + .scaleEffect(expanded || hovering ? 1.08 : 1) VStack(alignment: .leading, spacing: 2) { Text(course.title) + .font(.system(size: 13, weight: .medium)) .lineLimit(1) .foregroundStyle(WeiBeiTheme.ink) Text(store.ui("\(materialCount) 份资料 · \(noteCount) 份笔记", "\(materialCount) materials · \(noteCount) notes")) @@ -322,44 +418,55 @@ private struct SidebarCourseRow: View { .foregroundStyle(WeiBeiTheme.secondaryInk) .lineLimit(1) } + + Spacer(minLength: 6) + + Image(systemName: "chevron.right") + .font(.system(size: 9, weight: .semibold)) + .foregroundStyle(expanded ? accent.opacity(0.78) : WeiBeiTheme.tertiaryInk) + .rotationEffect(.degrees(expanded ? 90 : 0)) } .padding(.horizontal, 9) .frame(height: 48) .frame(maxWidth: .infinity, alignment: .leading) .background(rowBackground) - .offset(x: selected || hovering ? 2 : 0) + .offset(x: expanded || hovering ? 2 : 0) .clipShape(RoundedRectangle(cornerRadius: 8)) .overlay(alignment: .leading) { - if selected { + if expanded { Capsule() .fill(accent.opacity(0.72)) .frame(width: 3, height: 24) .padding(.leading, 2) } } - .weibeiHoverLift(active: hovering && !selected, amount: 1) + .weibeiHoverLift(active: hovering && !expanded, amount: 1) .onHover { hovering = $0 } - .animation(WeiBeiMotion.micro, value: selected) + .animation(WeiBeiMotion.layout, value: expanded) .animation(WeiBeiMotion.hover, value: hovering) } private var rowBackground: Color { - if selected { return WeiBeiTheme.paperInset.opacity(0.70) } + if expanded { return WeiBeiTheme.paperInset.opacity(0.70) } if hovering { return WeiBeiTheme.paperInset.opacity(0.30) } return .clear } private var accent: Color { - switch ((course.colorIndex % 4) + 4) % 4 { - case 0: - return WeiBeiTheme.cinnabar - case 1: - return WeiBeiTheme.moss - case 2: - return WeiBeiTheme.link - default: - return WeiBeiTheme.secondaryInk - } + sidebarCourseAccent(colorIndex: course.colorIndex) + } +} + +private func sidebarCourseAccent(colorIndex: Int) -> Color { + switch ((colorIndex % 4) + 4) % 4 { + case 0: + return WeiBeiTheme.cinnabar + case 1: + return WeiBeiTheme.moss + case 2: + return WeiBeiTheme.link + default: + return WeiBeiTheme.secondaryInk } } @@ -414,6 +521,8 @@ private struct NotebookRenameRow: View { @EnvironmentObject private var store: WorkspaceStore var item: StudyItem var selected: Bool + var compact: Bool + var accent: Color @FocusState private var focused: Bool private var title: Binding { @@ -428,10 +537,10 @@ private struct NotebookRenameRow: View { } var body: some View { - HStack(spacing: 8) { + HStack(spacing: compact ? 7 : 8) { Image(systemName: item.kind.systemImage) - .foregroundStyle(WeiBeiTheme.cinnabar.opacity(0.78)) - .frame(width: 18) + .foregroundStyle(accent.opacity(0.78)) + .frame(width: compact ? 15 : 18) TextField( "", @@ -441,7 +550,7 @@ private struct NotebookRenameRow: View { ) .textFieldStyle(.plain) .focused($focused) - .font(.system(size: 13, weight: .medium)) + .font(.system(size: compact ? 12.5 : 13, weight: .medium)) .foregroundColor(WeiBeiTheme.ink) .onSubmit { if canRename { @@ -458,15 +567,15 @@ private struct NotebookRenameRow: View { .keyboardShortcut(.cancelAction) .accessibilityLabel(Text(store.ui("取消", "Cancel"))) } - .padding(.horizontal, 9) - .frame(height: 48) + .padding(.horizontal, compact ? 7 : 9) + .frame(height: compact ? 38 : 48) .frame(maxWidth: .infinity, alignment: .leading) .background(WeiBeiTheme.paperInset.opacity(selected ? 0.74 : 0.44)) - .clipShape(RoundedRectangle(cornerRadius: 8)) + .clipShape(RoundedRectangle(cornerRadius: compact ? 6 : 8)) .overlay(alignment: .leading) { Capsule() - .fill(WeiBeiTheme.cinnabar.opacity(canRename ? 0.72 : 0.34)) - .frame(width: 3, height: 24) + .fill(accent.opacity(canRename ? 0.72 : 0.34)) + .frame(width: compact ? 2 : 3, height: compact ? 18 : 24) .padding(.leading, 2) } .onAppear { @@ -479,6 +588,8 @@ private struct LibraryRow: View { @EnvironmentObject private var store: WorkspaceStore var item: StudyItem var selected: Bool + var compact: Bool + var accent: Color? @State private var hovering = false private var tags: [String] { @@ -486,22 +597,23 @@ private struct LibraryRow: View { } var body: some View { - HStack(spacing: 10) { + HStack(spacing: compact ? 7 : 10) { Image(systemName: item.kind.systemImage) - .foregroundStyle(item.kind == .pdf ? WeiBeiTheme.link : WeiBeiTheme.tertiaryInk) - .frame(width: 18) + .foregroundStyle(iconColor) + .frame(width: compact ? 15 : 18) .scaleEffect(selected || hovering ? 1.08 : 1) .opacity(selected || hovering ? 1 : 0.78) - VStack(alignment: .leading, spacing: 2) { + VStack(alignment: .leading, spacing: compact ? 1 : 2) { Text(store.displayTitle(for: item)) + .font(.system(size: compact ? 12.5 : 13, weight: compact ? .medium : .regular)) .lineLimit(1) .foregroundStyle(WeiBeiTheme.ink) Text(store.displaySubtitle(for: item)) - .font(.caption) + .font(compact ? .system(size: 10.5) : .caption) .foregroundStyle(WeiBeiTheme.secondaryInk) .lineLimit(1) - if !tags.isEmpty { + if !compact, !tags.isEmpty { Text(tags.joined(separator: " ")) .font(.system(size: 10, weight: .medium)) .foregroundStyle(WeiBeiTheme.cinnabar.opacity(0.72)) @@ -509,17 +621,17 @@ private struct LibraryRow: View { } } } - .padding(.horizontal, 9) - .frame(height: tags.isEmpty ? 48 : 58) + .padding(.horizontal, compact ? 7 : 9) + .frame(height: compact ? 38 : (tags.isEmpty ? 48 : 58)) .frame(maxWidth: .infinity, alignment: .leading) .background(rowBackground) - .offset(x: selected || hovering ? 2 : 0) - .clipShape(RoundedRectangle(cornerRadius: 8)) + .offset(x: selected || hovering ? (compact ? 1 : 2) : 0) + .clipShape(RoundedRectangle(cornerRadius: compact ? 6 : 8)) .overlay(alignment: .leading) { if selected { Capsule() - .fill(WeiBeiTheme.cinnabar.opacity(0.72)) - .frame(width: 3, height: 24) + .fill((accent ?? WeiBeiTheme.cinnabar).opacity(0.72)) + .frame(width: compact ? 2 : 3, height: compact ? 18 : 24) .padding(.leading, 2) .transition(.scale(scale: 0.7, anchor: .center).combined(with: .opacity)) } @@ -535,8 +647,15 @@ private struct LibraryRow: View { } private var rowBackground: Color { - if selected { return WeiBeiTheme.paperInset.opacity(0.70) } - if hovering { return WeiBeiTheme.paperInset.opacity(0.30) } + if selected { return WeiBeiTheme.paperInset.opacity(compact ? 0.54 : 0.70) } + if hovering { return WeiBeiTheme.paperInset.opacity(compact ? 0.22 : 0.30) } return .clear } + + private var iconColor: Color { + if let accent { + return accent.opacity(item.isNotebookNote ? 0.70 : 0.82) + } + return item.kind == .pdf ? WeiBeiTheme.link : WeiBeiTheme.tertiaryInk + } } diff --git a/Sources/WeiBeiSelfCheck/main.swift b/Sources/WeiBeiSelfCheck/main.swift index 413d922a4..df312f226 100644 --- a/Sources/WeiBeiSelfCheck/main.swift +++ b/Sources/WeiBeiSelfCheck/main.swift @@ -1467,6 +1467,9 @@ expect(contentViewSource.contains("override func layout()"), "native split appli expect(contentViewSource.contains("CourseImmersiveDrawerView") && contentViewSource.contains("LayoutContentView()") && contentViewSource.contains("ZStack(alignment: .leading)") + && contentViewSource.contains(".transition(WeiBeiTransition.sidePanel)") + && contentViewSource.contains(".animation(WeiBeiMotion.layout, value: store.showLibrary)") + && contentViewSource.contains("withAnimation(WeiBeiMotion.layout)") && !contentViewSource.contains("libraryResizeHandle") && !contentViewSource.contains("minimumContentWidthWithLibrary"), "course drawer temporarily covers the living workspace instead of resizing or rebuilding it") expect(contentViewSource.contains("private let railWidth = ContentRailMetrics.railOnlyWidth") @@ -1599,7 +1602,7 @@ let sidebarSourceURL = URL(fileURLWithPath: FileManager.default.currentDirectory .appendingPathComponent("Sources/WeiBei/Views/SidebarView.swift") let sidebarSource = (try? String(contentsOf: sidebarSourceURL, encoding: .utf8)) ?? "" expect(sidebarSource.contains("Text(store.ui(\"课程目录\", \"Course Index\")") - && sidebarSource.contains("Text(store.ui(\"课程首页\", \"Course Home\")") + && sidebarSource.contains("Text(store.ui(\"资料关系台\", \"Course Relations\")") && sidebarSource.contains("store.presentCourseWorkspace()") && sidebarSource.contains("prompt: Text(store.ui(\"搜索课程资料与笔记\"") && sidebarSource.contains(".foregroundStyle(WeiBeiTheme.placeholderInk)") @@ -1679,10 +1682,13 @@ expect(!sidebarSource.contains("commandPalettePresented.toggle()") && !sidebarSo expect(sidebarSource.contains("ScrollView(showsIndicators: false)"), "sidebar hides the heavy system scroll indicator that reads as a divider") expect(sidebarSource.contains("sidebarSection(title: store.ui(\"内置示例\"") && sidebarSource.contains("courseSection") - && sidebarSource.contains("sidebarSection(title: store.ui(\"本课资料\"") - && sidebarSource.contains("sidebarSection(title: store.ui(\"本课笔记\"") + && sidebarSource.contains("courseContents(for: course)") + && sidebarSource.contains("courseItemGroup(") + && sidebarSource.contains("title: store.ui(\"资料\", \"Materials\")") + && sidebarSource.contains("title: store.ui(\"笔记\", \"Notes\")") + && sidebarSource.contains("LinearGradient(") && sidebarSource.contains("sidebarSection(title: store.ui(\"独立资料\"") - && sidebarSource.contains("sidebarSection(title: store.ui(\"全部笔记\""), "course drawer keeps the original course-index styling while adding course, active-course, unassigned, note, and sample levels") + && sidebarSource.contains("sidebarSection(title: store.ui(\"独立笔记\""), "course drawer keeps the original styling while expanding each course into a visually nested material-note tree") expect(sidebarSource.contains("store.unassignedCourseMaterials") && sidebarSource.contains("store.courseMaterials(in: courseID)") && sidebarSource.contains("store.courseNotes(in: courseID)") @@ -1697,7 +1703,8 @@ expect(sidebarSource.contains(".contextMenu") expect(sidebarSource.contains("private var tags: [String]") && sidebarSource.contains("store.displayTags(for: item)") && sidebarSource.contains("Text(tags.joined(separator: \" \"))") - && sidebarSource.contains(".frame(height: tags.isEmpty ? 48 : 58)"), "notebook rows surface Markdown tags without adding a separate tag management panel") + && sidebarSource.contains("if !compact, !tags.isEmpty") + && sidebarSource.contains("compact ? 38 : (tags.isEmpty ? 48 : 58)"), "full notebook rows surface Markdown tags while nested course rows stay compact") expect(contentViewSource.contains("topIconButton(\"command\", help: store.ui(\"命令面板\""), "top bar keeps the command palette entry") let commandPaletteSourceURL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) .appendingPathComponent("Sources/WeiBei/Views/CommandPaletteView.swift") @@ -2294,7 +2301,6 @@ let linkedSourcesSourceURL = URL(fileURLWithPath: FileManager.default.currentDir let linkedSourcesSource = (try? String(contentsOf: linkedSourcesSourceURL, encoding: .utf8)) ?? "" let courseWorkspaceSourceNames = [ "CourseWorkspaceView.swift", - "CourseOverviewView.swift", "CourseRelationsView.swift", "CourseRelationPaperView.swift", "CourseRelationGraphModel.swift", @@ -2330,14 +2336,12 @@ expect(contentViewSource.contains("if store.courseWorkspacePresented") && contentViewSource.contains("LayoutContentView()") && contentViewSource.contains("container.isHidden = store.courseWorkspacePresented") && !contentViewSource.contains("if store.courseWorkspacePresented {\n CourseWorkspaceView()\n } else"), "course workspace covers and hides native pane hosts without replacing the persistent pane tree") -expect(courseWorkspaceSource.contains("case overview") - && courseWorkspaceSource.contains("case relations") +expect(courseWorkspaceSource.contains("case relations") && courseWorkspaceSource.contains("case records") - && courseWorkspaceSource.contains("打开只是当前动作,关联才是长期关系。") - && courseWorkspaceSource.contains("尚未建立资料关联") - && courseWorkspaceSource.contains("尚无阅读位置") - && !courseWorkspaceSource.contains("已消化") - && !courseWorkspaceSource.contains("消化率"), "course workspace exposes overview, relationships, and learning records using only evidence-backed status language") + && !courseWorkspaceSource.contains("case overview") + && courseWorkspaceSource.contains("资料与笔记") + && courseWorkspaceSource.contains("资料关系台") + && courseWorkspaceSource.contains("MATERIALS × NOTES"), "course workspace opens directly into an explicit material-note relationship surface instead of an ambiguous overview") expect(courseWorkspaceSource.contains("CourseRelationPaperView(") && courseWorkspaceSource.contains("CourseImmersiveDrawerView") && courseWorkspaceSource.contains(".frame(width: 292)") @@ -2347,10 +2351,23 @@ expect(courseWorkspaceSource.contains("CourseRelationPaperView(") && courseWorkspaceSource.contains("edgeHazeColor") && courseWorkspaceSource.contains("nodeProminence") && courseWorkspaceSource.contains("private struct CourseRelationPaperNodeView: View"), "course drawer and relation paper share explicit course membership while keeping course assignment separate from note-material links") +expect(courseWorkspaceSource.contains("@State private var pendingConnection") + && courseWorkspaceSource.contains("private func handleConnectionTap") + && courseWorkspaceSource.contains("private func connectionButton") + && courseWorkspaceSource.contains("MagnificationGesture()") + && courseWorkspaceSource.contains("private func zoomControls") + && courseWorkspaceSource.contains("private func fitZoomScale") + && courseWorkspaceSource.contains("scrollProxy.scrollTo(Self.paperOriginID, anchor: .topLeading)") + && courseWorkspaceSource.contains("private struct CourseRelationNodeDragModifier") + && courseWorkspaceSource.contains(".accessibilityLabel(\"\\(node.item.title):\\(connectionLabel(state))\")") + && courseWorkspaceSource.contains("private static func fanOffsets") + && courseWorkspaceSource.contains("这里管理资料与笔记的长期关联,不表示当前打开状态。"), "relationship paper explains its boundary, supports click-to-link and zoom, and fans dense bands at shared nodes") expect(courseWorkspaceSource.contains("更改自动保存") - && courseWorkspaceSource.contains("showRecords(session.id)") - && courseWorkspaceSource.contains("courseMaterialsWithoutReadingPosition.first?.id") - && !courseWorkspaceSource.contains("store.courseMaterials + store.sampleItems"), "course relationship edits save immediately, route to the selected fact, and keep built-in samples outside course counts") + && courseWorkspaceSource.contains("private func addLink(materialID: String, noteID: String)") + && courseWorkspaceSource.contains("private func removeLink(noteID: String, materialID: String)") + && courseWorkspaceSource.contains("store.setLinkedNoteIDs") + && courseWorkspaceSource.contains("store.setLinkedCourseSourceIDs") + && !courseWorkspaceSource.contains("store.courseMaterials + store.sampleItems"), "course relationship edits save immediately in both directions while built-in samples stay outside course counts") expect(workspaceStoreSource.contains("@Published private(set) var workspaceSaveError") && workspaceStoreSource.contains("func retryWorkspaceSave()") && workspaceStoreSource.contains("Course changes were not saved to disk") @@ -2372,8 +2389,8 @@ expect(workspaceStoreSource.contains("func presentCourseWorkspace(") && courseWorkspaceSource.contains("确认 Markdown 的角色") && courseWorkspaceSource.contains("guard let noteID = store.createCourseNotebookNote") && courseWorkspaceSource.contains("newNoteError = store.noteFileError") - && appSource.contains("打开课程首页") - && commandPaletteSource.contains("打开课程首页") + && appSource.contains("打开资料关系台") + && commandPaletteSource.contains("打开资料关系台") && sidebarSource.contains("store.presentCourseWorkspace()") && linkedSourcesSource.contains("store.presentCourseWorkspace(.notes"), "course workspace is reachable from top-level commands and note relationships, while explicit open actions own navigation") expect(workspaceStoreSource.contains("scenario == \"course-index-navigation-flow\"") From e69a0561cddd72b0427c70e98444084b5fe13938 Mon Sep 17 00:00:00 2001 From: taekchef Date: Fri, 17 Jul 2026 07:29:12 +0800 Subject: [PATCH 4/4] fix: keep pane resizing active under course drawer --- Sources/WeiBei/Views/ContentView.swift | 8 +------- Sources/WeiBeiSelfCheck/main.swift | 4 +++- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/Sources/WeiBei/Views/ContentView.swift b/Sources/WeiBei/Views/ContentView.swift index 5cc5e10d5..bfa86877e 100644 --- a/Sources/WeiBei/Views/ContentView.swift +++ b/Sources/WeiBei/Views/ContentView.swift @@ -28,12 +28,7 @@ struct ContentView: View { ZStack(alignment: .leading) { if store.showLibrary { WeiBeiTheme.ink.opacity(0.035) - .contentShape(Rectangle()) - .onTapGesture { - withAnimation(WeiBeiMotion.layout) { - store.toggleLibrary() - } - } + .allowsHitTesting(false) .transition(.opacity) CourseImmersiveDrawerView { @@ -45,7 +40,6 @@ struct ContentView: View { } } .frame(maxWidth: .infinity, maxHeight: .infinity) - .allowsHitTesting(store.showLibrary) .zIndex(35) if store.commandPalettePresented { diff --git a/Sources/WeiBeiSelfCheck/main.swift b/Sources/WeiBeiSelfCheck/main.swift index df312f226..55eea91e1 100644 --- a/Sources/WeiBeiSelfCheck/main.swift +++ b/Sources/WeiBeiSelfCheck/main.swift @@ -1467,11 +1467,13 @@ expect(contentViewSource.contains("override func layout()"), "native split appli expect(contentViewSource.contains("CourseImmersiveDrawerView") && contentViewSource.contains("LayoutContentView()") && contentViewSource.contains("ZStack(alignment: .leading)") + && contentViewSource.contains("WeiBeiTheme.ink.opacity(0.035)\n .allowsHitTesting(false)") && contentViewSource.contains(".transition(WeiBeiTransition.sidePanel)") && contentViewSource.contains(".animation(WeiBeiMotion.layout, value: store.showLibrary)") && contentViewSource.contains("withAnimation(WeiBeiMotion.layout)") + && !contentViewSource.contains(".allowsHitTesting(store.showLibrary)") && !contentViewSource.contains("libraryResizeHandle") - && !contentViewSource.contains("minimumContentWidthWithLibrary"), "course drawer temporarily covers the living workspace instead of resizing or rebuilding it") + && !contentViewSource.contains("minimumContentWidthWithLibrary"), "course drawer temporarily covers the living workspace without blocking pane resizing or rebuilding it") expect(contentViewSource.contains("private let railWidth = ContentRailMetrics.railOnlyWidth") && contentRailSource.contains("static let snapThreshold = ContentRailPolicy.snapThreshold") && contentRailSource.contains("static let readableWidth = ContentRailPolicy.readableWidth")