@allkit/use 0.0.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/README.md ADDED
@@ -0,0 +1 @@
1
+ # vue use hooks 函数
package/dist/README.md ADDED
@@ -0,0 +1 @@
1
+ # vue use hooks 函数
@@ -0,0 +1,5 @@
1
+ export * from './useCtxState';
2
+ export * from './usePageVisibility';
3
+ export * from './useEventListener';
4
+ export * from './useScroll';
5
+ export * from './onMountedOrActivated';
@@ -0,0 +1 @@
1
+ export declare function onMountedOrActivated(hook: () => any): void;
@@ -0,0 +1,22 @@
1
+ {
2
+ "name": "@allkit/use",
3
+ "version": "0.0.1",
4
+ "description": "this is a vue3use package",
5
+ "type": "module",
6
+ "main": "./shared.umd.js",
7
+ "module":"./shared.es.js",
8
+ "types": "index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": "./shared.es.js",
12
+ "require": "./shared.umd.js"
13
+ },
14
+ },
15
+ "keywords": ["vue", "vueuse","@allkit/use"],
16
+ "license": "MIT",
17
+ "author": "SPig",
18
+ "publishConfig":{"access":"public"},
19
+ "dependencies":{},
20
+ "peerDependencies": {"vue":"^3.0.0","@allkit/shared":"workspace:*"}
21
+ }
22
+
@@ -0,0 +1,12 @@
1
+ import { MaybeRef, ComponentPublicInstance, MaybeRefOrGetter } from 'vue';
2
+ export interface ConfigurableWindow {
3
+ window?: Window;
4
+ }
5
+ export interface ConfigurableDocument {
6
+ document?: Document;
7
+ }
8
+ export type VueInstance = ComponentPublicInstance;
9
+ export type MaybeElement = Window | Document | HTMLElement | SVGElement | undefined | null;
10
+ export type MaybeElementRef<T extends MaybeElement = MaybeElement> = MaybeRef<T>;
11
+ export type MaybeComputedElementRef<T extends MaybeElement = MaybeElement> = MaybeRefOrGetter<T>;
12
+ export type TargetRef = MaybeElementRef<MaybeElement> | MaybeRef<EventTarget>;
@@ -0,0 +1,2 @@
1
+ export * from './index'
2
+ export {}
package/dist/use.es.js ADDED
@@ -0,0 +1,209 @@
1
+ var J = Object.defineProperty;
2
+ var V = Object.getOwnPropertySymbols;
3
+ var K = Object.prototype.hasOwnProperty, N = Object.prototype.propertyIsEnumerable;
4
+ var j = (o, t, n) => t in o ? J(o, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : o[t] = n, H = (o, t) => {
5
+ for (var n in t || (t = {}))
6
+ K.call(t, n) && j(o, n, t[n]);
7
+ if (V)
8
+ for (var n of V(t))
9
+ N.call(t, n) && j(o, n, t[n]);
10
+ return o;
11
+ };
12
+ import { reactive as D, getCurrentInstance as Y, onMounted as q, onBeforeUnmount as Q, nextTick as Z, onActivated as tt, onUnmounted as et, onDeactivated as ot, isRef as nt, watch as st, unref as k, ref as A, computed as U, toValue as S } from "vue";
13
+ import { isClient as z, debounce as lt, throttle as rt } from "@allkit/shared";
14
+ const dt = (o) => {
15
+ const t = D(o), s = [t, (l) => {
16
+ if (typeof l == "function") {
17
+ l(t);
18
+ return;
19
+ }
20
+ Object.assign(t, l);
21
+ }], c = Y();
22
+ if (!c)
23
+ return console.error("useCtxState must be called within a setup function"), s;
24
+ const { provides: u = {}, uid: d, type: v } = c, g = `state_${d}_${v.name || v.__name || ""}`;
25
+ return u[g] = s, s;
26
+ }, vt = () => {
27
+ const o = Y();
28
+ if (!o)
29
+ throw new Error(
30
+ "useCtxState is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup()"
31
+ );
32
+ const { provides: t = {}, uid: n, type: s } = o, c = `state_${n}_${s.name || s.__name || ""}`;
33
+ return t[c] || [];
34
+ }, mt = () => {
35
+ let o, t;
36
+ const n = (u) => {
37
+ o = u;
38
+ }, s = (u) => {
39
+ t = u;
40
+ }, c = () => {
41
+ if (document.visibilityState === "hidden") {
42
+ t && t();
43
+ return;
44
+ }
45
+ o && o();
46
+ };
47
+ return q(() => {
48
+ document.addEventListener("visibilitychange", c);
49
+ }), Q(() => {
50
+ document.removeEventListener("visibilitychange", c);
51
+ }), {
52
+ onPageShow: n,
53
+ onPageHidden: s
54
+ };
55
+ };
56
+ function F(o) {
57
+ let t;
58
+ q(() => {
59
+ o(), Z(() => {
60
+ t = !0;
61
+ });
62
+ }), tt(() => {
63
+ t && o();
64
+ });
65
+ }
66
+ function W(o, t, n = {}) {
67
+ if (!z)
68
+ return;
69
+ const { target: s = window, passive: c = !1, capture: u = !1 } = n;
70
+ let d = !1, v;
71
+ const g = (a) => {
72
+ if (d)
73
+ return;
74
+ const i = k(a);
75
+ i && !v && (i.addEventListener(o, t, {
76
+ capture: u,
77
+ passive: c
78
+ }), v = !0);
79
+ }, l = (a) => {
80
+ if (d)
81
+ return;
82
+ const i = k(a);
83
+ i && v && (i.removeEventListener(o, t, u), v = !1);
84
+ };
85
+ et(() => l(s)), ot(() => l(s)), F(() => g(s));
86
+ let E;
87
+ return nt(s) && (E = st(s, (a, i) => {
88
+ l(i), g(a);
89
+ })), () => {
90
+ E == null || E(), l(s), d = !0;
91
+ };
92
+ }
93
+ const X = () => ({});
94
+ function it(o) {
95
+ var n;
96
+ const t = S(o);
97
+ return (n = t == null ? void 0 : t.$el) != null ? n : t;
98
+ }
99
+ const B = 1, ct = z ? window : void 0;
100
+ function pt(o, t = {}) {
101
+ const {
102
+ throttle: n = 0,
103
+ idle: s = 200,
104
+ onStop: c = X,
105
+ onScroll: u = X,
106
+ offset: d = {
107
+ left: 0,
108
+ right: 0,
109
+ top: 0,
110
+ bottom: 0
111
+ },
112
+ eventListenerOptions: v = {
113
+ capture: !1,
114
+ passive: !0
115
+ },
116
+ behavior: g = "auto",
117
+ window: l = ct,
118
+ onError: E = (e) => {
119
+ console.error(e);
120
+ }
121
+ } = t, a = A(0), i = A(0), x = U({
122
+ get() {
123
+ return a.value;
124
+ },
125
+ set(e) {
126
+ M(e, void 0);
127
+ }
128
+ }), C = U({
129
+ get() {
130
+ return i.value;
131
+ },
132
+ set(e) {
133
+ M(void 0, e);
134
+ }
135
+ });
136
+ function M(e, f) {
137
+ var b, w, T, m;
138
+ if (!l) return;
139
+ const r = S(o);
140
+ if (!r) return;
141
+ (T = r instanceof Document ? l.document.body : r) == null || T.scrollTo({
142
+ top: (b = S(f)) != null ? b : C.value,
143
+ left: (w = S(e)) != null ? w : x.value,
144
+ behavior: S(g)
145
+ });
146
+ const y = ((m = r == null ? void 0 : r.document) == null ? void 0 : m.documentElement) || (r == null ? void 0 : r.documentElement) || r;
147
+ x.value != null && (a.value = y.scrollLeft), C.value != null && (i.value = y.scrollTop);
148
+ }
149
+ const L = A(!1), p = D({
150
+ left: !0,
151
+ right: !1,
152
+ top: !0,
153
+ bottom: !1
154
+ }), h = D({
155
+ left: !1,
156
+ right: !1,
157
+ top: !1,
158
+ bottom: !1
159
+ }), $ = (e) => {
160
+ L.value && (L.value = !1, h.left = !1, h.right = !1, h.top = !1, h.bottom = !1, c(e));
161
+ }, G = lt($, n + s), _ = (e) => {
162
+ var R;
163
+ if (!l) return;
164
+ const f = ((R = e == null ? void 0 : e.document) == null ? void 0 : R.documentElement) || (e == null ? void 0 : e.documentElement) || it(e), { display: r, flexDirection: y } = getComputedStyle(f), b = f.scrollLeft;
165
+ h.left = b < a.value, h.right = b > a.value;
166
+ const w = Math.abs(b) <= (d.left || 0), T = Math.abs(b) + f.clientWidth >= f.scrollWidth - (d.right || 0) - B;
167
+ r === "flex" && y === "row-reverse" ? (p.left = T, p.right = w) : (p.left = w, p.right = T), a.value = b;
168
+ let m = f.scrollTop;
169
+ e === l.document && !m && (m = l.document.body.scrollTop), h.top = m < i.value, h.bottom = m > i.value;
170
+ const I = Math.abs(m) <= (d.top || 0), O = Math.abs(m) + f.clientHeight >= f.scrollHeight - (d.bottom || 0) - B;
171
+ r === "flex" && y === "column-reverse" ? (p.top = O, p.bottom = I) : (p.top = I, p.bottom = O), i.value = m;
172
+ }, P = (e) => {
173
+ var r;
174
+ if (!l) return;
175
+ const f = (r = e.target.documentElement) != null ? r : e.target;
176
+ _(f), L.value = !0, G(e), u(e);
177
+ };
178
+ return W("scroll", n ? rt(P, n) : P, H({
179
+ target: o
180
+ }, v)), F(() => {
181
+ try {
182
+ const e = S(o);
183
+ if (!e) return;
184
+ _(e);
185
+ } catch (e) {
186
+ E(e);
187
+ }
188
+ }), W("scrollend", $, H({
189
+ target: o
190
+ }, v)), {
191
+ x,
192
+ y: C,
193
+ isScrolling: L,
194
+ arrivedState: p,
195
+ directions: h,
196
+ measure() {
197
+ const e = S(o);
198
+ l && e && _(e);
199
+ }
200
+ };
201
+ }
202
+ export {
203
+ dt as defineCtxState,
204
+ F as onMountedOrActivated,
205
+ vt as useCtxState,
206
+ W as useEventListener,
207
+ mt as usePageVisibility,
208
+ pt as useScroll
209
+ };
@@ -0,0 +1 @@
1
+ (function(s,t){typeof exports=="object"&&typeof module!="undefined"?t(exports,require("vue"),require("@allkit/shared")):typeof define=="function"&&define.amd?define(["exports","vue","@allkit/shared"],t):(s=typeof globalThis!="undefined"?globalThis:s||self,t(s.use={},s.Vue,s.shared))})(this,(function(s,t,c){"use strict";var K=Object.defineProperty;var U=Object.getOwnPropertySymbols;var N=Object.prototype.hasOwnProperty,Q=Object.prototype.propertyIsEnumerable;var W=(s,t,c)=>t in s?K(s,t,{enumerable:!0,configurable:!0,writable:!0,value:c}):s[t]=c,P=(s,t)=>{for(var c in t||(t={}))N.call(t,c)&&W(s,c,t[c]);if(U)for(var c of U(t))Q.call(t,c)&&W(s,c,t[c]);return s};const X=n=>{const o=t.reactive(n),i=[o,l=>{if(typeof l=="function"){l(o);return}Object.assign(o,l)}],f=t.getCurrentInstance();if(!f)return console.error("useCtxState must be called within a setup function"),i;const{provides:d={},uid:p,type:b}=f,E=`state_${p}_${b.name||b.__name||""}`;return d[E]=i,i},B=()=>{const n=t.getCurrentInstance();if(!n)throw new Error("useCtxState is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup()");const{provides:o={},uid:a,type:i}=n,f=`state_${a}_${i.name||i.__name||""}`;return o[f]||[]},Y=()=>{let n,o;const a=d=>{n=d},i=d=>{o=d},f=()=>{if(document.visibilityState==="hidden"){o&&o();return}n&&n()};return t.onMounted(()=>{document.addEventListener("visibilitychange",f)}),t.onBeforeUnmount(()=>{document.removeEventListener("visibilitychange",f)}),{onPageShow:a,onPageHidden:i}};function _(n){let o;t.onMounted(()=>{n(),t.nextTick(()=>{o=!0})}),t.onActivated(()=>{o&&n()})}function x(n,o,a={}){if(!c.isClient)return;const{target:i=window,passive:f=!1,capture:d=!1}=a;let p=!1,b;const E=m=>{if(p)return;const u=t.unref(m);u&&!b&&(u.addEventListener(n,o,{capture:d,passive:f}),b=!0)},l=m=>{if(p)return;const u=t.unref(m);u&&b&&(u.removeEventListener(n,o,d),b=!1)};t.onUnmounted(()=>l(i)),t.onDeactivated(()=>l(i)),_(()=>E(i));let T;return t.isRef(i)&&(T=t.watch(i,(m,u)=>{l(u),E(m)})),()=>{T==null||T(),l(i),p=!0}}const D=()=>({});function z(n){var a;const o=t.toValue(n);return(a=o==null?void 0:o.$el)!=null?a:o}const O=1,F=c.isClient?window:void 0;function G(n,o={}){const{throttle:a=0,idle:i=200,onStop:f=D,onScroll:d=D,offset:p={left:0,right:0,top:0,bottom:0},eventListenerOptions:b={capture:!1,passive:!0},behavior:E="auto",window:l=F,onError:T=e=>{console.error(e)}}=o,m=t.ref(0),u=t.ref(0),M=t.computed({get(){return m.value},set(e){I(e,void 0)}}),A=t.computed({get(){return u.value},set(e){I(void 0,e)}});function I(e,h){var g,C,L,v;if(!l)return;const r=t.toValue(n);if(!r)return;(L=r instanceof Document?l.document.body:r)==null||L.scrollTo({top:(g=t.toValue(h))!=null?g:A.value,left:(C=t.toValue(e))!=null?C:M.value,behavior:t.toValue(E)});const w=((v=r==null?void 0:r.document)==null?void 0:v.documentElement)||(r==null?void 0:r.documentElement)||r;M.value!=null&&(m.value=w.scrollLeft),A.value!=null&&(u.value=w.scrollTop)}const V=t.ref(!1),S=t.reactive({left:!0,right:!1,top:!0,bottom:!1}),y=t.reactive({left:!1,right:!1,top:!1,bottom:!1}),$=e=>{V.value&&(V.value=!1,y.left=!1,y.right=!1,y.top=!1,y.bottom=!1,f(e))},J=c.debounce($,a+i),H=e=>{var q;if(!l)return;const h=((q=e==null?void 0:e.document)==null?void 0:q.documentElement)||(e==null?void 0:e.documentElement)||z(e),{display:r,flexDirection:w}=getComputedStyle(h),g=h.scrollLeft;y.left=g<m.value,y.right=g>m.value;const C=Math.abs(g)<=(p.left||0),L=Math.abs(g)+h.clientWidth>=h.scrollWidth-(p.right||0)-O;r==="flex"&&w==="row-reverse"?(S.left=L,S.right=C):(S.left=C,S.right=L),m.value=g;let v=h.scrollTop;e===l.document&&!v&&(v=l.document.body.scrollTop),y.top=v<u.value,y.bottom=v>u.value;const k=Math.abs(v)<=(p.top||0),R=Math.abs(v)+h.clientHeight>=h.scrollHeight-(p.bottom||0)-O;r==="flex"&&w==="column-reverse"?(S.top=R,S.bottom=k):(S.top=k,S.bottom=R),u.value=v},j=e=>{var r;if(!l)return;const h=(r=e.target.documentElement)!=null?r:e.target;H(h),V.value=!0,J(e),d(e)};return x("scroll",a?c.throttle(j,a):j,P({target:n},b)),_(()=>{try{const e=t.toValue(n);if(!e)return;H(e)}catch(e){T(e)}}),x("scrollend",$,P({target:n},b)),{x:M,y:A,isScrolling:V,arrivedState:S,directions:y,measure(){const e=t.toValue(n);l&&e&&H(e)}}}s.defineCtxState=X,s.onMountedOrActivated=_,s.useCtxState=B,s.useEventListener=x,s.usePageVisibility=Y,s.useScroll=G,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})}));
@@ -0,0 +1,45 @@
1
+ type DeepPartial<T> = {
2
+ [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
3
+ };
4
+ type IStateTuple<T> = readonly [
5
+ Readonly<T>,
6
+ (state: DeepPartial<T> | ((newState: T) => void)) => void
7
+ ];
8
+ /**
9
+ * 定义当前组件作用域的共享数据
10
+ * @param data - 需要共享的数据
11
+ * @returns [state, setState]
12
+ * @example
13
+ * ```ts
14
+ * // state: 共享数据的只读代理
15
+ * const [state, setState] = defineCtxState({ count: 0 })
16
+ *
17
+ * //setState: 更新共享数据的方法,会合并旧数据
18
+ * setState({ count: 2 })
19
+ * //推荐函数写法
20
+ * setState((state) => {state.count = 2})
21
+ *
22
+ * ```
23
+ *
24
+ */
25
+ export declare const defineCtxState: <T extends Record<string, any>>(data: T) => readonly [T, (newState: DeepPartial<T> | ((newState: T) => void)) => void];
26
+ /**
27
+ * 获取当前组件作用域{@link defineCtxState}定义的共享数据
28
+ *
29
+ * @see defineCtxState
30
+ * @returns [state, setState]
31
+ * @example
32
+ *
33
+ * ```ts
34
+ * // state: 共享数据的只读代理
35
+ * const [state, setState] = usCtxState({ count: 0 })
36
+ *
37
+ * //setState: 更新共享数据的方法
38
+ * setState({ count: 2 })
39
+ * setState((state) => {state.count = 2})
40
+ *
41
+ * ```
42
+ *
43
+ */
44
+ export declare const useCtxState: <T = Record<string, any>>() => IStateTuple<T>;
45
+ export {};
@@ -0,0 +1,8 @@
1
+ import { TargetRef } from '../types';
2
+ export type UseEventListenerOptions = {
3
+ target?: TargetRef;
4
+ capture?: boolean;
5
+ passive?: boolean;
6
+ };
7
+ export declare function useEventListener<K extends keyof DocumentEventMap>(type: K, listener: (event: DocumentEventMap[K]) => void, options?: UseEventListenerOptions): () => void;
8
+ export declare function useEventListener(type: string, listener: EventListener, options?: UseEventListenerOptions): () => void;
@@ -0,0 +1,17 @@
1
+ type visibleCbFunc = () => void;
2
+ /**
3
+ * 判断页面是否可见或者不可见
4
+ * @example
5
+ * ```ts
6
+ * let {onPageShow,onPageHidden}=usePageVisibility()
7
+ * //页面显示可见
8
+ * onPageShow(()=>{})
9
+ * //页面隐藏
10
+ * onPageHidden(()=>{})
11
+ * ```
12
+ */
13
+ export declare const usePageVisibility: () => {
14
+ onPageShow: (cb: visibleCbFunc) => void;
15
+ onPageHidden: (cb: visibleCbFunc) => void;
16
+ };
17
+ export {};
@@ -0,0 +1,81 @@
1
+ import { MaybeRefOrGetter } from 'vue';
2
+ import { ConfigurableWindow, MaybeElement, MaybeElementRef } from '../types';
3
+ export interface UseScrollOptions extends ConfigurableWindow {
4
+ /**
5
+ * Throttle time for scroll event, it’s disabled by default.
6
+ *
7
+ * @defaultValue 0
8
+ */
9
+ throttle?: number;
10
+ /**
11
+ * The check time when scrolling ends.
12
+ * This configuration will be setting to (throttle + idle) when the `throttle` is configured.
13
+ *
14
+ * @defaultValue 200
15
+ */
16
+ idle?: number;
17
+ /**
18
+ * Offset arrived states by x pixels
19
+ *
20
+ */
21
+ offset?: {
22
+ left?: number;
23
+ right?: number;
24
+ top?: number;
25
+ bottom?: number;
26
+ };
27
+ /**
28
+ * Trigger it when scrolling.
29
+ *
30
+ */
31
+ onScroll?: (e: Event) => void;
32
+ /**
33
+ * Trigger it when scrolling ends.
34
+ *
35
+ */
36
+ onStop?: (e: Event) => void;
37
+ /**
38
+ * Listener options for scroll event.
39
+ *
40
+ * @defaultValue `{capture: false, passive: true}`
41
+ */
42
+ eventListenerOptions?: AddEventListenerOptions;
43
+ /**
44
+ * Optionally specify a scroll behavior of `auto` (default, not smooth scrolling) or
45
+ * `smooth` (for smooth scrolling) which takes effect when changing the `x` or `y` refs.
46
+ *
47
+ * @defaultValue 'auto'
48
+ */
49
+ behavior?: MaybeRefOrGetter<ScrollBehavior>;
50
+ /**
51
+ * On error callback
52
+ *
53
+ * Default log error to `console.error`
54
+ */
55
+ onError?: (error: unknown) => void;
56
+ }
57
+ /**
58
+ * 监听页面布局滚动 事件
59
+ * @param element -监听的元素,支持window,document,HTMLElement 以及 Ref引用
60
+ * @param options -{@link UseScrollOptions}
61
+ * @returns x,y轴滚动距离,方向,状态,以及是否到达边界
62
+ */
63
+ export declare function useScroll(element: MaybeElementRef<MaybeElement>, options?: UseScrollOptions): {
64
+ x: import('vue').WritableComputedRef<number, number>;
65
+ y: import('vue').WritableComputedRef<number, number>;
66
+ isScrolling: import('vue').Ref<boolean, boolean>;
67
+ arrivedState: {
68
+ left: boolean;
69
+ right: boolean;
70
+ top: boolean;
71
+ bottom: boolean;
72
+ };
73
+ directions: {
74
+ left: boolean;
75
+ right: boolean;
76
+ top: boolean;
77
+ bottom: boolean;
78
+ };
79
+ measure(): void;
80
+ };
81
+ export type UseScrollReturn = ReturnType<typeof useScroll>;
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@allkit/use",
3
+ "version": "0.0.1",
4
+ "description": "this is a vue3use package",
5
+ "main": "./src/index.ts",
6
+ "module": "./src/index.ts",
7
+ "type": "module",
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "scripts": {
12
+ "test": "vitest",
13
+ "coverage": "vitest run --coverage",
14
+ "build": "node ./scripts/build.mjs"
15
+ },
16
+ "dependencies": {},
17
+ "peerDependencies": {
18
+ "vue": "^3.0.0",
19
+ "@allkit/shared": "workspace:*"
20
+ }
21
+ }
@@ -0,0 +1,99 @@
1
+ import { createReadStream, createWriteStream } from 'fs'
2
+ import { createRequire } from 'module'
3
+ import { dirname, resolve } from 'path'
4
+ import { fileURLToPath } from 'url'
5
+ import fse from 'fs-extra'
6
+ // 引入 vite 的 build 方法,进行编译构建
7
+ import { build } from 'vite'
8
+ import { viteLibConfig } from '@allkit/vite-config'
9
+
10
+ const { outputFile } = fse
11
+
12
+ const require = createRequire(import.meta.url)
13
+
14
+ const __filename = fileURLToPath(import.meta.url)
15
+ const __dirname = dirname(__filename)
16
+
17
+ // 输出目录
18
+ const outputDir = resolve(__dirname, '../dist')
19
+
20
+ const {
21
+ version,
22
+ peerDependencies,
23
+ name,
24
+ description,
25
+ publishConfig,
26
+ dependencies,
27
+ type,
28
+ } = require('../package.json')
29
+ // 生成 package.json
30
+ const createPackageJson = () => {
31
+ const pkgName = name
32
+ const pkgUMD = './shared.umd.js'
33
+ const pkgESM = './shared.es.js'
34
+
35
+ const fileStr = `{
36
+ "name": "${pkgName}",
37
+ "version": "${version}",
38
+ "description": "${description}",
39
+ "type": "${type}",
40
+ "main": "${pkgUMD}",
41
+ "module":"${pkgESM}",
42
+ "types": "index.d.ts",
43
+ "exports": {
44
+ ".": {
45
+ "import": "${pkgESM}",
46
+ "require": "${pkgUMD}"
47
+ },
48
+ },
49
+ "keywords": ["vue", "vueuse","${name || ''}"],
50
+ "license": "MIT",
51
+ "author": "SPig",
52
+ "publishConfig":${JSON.stringify(publishConfig)},
53
+ "dependencies":${JSON.stringify(dependencies)},
54
+ "peerDependencies": ${peerDependencies ? JSON.stringify(peerDependencies) : '{}'}
55
+ }
56
+ `
57
+ // 单个组件 or 全量
58
+ const filePath = resolve(outputDir, 'package.json')
59
+ outputFile(filePath, fileStr, 'utf-8')
60
+ }
61
+
62
+ /** 全量构建 */
63
+ const buildAll = async () => {
64
+ const config = viteLibConfig({
65
+ mode: 'production',
66
+ build: {
67
+ target: 'es2015',
68
+ lib: {
69
+ entry: './src/index.ts',
70
+ name: 'use',
71
+ fileName: (format) => `use.${format}.js`,
72
+ },
73
+ rollupOptions: {
74
+ external: ['vue', '@allkit/shared'],
75
+ globals: {
76
+ vue: 'Vue',
77
+ },
78
+ },
79
+ },
80
+ })
81
+ await build(config)
82
+
83
+ createPackageJson()
84
+ }
85
+
86
+ // copy文件
87
+ // README.md
88
+ // 样式 index.css
89
+ const copyFiles = () => {
90
+ const markdown = createReadStream(resolve(__dirname, '../README.md'))
91
+ markdown.pipe(createWriteStream(resolve(__dirname, '../dist/README.md')))
92
+ }
93
+
94
+ const buildLib = async () => {
95
+ await buildAll()
96
+ copyFiles()
97
+ }
98
+
99
+ buildLib()
package/skill/SKILL.md ADDED
@@ -0,0 +1,40 @@
1
+ ---
2
+ name: use
3
+ description: Vue 3 组合式 API 工具函数库,提供状态管理、事件监听和常用 UI 模式 / Vue 3 Composition API hooks library
4
+ author: allkit
5
+ category: vue
6
+ ---
7
+
8
+ # @allkit/use
9
+
10
+ Vue 3 组合式 API 工具函数库
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ pnpm add @allkit/use
16
+ ```
17
+
18
+ ## Hooks
19
+
20
+ | Hook | Description |
21
+ |------|-------------|
22
+ | [defineCtxState](./references/defineCtxState.md) | 定义组件作用域共享数据 |
23
+ | [useCtxState](./references/useCtxState.md) | 获取共享数据 |
24
+ | [useEventListener](./references/useEventListener.md) | 事件监听 |
25
+ | [usePageVisibility](./references/usePageVisibility.md) | 页面可见性 |
26
+ | [useScroll](./references/useScroll.md) | 滚动监听 |
27
+ | [onMountedOrActivated](./references/onMountedOrActivated.md) | keep-alive 组件初始化 |
28
+
29
+ ## Usage
30
+
31
+ ```ts
32
+ import { defineCtxState, useCtxState, useEventListener } from '@allkit/use'
33
+
34
+ const [state, setState] = defineCtxState({
35
+ loading: false,
36
+ list: []
37
+ })
38
+
39
+ useEventListener('scroll', handleScroll)
40
+ ```
@@ -0,0 +1,83 @@
1
+ import { defineComponent, ref, computed } from 'vue'
2
+ import {
3
+ defineCtxState,
4
+ useCtxState,
5
+ useEventListener,
6
+ usePageVisibility,
7
+ useScroll,
8
+ onMountedOrActivated
9
+ } from '@allkit/use'
10
+
11
+ interface UserListState {
12
+ loading: boolean
13
+ list: Array<{ id: number; name: string }>
14
+ pagination: { current: number; size: number; total: number }
15
+ }
16
+
17
+ const useSearchForm = () => {
18
+ const [state, setState] = useCtxState<UserListState>()
19
+
20
+ const handleSearch = () => {
21
+ setState(s => {
22
+ s.loading = true
23
+ s.pagination.current = 1
24
+ })
25
+ }
26
+
27
+ return () => (
28
+ <div className="search-form">
29
+ <button onClick={handleSearch} disabled={state.loading}>
30
+ {state.loading ? '搜索中...' : '搜索'}
31
+ </button>
32
+ </div>
33
+ )
34
+ }
35
+
36
+ const useList = () => {
37
+ const [state, setState] = useCtxState<UserListState>()
38
+
39
+ return () => (
40
+ <div className="user-list">
41
+ {state.list.map(item => (
42
+ <div key={item.id}>{item.name}</div>
43
+ ))}
44
+ </div>
45
+ )
46
+ }
47
+
48
+ export default defineComponent({
49
+ setup() {
50
+ const [state, setState] = defineCtxState<UserListState>({
51
+ loading: false,
52
+ list: [],
53
+ pagination: { current: 1, size: 20, total: 0 }
54
+ })
55
+
56
+ const renderSearch = useSearchForm()
57
+ const renderList = useList()
58
+
59
+ useEventListener('resize', () => {
60
+ console.log('window resized')
61
+ })
62
+
63
+ const { onPageShow, onPageHidden } = usePageVisibility()
64
+ onPageShow(() => console.log('page show'))
65
+ onPageHidden(() => console.log('page hidden'))
66
+
67
+ const { y, arrivedState } = useScroll(window, { throttle: 100 })
68
+ const isBottom = computed(() => arrivedState.bottom)
69
+
70
+ onMountedOrActivated(() => {
71
+ console.log('mounted or activated')
72
+ })
73
+
74
+ return () => (
75
+ <div>
76
+ {renderSearch()}
77
+ {renderList()}
78
+ <p>scroll: {Math.round(y.value)}px</p>
79
+ <p>bottom: {isBottom.value ? 'yes' : 'no'}</p>
80
+ </div>
81
+ )
82
+ }
83
+ })