@vue-puzzle-vcode/core 2.0.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/dist/index.cjs ADDED
@@ -0,0 +1,318 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let vue_demi = require("vue-demi");
3
+ let _vue_puzzle_vcode_shared = require("@vue-puzzle-vcode/shared");
4
+ //#region src/context.ts
5
+ /**
6
+ * Radix-style typed context factory built on provide/inject.
7
+ *
8
+ * ```ts
9
+ * const [useVcodeContext, provideVcodeContext] = createContext<VcodeContext>('VcodeRoot')
10
+ * ```
11
+ */
12
+ function createContext(providerName) {
13
+ const key = Symbol(providerName);
14
+ function provideContext(value) {
15
+ (0, vue_demi.provide)(key, value);
16
+ return value;
17
+ }
18
+ function useContext(consumerName = "Component") {
19
+ const ctx = (0, vue_demi.inject)(key, null);
20
+ if (ctx === null) throw new Error(`[vue-puzzle-vcode] \`${consumerName}\` must be used within \`${providerName}\``);
21
+ return ctx;
22
+ }
23
+ return [useContext, provideContext];
24
+ }
25
+ //#endregion
26
+ //#region src/handle.ts
27
+ const key = Symbol("VcodeHandle");
28
+ function provideVcodeHandle(handle) {
29
+ (0, vue_demi.provide)(key, handle);
30
+ }
31
+ function injectVcodeHandle() {
32
+ return (0, vue_demi.inject)(key, null);
33
+ }
34
+ //#endregion
35
+ //#region src/compat.ts
36
+ /** True when running on Vue 2.7.x (detected at runtime from `vue` itself). */
37
+ const isVue2 = vue_demi.version.startsWith("2.");
38
+ /** True when running on Vue 3.x. */
39
+ const isVue3 = !isVue2;
40
+ const hLegacy = vue_demi.h;
41
+ const hV3 = vue_demi.h;
42
+ const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
43
+ /**
44
+ * `h()` that works identically on Vue 2.7 and Vue 3. See {@link HCompatProps}
45
+ * for the normalized prop contract.
46
+ */
47
+ function hCompat(type, props = {}, children) {
48
+ const { class: cls, style, attrs, on } = props;
49
+ if (isVue2) {
50
+ const data = {};
51
+ if (cls != null) data.class = cls;
52
+ if (style != null) data.style = style;
53
+ if (attrs != null) data.attrs = attrs;
54
+ if (on != null) data.on = on;
55
+ if (children != null && !Array.isArray(children) && typeof children === "object") {
56
+ data.scopedSlots = children;
57
+ return hLegacy(type, data);
58
+ }
59
+ return hLegacy(type, data, children);
60
+ }
61
+ const v3props = { ...attrs };
62
+ if (cls != null) v3props.class = cls;
63
+ if (style != null) v3props.style = style;
64
+ if (on != null) for (const [name, handler] of Object.entries(on)) v3props[`on${capitalize(name)}`] = handler;
65
+ return hV3(type, v3props, children);
66
+ }
67
+ //#endregion
68
+ //#region src/use-event-listener.ts
69
+ /**
70
+ * Minimal `useEventListener`: binds immediately and auto-removes when the
71
+ * current effect scope (component) is disposed. Returns a manual unbind.
72
+ *
73
+ * Self-contained on purpose — keeps the library dependency-free and safe on
74
+ * both Vue 2.7 and Vue 3.
75
+ */
76
+ function useEventListener(target, type, listener, options) {
77
+ const bound = listener;
78
+ target?.addEventListener(type, bound, options);
79
+ const off = () => target?.removeEventListener(type, bound, options);
80
+ if ((0, vue_demi.getCurrentScope)()) (0, vue_demi.onScopeDispose)(off);
81
+ return off;
82
+ }
83
+ //#endregion
84
+ //#region src/use-vcode.ts
85
+ const clientXOf = (e) => {
86
+ const t = e.changedTouches;
87
+ return t && t.length > 0 ? t[0].clientX : e.clientX;
88
+ };
89
+ /**
90
+ * Headless sliding-puzzle state machine. `VcodeRoot` creates it and provides
91
+ * the result through context; every `Vcode*` part consumes slices of it.
92
+ *
93
+ * The drag math, verification tolerance and drawing flow are a faithful port
94
+ * of the original `vue-puzzle-vcode` component.
95
+ */
96
+ function useVcode(props, emits) {
97
+ const mouseDown = (0, vue_demi.ref)(false);
98
+ const startWidth = (0, vue_demi.ref)(props.sliderSize);
99
+ const startX = (0, vue_demi.ref)(0);
100
+ const newX = (0, vue_demi.ref)(0);
101
+ const pinX = (0, vue_demi.ref)(0);
102
+ const pinY = (0, vue_demi.ref)(0);
103
+ const loading = (0, vue_demi.ref)(false);
104
+ const isCanSlide = (0, vue_demi.ref)(false);
105
+ const infoBoxShow = (0, vue_demi.ref)(false);
106
+ const infoText = (0, vue_demi.ref)("");
107
+ const infoBoxFail = (0, vue_demi.ref)(false);
108
+ const isSuccess = (0, vue_demi.ref)(false);
109
+ const isSubmting = (0, vue_demi.ref)(false);
110
+ const imgIndex = (0, vue_demi.ref)(-1);
111
+ let timer;
112
+ let closeDown = false;
113
+ const puzzleBaseSize = (0, vue_demi.computed)(() => (0, _vue_puzzle_vcode_shared.computePuzzleBaseSize)(props.puzzleScale));
114
+ const sliderBaseSize = (0, vue_demi.computed)(() => (0, _vue_puzzle_vcode_shared.computeSliderBaseSize)(props.sliderSize, props.canvasWidth));
115
+ /** Progress width while dragging, clamped to [sliderSize, canvasWidth]. */
116
+ const styleWidth = (0, vue_demi.computed)(() => {
117
+ const w = startWidth.value + newX.value - startX.value;
118
+ return w < sliderBaseSize.value ? sliderBaseSize.value : w > props.canvasWidth ? props.canvasWidth : w;
119
+ });
120
+ /** translateX of the floating puzzle piece, synced to the slider. */
121
+ const puzzleTranslateX = (0, vue_demi.computed)(() => styleWidth.value - sliderBaseSize.value - (puzzleBaseSize.value - sliderBaseSize.value) * ((styleWidth.value - sliderBaseSize.value) / (props.canvasWidth - sliderBaseSize.value)));
122
+ const canvases = {
123
+ main: (0, vue_demi.shallowRef)(),
124
+ puzzle: (0, vue_demi.shallowRef)(),
125
+ success: (0, vue_demi.shallowRef)()
126
+ };
127
+ const progressEl = (0, vue_demi.shallowRef)();
128
+ function registerCanvas(key, el) {
129
+ canvases[key].value = el ?? void 0;
130
+ }
131
+ function registerProgress(el) {
132
+ progressEl.value = el ?? void 0;
133
+ }
134
+ function clearTimer() {
135
+ if (timer !== void 0) {
136
+ clearTimeout(timer);
137
+ timer = void 0;
138
+ }
139
+ }
140
+ (0, vue_demi.onScopeDispose)(clearTimer);
141
+ /**
142
+ * (Re)draw a frame: pick a puzzle position, load a background image and
143
+ * paint all three canvases. `withCanvas` forces a generated image.
144
+ */
145
+ async function init(withCanvas = false) {
146
+ if (loading.value && !withCanvas) return;
147
+ const main = canvases.main.value;
148
+ const puzzle = canvases.puzzle.value;
149
+ const success = canvases.success.value;
150
+ if (!main || !puzzle || !success) return;
151
+ loading.value = true;
152
+ isCanSlide.value = false;
153
+ pinX.value = (0, _vue_puzzle_vcode_shared.randomInt)(puzzleBaseSize.value, props.canvasWidth - puzzleBaseSize.value - 20);
154
+ pinY.value = (0, _vue_puzzle_vcode_shared.randomInt)(20, props.canvasHeight - puzzleBaseSize.value - 20);
155
+ let src;
156
+ const imgs = props.imgs;
157
+ if (!withCanvas && imgs && imgs.length > 0) {
158
+ let n = (0, _vue_puzzle_vcode_shared.randomInt)(0, imgs.length - 1);
159
+ if (n === imgIndex.value) n = n === imgs.length - 1 ? 0 : n + 1;
160
+ imgIndex.value = n;
161
+ src = imgs[n];
162
+ } else src = (0, _vue_puzzle_vcode_shared.generateRandomImage)(props.canvasWidth, props.canvasHeight);
163
+ try {
164
+ const img = await (0, _vue_puzzle_vcode_shared.loadImage)(src);
165
+ if (canvases.main.value !== main) {
166
+ loading.value = false;
167
+ return init();
168
+ }
169
+ (0, _vue_puzzle_vcode_shared.drawPuzzleFrame)({
170
+ main,
171
+ puzzle,
172
+ success
173
+ }, img, {
174
+ canvasWidth: props.canvasWidth,
175
+ canvasHeight: props.canvasHeight,
176
+ puzzleScale: props.puzzleScale,
177
+ puzzleBaseSize: puzzleBaseSize.value,
178
+ pinX: pinX.value,
179
+ pinY: pinY.value
180
+ });
181
+ } catch {
182
+ return init(true);
183
+ }
184
+ loading.value = false;
185
+ isCanSlide.value = true;
186
+ }
187
+ function onThumbDown(e) {
188
+ if (!isCanSlide.value) return;
189
+ mouseDown.value = true;
190
+ startWidth.value = progressEl.value?.clientWidth ?? sliderBaseSize.value;
191
+ const x = clientXOf(e);
192
+ newX.value = x;
193
+ startX.value = x;
194
+ }
195
+ function onPointerMove(e) {
196
+ if (!mouseDown.value) return;
197
+ e.preventDefault();
198
+ newX.value = clientXOf(e);
199
+ }
200
+ function onPointerUp() {
201
+ if (!mouseDown.value) return;
202
+ mouseDown.value = false;
203
+ submit();
204
+ }
205
+ function submit() {
206
+ isSubmting.value = true;
207
+ const x = Math.abs(pinX.value - (styleWidth.value - sliderBaseSize.value) + (puzzleBaseSize.value - sliderBaseSize.value) * ((styleWidth.value - sliderBaseSize.value) / (props.canvasWidth - sliderBaseSize.value)) - 3);
208
+ clearTimer();
209
+ if (x < props.range) {
210
+ infoText.value = props.successText;
211
+ infoBoxFail.value = false;
212
+ infoBoxShow.value = true;
213
+ isCanSlide.value = false;
214
+ isSuccess.value = true;
215
+ timer = setTimeout(() => {
216
+ isSubmting.value = false;
217
+ emits.onSuccess?.(x);
218
+ }, 800);
219
+ } else {
220
+ infoText.value = props.failText;
221
+ infoBoxFail.value = true;
222
+ infoBoxShow.value = true;
223
+ isCanSlide.value = false;
224
+ emits.onFail?.(x);
225
+ timer = setTimeout(() => {
226
+ isSubmting.value = false;
227
+ reset();
228
+ }, 800);
229
+ }
230
+ }
231
+ function resetState() {
232
+ infoBoxFail.value = false;
233
+ infoBoxShow.value = false;
234
+ isCanSlide.value = false;
235
+ isSuccess.value = false;
236
+ startWidth.value = sliderBaseSize.value;
237
+ startX.value = 0;
238
+ newX.value = 0;
239
+ }
240
+ /** Public: redraw with a fresh puzzle. No-op while a verdict is pending. */
241
+ function reset() {
242
+ if (isSubmting.value) return;
243
+ resetState();
244
+ init();
245
+ }
246
+ /** Called when the captcha is hidden: cancel the pending verdict emit
247
+ * and clear verdict UI state. */
248
+ function onHide() {
249
+ clearTimer();
250
+ isSubmting.value = false;
251
+ isSuccess.value = false;
252
+ infoBoxShow.value = false;
253
+ }
254
+ function requestClose() {
255
+ if (!mouseDown.value && !isSubmting.value) {
256
+ clearTimer();
257
+ emits.onClose?.();
258
+ }
259
+ }
260
+ function onOverlayDown() {
261
+ closeDown = true;
262
+ }
263
+ function onOverlayUp() {
264
+ if (closeDown) requestClose();
265
+ closeDown = false;
266
+ }
267
+ return {
268
+ /** Reactive props owned by the root (sizes, texts, show…). */
269
+ config: props,
270
+ mouseDown,
271
+ loading,
272
+ isCanSlide,
273
+ infoBoxShow,
274
+ infoText,
275
+ infoBoxFail,
276
+ isSuccess,
277
+ isSubmting,
278
+ pinX,
279
+ pinY,
280
+ puzzleBaseSize,
281
+ sliderBaseSize,
282
+ styleWidth,
283
+ puzzleTranslateX,
284
+ canvases,
285
+ progressEl,
286
+ registerCanvas,
287
+ registerProgress,
288
+ init,
289
+ reset,
290
+ submit,
291
+ onHide,
292
+ onThumbDown,
293
+ onPointerMove,
294
+ onPointerUp,
295
+ requestClose,
296
+ onOverlayDown,
297
+ onOverlayUp
298
+ };
299
+ }
300
+ //#endregion
301
+ //#region src/index.ts
302
+ /**
303
+ * Shared context pair for the `Vcode*` component family.
304
+ * `VcodeRoot` provides; every other part injects with a descriptive error
305
+ * when used standalone.
306
+ */
307
+ const [useVcodeContext, provideVcodeContext] = createContext("VcodeRoot");
308
+ //#endregion
309
+ exports.createContext = createContext;
310
+ exports.hCompat = hCompat;
311
+ exports.injectVcodeHandle = injectVcodeHandle;
312
+ exports.isVue2 = isVue2;
313
+ exports.isVue3 = isVue3;
314
+ exports.provideVcodeContext = provideVcodeContext;
315
+ exports.provideVcodeHandle = provideVcodeHandle;
316
+ exports.useEventListener = useEventListener;
317
+ exports.useVcode = useVcode;
318
+ exports.useVcodeContext = useVcodeContext;
@@ -0,0 +1,151 @@
1
+ import { ComputedRef, Ref, ShallowRef, VNode } from "vue-demi";
2
+ //#region src/use-vcode.d.ts
3
+ /** Reactive props the state machine reads (owned by `VcodeRoot`). */
4
+ interface VcodePropsLike {
5
+ show: boolean;
6
+ canvasWidth: number;
7
+ canvasHeight: number;
8
+ puzzleScale: number;
9
+ sliderSize: number;
10
+ range: number;
11
+ imgs?: string[] | undefined;
12
+ successText: string;
13
+ failText: string;
14
+ sliderText: string;
15
+ }
16
+ /** Event callbacks wired to the root component's emits. */
17
+ interface VcodeEmitters {
18
+ onSuccess?: (diff: number) => void;
19
+ onFail?: (diff: number) => void;
20
+ onClose?: () => void;
21
+ }
22
+ type VcodeCanvasKey = 'main' | 'puzzle' | 'success';
23
+ /**
24
+ * Public return type of {@link useVcode}. Declared explicitly (instead of
25
+ * inferred) with single-argument `Ref<T>` / `ShallowRef<T>` applications so
26
+ * the emitted declarations typecheck against both Vue 2.7 (`Ref<T>`) and
27
+ * Vue 3 (`Ref<T, S = T>`) typings.
28
+ */
29
+ interface UseVcodeReturn {
30
+ /** Reactive props owned by the root (sizes, texts, show…). */
31
+ config: VcodePropsLike;
32
+ mouseDown: Ref<boolean>;
33
+ loading: Ref<boolean>;
34
+ isCanSlide: Ref<boolean>;
35
+ infoBoxShow: Ref<boolean>;
36
+ infoText: Ref<string>;
37
+ infoBoxFail: Ref<boolean>;
38
+ isSuccess: Ref<boolean>;
39
+ isSubmting: Ref<boolean>;
40
+ pinX: Ref<number>;
41
+ pinY: Ref<number>;
42
+ puzzleBaseSize: ComputedRef<number>;
43
+ sliderBaseSize: ComputedRef<number>;
44
+ styleWidth: ComputedRef<number>;
45
+ puzzleTranslateX: ComputedRef<number>;
46
+ canvases: Record<VcodeCanvasKey, ShallowRef<HTMLCanvasElement | undefined>>;
47
+ progressEl: ShallowRef<HTMLElement | undefined>;
48
+ registerCanvas: (key: VcodeCanvasKey, el: HTMLCanvasElement | null) => void;
49
+ registerProgress: (el: HTMLElement | null) => void;
50
+ init: (withCanvas?: boolean) => Promise<void>;
51
+ reset: () => void;
52
+ submit: () => void;
53
+ onHide: () => void;
54
+ onThumbDown: (e: MouseEvent | TouchEvent) => void;
55
+ onPointerMove: (e: MouseEvent | TouchEvent) => void;
56
+ onPointerUp: () => void;
57
+ requestClose: () => void;
58
+ onOverlayDown: () => void;
59
+ onOverlayUp: () => void;
60
+ }
61
+ /**
62
+ * Headless sliding-puzzle state machine. `VcodeRoot` creates it and provides
63
+ * the result through context; every `Vcode*` part consumes slices of it.
64
+ *
65
+ * The drag math, verification tolerance and drawing flow are a faithful port
66
+ * of the original `vue-puzzle-vcode` component.
67
+ */
68
+ declare function useVcode(props: VcodePropsLike, emits: VcodeEmitters): UseVcodeReturn;
69
+ type VcodeContext = UseVcodeReturn;
70
+ //#endregion
71
+ //#region src/context.d.ts
72
+ interface ContextPair<T> {
73
+ /** Provide the context value. Call inside the provider component's `setup()`. */
74
+ provideContext: (value: T) => T;
75
+ /**
76
+ * Inject the context value. Throws a descriptive error when the component
77
+ * is used outside of its provider (Radix-style guard).
78
+ */
79
+ useContext: (consumerName?: string) => T;
80
+ }
81
+ /**
82
+ * Radix-style typed context factory built on provide/inject.
83
+ *
84
+ * ```ts
85
+ * const [useVcodeContext, provideVcodeContext] = createContext<VcodeContext>('VcodeRoot')
86
+ * ```
87
+ */
88
+ declare function createContext<T>(providerName: string): readonly [useContext: (consumerName?: string) => T, provideContext: (value: T) => T];
89
+ //#endregion
90
+ //#region src/handle.d.ts
91
+ /**
92
+ * Reverse channel letting an outer wrapper (the default `Vcode` composition)
93
+ * capture the root's state machine to re-expose `reset()` on template refs.
94
+ */
95
+ interface VcodeHandle {
96
+ register: (ctx: VcodeContext) => void;
97
+ }
98
+ declare function provideVcodeHandle(handle: VcodeHandle): void;
99
+ declare function injectVcodeHandle(): VcodeHandle | null;
100
+ //#endregion
101
+ //#region src/compat.d.ts
102
+ /** True when running on Vue 2.7.x (detected at runtime from `vue` itself). */
103
+ declare const isVue2: boolean;
104
+ /** True when running on Vue 3.x. */
105
+ declare const isVue3: boolean;
106
+ /**
107
+ * Vue-version-agnostic props for {@link hCompat}.
108
+ *
109
+ * Render-function signatures differ between Vue 2.7 (`createElement`: props
110
+ * nested under `attrs`/`on`/`scopedSlots`) and Vue 3 (flat props, `onXxx`
111
+ * listeners, object slots). This interface is the common denominator:
112
+ *
113
+ * - `class` / `style` — passed through (both versions normalize them)
114
+ * - `attrs` — DOM attributes and/or component props (v2 pulls declared props
115
+ * out of `attrs`; v3 receives them flat)
116
+ * - `on` — event handlers keyed by raw event name (`click`, `update:show`,
117
+ * `success`…). Mapped to `onClick` / `onUpdate:show` / `onSuccess` on v3.
118
+ */
119
+ interface HCompatProps {
120
+ class?: unknown;
121
+ style?: unknown;
122
+ attrs?: Record<string, unknown>;
123
+ on?: Record<string, unknown>;
124
+ }
125
+ /** Object form = component slots; array/string form = element children. */
126
+ type HCompatChildren = Record<string, (...args: any[]) => unknown> | unknown[] | string | undefined;
127
+ /**
128
+ * `h()` that works identically on Vue 2.7 and Vue 3. See {@link HCompatProps}
129
+ * for the normalized prop contract.
130
+ */
131
+ declare function hCompat(type: unknown, props?: HCompatProps, children?: HCompatChildren): VNode;
132
+ //#endregion
133
+ //#region src/use-event-listener.d.ts
134
+ /**
135
+ * Minimal `useEventListener`: binds immediately and auto-removes when the
136
+ * current effect scope (component) is disposed. Returns a manual unbind.
137
+ *
138
+ * Self-contained on purpose — keeps the library dependency-free and safe on
139
+ * both Vue 2.7 and Vue 3.
140
+ */
141
+ declare function useEventListener<E extends Event = Event>(target: EventTarget | null | undefined, type: string, listener: (event: E) => void, options?: boolean | AddEventListenerOptions): () => void;
142
+ //#endregion
143
+ //#region src/index.d.ts
144
+ /**
145
+ * Shared context pair for the `Vcode*` component family.
146
+ * `VcodeRoot` provides; every other part injects with a descriptive error
147
+ * when used standalone.
148
+ */
149
+ declare const useVcodeContext: (consumerName?: string) => UseVcodeReturn, provideVcodeContext: (value: UseVcodeReturn) => UseVcodeReturn;
150
+ //#endregion
151
+ export { type ContextPair, type HCompatChildren, type HCompatProps, type VcodeCanvasKey, type VcodeContext, type VcodeEmitters, type VcodeHandle, type VcodePropsLike, createContext, hCompat, injectVcodeHandle, isVue2, isVue3, provideVcodeContext, provideVcodeHandle, useEventListener, useVcode, useVcodeContext };
@@ -0,0 +1,151 @@
1
+ import { ComputedRef, Ref, ShallowRef, VNode } from "vue-demi";
2
+ //#region src/use-vcode.d.ts
3
+ /** Reactive props the state machine reads (owned by `VcodeRoot`). */
4
+ interface VcodePropsLike {
5
+ show: boolean;
6
+ canvasWidth: number;
7
+ canvasHeight: number;
8
+ puzzleScale: number;
9
+ sliderSize: number;
10
+ range: number;
11
+ imgs?: string[] | undefined;
12
+ successText: string;
13
+ failText: string;
14
+ sliderText: string;
15
+ }
16
+ /** Event callbacks wired to the root component's emits. */
17
+ interface VcodeEmitters {
18
+ onSuccess?: (diff: number) => void;
19
+ onFail?: (diff: number) => void;
20
+ onClose?: () => void;
21
+ }
22
+ type VcodeCanvasKey = 'main' | 'puzzle' | 'success';
23
+ /**
24
+ * Public return type of {@link useVcode}. Declared explicitly (instead of
25
+ * inferred) with single-argument `Ref<T>` / `ShallowRef<T>` applications so
26
+ * the emitted declarations typecheck against both Vue 2.7 (`Ref<T>`) and
27
+ * Vue 3 (`Ref<T, S = T>`) typings.
28
+ */
29
+ interface UseVcodeReturn {
30
+ /** Reactive props owned by the root (sizes, texts, show…). */
31
+ config: VcodePropsLike;
32
+ mouseDown: Ref<boolean>;
33
+ loading: Ref<boolean>;
34
+ isCanSlide: Ref<boolean>;
35
+ infoBoxShow: Ref<boolean>;
36
+ infoText: Ref<string>;
37
+ infoBoxFail: Ref<boolean>;
38
+ isSuccess: Ref<boolean>;
39
+ isSubmting: Ref<boolean>;
40
+ pinX: Ref<number>;
41
+ pinY: Ref<number>;
42
+ puzzleBaseSize: ComputedRef<number>;
43
+ sliderBaseSize: ComputedRef<number>;
44
+ styleWidth: ComputedRef<number>;
45
+ puzzleTranslateX: ComputedRef<number>;
46
+ canvases: Record<VcodeCanvasKey, ShallowRef<HTMLCanvasElement | undefined>>;
47
+ progressEl: ShallowRef<HTMLElement | undefined>;
48
+ registerCanvas: (key: VcodeCanvasKey, el: HTMLCanvasElement | null) => void;
49
+ registerProgress: (el: HTMLElement | null) => void;
50
+ init: (withCanvas?: boolean) => Promise<void>;
51
+ reset: () => void;
52
+ submit: () => void;
53
+ onHide: () => void;
54
+ onThumbDown: (e: MouseEvent | TouchEvent) => void;
55
+ onPointerMove: (e: MouseEvent | TouchEvent) => void;
56
+ onPointerUp: () => void;
57
+ requestClose: () => void;
58
+ onOverlayDown: () => void;
59
+ onOverlayUp: () => void;
60
+ }
61
+ /**
62
+ * Headless sliding-puzzle state machine. `VcodeRoot` creates it and provides
63
+ * the result through context; every `Vcode*` part consumes slices of it.
64
+ *
65
+ * The drag math, verification tolerance and drawing flow are a faithful port
66
+ * of the original `vue-puzzle-vcode` component.
67
+ */
68
+ declare function useVcode(props: VcodePropsLike, emits: VcodeEmitters): UseVcodeReturn;
69
+ type VcodeContext = UseVcodeReturn;
70
+ //#endregion
71
+ //#region src/context.d.ts
72
+ interface ContextPair<T> {
73
+ /** Provide the context value. Call inside the provider component's `setup()`. */
74
+ provideContext: (value: T) => T;
75
+ /**
76
+ * Inject the context value. Throws a descriptive error when the component
77
+ * is used outside of its provider (Radix-style guard).
78
+ */
79
+ useContext: (consumerName?: string) => T;
80
+ }
81
+ /**
82
+ * Radix-style typed context factory built on provide/inject.
83
+ *
84
+ * ```ts
85
+ * const [useVcodeContext, provideVcodeContext] = createContext<VcodeContext>('VcodeRoot')
86
+ * ```
87
+ */
88
+ declare function createContext<T>(providerName: string): readonly [useContext: (consumerName?: string) => T, provideContext: (value: T) => T];
89
+ //#endregion
90
+ //#region src/handle.d.ts
91
+ /**
92
+ * Reverse channel letting an outer wrapper (the default `Vcode` composition)
93
+ * capture the root's state machine to re-expose `reset()` on template refs.
94
+ */
95
+ interface VcodeHandle {
96
+ register: (ctx: VcodeContext) => void;
97
+ }
98
+ declare function provideVcodeHandle(handle: VcodeHandle): void;
99
+ declare function injectVcodeHandle(): VcodeHandle | null;
100
+ //#endregion
101
+ //#region src/compat.d.ts
102
+ /** True when running on Vue 2.7.x (detected at runtime from `vue` itself). */
103
+ declare const isVue2: boolean;
104
+ /** True when running on Vue 3.x. */
105
+ declare const isVue3: boolean;
106
+ /**
107
+ * Vue-version-agnostic props for {@link hCompat}.
108
+ *
109
+ * Render-function signatures differ between Vue 2.7 (`createElement`: props
110
+ * nested under `attrs`/`on`/`scopedSlots`) and Vue 3 (flat props, `onXxx`
111
+ * listeners, object slots). This interface is the common denominator:
112
+ *
113
+ * - `class` / `style` — passed through (both versions normalize them)
114
+ * - `attrs` — DOM attributes and/or component props (v2 pulls declared props
115
+ * out of `attrs`; v3 receives them flat)
116
+ * - `on` — event handlers keyed by raw event name (`click`, `update:show`,
117
+ * `success`…). Mapped to `onClick` / `onUpdate:show` / `onSuccess` on v3.
118
+ */
119
+ interface HCompatProps {
120
+ class?: unknown;
121
+ style?: unknown;
122
+ attrs?: Record<string, unknown>;
123
+ on?: Record<string, unknown>;
124
+ }
125
+ /** Object form = component slots; array/string form = element children. */
126
+ type HCompatChildren = Record<string, (...args: any[]) => unknown> | unknown[] | string | undefined;
127
+ /**
128
+ * `h()` that works identically on Vue 2.7 and Vue 3. See {@link HCompatProps}
129
+ * for the normalized prop contract.
130
+ */
131
+ declare function hCompat(type: unknown, props?: HCompatProps, children?: HCompatChildren): VNode;
132
+ //#endregion
133
+ //#region src/use-event-listener.d.ts
134
+ /**
135
+ * Minimal `useEventListener`: binds immediately and auto-removes when the
136
+ * current effect scope (component) is disposed. Returns a manual unbind.
137
+ *
138
+ * Self-contained on purpose — keeps the library dependency-free and safe on
139
+ * both Vue 2.7 and Vue 3.
140
+ */
141
+ declare function useEventListener<E extends Event = Event>(target: EventTarget | null | undefined, type: string, listener: (event: E) => void, options?: boolean | AddEventListenerOptions): () => void;
142
+ //#endregion
143
+ //#region src/index.d.ts
144
+ /**
145
+ * Shared context pair for the `Vcode*` component family.
146
+ * `VcodeRoot` provides; every other part injects with a descriptive error
147
+ * when used standalone.
148
+ */
149
+ declare const useVcodeContext: (consumerName?: string) => UseVcodeReturn, provideVcodeContext: (value: UseVcodeReturn) => UseVcodeReturn;
150
+ //#endregion
151
+ export { type ContextPair, type HCompatChildren, type HCompatProps, type VcodeCanvasKey, type VcodeContext, type VcodeEmitters, type VcodeHandle, type VcodePropsLike, createContext, hCompat, injectVcodeHandle, isVue2, isVue3, provideVcodeContext, provideVcodeHandle, useEventListener, useVcode, useVcodeContext };
package/dist/index.js ADDED
@@ -0,0 +1,308 @@
1
+ import { computed, getCurrentScope, h, inject, onScopeDispose, provide, ref, shallowRef, version } from "vue-demi";
2
+ import { computePuzzleBaseSize, computeSliderBaseSize, drawPuzzleFrame, generateRandomImage, loadImage, randomInt } from "@vue-puzzle-vcode/shared";
3
+ //#region src/context.ts
4
+ /**
5
+ * Radix-style typed context factory built on provide/inject.
6
+ *
7
+ * ```ts
8
+ * const [useVcodeContext, provideVcodeContext] = createContext<VcodeContext>('VcodeRoot')
9
+ * ```
10
+ */
11
+ function createContext(providerName) {
12
+ const key = Symbol(providerName);
13
+ function provideContext(value) {
14
+ provide(key, value);
15
+ return value;
16
+ }
17
+ function useContext(consumerName = "Component") {
18
+ const ctx = inject(key, null);
19
+ if (ctx === null) throw new Error(`[vue-puzzle-vcode] \`${consumerName}\` must be used within \`${providerName}\``);
20
+ return ctx;
21
+ }
22
+ return [useContext, provideContext];
23
+ }
24
+ //#endregion
25
+ //#region src/handle.ts
26
+ const key = Symbol("VcodeHandle");
27
+ function provideVcodeHandle(handle) {
28
+ provide(key, handle);
29
+ }
30
+ function injectVcodeHandle() {
31
+ return inject(key, null);
32
+ }
33
+ //#endregion
34
+ //#region src/compat.ts
35
+ /** True when running on Vue 2.7.x (detected at runtime from `vue` itself). */
36
+ const isVue2 = version.startsWith("2.");
37
+ /** True when running on Vue 3.x. */
38
+ const isVue3 = !isVue2;
39
+ const hLegacy = h;
40
+ const hV3 = h;
41
+ const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
42
+ /**
43
+ * `h()` that works identically on Vue 2.7 and Vue 3. See {@link HCompatProps}
44
+ * for the normalized prop contract.
45
+ */
46
+ function hCompat(type, props = {}, children) {
47
+ const { class: cls, style, attrs, on } = props;
48
+ if (isVue2) {
49
+ const data = {};
50
+ if (cls != null) data.class = cls;
51
+ if (style != null) data.style = style;
52
+ if (attrs != null) data.attrs = attrs;
53
+ if (on != null) data.on = on;
54
+ if (children != null && !Array.isArray(children) && typeof children === "object") {
55
+ data.scopedSlots = children;
56
+ return hLegacy(type, data);
57
+ }
58
+ return hLegacy(type, data, children);
59
+ }
60
+ const v3props = { ...attrs };
61
+ if (cls != null) v3props.class = cls;
62
+ if (style != null) v3props.style = style;
63
+ if (on != null) for (const [name, handler] of Object.entries(on)) v3props[`on${capitalize(name)}`] = handler;
64
+ return hV3(type, v3props, children);
65
+ }
66
+ //#endregion
67
+ //#region src/use-event-listener.ts
68
+ /**
69
+ * Minimal `useEventListener`: binds immediately and auto-removes when the
70
+ * current effect scope (component) is disposed. Returns a manual unbind.
71
+ *
72
+ * Self-contained on purpose — keeps the library dependency-free and safe on
73
+ * both Vue 2.7 and Vue 3.
74
+ */
75
+ function useEventListener(target, type, listener, options) {
76
+ const bound = listener;
77
+ target?.addEventListener(type, bound, options);
78
+ const off = () => target?.removeEventListener(type, bound, options);
79
+ if (getCurrentScope()) onScopeDispose(off);
80
+ return off;
81
+ }
82
+ //#endregion
83
+ //#region src/use-vcode.ts
84
+ const clientXOf = (e) => {
85
+ const t = e.changedTouches;
86
+ return t && t.length > 0 ? t[0].clientX : e.clientX;
87
+ };
88
+ /**
89
+ * Headless sliding-puzzle state machine. `VcodeRoot` creates it and provides
90
+ * the result through context; every `Vcode*` part consumes slices of it.
91
+ *
92
+ * The drag math, verification tolerance and drawing flow are a faithful port
93
+ * of the original `vue-puzzle-vcode` component.
94
+ */
95
+ function useVcode(props, emits) {
96
+ const mouseDown = ref(false);
97
+ const startWidth = ref(props.sliderSize);
98
+ const startX = ref(0);
99
+ const newX = ref(0);
100
+ const pinX = ref(0);
101
+ const pinY = ref(0);
102
+ const loading = ref(false);
103
+ const isCanSlide = ref(false);
104
+ const infoBoxShow = ref(false);
105
+ const infoText = ref("");
106
+ const infoBoxFail = ref(false);
107
+ const isSuccess = ref(false);
108
+ const isSubmting = ref(false);
109
+ const imgIndex = ref(-1);
110
+ let timer;
111
+ let closeDown = false;
112
+ const puzzleBaseSize = computed(() => computePuzzleBaseSize(props.puzzleScale));
113
+ const sliderBaseSize = computed(() => computeSliderBaseSize(props.sliderSize, props.canvasWidth));
114
+ /** Progress width while dragging, clamped to [sliderSize, canvasWidth]. */
115
+ const styleWidth = computed(() => {
116
+ const w = startWidth.value + newX.value - startX.value;
117
+ return w < sliderBaseSize.value ? sliderBaseSize.value : w > props.canvasWidth ? props.canvasWidth : w;
118
+ });
119
+ /** translateX of the floating puzzle piece, synced to the slider. */
120
+ const puzzleTranslateX = computed(() => styleWidth.value - sliderBaseSize.value - (puzzleBaseSize.value - sliderBaseSize.value) * ((styleWidth.value - sliderBaseSize.value) / (props.canvasWidth - sliderBaseSize.value)));
121
+ const canvases = {
122
+ main: shallowRef(),
123
+ puzzle: shallowRef(),
124
+ success: shallowRef()
125
+ };
126
+ const progressEl = shallowRef();
127
+ function registerCanvas(key, el) {
128
+ canvases[key].value = el ?? void 0;
129
+ }
130
+ function registerProgress(el) {
131
+ progressEl.value = el ?? void 0;
132
+ }
133
+ function clearTimer() {
134
+ if (timer !== void 0) {
135
+ clearTimeout(timer);
136
+ timer = void 0;
137
+ }
138
+ }
139
+ onScopeDispose(clearTimer);
140
+ /**
141
+ * (Re)draw a frame: pick a puzzle position, load a background image and
142
+ * paint all three canvases. `withCanvas` forces a generated image.
143
+ */
144
+ async function init(withCanvas = false) {
145
+ if (loading.value && !withCanvas) return;
146
+ const main = canvases.main.value;
147
+ const puzzle = canvases.puzzle.value;
148
+ const success = canvases.success.value;
149
+ if (!main || !puzzle || !success) return;
150
+ loading.value = true;
151
+ isCanSlide.value = false;
152
+ pinX.value = randomInt(puzzleBaseSize.value, props.canvasWidth - puzzleBaseSize.value - 20);
153
+ pinY.value = randomInt(20, props.canvasHeight - puzzleBaseSize.value - 20);
154
+ let src;
155
+ const imgs = props.imgs;
156
+ if (!withCanvas && imgs && imgs.length > 0) {
157
+ let n = randomInt(0, imgs.length - 1);
158
+ if (n === imgIndex.value) n = n === imgs.length - 1 ? 0 : n + 1;
159
+ imgIndex.value = n;
160
+ src = imgs[n];
161
+ } else src = generateRandomImage(props.canvasWidth, props.canvasHeight);
162
+ try {
163
+ const img = await loadImage(src);
164
+ if (canvases.main.value !== main) {
165
+ loading.value = false;
166
+ return init();
167
+ }
168
+ drawPuzzleFrame({
169
+ main,
170
+ puzzle,
171
+ success
172
+ }, img, {
173
+ canvasWidth: props.canvasWidth,
174
+ canvasHeight: props.canvasHeight,
175
+ puzzleScale: props.puzzleScale,
176
+ puzzleBaseSize: puzzleBaseSize.value,
177
+ pinX: pinX.value,
178
+ pinY: pinY.value
179
+ });
180
+ } catch {
181
+ return init(true);
182
+ }
183
+ loading.value = false;
184
+ isCanSlide.value = true;
185
+ }
186
+ function onThumbDown(e) {
187
+ if (!isCanSlide.value) return;
188
+ mouseDown.value = true;
189
+ startWidth.value = progressEl.value?.clientWidth ?? sliderBaseSize.value;
190
+ const x = clientXOf(e);
191
+ newX.value = x;
192
+ startX.value = x;
193
+ }
194
+ function onPointerMove(e) {
195
+ if (!mouseDown.value) return;
196
+ e.preventDefault();
197
+ newX.value = clientXOf(e);
198
+ }
199
+ function onPointerUp() {
200
+ if (!mouseDown.value) return;
201
+ mouseDown.value = false;
202
+ submit();
203
+ }
204
+ function submit() {
205
+ isSubmting.value = true;
206
+ const x = Math.abs(pinX.value - (styleWidth.value - sliderBaseSize.value) + (puzzleBaseSize.value - sliderBaseSize.value) * ((styleWidth.value - sliderBaseSize.value) / (props.canvasWidth - sliderBaseSize.value)) - 3);
207
+ clearTimer();
208
+ if (x < props.range) {
209
+ infoText.value = props.successText;
210
+ infoBoxFail.value = false;
211
+ infoBoxShow.value = true;
212
+ isCanSlide.value = false;
213
+ isSuccess.value = true;
214
+ timer = setTimeout(() => {
215
+ isSubmting.value = false;
216
+ emits.onSuccess?.(x);
217
+ }, 800);
218
+ } else {
219
+ infoText.value = props.failText;
220
+ infoBoxFail.value = true;
221
+ infoBoxShow.value = true;
222
+ isCanSlide.value = false;
223
+ emits.onFail?.(x);
224
+ timer = setTimeout(() => {
225
+ isSubmting.value = false;
226
+ reset();
227
+ }, 800);
228
+ }
229
+ }
230
+ function resetState() {
231
+ infoBoxFail.value = false;
232
+ infoBoxShow.value = false;
233
+ isCanSlide.value = false;
234
+ isSuccess.value = false;
235
+ startWidth.value = sliderBaseSize.value;
236
+ startX.value = 0;
237
+ newX.value = 0;
238
+ }
239
+ /** Public: redraw with a fresh puzzle. No-op while a verdict is pending. */
240
+ function reset() {
241
+ if (isSubmting.value) return;
242
+ resetState();
243
+ init();
244
+ }
245
+ /** Called when the captcha is hidden: cancel the pending verdict emit
246
+ * and clear verdict UI state. */
247
+ function onHide() {
248
+ clearTimer();
249
+ isSubmting.value = false;
250
+ isSuccess.value = false;
251
+ infoBoxShow.value = false;
252
+ }
253
+ function requestClose() {
254
+ if (!mouseDown.value && !isSubmting.value) {
255
+ clearTimer();
256
+ emits.onClose?.();
257
+ }
258
+ }
259
+ function onOverlayDown() {
260
+ closeDown = true;
261
+ }
262
+ function onOverlayUp() {
263
+ if (closeDown) requestClose();
264
+ closeDown = false;
265
+ }
266
+ return {
267
+ /** Reactive props owned by the root (sizes, texts, show…). */
268
+ config: props,
269
+ mouseDown,
270
+ loading,
271
+ isCanSlide,
272
+ infoBoxShow,
273
+ infoText,
274
+ infoBoxFail,
275
+ isSuccess,
276
+ isSubmting,
277
+ pinX,
278
+ pinY,
279
+ puzzleBaseSize,
280
+ sliderBaseSize,
281
+ styleWidth,
282
+ puzzleTranslateX,
283
+ canvases,
284
+ progressEl,
285
+ registerCanvas,
286
+ registerProgress,
287
+ init,
288
+ reset,
289
+ submit,
290
+ onHide,
291
+ onThumbDown,
292
+ onPointerMove,
293
+ onPointerUp,
294
+ requestClose,
295
+ onOverlayDown,
296
+ onOverlayUp
297
+ };
298
+ }
299
+ //#endregion
300
+ //#region src/index.ts
301
+ /**
302
+ * Shared context pair for the `Vcode*` component family.
303
+ * `VcodeRoot` provides; every other part injects with a descriptive error
304
+ * when used standalone.
305
+ */
306
+ const [useVcodeContext, provideVcodeContext] = createContext("VcodeRoot");
307
+ //#endregion
308
+ export { createContext, hCompat, injectVcodeHandle, isVue2, isVue3, provideVcodeContext, provideVcodeHandle, useEventListener, useVcode, useVcodeContext };
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@vue-puzzle-vcode/core",
3
+ "version": "2.0.0",
4
+ "description": "Headless core for vue-puzzle-vcode: context factory, v2/v3 render compat, state machine",
5
+ "license": "ISC",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/javaLuo/vue-puzzle-vcode.git",
9
+ "directory": "packages/core"
10
+ },
11
+ "type": "module",
12
+ "exports": {
13
+ ".": {
14
+ "import": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ },
18
+ "require": {
19
+ "types": "./dist/index.d.cts",
20
+ "default": "./dist/index.cjs"
21
+ }
22
+ }
23
+ },
24
+ "main": "./dist/index.cjs",
25
+ "module": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
27
+ "files": [
28
+ "dist"
29
+ ],
30
+ "sideEffects": false,
31
+ "dependencies": {
32
+ "vue-demi": "0.14.10",
33
+ "@vue-puzzle-vcode/shared": "^2.0.0"
34
+ },
35
+ "peerDependencies": {
36
+ "vue": "^2.7.0 || ^3.0.0"
37
+ },
38
+ "devDependencies": {
39
+ "tsdown": "0.22.14",
40
+ "typescript": "7.0.2",
41
+ "vue": "3.5.40"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "scripts": {
47
+ "build": "tsdown",
48
+ "dev": "tsdown --watch",
49
+ "typecheck": "tsc --noEmit"
50
+ }
51
+ }