Skip to content

fix(client): pagefind 事件、请求拒绝与图表监听器生命周期 - #742

Open
markd3ng wants to merge 2 commits into
CuteLeaf:masterfrom
markd3ng:ff/client-lifecycle
Open

markd3ng wants to merge 2 commits into
CuteLeaf:masterfrom
markd3ng:ff/client-lifecycle

Conversation

@markd3ng

@markd3ng markd3ng commented Nov 29, 2026 •

Copy link
Copy Markdown

背景

复核客户端生命周期时发现若干独立缺陷,本 PR 逐项修复。

变更

  • FF-8 搜索页 pagefind 事件不可达 (src/pages/search.astro):HEAD 探测非 200 时原本裸 return,pagefindready/pagefindloaderror 既不派发也派发到 window;而消费者 AdvancedSearch.svelte / Search.svelte 只监听 document。现在非 200 走既有 catch 分支,两个事件统一派发到 document(与常驻 Navbar 加载器一致),失败时仍能结束搜索页加载态。
  • FF-15 请求去重的未处理拒绝 (src/utils/fetch-dedup.ts, src/utils/memos-adapter.ts):promise.finally(清理) 产生的派生 Promise 在请求失败时无人处理,触发 unhandledrejection。现在对派生 Promise 追加空 catch;原 Promise 仍原样返回给调用方,错误语义不变。
  • FF-20 沉浸阅读重入 (src/utils/immersive-reading-utils.ts):initImmersiveReading() 被 astro:page-load 每次触发,TOC 点击监听本应按需重绑(容器随换页替换),但补充注释明确全局监听只在 __immersiveReadingInit 守卫内注册,避免误读为泄漏。
  • FF-44 图表 reinit 监听器累积 (src/plugins/diagram-panzoom-script.js):window._diagramPanZoomReinit() 重置 pzInit 后重绑控制栏按钮,每次重试遗留旧回调。现在每次 init 用 AbortController 先中止旧监听器,并把 signal 传给控制栏 click 监听。

验证

  • pnpm run check:0 errors / 0 warnings / 0 hints
  • astro build:40 page(s) built
  • biome check 改动 5 文件:无 fixes applied
  • 构建产物断言:dist/search/index.html 中两处 pagefindready / pagefindloaderror 均已派发到 document,与消费者监听目标一致。

Sourcery 摘要

修复客户端搜索、请求去重、沉浸阅读和图表交互的生命周期问题,确保错误事件可达、请求失败后可安全清理,并避免监听器重复累积。

问题修复:

  • 修复搜索页的 Pagefind 加载事件在索引不可用或加载失败时无法被消费者接收的问题。
  • 修复请求去重清理逻辑导致未处理的 Promise rejection 的问题。
  • 修复图表重复初始化时控制栏事件监听器不断累积的问题。

改进:

  • 明确沉浸阅读的生命周期行为:页面切换时重新绑定目录监听器,全局监听器仅注册一次。
Original summary in English

Sourcery 总结

修复客户端对搜索加载、去重请求、沉浸式阅读和图表交互的生命周期处理。

Bug 修复:

  • 确保 Pagefind 的成功和失败事件能够传递给搜索调用方,包括索引不可用时。
  • 清理去重请求时防止出现未处理的 Promise 拒绝,同时保留请求错误并传递给调用方。
  • 防止图表交互监听器在重新初始化时不断累积。

增强功能:

  • 明确沉浸式阅读的生命周期行为:刷新页面专属的目录绑定,同时确保全局监听器只注册一次。
Original summary in English

Summary by Sourcery

Fix client-side lifecycle handling for search loading, deduplicated requests, immersive reading, and diagram interactions.

Bug Fixes:

  • Ensure Pagefind success and failure events reach search consumers, including when the index is unavailable.
  • Prevent unhandled promise rejections during deduplicated request cleanup while preserving request errors for callers.
  • Prevent diagram interaction listeners from accumulating across reinitializations.

Enhancements:

  • Clarify immersive reading lifecycle behavior so page-specific TOC bindings are refreshed while global listeners remain single-registered.

- search.astro: 非 200 走错误分支,ready/error 事件派发到 document(消费者只监听 document)
- fetch-dedup/memos-adapter: 处理 finally 派生 Promise 的 rejection,避免未处理拒绝
- diagram-panzoom-script: reinit 前 AbortController 中止旧监听器
- immersive-reading-utils: 说明 TOC 按需重绑与全局监听一次性守卫的分工
@netlify

netlify Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

👷 Deploy request for demo-firefly pending review.

Visit the deploys page to approve it

Name Link
🔨 Latest commit 4fe3e3f

@sourcery-ai

sourcery-ai Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

审阅者指南

实现

为清理 Promise 添加拒绝处理,同时原样返回原始请求 Promise。

  • src/utils/fetch-dedup.ts L17-18
  • src/utils/memos-adapter.ts L154-155

移除先前图表初始化时注册的中止监听器,并将每个控件和交互监听器关联到当前初始化的 signal。

  • src/plugins/diagram-panzoom-script.js L98-106, L117-142, L149-161(另有 1 处小改动)

为当前页面重新绑定目录导航,在初始化后更新可见状态,并保留全局监听器的一次性保护机制。

  • src/utils/immersive-reading-utils.ts L204, L206(已删除的行), L215

用户界面

使 Pagefind 加载失败事件能够传递给文档级监听器,并让高级搜索组件处理 ready 或 error 事件。

  • src/components/pages/AdvancedSearch.svelte L102-104
  • src/pages/search.astro L20-23, L29-37

提示和命令

使用 Sourcery

  • 触发新的审阅: 在拉取请求中评论 @sourcery-ai review。
  • 继续讨论: 直接回复 Sourcery 的审阅评论。
  • 根据审阅评论创建 GitHub issue: 回复审阅评论,请 Sourcery 根据该评论创建 issue。你也可以在审阅评论中回复 @sourcery-ai issue,以此创建 issue。
  • 生成拉取请求标题: 在拉取请求标题中的任意位置写入 @sourcery-ai,即可随时生成标题。你也可以在拉取请求中评论 @sourcery-ai title,以随时重新生成标题。
  • 生成拉取请求摘要: 在拉取请求正文中任意位置写入 @sourcery-ai summary,即可在指定位置随时生成 PR 摘要。你也可以在拉取请求中评论 @sourcery-ai summary,以随时重新生成摘要。
  • 生成审阅者指南: 在拉取请求中评论 @sourcery-ai guide,即可随时重新生成审阅者指南。
  • 解决所有 Sourcery 评论: 在拉取请求中评论 @sourcery-ai resolve,即可解决所有 Sourcery 评论。如果你已处理完所有评论且不想再看到它们,这个命令会很有用。
  • 忽略所有 Sourcery 审阅: 在拉取请求中评论 @sourcery-ai dismiss,即可忽略所有现有的 Sourcery 审阅。如果你想从头开始进行新的审阅,这个命令尤其有用——别忘了评论 @sourcery-ai review 来触发新的审阅!

自定义使用体验

访问你的控制面板,即可:

  • 启用或禁用审阅功能,例如 Sourcery 生成的拉取请求摘要、审阅者指南等。
  • 更改审阅语言。
  • 添加、移除或编辑自定义审阅说明。
  • 调整其他审阅设置。

获取帮助

Original review guide in English

Reviewer's Guide

Implementation

Attach rejection handling to the cleanup promises while returning the original request promises unchanged.

  • src/utils/fetch-dedup.ts L17-18
  • src/utils/memos-adapter.ts L154-155

Abort listeners from prior diagram initializations and associate each control and interaction listener with the current initialization’s signal.

  • src/plugins/diagram-panzoom-script.js L98-106, L117-142, L149-161 (+1 small edits)

Rebind the TOC navigation for the current page, update visibility after initialization, and retain the one-time guard for global listeners.

  • src/utils/immersive-reading-utils.ts L204, L206 (removed lines), L215

UI

Make Pagefind loading failures reach document-level listeners and have the advanced search component handle either ready or error events.

  • src/components/pages/AdvancedSearch.svelte L102-104
  • src/pages/search.astro L20-23, L29-37

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

你好——我发现了 4 个问题

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/utils/immersive-reading-utils.ts" line_range="205" />
<code_context>
 	IR.toc = document.getElementById("immersive-toc");
+	// TOC 容器随 Swup 换页被替换,须在每次 init 重绑;仅在首次 init 注册全局监听
 	bindImmersiveTOCNav();
-	updateImmersiveReadingVisibility();

 	// 跨 Swup 切到另一篇文章时若仍在沉浸态,重建目录(SSR 锚点已过期)
</code_context>
<issue_to_address>
**Immersive controls keep stale visibility**

When initialization or Swup navigation occurs before a resize or another visibility update, `initImmersiveReading()` refreshes `IR.btn` without calling `updateImmersiveReadingVisibility()`, so the new button keeps its SSR `hide` class or stale visibility. Desktop readers cannot enter immersive reading when it is enabled with `defaultOn` false, and controls can remain visible where immersive reading is unavailable.

Call `updateImmersiveReadingVisibility()` after refreshing the page’s button references in `initImmersiveReading()`.

Also at `src/utils/immersive-reading-utils.ts:204`.
</issue_to_address>

### Comment 2
<location path="src/plugins/diagram-panzoom-script.js" line_range="34" />
<code_context>
 		container.dataset.pzInit = "true";
+		// reinit 时旧监听器须随旧控制栏一起移除,否则每次重试多留一组回调
+		if (container._pzAbort) container._pzAbort.abort();
+		container._pzAbort = new AbortController();
+		var signal = container._pzAbort.signal;

</code_context>
<issue_to_address>
**Diagram retries accumulate interaction handlers**

When a diagram container is reinitialized, `_diagramPanZoomReinit()` aborts the previous signal, but the container’s pointer and double-click listeners do not use it. Each retry leaves stale callbacks and targets attached, so a gesture runs multiple handlers and diagram interactions behave incorrectly.

Pass the current abort signal to every pointer and double-click listener registered on the container.

Also at `src/plugins/diagram-panzoom-script.js:35`, `src/plugins/diagram-panzoom-script.js:105-106`.
</issue_to_address>

### Comment 3
<location path="src/pages/search.astro" line_range="37" />
<code_context>
             } catch (error) {
                 console.warn("Pagefind script not found or failed to load.");
-                window.dispatchEvent(new Event('pagefindloaderror'));
+                document.dispatchEvent(new CustomEvent('pagefindloaderror'));
             }
         }
</code_context>
<issue_to_address>
**Search stays unusable after load failure**

When the Pagefind HEAD probe or script import fails, `AdvancedSearch` listens for `pagefindready` but not `pagefindloaderror`, so the failure event does not initialize it and `initialized` remains false. Searches return without querying Pagefind, leaving the search page unusable.

Handle `pagefindloaderror` in `AdvancedSearch` and initialize an appropriate failure or fallback state.
</issue_to_address>

### Comment 4
<location path="src/pages/search.astro" line_range="37" />
<code_context>
             } catch (error) {
                 console.warn("Pagefind script not found or failed to load.");
-                window.dispatchEvent(new Event('pagefindloaderror'));
+                document.dispatchEvent(new CustomEvent('pagefindloaderror'));
             }
         }
</code_context>
<issue_to_address>
**Concurrent loaders race initialization**

When the page-local and Navbar loader requests complete with different outcomes, the search page starts its own Pagefind load while `AdvancedSearch` also starts the Navbar loader. If those independent requests produce different outcomes, `Search.svelte` handles both the error and ready events, initializing twice; the Navbar loader can also replace a successfully loaded `window.pagefind` with its empty-result fallback, so search returns no results despite the other load succeeding.

Use one shared, deduplicated Pagefind loading promise and dispatch a single terminal event for its outcome.
</issue_to_address>

Sourcery 评估

等待批准。 请先处理 4 项发现。

阻塞性发现:src/utils/immersive-reading-utils.ts:205、src/plugins/diagram-panzoom-script.js:34、src/pages/search.astro:37、src/pages/search.astro:37


Sourcery 对开源项目免费——如果你喜欢我们的评审,欢迎分享 ✨
Original comment in English

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/utils/immersive-reading-utils.ts" line_range="205" />
<code_context>
 	IR.toc = document.getElementById("immersive-toc");
+	// TOC 容器随 Swup 换页被替换,须在每次 init 重绑;仅在首次 init 注册全局监听
 	bindImmersiveTOCNav();
-	updateImmersiveReadingVisibility();

 	// 跨 Swup 切到另一篇文章时若仍在沉浸态,重建目录(SSR 锚点已过期)
</code_context>
<issue_to_address>
**Immersive controls keep stale visibility**

When initialization or Swup navigation occurs before a resize or another visibility update, `initImmersiveReading()` refreshes `IR.btn` without calling `updateImmersiveReadingVisibility()`, so the new button keeps its SSR `hide` class or stale visibility. Desktop readers cannot enter immersive reading when it is enabled with `defaultOn` false, and controls can remain visible where immersive reading is unavailable.

Call `updateImmersiveReadingVisibility()` after refreshing the page’s button references in `initImmersiveReading()`.

Also at `src/utils/immersive-reading-utils.ts:204`.
</issue_to_address>

### Comment 2
<location path="src/plugins/diagram-panzoom-script.js" line_range="34" />
<code_context>
 		container.dataset.pzInit = "true";
+		// reinit 时旧监听器须随旧控制栏一起移除,否则每次重试多留一组回调
+		if (container._pzAbort) container._pzAbort.abort();
+		container._pzAbort = new AbortController();
+		var signal = container._pzAbort.signal;

</code_context>
<issue_to_address>
**Diagram retries accumulate interaction handlers**

When a diagram container is reinitialized, `_diagramPanZoomReinit()` aborts the previous signal, but the container’s pointer and double-click listeners do not use it. Each retry leaves stale callbacks and targets attached, so a gesture runs multiple handlers and diagram interactions behave incorrectly.

Pass the current abort signal to every pointer and double-click listener registered on the container.

Also at `src/plugins/diagram-panzoom-script.js:35`, `src/plugins/diagram-panzoom-script.js:105-106`.
</issue_to_address>

### Comment 3
<location path="src/pages/search.astro" line_range="37" />
<code_context>
             } catch (error) {
                 console.warn("Pagefind script not found or failed to load.");
-                window.dispatchEvent(new Event('pagefindloaderror'));
+                document.dispatchEvent(new CustomEvent('pagefindloaderror'));
             }
         }
</code_context>
<issue_to_address>
**Search stays unusable after load failure**

When the Pagefind HEAD probe or script import fails, `AdvancedSearch` listens for `pagefindready` but not `pagefindloaderror`, so the failure event does not initialize it and `initialized` remains false. Searches return without querying Pagefind, leaving the search page unusable.

Handle `pagefindloaderror` in `AdvancedSearch` and initialize an appropriate failure or fallback state.
</issue_to_address>

### Comment 4
<location path="src/pages/search.astro" line_range="37" />
<code_context>
             } catch (error) {
                 console.warn("Pagefind script not found or failed to load.");
-                window.dispatchEvent(new Event('pagefindloaderror'));
+                document.dispatchEvent(new CustomEvent('pagefindloaderror'));
             }
         }
</code_context>
<issue_to_address>
**Concurrent loaders race initialization**

When the page-local and Navbar loader requests complete with different outcomes, the search page starts its own Pagefind load while `AdvancedSearch` also starts the Navbar loader. If those independent requests produce different outcomes, `Search.svelte` handles both the error and ready events, initializing twice; the Navbar loader can also replace a successfully loaded `window.pagefind` with its empty-result fallback, so search returns no results despite the other load succeeding.

Use one shared, deduplicated Pagefind loading promise and dispatch a single terminal event for its outcome.
</issue_to_address>

Sourcery assessment

Approval pending. 4 findings to address first.

Blocking findings: src/utils/immersive-reading-utils.ts:205, src/plugins/diagram-panzoom-script.js:34, src/pages/search.astro:37, src/pages/search.astro:37


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src/utils/immersive-reading-utils.ts Resolved
Comment thread src/plugins/diagram-panzoom-script.js Resolved
Comment thread src/pages/search.astro Resolved
Comment thread src/pages/search.astro Resolved
- Share Navbar Pagefind loader with the search page and handle load failure.
- Update immersive button visibility after init.
- Abort diagram panzoom listeners when the diagram reinitializes.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant