Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
77727fc
发问读取实时 PDF 页码并在离开时保存阅读位置
taekchef Sep 26, 2026
95b52b4
重选跨课程共享资料时保留当前阅读页
taekchef Sep 26, 2026
cf3c866
补齐五种文稿的实时阅读位置、精确读取与恢复
taekchef Sep 26, 2026
d51cfb7
fix: 确认 PDF 恢复页后再消费请求
taekchef Sep 28, 2026
15666b4
fix: 保留 Markdown 分页原文换行
taekchef Sep 28, 2026
945e161
fix: 收紧 PDF 恢复请求生命周期
taekchef Sep 28, 2026
9de7568
fix: 避免 PDF 请求编号遮蔽状态
taekchef Sep 28, 2026
5e18030
test: cover complete HTML reads and parsed block locations
Oct 1, 2026
aaf18b8
fix: preserve HTML full text and parse exact block aliases
Oct 1, 2026
3e615a0
Merge commit '0dc5238ecc7fce15c2372f1b1c31c54ac2fcb741' into codex/fi…
Oct 1, 2026
f65c7aa
fix: use pinned HTML5 parser for reader block identity
Oct 1, 2026
d2a2a65
Integrate PR513 reading locations with PR515 language updates
Oct 1, 2026
768b5a5
Merge branch 'codex/fix-20261001-pr513' into codex/fix-20261001-pr513…
Oct 1, 2026
646b0f1
Merge branch 'codex/report-package-size-20261001' into codex/fix-2026…
Oct 1, 2026
e0d908b
Merge branch 'codex/pr515-followup-20261002' into codex/pr513-followu…
taekchef Oct 2, 2026
8e655cd
fix: make reading location restoration one-shot
taekchef Oct 2, 2026
291608a
fix: preserve confirmed markdown reading location
taekchef Oct 2, 2026
274901b
Merge remote-tracking branch 'refs/remotes/origin/main' into codex/pr…
taekchef Oct 2, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions App/Dependencies.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
{
"swiftPackages": [
{
"identity": "swiftsoup",
"kind": "remoteSourceControl",
"location": "https://github.com/scinfu/SwiftSoup.git",
"state": {
"revision": "18b80329749eca5ea29fc50211dca5c7eff5bfec",
"version": "2.13.9"
}
},
{
"identity": "highlightr",
"kind": "remoteSourceControl",
Expand Down
26 changes: 26 additions & 0 deletions App/Resources/ThirdPartyNotices.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2199,3 +2199,29 @@ ReportLab 4.4.9 — BSD; Symbol byte-to-Unicode facts derived from its SymbolEnc
# SUCH DAMAGE.
#
#####################################################################################


SwiftSoup/LICENSE
============================================================
The MIT License

Copyright (c) 2009-2025 Jonathan Hedley <https://jsoup.org/>
Copyright (c) 2016-2025 Nabil Chatbi (Swift port)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 2 additions & 0 deletions App/Sources/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,7 @@ final class AppDelegate: UIResponder, UIApplicationDelegate {
func saveWorkspace() {
guard !Self.usesFixture else { return }
guard saveTask == nil else { return }
Self.workspace.commitCurrentReaderLocation()
backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "保存魏碑工作台") { [weak self] in
MainActor.assumeIsolated {
self?.saveTask?.cancel()
Expand Down Expand Up @@ -355,6 +356,7 @@ final class AppDelegate: UIResponder, UIApplicationDelegate {
func applicationWillTerminate(_ application: UIApplication) {
guard !Self.usesFixture else { return }
Self.workspace.cancelAllAgentRequests()
Self.workspace.commitCurrentReaderLocation()
_ = Self.workspace.flushPendingWorkspaceSave()
Self.workspace.shutdownAgentRuntime()
}
Expand Down
25 changes: 8 additions & 17 deletions App/Sources/CatalystReaders.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,20 @@ extension PDFView { var isFlipped: Bool { true } }

final class ReaderPDFView: PDFView {
var reportCurrentSelection: (() -> Void)?
var onUserScroll: (() -> Void)?
var handleAskUnderlineHover: ((CGPoint) -> Void)?
var handleAskUnderlineClick: ((CGPoint) -> Bool)?
/// X8: plain tap inside the document (not on an ask-underline) — clears the
/// source-reference jump highlight, mirroring the AppKit mouseDown path.
var handleTapInDocument: (() -> Void)?
var onPointerEvent: ((CGPoint?, UIGestureRecognizer.State) -> Void)?
/// R1: trackpad / scroll-wheel only. Kept off the touch pan so text selection
/// does not share a recognizer with scrolling.
var onScrollNavigation: (() -> Void)?
private var adaptsDocumentColors = true
private var documentAppearanceMode: WeiBeiAppearanceMode = .paper
override init(frame: CGRect) {
super.init(frame: frame)
let pan = UIPanGestureRecognizer(target: self, action: #selector(pointer(_:)))
pan.cancelsTouchesInView = false; pan.delegate = self
addGestureRecognizer(pan)
let scroll = UIPanGestureRecognizer(target: self, action: #selector(scrollNavigation(_:)))
scroll.allowedScrollTypesMask = .all
scroll.allowedTouchTypes = []
scroll.cancelsTouchesInView = false
scroll.delegate = self
addGestureRecognizer(scroll)
let tap = UITapGestureRecognizer(target: self, action: #selector(tap(_:)))
tap.cancelsTouchesInView = false; tap.delegate = self
addGestureRecognizer(tap)
Expand All @@ -41,17 +33,16 @@ final class ReaderPDFView: PDFView {
}
override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { true }
@objc private func pointer(_ gesture: UIGestureRecognizer) {
if (gesture.state == .began || gesture.state == .changed),
let pan = gesture as? UIPanGestureRecognizer {
let translation = pan.translation(in: self)
if translation.x != 0 || translation.y != 0 {
onUserScroll?()
}
}
onPointerEvent?(gesture.location(in: self), gesture.state)
reportCurrentSelection?()
}
@objc private func scrollNavigation(_ gesture: UIPanGestureRecognizer) {
switch gesture.state {
case .began, .changed, .ended:
onScrollNavigation?()
default:
break
}
}
@objc private func tap(_ gesture: UITapGestureRecognizer) {
let point = gesture.location(in: self)
if handleAskUnderlineClick?(point) == true { return }
Expand Down
17 changes: 17 additions & 0 deletions App/WeiBei.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -1030,9 +1030,11 @@
dependencies = (
49E6D4A20DE48D1533107998 /* PBXTargetDependency */,
0F01CE000000000000000003 /* PBXTargetDependency */,
D5130ACE0000000000000001 /* PBXTargetDependency */,
);
name = WeiBeiCore;
packageProductDependencies = (
D5130ACE0000000000000002 /* SwiftSoup */,
2357C0DC96C864EA89194FC2 /* Markdown */,
0F01CE000000000000000004 /* ZIPFoundation */,
);
Expand Down Expand Up @@ -1065,6 +1067,7 @@
mainGroup = CD245EE5BAF3B71C96D5FFE0;
minimizedProjectReferenceProxies = 1;
packageReferences = (
D5130ACE0000000000000003 /* XCRemoteSwiftPackageReference "SwiftSoup" */,
0F01CE000000000000000005 /* XCRemoteSwiftPackageReference "ZIPFoundation" */,
EB07E84F9F479A4FC27B9DFB /* XCRemoteSwiftPackageReference "MarkdownView" */,
A362C2116CE98A2EFABB6D0E /* XCRemoteSwiftPackageReference "Sparkle" */,
Expand Down Expand Up @@ -1360,6 +1363,10 @@
/* End PBXSourcesBuildPhase section */

/* Begin PBXTargetDependency section */
D5130ACE0000000000000001 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
productRef = D5130ACE0000000000000002 /* SwiftSoup */;
};
0F01CE000000000000000003 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
productRef = 0F01CE000000000000000004 /* ZIPFoundation */;
Expand Down Expand Up @@ -1744,6 +1751,11 @@
/* End XCConfigurationList section */

/* Begin XCRemoteSwiftPackageReference section */
D5130ACE0000000000000003 /* XCRemoteSwiftPackageReference "SwiftSoup" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/scinfu/SwiftSoup.git";
requirement = {kind = exactVersion; version = 2.13.9; };
};
0F01CE000000000000000005 /* XCRemoteSwiftPackageReference "ZIPFoundation" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/weichsel/ZIPFoundation";
Expand Down Expand Up @@ -1784,6 +1796,11 @@
/* End XCRemoteSwiftPackageReference section */

/* Begin XCSwiftPackageProductDependency section */
D5130ACE0000000000000002 /* SwiftSoup */ = {
isa = XCSwiftPackageProductDependency;
package = D5130ACE0000000000000003 /* XCRemoteSwiftPackageReference "SwiftSoup" */;
productName = SwiftSoup;
};
0F01CE000000000000000004 /* ZIPFoundation */ = {
isa = XCSwiftPackageProductDependency;
package = 0F01CE000000000000000005 /* XCRemoteSwiftPackageReference "ZIPFoundation" */;
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions App/project.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ packages:
ZIPFoundation:
url: https://github.com/weichsel/ZIPFoundation
exactVersion: 0.9.20
SwiftSoup:
url: https://github.com/scinfu/SwiftSoup.git
exactVersion: 2.13.9
targets:
WeiBei:
type: application
Expand Down Expand Up @@ -209,6 +212,8 @@ targets:
product: Markdown
- package: ZIPFoundation
product: ZIPFoundation
- package: SwiftSoup
product: SwiftSoup
WeiBeiPDFTextWorker:
type: tool
platform: macOS
Expand Down
9 changes: 9 additions & 0 deletions Package.resolved

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,15 @@ let package = Package(
],
dependencies: [
.package(url: "https://github.com/weichsel/ZIPFoundation", exact: "0.9.20"),
.package(url: "https://github.com/scinfu/SwiftSoup.git", exact: "2.13.9"),
.package(url: "https://github.com/sparkle-project/Sparkle", exact: "2.9.6"),
.package(url: "https://github.com/swiftlang/swift-markdown.git", exact: "0.7.3"),
.package(url: "https://github.com/WroughtMind/SwiftMath", revision: "b6d15610552aa04a54c36bf205efaf34409dc335")
],
targets: [
.target(
name: "WeiBeiCore",
dependencies: [.product(name: "Markdown", package: "swift-markdown"), "ZIPFoundation"],
dependencies: [.product(name: "Markdown", package: "swift-markdown"), "ZIPFoundation", "SwiftSoup"],
resources: [
.copy("AgentResources")
],
Expand Down
57 changes: 46 additions & 11 deletions Sources/WeiBei/OfficeReader/office.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@ const mathNS = 'http://schemas.openxmlformats.org/officeDocument/2006/math';
const drawingNS = 'http://schemas.openxmlformats.org/drawingml/2006/main';
const pptNS = 'http://schemas.openxmlformats.org/presentationml/2006/main';
const serialize = (e: Node) => new XMLSerializer().serializeToString(e);
const post = (name: string, payload: unknown) => (window as any).webkit?.messageHandlers?.[name]?.postMessage(payload);
const post = (name: string, payload: unknown) => {
const tagged = payload && typeof payload === 'object' && !Array.isArray(payload)
? { ...(payload as Record<string, unknown>), loadToken: document.body?.dataset.weibeiReaderLoadToken || '' }
: payload;
(window as any).webkit?.messageHandlers?.[name]?.postMessage(tagged);
};
const parse = (xml: string) => {
const doc = new DOMParser().parseFromString(xml, 'application/xml');
if (doc.querySelector('parsererror')) throw new Error(t('文稿内容损坏,无法读取', 'This document is damaged and cannot be read'));
Expand Down Expand Up @@ -140,7 +145,7 @@ function verifyEquations(element: Element, part: string) {
let resourceIssues: string[] = [];
const reportResourceIssue = (message: string) => {
if (!resourceIssues.includes(message)) resourceIssues.push(message);
post('htmlResourceIssues', resourceIssues.slice(0, 100));
post('htmlResourceIssues', { missing: resourceIssues.slice(0, 100) });
};
const verifyEquationsQuietly = (element: Element, part: string) => {
try { verifyEquations(element, part); }
Expand All @@ -166,14 +171,18 @@ function sections() {
const headings = blocks.filter(p => /heading|标题/i.test(p.className) || p.getAttribute('role') === 'heading');
return (headings.length ? headings : blocks.filter((_, i) => i % 15 === 0)).map((p, i, all) => ({ id: p.dataset.weibeiLocation!, title: clean(p.textContent).slice(0, 60), excerpt: '', level: 1, position: i / Math.max(1, all.length - 1), metadata: 'Word' }));
}
const postSections = () => post('contentRailSections', { sections: sections() });
let officeNavigationInProgress = false;
let presentationHasReportedPosition = false;
async function goTo(location: string) {
officeNavigationInProgress = true;
let activeID = location;
if (viewer) {
const index = viewer.presentationData!.slides.findIndex(s => s.slidePath === location.split('#')[0]);
// Notes have the source location of their own part, but belong to one slide.
const noteIndex = viewer.presentationData!.slides.findIndex(s => noteParts.get(s.slidePath) === location.split('#')[0]);
const target = index >= 0 ? index : noteIndex;
if (target < 0) return false;
if (target < 0) { officeNavigationInProgress = false; return false; }
activeID = viewer.presentationData!.slides[target].slidePath;
await viewer.goToSlide(target, { behavior: 'instant', block: 'start' });
}
Expand All @@ -184,10 +193,16 @@ async function goTo(location: string) {
note.showPopover();
element!.scrollIntoView({ block: 'nearest', behavior: 'instant' });
} else if (element && (!viewer || location.includes('#'))) element.scrollIntoView({ block: 'center', behavior: 'instant' });
else if (!viewer) return false;
post('contentRailActive', { id: activeID, reason: 'jump' });
else if (!viewer) { officeNavigationInProgress = false; return false; }
post('contentRailActive', { id: activeID, title: sections().find(section => section.id === activeID)?.title, reason: 'jump' });
window.setTimeout(() => { officeNavigationInProgress = false; }, 0);
return true;
}
function canGoTo(location: string) {
if (!viewer) return Boolean(sourceElement(location));
const part = location.split('#')[0];
return viewer.presentationData!.slides.some(slide => slide.slidePath === part || noteParts.get(slide.slidePath) === part);
}
async function find(query: string) {
if (!viewer) return (window as any).find(query, false, false, true, false, true, false);
if (query !== searchQuery) { searchQuery = query; searchResult = -1; }
Expand Down Expand Up @@ -347,14 +362,15 @@ function setLanguage(language?: string) {
const page = Number(label.dataset.weibeiSlideLabel);
if (Number.isFinite(page)) label.textContent = pageLabel(page);
});
if (viewer || root) post('contentRailSections', sections());
if (viewer || root) postSections();
}

async function open(url: string | ArrayBuffer, format: string, language?: string) {
english = language === 'english';
root = document.getElementById('office-document')!;
document.documentElement.style.setProperty('-webkit-text-size-adjust', '100%');
kind = format; loadError = ''; resourceIssues = []; notes.clear(); noteParts.clear(); equations.clear(); mainPart = '';
officeNavigationInProgress = false; presentationHasReportedPosition = false;
try {
const bytes = typeof url === 'string' ? await (await fetch(url)).arrayBuffer() : url;
const zip = await prepare(bytes, format);
Expand All @@ -372,7 +388,13 @@ async function open(url: string | ArrayBuffer, format: string, language?: string
zipLimits: RECOMMENDED_ZIP_LIMITS, lazySlides: true, lazyMedia: true, pdfjs: false,
onNodeError: (_id, error) => { loadError = String(error); queueMicrotask(() => fail(error)); },
onSlideError: (_index, error) => { loadError = String(error); queueMicrotask(() => fail(error)); },
onSlideChange: index => post('contentRailActive', { id: viewer?.presentationData?.slides[index].slidePath, reason: 'scroll' }),
onSlideChange: index => post('contentRailActive', {
id: viewer?.presentationData?.slides[index].slidePath,
title: t(`第 ${index + 1} 页`, `Page ${index + 1}`),
reason: officeNavigationInProgress
? 'programmatic'
: (presentationHasReportedPosition ? 'scroll' : (presentationHasReportedPosition = true, 'initial')),
}),
onSlideRendered: (index, element) => {
const slide = viewer?.presentationData?.slides[index];
if (slide) {
Expand Down Expand Up @@ -407,7 +429,8 @@ async function open(url: string | ArrayBuffer, format: string, language?: string
const broken = await Promise.all(Array.from(root.querySelectorAll('img, svg image')).map(async element => { const img = new Image(); img.src = element instanceof HTMLImageElement ? element.src : (element as SVGImageElement).href.baseVal; try { await img.decode(); return false; } catch { return true; } }));
const brokenCount = broken.filter(Boolean).length;
if (brokenCount > 0) reportResourceIssue(t(`文稿中有 ${brokenCount} 张图片未能显示,正文已导入`, `${brokenCount} images could not be shown; the text was imported`));
post('contentRailSections', sections());
postSections();
if (format === 'docx') reportWordActive('initial');
post('officeReady', { loaded: true });
} catch (error) { fail(error); }
}
Expand All @@ -427,13 +450,25 @@ async function applyMarks(asks: unknown[], remarks: any[]) {
(window as any).WeiBeiRemarkMarks?.apply(remarks);
}

window.addEventListener('scroll', () => {
const reportWordActive = (reason: 'initial' | 'scroll' | 'programmatic') => {
if (kind !== 'docx' || !root) return;
const line = window.innerHeight * .3;
const candidates = Array.from(root.querySelectorAll<HTMLElement>('p[data-weibei-location]'));
const active = candidates.find(p => { const r = p.getBoundingClientRect(); return r.bottom >= line; });
if (active) post('contentRailActive', { id: active.dataset.weibeiLocation, reason: 'scroll' });
if (active) post('contentRailActive', { id: active.dataset.weibeiLocation, reason });
};
window.addEventListener('scroll', () => {
reportWordActive(officeNavigationInProgress ? 'programmatic' : 'scroll');
}, { passive: true });

(window as any).WeiBeiOffice = { open, math, drawWMFText, renderGraphic, graphicRelations, has3DChart, render3DChart, goTo, find, searchResults, activateSearchResult, sections, sourceOrder, applyMarks, attachNote, pageLabel, setLanguage, get isPresentation() { return Boolean(viewer); }, get error() { return loadError; } };
(window as any).WeiBeiContentRail = { installed: true, scrollTo: (id: string) => { void goTo(id); }, scan: () => post('contentRailSections', sections()), setLanguage };
(window as any).WeiBeiContentRail = {
installed: true,
scrollTo: (id: string) => {
if (!canGoTo(id)) return false;
void goTo(id);
return true;
},
scan: postSections,
setLanguage
};
Loading
Loading