@web-ppt/viewer-core 0.1.0

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 [yyyy] [name of copyright owner]
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 ADDED
@@ -0,0 +1,53 @@
1
+ # @web-ppt/viewer-core
2
+
3
+ [Web-PPT](https://github.com/unStone/web-ppt) 查看器的 headless 层。
4
+
5
+ `PresentationState` 是零 DOM 的纯状态机——导航 / 缩放 / 搜索 / 动画批次 / 自动换片,
6
+ 可被原生 DOM、React、Vue、Svelte 任意 UI 驱动,也能在 Node 里直接跑测试。
7
+ `Viewer` 是它之上最薄的一层 DOM 绑定(塞 SVG、设可见性、调播放,约 24 行)。
8
+
9
+ ```bash
10
+ npm i @web-ppt/core @web-ppt/viewer-core
11
+ ```
12
+
13
+ ## 开箱即用
14
+
15
+ ```ts
16
+ import { parse } from '@web-ppt/core';
17
+ import { Viewer } from '@web-ppt/viewer-core';
18
+
19
+ const pres = await parse(file);
20
+ const v = new Viewer(container, pres, { animate: true, autoAdvance: true });
21
+
22
+ v.next(); // 有待播动画时先播动画,否则翻页
23
+ v.finishAnimations(); // 跳到本页动画终态
24
+ v.setZoom(1.5);
25
+ v.search('关键词'); // → 命中的页索引数组
26
+ await v.exportPng(2); // → Blob
27
+ ```
28
+
29
+ ## 接自己的 UI
30
+
31
+ ```ts
32
+ import { PresentationState, playGroup, playTransition } from '@web-ppt/viewer-core';
33
+
34
+ const st = new PresentationState(pres, { skipHidden: true, animate: true });
35
+
36
+ st.subscribe((change) => {
37
+ if (change.type === 'slide') {
38
+ render(change.index);
39
+ if (change.transition) playTransition(prevEl, nextEl, change.transition);
40
+ } else if (change.type === 'animation' && change.group) {
41
+ playGroup(container, change.group);
42
+ }
43
+ });
44
+
45
+ st.next();
46
+ st.hiddenElementIds; // 当前批次下应隐藏的元素 id
47
+ st.resolveLink(href); // 'slide:3' → 2,外链 → null
48
+ ```
49
+
50
+ 状态机只决定「该显示什么」,实际播放由 UI 层调 `playGroup` / `playTransition` 完成——
51
+ 所以换框架时不需要重写任何逻辑。
52
+
53
+ MIT
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @web-ppt/viewer-core —— 查看器的 headless 层。
3
+ *
4
+ * `PresentationState` 是纯状态机(零 DOM),`Viewer` 是它之上最薄的 DOM 绑定。
5
+ * 想接 React / Vue / Svelte 就直接驱动 `PresentationState`,
6
+ * 播放动画与切换用这里导出的 `playGroup` / `playTransition`。
7
+ */
8
+ export { PresentationState } from './state';
9
+ export type { PresentationStateOptions, StateChange } from './state';
10
+ export { Viewer } from './viewer';
11
+ export type { ViewerOptions } from './viewer';
12
+ export { autoAdvanceMs, framesFor, groupSteps, hiddenBefore, playGroup, playTransition, } from './playback';
13
+ export type { PlayHandle } from './playback';
@@ -0,0 +1,24 @@
1
+ import type { AnimStep, Slide, Transition } from '@web-ppt/core';
2
+ interface Keyframes {
3
+ from: Keyframe;
4
+ to: Keyframe;
5
+ }
6
+ export declare function framesFor(step: AnimStep): Keyframes;
7
+ /** 把动画按点击批次分组 */
8
+ export declare function groupSteps(steps: AnimStep[] | undefined): AnimStep[][];
9
+ /** 一批动画开始前,哪些元素应处于隐藏状态 */
10
+ export declare function hiddenBefore(groups: AnimStep[][], upTo: number): Set<number>;
11
+ export interface PlayHandle {
12
+ cancel(): void;
13
+ finished: Promise<void>;
14
+ }
15
+ /** 播放一批动画;返回可取消的句柄 */
16
+ export declare function playGroup(container: Element, group: AnimStep[]): PlayHandle;
17
+ /**
18
+ * 播放切换:把旧内容截图式地留在下层,新内容在上层按效果进场。
19
+ * outgoing 为旧内容节点(可为 null),incoming 为新内容节点。
20
+ */
21
+ export declare function playTransition(outgoing: HTMLElement | null, incoming: HTMLElement, t: Transition | undefined): Promise<void>;
22
+ /** 幻灯片是否配置了自动换片 */
23
+ export declare function autoAdvanceMs(slide: Slide): number | null;
24
+ export {};
@@ -0,0 +1,94 @@
1
+ import type { AnimStep, Presentation, Slide, Transition } from '@web-ppt/core';
2
+ /**
3
+ * 演示文稿的 headless 状态机:翻页、缩放、搜索、动画批次。
4
+ *
5
+ * 不碰任何 DOM,因此可以被原生 / React / Vue / Svelte 任意 UI 驱动,
6
+ * 也能在 Node 里直接跑测试。UI 层只负责两件事:
7
+ * 订阅变更 → 把 `renderSlideToSvg` 的结果放进容器。
8
+ */
9
+ export interface PresentationStateOptions {
10
+ /** 初始页 */
11
+ index?: number;
12
+ /** 翻页时跳过隐藏页 */
13
+ skipHidden?: boolean;
14
+ /** 启用切换与元素动画(演示模式建议开启) */
15
+ animate?: boolean;
16
+ /** 遵循文件里的自动换片设置 */
17
+ autoAdvance?: boolean;
18
+ }
19
+ export type StateChange =
20
+ /** 换页。`transition` 非空表示应播放切换效果 */
21
+ {
22
+ type: 'slide';
23
+ index: number;
24
+ previous: number;
25
+ transition?: Transition;
26
+ }
27
+ /** 动画批次推进。`group` 是本次应播放的这一批 */
28
+ | {
29
+ type: 'animation';
30
+ done: number;
31
+ total: number;
32
+ group: AnimStep[] | null;
33
+ } | {
34
+ type: 'zoom';
35
+ zoom: number;
36
+ };
37
+ type Listener = (change: StateChange) => void;
38
+ export declare class PresentationState {
39
+ readonly presentation: Presentation;
40
+ private options;
41
+ private idx;
42
+ private zoomValue;
43
+ private groups;
44
+ private cursor;
45
+ private listeners;
46
+ private autoTimer;
47
+ /** 每页渲染结果的缓存交给 UI 层,这里只缓存文本以便搜索 */
48
+ private textCache;
49
+ constructor(presentation: Presentation, options?: PresentationStateOptions);
50
+ get index(): number;
51
+ get count(): number;
52
+ get slide(): Slide;
53
+ get zoom(): number;
54
+ get animate(): boolean;
55
+ get animationTotal(): number;
56
+ get animationDone(): number;
57
+ get hasPendingAnimation(): boolean;
58
+ /** 当前批次下应当隐藏的元素 id —— UI 据此设置可见性 */
59
+ get hiddenElementIds(): ReadonlySet<number>;
60
+ /** 本页的自动换片延迟(毫秒),未配置则为 null */
61
+ get autoAdvanceDelay(): number | null;
62
+ subscribe(fn: Listener): () => void;
63
+ private emit;
64
+ private clamp;
65
+ private visible;
66
+ /**
67
+ * 跳转到指定页。返回是否真的换了页。
68
+ * 前进时带上目标页的切换效果;回退不播切换,避免观感错乱。
69
+ */
70
+ goTo(i: number, direction?: 'forward' | 'backward'): boolean;
71
+ /** 有待播动画时先播动画,否则翻页 */
72
+ next(): void;
73
+ prev(): void;
74
+ setZoom(z: number): void;
75
+ setAnimate(on: boolean): void;
76
+ private loadAnimations;
77
+ /**
78
+ * 推进一批动画。返回应播放的这一批;没有待播批次时返回 null。
79
+ * 真正的播放由 UI 层执行——状态机只负责「该播哪一批」。
80
+ */
81
+ playNextAnimation(): AnimStep[] | null;
82
+ /** 直接跳到本页动画终态 */
83
+ finishAnimations(): void;
84
+ /** 启动自动换片计时;返回取消函数。由 UI 层在每次换页后调用。 */
85
+ scheduleAutoAdvance(): () => void;
86
+ cancelAutoAdvance(): void;
87
+ text(i: number): string;
88
+ /** 全文搜索,返回命中的页索引 */
89
+ search(query: string): number[];
90
+ /** 解析内部跳转目标(`slide:3` / `slide:last`)为页索引;外部链接返回 null */
91
+ resolveLink(href: string): number | null;
92
+ destroy(): void;
93
+ }
94
+ export {};
@@ -0,0 +1,484 @@
1
+ import { slideText as m, renderSlideToSvg as d, slideToPng as y } from "@web-ppt/core";
2
+ const l = 1.15;
3
+ function v(s) {
4
+ switch (s) {
5
+ case "l":
6
+ return [-100 * l, 0];
7
+ case "r":
8
+ return [100 * l, 0];
9
+ case "u":
10
+ return [0, -100 * l];
11
+ case "d":
12
+ return [0, 100 * l];
13
+ case "lu":
14
+ return [-100 * l, -100 * l];
15
+ case "ru":
16
+ return [100 * l, -100 * l];
17
+ case "ld":
18
+ return [-100 * l, 100 * l];
19
+ case "rd":
20
+ return [100 * l, 100 * l];
21
+ default:
22
+ return [0, 100 * l];
23
+ }
24
+ }
25
+ function u(s, t) {
26
+ const e = t ? 100 : 0;
27
+ switch (s) {
28
+ case "l":
29
+ return `inset(0 ${e}% 0 0)`;
30
+ case "r":
31
+ return `inset(0 0 0 ${e}%)`;
32
+ case "u":
33
+ return `inset(0 0 ${e}% 0)`;
34
+ case "horz":
35
+ return `inset(0 ${e / 2}% 0 ${e / 2}%)`;
36
+ case "vert":
37
+ return `inset(${e / 2}% 0 ${e / 2}% 0)`;
38
+ default:
39
+ return `inset(${e}% 0 0 0)`;
40
+ }
41
+ }
42
+ function f(s) {
43
+ switch (s.effect) {
44
+ case "appear":
45
+ return { from: { opacity: 0 }, to: { opacity: 1 } };
46
+ case "fly": {
47
+ const [t, e] = v(s.dir);
48
+ return {
49
+ from: { opacity: 0, transform: `translate(${t}%, ${e}%)` },
50
+ to: { opacity: 1, transform: "translate(0, 0)" }
51
+ };
52
+ }
53
+ case "zoom":
54
+ return {
55
+ from: { opacity: 0, transform: s.dir === "out" ? "scale(1.6)" : "scale(0.1)" },
56
+ to: { opacity: 1, transform: "scale(1)" }
57
+ };
58
+ case "grow":
59
+ return { from: { opacity: 0, transform: "scale(0.2) rotate(-90deg)" }, to: { opacity: 1, transform: "scale(1) rotate(0)" } };
60
+ case "spin":
61
+ return { from: { opacity: 0, transform: "rotate(-180deg) scale(0.4)" }, to: { opacity: 1, transform: "rotate(0) scale(1)" } };
62
+ case "swivel":
63
+ return { from: { opacity: 0, transform: "rotateY(90deg)" }, to: { opacity: 1, transform: "rotateY(0)" } };
64
+ case "float":
65
+ return { from: { opacity: 0, transform: "translateY(30%)" }, to: { opacity: 1, transform: "translateY(0)" } };
66
+ case "bounce":
67
+ return { from: { opacity: 0, transform: "translateY(-60%)" }, to: { opacity: 1, transform: "translateY(0)" } };
68
+ case "stretch":
69
+ return { from: { opacity: 0, transform: "scaleX(0.05)" }, to: { opacity: 1, transform: "scaleX(1)" } };
70
+ case "wipe":
71
+ case "blinds":
72
+ case "split":
73
+ case "wheel":
74
+ return {
75
+ from: { opacity: 1, clipPath: u(s.dir, !0) },
76
+ to: { opacity: 1, clipPath: u(s.dir, !1) }
77
+ };
78
+ case "dissolve":
79
+ case "fade":
80
+ case "random":
81
+ default:
82
+ return { from: { opacity: 0 }, to: { opacity: 1 } };
83
+ }
84
+ }
85
+ function g(s) {
86
+ const t = f({ ...s });
87
+ return { from: t.to, to: t.from };
88
+ }
89
+ function x(s) {
90
+ switch (s.effect) {
91
+ case "spin":
92
+ return { from: { transform: "rotate(0)" }, to: { transform: "rotate(360deg)" } };
93
+ case "grow":
94
+ return { from: { transform: "scale(1)" }, to: { transform: "scale(1.25)" } };
95
+ default:
96
+ return { from: { opacity: 1 }, to: { opacity: 0.35 } };
97
+ }
98
+ }
99
+ function A(s) {
100
+ return s.kind === "exit" ? g(s) : s.kind === "emphasis" ? x(s) : f(s);
101
+ }
102
+ function w(s) {
103
+ if (!(s != null && s.length)) return [];
104
+ const t = [];
105
+ for (const e of s) {
106
+ const n = e.clickGroup ?? 0;
107
+ (t[n] ?? (t[n] = [])).push(e);
108
+ }
109
+ return t.filter(Boolean);
110
+ }
111
+ function b(s, t) {
112
+ const e = /* @__PURE__ */ new Set();
113
+ for (let n = t; n < s.length; n++)
114
+ for (const i of s[n]) i.kind === "entrance" && e.add(i.target);
115
+ for (let n = 0; n < t; n++)
116
+ for (const i of s[n]) i.kind === "exit" && e.add(i.target);
117
+ for (let n = t; n < s.length; n++)
118
+ for (const i of s[n]) i.kind === "entrance" && e.add(i.target);
119
+ return e;
120
+ }
121
+ function T(s, t) {
122
+ const e = [];
123
+ let n = 0;
124
+ for (const i of t) {
125
+ const r = s.querySelector(`[data-el="${i.target}"]`);
126
+ if (!r) continue;
127
+ const a = i.trigger === "afterPrev" ? n + i.delayMs : i.delayMs;
128
+ i.trigger === "afterPrev" ? n = a + i.durationMs : n = Math.max(n, a + i.durationMs);
129
+ const { from: c, to: o } = A(i);
130
+ r.style.visibility = "visible", i.kind === "entrance" && (r.style.opacity = "");
131
+ try {
132
+ const h = r.animate([c, o], {
133
+ duration: i.durationMs,
134
+ delay: a,
135
+ easing: "cubic-bezier(0.25, 0.46, 0.45, 0.94)",
136
+ fill: "both"
137
+ });
138
+ i.kind === "exit" && h.finished.then(() => {
139
+ r.style.visibility = "hidden";
140
+ }).catch(() => {
141
+ }), e.push(h);
142
+ } catch {
143
+ Object.assign(r.style, o);
144
+ }
145
+ }
146
+ return {
147
+ cancel: () => e.forEach((i) => {
148
+ try {
149
+ i.finish();
150
+ } catch {
151
+ }
152
+ }),
153
+ finished: Promise.all(e.map((i) => i.finished.catch(() => {
154
+ }))).then(() => {
155
+ })
156
+ };
157
+ }
158
+ function p(s, t) {
159
+ const e = s.dir ?? "", n = (r, a) => `translate(${r}, ${a})`, i = () => e.includes("l") ? ["-100%", "0"] : e.includes("r") ? ["100%", "0"] : e.includes("u") ? ["0", "-100%"] : ["0", "100%"];
160
+ switch (s.type) {
161
+ case "cut":
162
+ return t ? [{ opacity: 1 }, { opacity: 1 }] : [{ opacity: 0 }, { opacity: 0 }];
163
+ case "push":
164
+ case "pull": {
165
+ const [r, a] = i(), c = s.type === "pull" ? -1 : 1, o = (h) => h === "0" ? "0" : `${-parseFloat(h) * c}%`;
166
+ return t ? [{ transform: n(c > 0 ? r : o(r), c > 0 ? a : o(a)) }, { transform: "translate(0,0)" }] : [{ transform: "translate(0,0)" }, { transform: n(o(r), o(a)) }];
167
+ }
168
+ case "cover": {
169
+ const [r, a] = i();
170
+ return t ? [{ transform: n(r, a) }, { transform: "translate(0,0)" }] : [{ opacity: 1 }, { opacity: 1 }];
171
+ }
172
+ case "wipe": {
173
+ const r = u(e || "d", !0), a = u(e || "d", !1);
174
+ return t ? [{ clipPath: r }, { clipPath: a }] : [{ opacity: 1 }, { opacity: 1 }];
175
+ }
176
+ case "split": {
177
+ const r = e.startsWith("vert"), a = e.endsWith("out"), c = r ? "inset(0 50% 0 50%)" : "inset(50% 0 50% 0)", o = "inset(0 0 0 0)";
178
+ return t ? a ? [{ clipPath: c }, { clipPath: o }] : [{ clipPath: o }, { clipPath: o }] : [{ clipPath: o }, { clipPath: c }];
179
+ }
180
+ case "zoom":
181
+ return t ? [{ opacity: 0, transform: e === "out" ? "scale(1.4)" : "scale(0.6)" }, { opacity: 1, transform: "scale(1)" }] : [{ opacity: 1 }, { opacity: 0 }];
182
+ case "wheel":
183
+ case "circle":
184
+ case "diamond":
185
+ case "plus":
186
+ case "wedge":
187
+ return t ? [{ opacity: 0, transform: "scale(0.7)" }, { opacity: 1, transform: "scale(1)" }] : [{ opacity: 1 }, { opacity: 0 }];
188
+ case "blinds":
189
+ case "checker":
190
+ case "comb":
191
+ case "randomBar":
192
+ case "strips":
193
+ case "newsflash":
194
+ case "dissolve":
195
+ case "fade":
196
+ default:
197
+ return t ? [{ opacity: 0 }, { opacity: 1 }] : [{ opacity: 1 }, { opacity: 0 }];
198
+ }
199
+ }
200
+ function k(s, t, e) {
201
+ if (!e || e.type === "none")
202
+ return s == null || s.remove(), Promise.resolve();
203
+ const n = { duration: e.durationMs, easing: "ease-in-out", fill: "both" }, i = [];
204
+ try {
205
+ i.push(t.animate(p(e, !0), n).finished), s && i.push(s.animate(p(e, !1), n).finished);
206
+ } catch {
207
+ return s == null || s.remove(), Promise.resolve();
208
+ }
209
+ return Promise.all(i.map((r) => r.catch(() => {
210
+ }))).then(() => {
211
+ s == null || s.remove();
212
+ });
213
+ }
214
+ function C(s) {
215
+ var e;
216
+ const t = (e = s.transition) == null ? void 0 : e.advanceAfterMs;
217
+ return t !== void 0 && t > 0 ? t : null;
218
+ }
219
+ class P {
220
+ constructor(t, e = {}) {
221
+ this.presentation = t, this.options = e, this.idx = 0, this.zoomValue = 1, this.groups = [], this.cursor = 0, this.listeners = /* @__PURE__ */ new Set(), this.autoTimer = null, this.textCache = /* @__PURE__ */ new Map(), this.idx = this.clamp(e.index ?? 0), this.loadAnimations();
222
+ }
223
+ // ---------------- 只读状态 ----------------
224
+ get index() {
225
+ return this.idx;
226
+ }
227
+ get count() {
228
+ return this.presentation.slides.length;
229
+ }
230
+ get slide() {
231
+ return this.presentation.slides[this.idx];
232
+ }
233
+ get zoom() {
234
+ return this.zoomValue;
235
+ }
236
+ get animate() {
237
+ return this.options.animate === !0;
238
+ }
239
+ get animationTotal() {
240
+ return this.groups.length;
241
+ }
242
+ get animationDone() {
243
+ return this.cursor;
244
+ }
245
+ get hasPendingAnimation() {
246
+ return this.animate && this.cursor < this.groups.length;
247
+ }
248
+ /** 当前批次下应当隐藏的元素 id —— UI 据此设置可见性 */
249
+ get hiddenElementIds() {
250
+ return this.animate ? b(this.groups, this.cursor) : /* @__PURE__ */ new Set();
251
+ }
252
+ /** 本页的自动换片延迟(毫秒),未配置则为 null */
253
+ get autoAdvanceDelay() {
254
+ return this.options.autoAdvance ? C(this.slide) : null;
255
+ }
256
+ // ---------------- 订阅 ----------------
257
+ subscribe(t) {
258
+ return this.listeners.add(t), () => this.listeners.delete(t);
259
+ }
260
+ emit(t) {
261
+ for (const e of this.listeners) e(t);
262
+ }
263
+ // ---------------- 导航 ----------------
264
+ clamp(t) {
265
+ return Math.max(0, Math.min(this.count - 1, t));
266
+ }
267
+ visible(t) {
268
+ var e;
269
+ return !this.options.skipHidden || !((e = this.presentation.slides[t]) != null && e.hidden);
270
+ }
271
+ /**
272
+ * 跳转到指定页。返回是否真的换了页。
273
+ * 前进时带上目标页的切换效果;回退不播切换,避免观感错乱。
274
+ */
275
+ goTo(t, e = "forward") {
276
+ const n = this.clamp(t);
277
+ if (n === this.idx) return !1;
278
+ const i = this.idx;
279
+ return this.idx = n, this.loadAnimations(), this.emit({
280
+ type: "slide",
281
+ index: n,
282
+ previous: i,
283
+ transition: e === "forward" && this.animate ? this.slide.transition : void 0
284
+ }), !0;
285
+ }
286
+ /** 有待播动画时先播动画,否则翻页 */
287
+ next() {
288
+ if (this.playNextAnimation()) return;
289
+ let t = this.idx + 1;
290
+ for (; t < this.count && !this.visible(t); ) t++;
291
+ t < this.count && this.goTo(t);
292
+ }
293
+ prev() {
294
+ let t = this.idx - 1;
295
+ for (; t >= 0 && !this.visible(t); ) t--;
296
+ t >= 0 && this.goTo(t, "backward");
297
+ }
298
+ setZoom(t) {
299
+ const e = Math.max(0.1, Math.min(8, t));
300
+ e !== this.zoomValue && (this.zoomValue = e, this.emit({ type: "zoom", zoom: e }));
301
+ }
302
+ setAnimate(t) {
303
+ this.options.animate !== t && (this.options = { ...this.options, animate: t }, this.loadAnimations(), this.emit({ type: "animation", done: this.cursor, total: this.groups.length, group: null }));
304
+ }
305
+ // ---------------- 动画 ----------------
306
+ loadAnimations() {
307
+ this.groups = this.animate ? w(this.slide.animations) : [], this.cursor = 0;
308
+ }
309
+ /**
310
+ * 推进一批动画。返回应播放的这一批;没有待播批次时返回 null。
311
+ * 真正的播放由 UI 层执行——状态机只负责「该播哪一批」。
312
+ */
313
+ playNextAnimation() {
314
+ if (!this.hasPendingAnimation) return null;
315
+ const t = this.groups[this.cursor];
316
+ return this.cursor++, this.emit({ type: "animation", done: this.cursor, total: this.groups.length, group: t }), t;
317
+ }
318
+ /** 直接跳到本页动画终态 */
319
+ finishAnimations() {
320
+ this.cursor !== this.groups.length && (this.cursor = this.groups.length, this.emit({ type: "animation", done: this.cursor, total: this.groups.length, group: null }));
321
+ }
322
+ // ---------------- 自动换片 ----------------
323
+ /** 启动自动换片计时;返回取消函数。由 UI 层在每次换页后调用。 */
324
+ scheduleAutoAdvance() {
325
+ this.cancelAutoAdvance();
326
+ const t = this.autoAdvanceDelay;
327
+ return t === null ? () => {
328
+ } : (this.autoTimer = setTimeout(() => {
329
+ this.autoTimer = null, this.next();
330
+ }, t), () => this.cancelAutoAdvance());
331
+ }
332
+ cancelAutoAdvance() {
333
+ this.autoTimer !== null && (clearTimeout(this.autoTimer), this.autoTimer = null);
334
+ }
335
+ // ---------------- 文本 / 搜索 ----------------
336
+ text(t) {
337
+ let e = this.textCache.get(t);
338
+ return e === void 0 && (e = m(this.presentation.slides[t]), this.textCache.set(t, e)), e;
339
+ }
340
+ /** 全文搜索,返回命中的页索引 */
341
+ search(t) {
342
+ const e = t.trim().toLowerCase();
343
+ if (!e) return [];
344
+ const n = [];
345
+ for (let i = 0; i < this.count; i++)
346
+ this.text(i).toLowerCase().includes(e) && n.push(i);
347
+ return n;
348
+ }
349
+ /** 解析内部跳转目标(`slide:3` / `slide:last`)为页索引;外部链接返回 null */
350
+ resolveLink(t) {
351
+ if (!t.startsWith("slide:")) return null;
352
+ const e = t.slice(6), n = e === "last" ? this.count : Number(e);
353
+ return Number.isFinite(n) ? this.clamp(n - 1) : null;
354
+ }
355
+ destroy() {
356
+ this.cancelAutoAdvance(), this.listeners.clear(), this.textCache.clear();
357
+ }
358
+ }
359
+ class M {
360
+ constructor(t, e, n = {}) {
361
+ this.container = t, this.presentation = e, this.svgCache = /* @__PURE__ */ new Map(), this.playing = null, this.cancelAuto = null, this.onChange = null, this.onAnimStep = null, this.onLinkClick = null, this.handleClick = (i) => {
362
+ const r = i.target, a = r == null ? void 0 : r.closest("[data-slide]");
363
+ if (a) {
364
+ i.preventDefault();
365
+ const h = this.state.resolveLink(`slide:${a.getAttribute("data-slide") ?? ""}`);
366
+ h !== null && this.goTo(h);
367
+ return;
368
+ }
369
+ const c = r == null ? void 0 : r.closest("a[href]"), o = c == null ? void 0 : c.getAttribute("href");
370
+ o && this.onLinkClick && this.onLinkClick(o) === !0 && i.preventDefault();
371
+ }, this.state = new P(e, n), this.unsubscribe = this.state.subscribe((i) => {
372
+ var r, a;
373
+ i.type === "slide" ? (this.paint(i.transition), (r = this.onChange) == null || r.call(this, i.index)) : i.type === "animation" ? (i.group ? this.play(i.group) : this.applyVisibility(), (a = this.onAnimStep) == null || a.call(this, i.done, i.total)) : i.type === "zoom" && this.applyZoom();
374
+ }), this.container.addEventListener("click", this.handleClick), this.paint();
375
+ }
376
+ // ---------------- 转发给状态机 ----------------
377
+ get index() {
378
+ return this.state.index;
379
+ }
380
+ get count() {
381
+ return this.state.count;
382
+ }
383
+ get slide() {
384
+ return this.state.slide;
385
+ }
386
+ get zoomLevel() {
387
+ return this.state.zoom;
388
+ }
389
+ get animationTotal() {
390
+ return this.state.animationTotal;
391
+ }
392
+ get animationDone() {
393
+ return this.state.animationDone;
394
+ }
395
+ get hasPendingAnimation() {
396
+ return this.state.hasPendingAnimation;
397
+ }
398
+ goTo(t, e = "forward") {
399
+ this.state.goTo(t, e);
400
+ }
401
+ next() {
402
+ this.state.next();
403
+ }
404
+ prev() {
405
+ this.state.prev();
406
+ }
407
+ setZoom(t) {
408
+ this.state.setZoom(t);
409
+ }
410
+ finishAnimations() {
411
+ this.state.finishAnimations();
412
+ }
413
+ search(t) {
414
+ return this.state.search(t);
415
+ }
416
+ text(t) {
417
+ return this.state.text(t);
418
+ }
419
+ setAnimate(t) {
420
+ this.state.setAnimate(t), this.paint();
421
+ }
422
+ playNextAnimation() {
423
+ return this.state.playNextAnimation() !== null;
424
+ }
425
+ // ---------------- 渲染 ----------------
426
+ /** 带缓存的单页 SVG(主视图用) */
427
+ slideSvg(t) {
428
+ let e = this.svgCache.get(t);
429
+ return e === void 0 && (e = d(this.presentation, this.presentation.slides[t]), this.svgCache.set(t, e)), e;
430
+ }
431
+ /** 不走缓存,用于缩略图等需要独立 defs id 的场景 */
432
+ renderSlide(t) {
433
+ return d(this.presentation, this.presentation.slides[t]);
434
+ }
435
+ exportPng(t = 2, e = this.index) {
436
+ return y(this.presentation, this.presentation.slides[e], t);
437
+ }
438
+ paint(t) {
439
+ var a, c, o;
440
+ (a = this.playing) == null || a.cancel(), this.playing = null, (c = this.cancelAuto) == null || c.call(this);
441
+ const e = document.createElement("div");
442
+ e.style.cssText = "position:absolute;inset:0;display:flex;align-items:center;justify-content:center", e.innerHTML = this.slideSvg(this.index);
443
+ const n = this.container.firstElementChild, i = this.container.ownerDocument.defaultView;
444
+ (!i || i.getComputedStyle(this.container).position === "static") && (this.container.style.position = "relative"), t && n ? (this.container.appendChild(e), k(n, e, t).then(() => this.startAutoAdvance())) : (this.container.innerHTML = "", this.container.appendChild(e), this.startAutoAdvance());
445
+ const r = e.querySelector("svg");
446
+ r && (r.style.display = "block", r.style.maxWidth = "none"), this.applyZoom(), this.applyVisibility(), (o = this.onAnimStep) == null || o.call(this, this.state.animationDone, this.state.animationTotal);
447
+ }
448
+ play(t) {
449
+ var e;
450
+ (e = this.playing) == null || e.cancel(), this.playing = T(this.container, t), this.applyVisibility();
451
+ }
452
+ /** 按状态机给出的隐藏集合设置元素可见性 */
453
+ applyVisibility() {
454
+ if (!this.state.animate) return;
455
+ const t = this.state.hiddenElementIds;
456
+ this.container.querySelectorAll("[data-el]").forEach((e) => {
457
+ const n = Number(e.getAttribute("data-el"));
458
+ e.style.visibility = t.has(n) ? "hidden" : "visible";
459
+ });
460
+ }
461
+ applyZoom() {
462
+ const t = this.container.querySelector("svg");
463
+ if (!t) return;
464
+ const e = this.state.zoom;
465
+ e === 1 ? (t.style.width = "100%", t.style.height = "100%") : (t.style.width = `${this.presentation.width * e}px`, t.style.height = `${this.presentation.height * e}px`);
466
+ }
467
+ startAutoAdvance() {
468
+ this.cancelAuto = this.state.scheduleAutoAdvance();
469
+ }
470
+ destroy() {
471
+ var t, e;
472
+ this.container.removeEventListener("click", this.handleClick), this.unsubscribe(), (t = this.playing) == null || t.cancel(), (e = this.cancelAuto) == null || e.call(this), this.state.destroy(), this.container.innerHTML = "", this.svgCache.clear();
473
+ }
474
+ }
475
+ export {
476
+ P as PresentationState,
477
+ M as Viewer,
478
+ C as autoAdvanceMs,
479
+ A as framesFor,
480
+ w as groupSteps,
481
+ b as hiddenBefore,
482
+ T as playGroup,
483
+ k as playTransition
484
+ };
@@ -0,0 +1,54 @@
1
+ import type { Presentation, Slide } from '@web-ppt/core';
2
+ import { PresentationState, type PresentationStateOptions } from './state';
3
+ /**
4
+ * 原生 DOM 查看器:`PresentationState` 之上最薄的一层绑定。
5
+ *
6
+ * 它做的全部事情只有三件——把 SVG 塞进容器、按状态设元素可见性、
7
+ * 在状态机说「该播这一批」时调用播放层。所有决策都在状态机里,
8
+ * 因此换成 React / Vue 只需重写这三件事。
9
+ */
10
+ export interface ViewerOptions extends PresentationStateOptions {
11
+ }
12
+ export declare class Viewer {
13
+ private container;
14
+ readonly presentation: Presentation;
15
+ readonly state: PresentationState;
16
+ private svgCache;
17
+ private playing;
18
+ private cancelAuto;
19
+ private unsubscribe;
20
+ onChange: ((index: number) => void) | null;
21
+ onAnimStep: ((done: number, total: number) => void) | null;
22
+ /** 点击外部链接时回调;返回 true 表示宿主已处理,不再打开新窗口 */
23
+ onLinkClick: ((href: string) => boolean | void) | null;
24
+ constructor(container: HTMLElement, presentation: Presentation, options?: ViewerOptions);
25
+ get index(): number;
26
+ get count(): number;
27
+ get slide(): Slide;
28
+ get zoomLevel(): number;
29
+ get animationTotal(): number;
30
+ get animationDone(): number;
31
+ get hasPendingAnimation(): boolean;
32
+ goTo(i: number, direction?: 'forward' | 'backward'): void;
33
+ next(): void;
34
+ prev(): void;
35
+ setZoom(z: number): void;
36
+ finishAnimations(): void;
37
+ search(q: string): number[];
38
+ text(i: number): string;
39
+ setAnimate(on: boolean): void;
40
+ playNextAnimation(): boolean;
41
+ /** 带缓存的单页 SVG(主视图用) */
42
+ slideSvg(i: number): string;
43
+ /** 不走缓存,用于缩略图等需要独立 defs id 的场景 */
44
+ renderSlide(i: number): string;
45
+ exportPng(scale?: number, i?: number): Promise<Blob>;
46
+ private paint;
47
+ private play;
48
+ /** 按状态机给出的隐藏集合设置元素可见性 */
49
+ private applyVisibility;
50
+ private applyZoom;
51
+ private startAutoAdvance;
52
+ private handleClick;
53
+ destroy(): void;
54
+ }
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@web-ppt/viewer-core",
3
+ "version": "0.1.0",
4
+ "description": "Web-PPT 查看器的 headless 状态机与播放层:导航 / 缩放 / 搜索 / 动画批次,可被任意 UI 框架驱动",
5
+ "keywords": [
6
+ "pptx",
7
+ "viewer",
8
+ "headless",
9
+ "state-machine"
10
+ ],
11
+ "license": "MIT",
12
+ "author": "unStone",
13
+ "homepage": "https://github.com/unStone/web-ppt#readme",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/unStone/web-ppt.git",
17
+ "directory": "packages/viewer-core"
18
+ },
19
+ "type": "module",
20
+ "sideEffects": false,
21
+ "main": "./dist/viewer-core.js",
22
+ "module": "./dist/viewer-core.js",
23
+ "types": "./dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/viewer-core.js"
28
+ },
29
+ "./package.json": "./package.json"
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ "scripts": {
37
+ "build": "vite build && tsc -p tsconfig.build.json",
38
+ "prepack": "node ../../tooling/sync-package-docs.mjs"
39
+ },
40
+ "peerDependencies": {
41
+ "@web-ppt/core": "^0.1.0"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ }
46
+ }