@bhxch/vviewer-lightbox 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 vviewer contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,65 @@
1
- # Temporary Holding Version
1
+ # @bhxch/vviewer-lightbox
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 零依赖灯箱组件包:body 级单例 overlay——画廊导航(←/→ 环绕)、键盘集、光标锚定
4
+ 缩放平移(滚轮/按钮/+− 键)、owner 代币防多实例互删。自 render-text 管线迁出的
5
+ 全自研组件,供任何需要图片/SVG 灯箱的查看器复用。组件只负责 DOM 装配与交互;
6
+ 样式由宿主按类名约定自备(web 端示例见 `apps/web/src/app.css` 的 `.md-lightbox-*`
7
+ 规则组,app.css:217-237)。
8
+
9
+ ## 安装
10
+
11
+ ```bash
12
+ npm install @bhxch/vviewer-lightbox
13
+ ```
14
+
15
+ ## 公共导出面(`src/index.ts`)
16
+
17
+ | 符号 | 说明 |
18
+ | --- | --- |
19
+ | `collectGallery(root)` | 收集渲染根下画廊条目(img 在前、`.md-diagram-view` 内 svg 在后;跳过 <32px 微缩图与 KaTeX 内 img) |
20
+ | `openLightbox(el, ctx, gallery)` | 点击画廊元素打开灯箱:按元素身份定位画廊位置,未命中退化单条 |
21
+ | `removeLightboxOverlay(doc, ownerId?)` | 移除 overlay(宿主渲染器 destroy 调用);传 ownerId 时校验 owner 代币,非 owner 跳过 |
22
+ | `clampZoom` / `zoomAt` / `navigate` | 状态机纯函数:缩放限幅(0.2–8)/ 光标锚定缩放 / 画廊环绕导航 |
23
+ | `LIGHTBOX_OVERLAY_ID` | overlay 元素 id 常量(`'md-lightbox-overlay'`) |
24
+ | `LIGHTBOX_OWNER_ATTR` | owner 代币属性常量(`'data-md-lightbox-owner'`) |
25
+ | `GalleryItem` / `LightboxState` / `LightboxCtx` | 类型 |
26
+
27
+ ## 类名与 themeClassPrefix 前缀(公开约定)
28
+
29
+ 组件生成元素的类名走 `md-lightbox-*` 基名 + `ctx.themeClassPrefix` 前缀机制:
30
+ 前缀非空时输出 `${themeClassPrefix}${base}`(如 `'dark-'` → `.dark-md-lightbox-overlay`)。
31
+ 该机制是本包公开约定——宿主启用前缀时,样式必须按同规则加前缀写作用域选择器;
32
+ 不传前缀则为裸基名(web 端当前即裸基名形态)。基名清单:`md-lightbox`(内容 img)、
33
+ `md-lightbox-overlay`、`-stage`、`-svg`、`-bar`、`-btn`(及 `-prev/-next/-zoom-in/
34
+ -zoom-out/-reset/-close` 变体)、`-count`、`-dragging`。
35
+
36
+ `LIGHTBOX_OVERLAY_ID` 为 overlay 的 DOM id 常量:宿主生成其它元素 id 应避让该值
37
+ (render-text `markdownRenderer.assignHeadingIds` 即消费此常量预填 id 避让集);
38
+ 导出剥离/选择器拼接等场景应引用常量而非字面量,防双端漂移。
39
+
40
+ ## owner 代币(多实例防互删)
41
+
42
+ body 级 overlay 是跨渲染实例的单例:宿主每次 render 生成唯一 token 经
43
+ `ctx.lightboxOwner` 传入,`openLightbox` 把「最后打开者」记在 overlay 上;
44
+ `removeLightboxOverlay(doc, ownerId)` 只许 owner 随自身 destroy 摘除——多渲染
45
+ 实例(多 tab)共存时互不删对方正开着的灯箱。不传 ownerId(Esc/点背景等自有关
46
+ 场景)则无条件移除。
47
+
48
+ ## ctx 最小局部接口(依赖倒置)
49
+
50
+ `LightboxCtx` 仅含 `themeClassPrefix` / `lightboxOwner` 两个可选字段——实测
51
+ `openLightbox`/`cls` 的消费面仅此两项。宿主管线上下文(如 render-text 的
52
+ `PipelineCtx`)结构性兼容即可直接传参,类型擦除、无运行时环。
53
+
54
+ ## 发布注意(未来转公开发布时)
55
+
56
+ - monorepo 态 exports 指 `src/*.ts`(与仓库各包一致,当前 private 无构建);
57
+ 转发布时 build script `tsc` emit 到 dist 并改写 exports/main/types 指向 dist
58
+ (相对形式不变)。零第三方依赖、无资产文件,无需额外拷贝步骤。
59
+ - `LIGHTBOX_OVERLAY_ID` / 类名基名是跨端契约面:发布版与宿主样式、导出剥离逻辑
60
+ 必须同步演进。
61
+
62
+ ## 仓库与许可
63
+
64
+ - 仓库:[bhxch/vviewer](https://github.com/bhxch/vviewer),源码位于 `packages/vviewer-lightbox/`
65
+ - 许可:Apache-2.0;第三方依赖许可见仓库 `THIRD_PARTY_NOTICES.md`
package/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { clampZoom, collectGallery, LIGHTBOX_OVERLAY_ID, LIGHTBOX_OWNER_ATTR, navigate, openLightbox, removeLightboxOverlay, zoomAt, type GalleryItem, type LightboxCtx, type LightboxState, } from './lightbox.js';
package/index.js ADDED
@@ -0,0 +1,5 @@
1
+ // index.ts — @bhxch/vviewer-lightbox 包根导出面:零依赖灯箱组件(画廊收集 / 键盘集 /
2
+ // 光标锚定缩放平移 / owner 代币防互删),自 render-text 管线迁出的全自研组件。
3
+ // 跨包消费一律经包根 import(含主应用改造点所需的全部符号:
4
+ // collectGallery/openLightbox/removeLightboxOverlay/LIGHTBOX_OVERLAY_ID/LIGHTBOX_OWNER_ATTR)。
5
+ export { clampZoom, collectGallery, LIGHTBOX_OVERLAY_ID, LIGHTBOX_OWNER_ATTR, navigate, openLightbox, removeLightboxOverlay, zoomAt, } from './lightbox.js';
package/lightbox.d.ts ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * 灯箱消费的宿主上下文最小局部接口(依赖倒置:类型擦除无运行时环,宿主管线
3
+ * 上下文——如 render-text 的 PipelineCtx——结构性兼容即可直接传参)。实测消费面
4
+ * 仅 themeClassPrefix/lightboxOwner 两项。
5
+ */
6
+ export interface LightboxCtx {
7
+ /** 主题类前缀:灯箱生成元素的类名前缀,供主题作用域样式(公开约定见 README)。 */
8
+ themeClassPrefix?: string;
9
+ /**
10
+ * 灯箱归属实例代币:body 级 overlay 是跨渲染实例的单例,宿主每次 render 生成
11
+ * 唯一值传入;openLightbox 把「最后打开者」记在 overlay 上,removeLightboxOverlay
12
+ * 只许 owner 随自身 destroy 摘除——多渲染实例(多 tab)共存时互不删对方正开着的灯箱。
13
+ */
14
+ lightboxOwner?: string;
15
+ }
16
+ /** body 级灯箱 overlay 的元素 id(openLightbox 创建;宿主渲染器 destroy 时清理防泄漏。
17
+ * 宿主若生成其它元素 id 应避让该值——render-text assignHeadingIds 即消费此常量预填避让集)。 */
18
+ export declare const LIGHTBOX_OVERLAY_ID = "md-lightbox-overlay";
19
+ /** overlay 上的打开者代币属性(openLightbox 写入、removeLightboxOverlay 校验,遗留 U3) */
20
+ export declare const LIGHTBOX_OWNER_ATTR = "data-md-lightbox-owner";
21
+ /** 画廊条目:img 取 src/alt;svg(图表视图)取 outerHTML(alt 空)。保持纯数据形态,
22
+ * 元素身份走 itemEls 副表(WeakMap)——同 src 多图按元素引用定位,src 匹配不复用。 */
23
+ export interface GalleryItem {
24
+ type: 'img' | 'svg';
25
+ src: string;
26
+ alt: string;
27
+ }
28
+ /** 视图状态:zoom 缩放、tx/ty 平移(overlay 坐标系,stage origin 0 0)、index 画廊位置。 */
29
+ export interface LightboxState {
30
+ zoom: number;
31
+ tx: number;
32
+ ty: number;
33
+ index: number;
34
+ }
35
+ /** 缩放限幅:下限 0.2 防缩没、上限 8 防性能塌方。 */
36
+ export declare function clampZoom(zoom: number): number;
37
+ /** 光标中心锚定缩放:缩放后光标下内容点保持原屏幕位置(推导见文件头)。 */
38
+ export declare function zoomAt(state: LightboxState, factor: number, cx: number, cy: number): LightboxState;
39
+ /** 画廊导航(index 环绕):count 非正不挪。 */
40
+ export declare function navigate(state: {
41
+ index: number;
42
+ count: number;
43
+ }, delta: number): {
44
+ index: number;
45
+ };
46
+ /**
47
+ * 收集渲染根下的画廊条目(文档序:img 在前、图表 svg 在后):img 跳过两类——
48
+ * 宽高属性均在且均 <32px 的微缩图(图标/表情)、KaTeX 排版产物内的 img;图表
49
+ * 视图(.md-diagram-view)内的 svg 整体入列(src 记 outerHTML 供灯箱回放)。
50
+ */
51
+ export declare function collectGallery(root: ParentNode): GalleryItem[];
52
+ /**
53
+ * 从文档移除灯箱 overlay(宿主渲染器 destroy 调用;overlay 挂在 body,不随渲染节点销毁)。
54
+ * ownerId 传时校验打开者代币:非当前 owner 的 destroy 直接跳过(多渲染实例
55
+ * 共存时互删对方正开着的灯箱,遗留 U3);不传(Esc / overlay 点击等自有关场景)
56
+ * 行为不变,无条件移除。
57
+ */
58
+ export declare function removeLightboxOverlay(doc: Document, ownerId?: string): void;
59
+ /**
60
+ * 点击画廊元素(img 或图表 svg)打开灯箱:按收集时的元素身份定位画廊位置(同 src
61
+ * 多图各归各位;未命中退化为单条画廊)。gallery 由调用方(宿主管线的 lightbox 步)
62
+ * 点击时对渲染根收集:同一文档内的 img 与图表 svg 可在灯箱内 ←/→ 连续导航。
63
+ */
64
+ export declare function openLightbox(el: Element, ctx: LightboxCtx, gallery: GalleryItem[]): void;
package/lightbox.js ADDED
@@ -0,0 +1,329 @@
1
+ // lightbox.ts — markdown 灯箱(body 级单例 overlay):画廊导航 + 键盘集 + 缩放平移。
2
+ // 全自研零依赖灯箱组件,自 render-text pipeline 迁入本包(原位置 render-text 侧
3
+ // 已于迁出前收口为三导出转发,下游阶段由消费方改引本包);三导出
4
+ // (LIGHTBOX_OVERLAY_ID / LIGHTBOX_OWNER_ATTR / removeLightboxOverlay)语义原样。
5
+ // 对宿主管线上下文只依赖最小局部接口 LightboxCtx(类型擦除,无运行时环)。
6
+ // - 状态机纯函数(clampZoom/zoomAt/navigate)单测直测:zoomAt 光标中心锚定——
7
+ // 屏幕点 p = 内容点 c × zoom + t(stage transform-origin 0 0 同构),令光标处
8
+ // 缩放前后 p 不变解出 t' = (cx,cy) − applied × ((cx,cy) − t)。
9
+ // - 关闭语义(T1 裁决):点背景(overlay 本体/stage 空白)或关闭钮关;点内容与
10
+ // 控制件不关——比原「点 overlay 任意处关」多一层 target 判定,原有语义测试
11
+ // (overlay.click())不受影响。
12
+ // - 拖拽 pan 与关闭的冲突(T2 裁决):拖拽位移超阈值置 dragMoved,吞掉 mouseup
13
+ // 后收尾的 click(该 click 经冒泡会落在 overlay 上,否则拖完即误关)。
14
+ // - 递延清偿(5-2/5-3/5-5):输入控件内按键直通不劫持;overlay 具对话框语义
15
+ // (role/aria-modal/开启焦点入/关闭焦点还原/计数 aria-live);画廊按元素身份定位
16
+ // (同 src 多图各归各位,条目纯数据 + itemEls 副表)。
17
+ /** body 级灯箱 overlay 的元素 id(openLightbox 创建;宿主渲染器 destroy 时清理防泄漏。
18
+ * 宿主若生成其它元素 id 应避让该值——render-text assignHeadingIds 即消费此常量预填避让集)。 */
19
+ export const LIGHTBOX_OVERLAY_ID = 'md-lightbox-overlay';
20
+ /** overlay 上的打开者代币属性(openLightbox 写入、removeLightboxOverlay 校验,遗留 U3) */
21
+ export const LIGHTBOX_OWNER_ATTR = 'data-md-lightbox-owner';
22
+ /** 缩放限幅:下限 0.2 防缩没、上限 8 防性能塌方。 */
23
+ export function clampZoom(zoom) {
24
+ return Math.min(8, Math.max(0.2, zoom));
25
+ }
26
+ /** 光标中心锚定缩放:缩放后光标下内容点保持原屏幕位置(推导见文件头)。 */
27
+ export function zoomAt(state, factor, cx, cy) {
28
+ const zoom = clampZoom(state.zoom * factor);
29
+ const applied = zoom / state.zoom;
30
+ return { zoom, tx: cx - applied * (cx - state.tx), ty: cy - applied * (cy - state.ty), index: state.index };
31
+ }
32
+ /** 画廊导航(index 环绕):count 非正不挪。 */
33
+ export function navigate(state, delta) {
34
+ if (state.count <= 0)
35
+ return { index: state.index };
36
+ return { index: ((state.index + delta) % state.count + state.count) % state.count };
37
+ }
38
+ /** 画廊条目 → 收集时源元素:同 src 多图按元素身份定位用。收集即注册(点击时现场
39
+ * 收集,引用恒新鲜);条目为一次性对象,WeakMap 弱引用随条目回收,无泄漏面。 */
40
+ const itemEls = new WeakMap();
41
+ /**
42
+ * 收集渲染根下的画廊条目(文档序:img 在前、图表 svg 在后):img 跳过两类——
43
+ * 宽高属性均在且均 <32px 的微缩图(图标/表情)、KaTeX 排版产物内的 img;图表
44
+ * 视图(.md-diagram-view)内的 svg 整体入列(src 记 outerHTML 供灯箱回放)。
45
+ */
46
+ export function collectGallery(root) {
47
+ const items = [];
48
+ for (const img of Array.from(root.querySelectorAll('img'))) {
49
+ if (img.closest('.katex'))
50
+ continue;
51
+ // 宽高属性均在且均 <32 才跳过;属性缺失(Number(null)=0)不得误判——常规文档图无宽高属性
52
+ const wAttr = img.getAttribute('width');
53
+ const hAttr = img.getAttribute('height');
54
+ if (wAttr !== null && hAttr !== null && Number(wAttr) < 32 && Number(hAttr) < 32)
55
+ continue;
56
+ const item = { type: 'img', src: img.getAttribute('src') ?? '', alt: img.getAttribute('alt') ?? '' };
57
+ itemEls.set(item, img);
58
+ items.push(item);
59
+ }
60
+ for (const svg of Array.from(root.querySelectorAll('.md-diagram-view svg'))) {
61
+ const item = { type: 'svg', src: svg.outerHTML, alt: '' };
62
+ itemEls.set(item, svg);
63
+ items.push(item);
64
+ }
65
+ return items;
66
+ }
67
+ // ---------- DOM 装配 ----------
68
+ /** 灯箱元素类名(公开约定:可被 ctx.themeClassPrefix 前缀供主题作用域,见 README)。 */
69
+ const CLS = {
70
+ lightbox: 'md-lightbox',
71
+ lightboxOverlay: 'md-lightbox-overlay',
72
+ stage: 'md-lightbox-stage',
73
+ svgHost: 'md-lightbox-svg',
74
+ bar: 'md-lightbox-bar',
75
+ btn: 'md-lightbox-btn',
76
+ btnPrev: 'md-lightbox-btn-prev',
77
+ btnNext: 'md-lightbox-btn-next',
78
+ btnZoomIn: 'md-lightbox-btn-zoom-in',
79
+ btnZoomOut: 'md-lightbox-btn-zoom-out',
80
+ btnReset: 'md-lightbox-btn-reset',
81
+ btnClose: 'md-lightbox-btn-close',
82
+ count: 'md-lightbox-count',
83
+ dragging: 'md-lightbox-dragging',
84
+ };
85
+ function cls(ctx, base) {
86
+ const name = CLS[base];
87
+ return ctx.themeClassPrefix ? ctx.themeClassPrefix + name : name;
88
+ }
89
+ /** overlay → 其 document 级键盘监听(removeLightboxOverlay / 关闭时随之摘除,防监听器累积) */
90
+ const escHandlers = new WeakMap();
91
+ /** overlay → 其打开函数(复用单例时取回闭包状态;随元素由 WeakMap 回收) */
92
+ const openers = new WeakMap();
93
+ /** overlay → 其触发元素(关闭时焦点还原,a11y 基线;随元素由 WeakMap 回收) */
94
+ const origins = new WeakMap();
95
+ /** 缩放步进(键盘/滚轮/按钮同规) */
96
+ const ZOOM_STEP = 1.25;
97
+ /** 拖拽位移超过该值(Manhattan 距离,px)才算真拖拽:吞掉收尾 click 防拖完误关 */
98
+ const DRAG_THRESHOLD = 3;
99
+ /**
100
+ * 从文档移除灯箱 overlay(宿主渲染器 destroy 调用;overlay 挂在 body,不随渲染节点销毁)。
101
+ * ownerId 传时校验打开者代币:非当前 owner 的 destroy 直接跳过(多渲染实例
102
+ * 共存时互删对方正开着的灯箱,遗留 U3);不传(Esc / overlay 点击等自有关场景)
103
+ * 行为不变,无条件移除。
104
+ */
105
+ export function removeLightboxOverlay(doc, ownerId) {
106
+ const overlay = doc.getElementById(LIGHTBOX_OVERLAY_ID);
107
+ if (!overlay)
108
+ return;
109
+ if (ownerId !== undefined && overlay.getAttribute(LIGHTBOX_OWNER_ATTR) !== ownerId)
110
+ return;
111
+ const onKey = escHandlers.get(overlay);
112
+ if (onKey)
113
+ doc.removeEventListener('keydown', onKey);
114
+ escHandlers.delete(overlay);
115
+ const origin = origins.get(overlay);
116
+ origins.delete(overlay);
117
+ overlay.remove();
118
+ // 焦点还原到触发元素(a11y 基线):focus 定义于 HTMLElement/SVGElement 而 Element
119
+ // 接口未声明,此表运行时只存 img/svg 触发元素,最小收窄安全;触发元素不可聚焦
120
+ // (img/svg 默认无 tabindex)或已脱离文档时 focus 为无害 no-op
121
+ origin?.focus();
122
+ }
123
+ /** 未入画廊元素的退化条目(微缩图/KaTeX 内 img 等被收集规则跳过时的单开):svg 取
124
+ * outerHTML 回放,img 取 src/alt。 */
125
+ function fallbackItem(el) {
126
+ return el.tagName.toLowerCase() === 'svg'
127
+ ? { type: 'svg', src: el.outerHTML, alt: '' }
128
+ : { type: 'img', src: el.getAttribute('src') ?? '', alt: el.getAttribute('alt') ?? '' };
129
+ }
130
+ /**
131
+ * 点击画廊元素(img 或图表 svg)打开灯箱:按收集时的元素身份定位画廊位置(同 src
132
+ * 多图各归各位;未命中退化为单条画廊)。gallery 由调用方(宿主管线的 lightbox 步)
133
+ * 点击时对渲染根收集:同一文档内的 img 与图表 svg 可在灯箱内 ←/→ 连续导航。
134
+ */
135
+ export function openLightbox(el, ctx, gallery) {
136
+ const doc = el.ownerDocument;
137
+ // body 级单例:首次点击创建,之后所有图共用
138
+ let overlay = doc.getElementById(LIGHTBOX_OVERLAY_ID);
139
+ if (!overlay) {
140
+ const built = buildOverlay(doc, ctx);
141
+ overlay = built.overlay;
142
+ openers.set(overlay, built.open);
143
+ }
144
+ const idx = gallery.findIndex((it) => itemEls.get(it) === el);
145
+ const items = idx === -1 ? [fallbackItem(el)] : gallery;
146
+ const open = openers.get(overlay);
147
+ if (!open) {
148
+ // 防御(不裸非空断言):同 id 陌生元素(外部 DOM 注入/序列化恢复等理论路径)
149
+ // 无打开表项——不复用不重建,按脏状态移除,下次点击走全新构建
150
+ removeLightboxOverlay(doc);
151
+ return;
152
+ }
153
+ origins.set(overlay, el); // 关闭时焦点还原目标(每次打开跟随最新触发元素)
154
+ open(items, idx === -1 ? 0 : idx);
155
+ // 最后打开者即 owner(覆盖旧记号):其后仅 owner 的 destroy 可随生命周期摘除(U3)。
156
+ // 注意须在此处写(而非 buildOverlay 闭包):复用单例时归属跟随本次打开者的 ctx。
157
+ overlay.setAttribute(LIGHTBOX_OWNER_ATTR, ctx.lightboxOwner ?? '');
158
+ }
159
+ /**
160
+ * 构造 overlay DOM 并接线全部交互,挂入 doc.body,返回 { overlay, open }:
161
+ * open(items, index) 装载画廊条目并复位视图。闭包持有可变状态(items/state),
162
+ * 单 overlay 一份——多 document(多渲染实例)互不串扰。
163
+ */
164
+ function buildOverlay(doc, ctx) {
165
+ let items = [];
166
+ let state = { zoom: 1, tx: 0, ty: 0, index: 0 };
167
+ let dragMoved = false;
168
+ const overlay = doc.createElement('div');
169
+ overlay.id = LIGHTBOX_OVERLAY_ID;
170
+ overlay.className = cls(ctx, 'lightboxOverlay');
171
+ // a11y 基线(5-3):对话框语义 + 程序化聚焦宿主(Tab 序不掺入 overlay 本体)
172
+ overlay.setAttribute('role', 'dialog');
173
+ overlay.setAttribute('aria-modal', 'true');
174
+ overlay.tabIndex = -1;
175
+ // 内容容器(stage):缩放平移的变换面,absolute 铺满 overlay 使其坐标系与
176
+ // zoomAt 的光标坐标同系(CSS transform-origin: 0 0)
177
+ const stage = doc.createElement('div');
178
+ stage.className = cls(ctx, 'stage');
179
+ const clone = doc.createElement('img');
180
+ clone.className = cls(ctx, 'lightbox');
181
+ const svgHost = doc.createElement('div');
182
+ svgHost.className = cls(ctx, 'svgHost');
183
+ svgHost.setAttribute('hidden', '');
184
+ stage.append(clone, svgHost);
185
+ // 控制件条:prev/next/计数 + 缩放钮组 + 关闭
186
+ const bar = doc.createElement('div');
187
+ bar.className = cls(ctx, 'bar');
188
+ const count = doc.createElement('span');
189
+ count.className = cls(ctx, 'count');
190
+ count.setAttribute('aria-live', 'polite'); // 计数切换对读屏播报(a11y 基线)
191
+ const applyState = () => {
192
+ stage.style.transform = `translate(${state.tx}px, ${state.ty}px) scale(${state.zoom})`;
193
+ count.textContent = `${state.index + 1}/${items.length}`;
194
+ };
195
+ /** 按当前 index 渲染条目内容(img 换 src/alt;svg 注入 outerHTML),切换两宿主显隐。 */
196
+ const showItem = () => {
197
+ const item = items[state.index];
198
+ if (item.type === 'img') {
199
+ clone.setAttribute('src', item.src);
200
+ clone.setAttribute('alt', item.alt);
201
+ clone.removeAttribute('hidden');
202
+ svgHost.setAttribute('hidden', '');
203
+ }
204
+ else {
205
+ svgHost.innerHTML = item.src;
206
+ svgHost.removeAttribute('hidden');
207
+ clone.setAttribute('hidden', '');
208
+ }
209
+ };
210
+ const resetView = () => {
211
+ state = { zoom: 1, tx: 0, ty: 0, index: state.index };
212
+ applyState();
213
+ };
214
+ const centerZoom = (factor) => {
215
+ state = zoomAt(state, factor, overlay.clientWidth / 2, overlay.clientHeight / 2);
216
+ applyState();
217
+ };
218
+ /** 环绕导航:内容切换且视图复位(新图从 1:1 看起)。 */
219
+ const go = (delta) => {
220
+ state = { zoom: 1, tx: 0, ty: 0, index: navigate({ index: state.index, count: items.length }, delta).index };
221
+ showItem();
222
+ applyState();
223
+ };
224
+ const mkBtn = (base, glyph, label, onClick) => {
225
+ const b = doc.createElement('button');
226
+ b.type = 'button';
227
+ b.className = `${cls(ctx, 'btn')} ${cls(ctx, base)}`;
228
+ b.textContent = glyph;
229
+ b.setAttribute('aria-label', label);
230
+ b.addEventListener('click', onClick);
231
+ return b;
232
+ };
233
+ const prev = mkBtn('btnPrev', '‹', '上一张', () => go(-1));
234
+ const next = mkBtn('btnNext', '›', '下一张', () => go(1));
235
+ const zoomOut = mkBtn('btnZoomOut', '−', '缩小', () => centerZoom(1 / ZOOM_STEP));
236
+ const zoomIn = mkBtn('btnZoomIn', '+', '放大', () => centerZoom(ZOOM_STEP));
237
+ const reset = mkBtn('btnReset', '⟲', '重置视图', resetView);
238
+ const closeBtn = mkBtn('btnClose', '×', '关闭', () => removeLightboxOverlay(doc));
239
+ bar.append(prev, next, count, zoomOut, zoomIn, reset, closeBtn);
240
+ overlay.append(stage, bar);
241
+ // 键盘集(document 级,escHandlers 既有模式:关闭随之摘除防监听器累积)。
242
+ // 输入守卫(5-2):输入控件内的按键直通(打字与原生快捷键不劫持灯箱键集);
243
+ // 测试经 document 直派 keydown 时 target 是 Document(非 Element),不误拦。
244
+ const onKey = (ev) => {
245
+ const target = ev.target;
246
+ if (target instanceof Element && target.closest('input,textarea,select,[contenteditable]'))
247
+ return;
248
+ if (ev.key === 'Escape')
249
+ removeLightboxOverlay(doc);
250
+ else if (ev.key === 'ArrowRight') {
251
+ ev.preventDefault();
252
+ go(1);
253
+ }
254
+ else if (ev.key === 'ArrowLeft') {
255
+ ev.preventDefault();
256
+ go(-1);
257
+ }
258
+ else if (ev.key === '+' || ev.key === '=')
259
+ centerZoom(ZOOM_STEP);
260
+ else if (ev.key === '-')
261
+ centerZoom(1 / ZOOM_STEP);
262
+ else if (ev.key === 'r' || ev.key === 'f')
263
+ resetView();
264
+ };
265
+ escHandlers.set(overlay, onKey);
266
+ doc.addEventListener('keydown', onKey);
267
+ // 点击关闭:仅背景(overlay 本体/stage 空白);内容与控制件不关(T1 裁决)
268
+ overlay.addEventListener('click', (ev) => {
269
+ if (dragMoved) {
270
+ dragMoved = false;
271
+ return;
272
+ } // 拖拽收尾 click 吞掉,不误关(T2 裁决)
273
+ if (ev.target === overlay || ev.target === stage)
274
+ removeLightboxOverlay(doc);
275
+ });
276
+ // 滚轮缩放(光标中心锚定):preventDefault 防 overlay 之下页面滚动
277
+ overlay.addEventListener('wheel', (ev) => {
278
+ ev.preventDefault();
279
+ const rect = overlay.getBoundingClientRect();
280
+ state = zoomAt(state, ev.deltaY < 0 ? ZOOM_STEP : 1 / ZOOM_STEP, ev.clientX - rect.left, ev.clientY - rect.top);
281
+ applyState();
282
+ }, { passive: false });
283
+ // 拖拽平移:mousedown 记起点与基准位移,document 级 mousemove 增量写 tx/ty(按下
284
+ // 态才挂监听),mouseup 收监听;位移超阈值置 dragMoved(恒允许 pan,zoom=1 时
285
+ // 拖动即平移、无边界回弹——实现取简)
286
+ stage.addEventListener('mousedown', (ev) => {
287
+ if (ev.button !== 0)
288
+ return;
289
+ ev.preventDefault(); // 防原生 img 拖拽与选中
290
+ dragMoved = false;
291
+ const startX = ev.clientX;
292
+ const startY = ev.clientY;
293
+ const base = { tx: state.tx, ty: state.ty };
294
+ const onMove = (me) => {
295
+ const dx = me.clientX - startX;
296
+ const dy = me.clientY - startY;
297
+ if (Math.abs(dx) + Math.abs(dy) > DRAG_THRESHOLD)
298
+ dragMoved = true;
299
+ state = { ...state, tx: base.tx + dx, ty: base.ty + dy };
300
+ applyState();
301
+ };
302
+ const onUp = () => {
303
+ stage.classList.remove(cls(ctx, 'dragging'));
304
+ doc.removeEventListener('mousemove', onMove);
305
+ doc.removeEventListener('mouseup', onUp);
306
+ };
307
+ stage.classList.add(cls(ctx, 'dragging'));
308
+ doc.addEventListener('mousemove', onMove);
309
+ doc.addEventListener('mouseup', onUp);
310
+ });
311
+ // HTML5 原生拖拽与指针平移冲突,禁掉
312
+ stage.addEventListener('dragstart', (ev) => ev.preventDefault());
313
+ (doc.body ?? doc.documentElement).appendChild(overlay);
314
+ return {
315
+ overlay,
316
+ open(nextItems, index) {
317
+ items = nextItems;
318
+ state = { zoom: 1, tx: 0, ty: 0, index };
319
+ dragMoved = false; // 跨打开不复用旧拖拽态:重开后的首个 click 按正常语义判定
320
+ const multi = items.length > 1;
321
+ prev.toggleAttribute('hidden', !multi);
322
+ next.toggleAttribute('hidden', !multi);
323
+ count.toggleAttribute('hidden', !multi);
324
+ showItem();
325
+ applyState();
326
+ overlay.focus(); // 焦点入灯箱(a11y 基线;复用重开亦然)
327
+ },
328
+ };
329
+ }
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@bhxch/vviewer-lightbox",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "private": false,
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "types": "./index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./index.d.ts",
11
+ "default": "./index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "LICENSE",
16
+ "README.md",
17
+ "index.d.ts",
18
+ "index.js",
19
+ "lightbox.d.ts",
20
+ "lightbox.js"
21
+ ],
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/bhxch/vviewer.git",
25
+ "directory": "packages/vviewer-lightbox"
26
+ },
27
+ "license": "Apache-2.0",
28
+ "contentHash": "703f278b5a226118"
29
+ }