@sprawlify/vue 0.0.63 → 0.0.65

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/dist/index.js CHANGED
@@ -1,337 +1,52 @@
1
- import { INIT_STATE, MachineStatus, createScope, mergeProps } from "@sprawlify/primitives/core";
2
- import { createNormalizer } from "@sprawlify/primitives/types";
3
- import { compact, ensure, isEqual, isFunction, isString, toArray, warn } from "@sprawlify/primitives/utils";
4
- import { computed, nextTick, onBeforeUnmount, onMounted, onUnmounted, shallowRef, toValue, watch } from "vue";
1
+ import { a as DEFAULT_LOCALE, c as DEFAULT_ENVIRONMENT, d as mergeProps, f as useMachine, i as locale_provider_default, l as useEnvironmentContext, n as useFilter, o as useLocaleContext, p as normalizeProps, r as useCollator, s as environment_provider_default, t as useForwardExpose, u as createContext } from "./use-forward-expose-BIk4OI3R.js";
2
+ import { camelize, computed, getCurrentInstance, toHandlerKey, toRef } from "vue";
5
3
 
6
- //#region src/core/normalize-props.ts
7
- function toCase(txt) {
8
- return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
9
- }
10
- const propMap = {
11
- htmlFor: "for",
12
- className: "class",
13
- onDoubleClick: "onDblclick",
14
- onChange: "onInput",
15
- onFocus: "onFocusin",
16
- onBlur: "onFocusout",
17
- defaultValue: "value",
18
- defaultChecked: "checked"
19
- };
20
- const preserveKeys = "viewBox,className,preserveAspectRatio,fillRule,clipPath,clipRule,strokeWidth,strokeLinecap,strokeLinejoin,strokeDasharray,strokeDashoffset,strokeMiterlimit".split(",");
21
- function toVueProp(prop) {
22
- if (prop in propMap) return propMap[prop];
23
- if (prop.startsWith("on")) return `on${toCase(prop.substr(2))}`;
24
- if (preserveKeys.includes(prop)) return prop;
25
- return prop.toLowerCase();
26
- }
27
- const normalizeProps = createNormalizer((props) => {
28
- const normalized = {};
29
- for (const key in props) {
30
- const value = props[key];
31
- if (key === "children") {
32
- if (typeof value === "string") normalized["innerHTML"] = value;
33
- else if (process.env.NODE_ENV !== "production" && value != null) console.warn("[Vue Normalize Prop] : avoid passing non-primitive value as `children`");
34
- } else normalized[toVueProp(key)] = props[key];
35
- }
36
- return normalized;
37
- });
38
-
39
- //#endregion
40
- //#region src/core/bindable.ts
41
- function bindable(props) {
42
- const initial = props().defaultValue ?? props().value;
43
- const eq = props().isEqual ?? Object.is;
44
- const v = shallowRef(initial);
45
- const controlled = computed(() => props().value !== void 0);
46
- return {
47
- initial,
48
- ref: shallowRef(controlled.value ? props().value : v.value),
49
- get() {
50
- return controlled.value ? props().value : v.value;
51
- },
52
- set(val) {
53
- const prev = controlled.value ? props().value : v.value;
54
- const next = isFunction(val) ? val(prev) : val;
55
- if (props().debug) console.log(`[bindable > ${props().debug}] setValue`, {
56
- next,
57
- prev
58
- });
59
- if (!controlled.value) v.value = next;
60
- if (!eq(next, prev)) props().onChange?.(next, prev);
61
- },
62
- invoke(nextValue, prevValue) {
63
- props().onChange?.(nextValue, prevValue);
64
- },
65
- hash(value) {
66
- return props().hash?.(value) ?? String(value);
67
- }
68
- };
69
- }
70
- bindable.cleanup = (fn) => {
71
- onUnmounted(() => fn());
72
- };
73
- bindable.ref = (defaultValue) => {
74
- let value = defaultValue;
75
- return {
76
- get: () => value,
77
- set: (next) => {
78
- value = next;
79
- }
80
- };
81
- };
82
-
83
- //#endregion
84
- //#region src/core/refs.ts
85
- function useRefs(refs) {
86
- const ref = { current: refs };
87
- return {
88
- get(key) {
89
- return ref.current[key];
90
- },
91
- set(key, value) {
92
- ref.current[key] = value;
93
- }
94
- };
4
+ //#region src/utils/use-emits-as-props.ts
5
+ function useEmitAsProps(emit) {
6
+ const vm = getCurrentInstance();
7
+ const events = vm?.type.emits;
8
+ const result = {};
9
+ if (!events?.length) console.warn(`No emitted event found. Please check component: ${vm?.type.__name}`);
10
+ for (const event of events) result[toHandlerKey(camelize(event))] = (...arg) => emit(event, ...arg);
11
+ return result;
95
12
  }
96
13
 
97
14
  //#endregion
98
- //#region src/core/track.ts
99
- const useTrack = (deps, effect) => {
100
- watch(() => [...deps.map((d) => d())], (current, previous) => {
101
- let changed = false;
102
- for (let i = 0; i < current.length; i++) if (!isEqual(previous[i], toValue(current[i]))) {
103
- changed = true;
104
- break;
105
- }
106
- if (changed) effect();
15
+ //#region src/utils/use-forward-props.ts
16
+ function useForwardProps(props) {
17
+ const vm = getCurrentInstance();
18
+ const defaultProps = Object.keys(vm?.type.props ?? {}).reduce((prev, curr) => {
19
+ const defaultValue = (vm?.type.props[curr]).default;
20
+ if (defaultValue !== void 0) prev[curr] = defaultValue;
21
+ return prev;
22
+ }, {});
23
+ const refProps = toRef(props);
24
+ return computed(() => {
25
+ const preservedProps = {};
26
+ const assignedProps = vm?.vnode.props ?? {};
27
+ Object.keys(assignedProps).forEach((key) => {
28
+ preservedProps[camelize(key)] = assignedProps[key];
29
+ });
30
+ return Object.keys({
31
+ ...defaultProps,
32
+ ...preservedProps
33
+ }).reduce((prev, curr) => {
34
+ if (refProps.value[curr] !== void 0) prev[curr] = refProps.value[curr];
35
+ return prev;
36
+ }, {});
107
37
  });
108
- };
38
+ }
109
39
 
110
40
  //#endregion
111
- //#region src/core/machine.ts
112
- function useMachine(machine, userProps = {}) {
113
- const scope = computed(() => {
114
- const { id, ids, getRootNode } = toValue(userProps);
115
- return createScope({
116
- id,
117
- ids,
118
- getRootNode
119
- });
120
- });
121
- const debug = (...args) => {
122
- if (machine.debug) console.log(...args);
123
- };
124
- const prop = useProp(computed(() => machine.props?.({
125
- props: compact(toValue(userProps)),
126
- get scope() {
127
- return scope.value;
128
- }
129
- }) ?? toValue(userProps)));
130
- const context = machine.context?.({
131
- prop,
132
- bindable,
133
- get scope() {
134
- return scope.value;
135
- },
136
- flush,
137
- getContext() {
138
- return ctx;
139
- },
140
- getComputed() {
141
- return computed$1;
142
- },
143
- getRefs() {
144
- return refs;
145
- },
146
- getEvent() {
147
- return getEvent();
148
- }
149
- });
150
- const ctx = {
151
- get(key) {
152
- return context[key]?.get();
153
- },
154
- set(key, value) {
155
- context[key]?.set(value);
156
- },
157
- initial(key) {
158
- return context[key]?.initial;
159
- },
160
- hash(key) {
161
- const current = context[key]?.get();
162
- return context[key]?.hash(current);
163
- }
164
- };
165
- let effects = /* @__PURE__ */ new Map();
166
- let transitionRef = null;
167
- const previousEventRef = { current: null };
168
- const eventRef = { current: { type: "" } };
169
- const getEvent = () => ({
170
- ...eventRef.current,
171
- current() {
172
- return eventRef.current;
173
- },
174
- previous() {
175
- return previousEventRef.current;
176
- }
177
- });
178
- const getState = () => ({
179
- ...state,
180
- matches(...values) {
181
- const currentState = state.get();
182
- return values.includes(currentState);
183
- },
184
- hasTag(tag) {
185
- const currentState = state.get();
186
- return !!machine.states[currentState]?.tags?.includes(tag);
187
- }
188
- });
189
- const refs = useRefs(machine.refs?.({
190
- prop,
191
- context: ctx
192
- }) ?? {});
193
- const getParams = () => ({
194
- state: getState(),
195
- context: ctx,
196
- event: getEvent(),
197
- prop,
198
- send,
199
- action,
200
- guard,
201
- track: useTrack,
202
- refs,
203
- computed: computed$1,
204
- flush,
205
- get scope() {
206
- return scope.value;
207
- },
208
- choose
209
- });
210
- const action = (keys) => {
211
- const strs = isFunction(keys) ? keys(getParams()) : keys;
212
- if (!strs) return;
213
- const fns = strs.map((s) => {
214
- const fn = machine.implementations?.actions?.[s];
215
- if (!fn) warn(`[sprawlify-js] No implementation found for action "${JSON.stringify(s)}"`);
216
- return fn;
217
- });
218
- for (const fn of fns) fn?.(getParams());
219
- };
220
- const guard = (str) => {
221
- if (isFunction(str)) return str(getParams());
222
- return machine.implementations?.guards?.[str](getParams());
223
- };
224
- const effect = (keys) => {
225
- const strs = isFunction(keys) ? keys(getParams()) : keys;
226
- if (!strs) return;
227
- const fns = strs.map((s) => {
228
- const fn = machine.implementations?.effects?.[s];
229
- if (!fn) warn(`[sprawlify-js] No implementation found for effect "${JSON.stringify(s)}"`);
230
- return fn;
231
- });
232
- const cleanups = [];
233
- for (const fn of fns) {
234
- const cleanup = fn?.(getParams());
235
- if (cleanup) cleanups.push(cleanup);
236
- }
237
- return () => cleanups.forEach((fn) => fn?.());
238
- };
239
- const choose = (transitions) => {
240
- return toArray(transitions).find((t) => {
241
- let result = !t.guard;
242
- if (isString(t.guard)) result = !!guard(t.guard);
243
- else if (isFunction(t.guard)) result = t.guard(getParams());
244
- return result;
245
- });
246
- };
247
- const computed$1 = (key) => {
248
- ensure(machine.computed, () => `[sprawlify-js] No computed object found on machine`);
249
- const fn = machine.computed[key];
250
- return fn({
251
- context: ctx,
252
- event: getEvent(),
253
- prop,
254
- refs,
255
- get scope() {
256
- return scope.value;
257
- },
258
- computed: computed$1
259
- });
260
- };
261
- const state = bindable(() => ({
262
- defaultValue: machine.initialState({ prop }),
263
- onChange(nextState, prevState) {
264
- if (prevState) {
265
- effects.get(prevState)?.();
266
- effects.delete(prevState);
267
- }
268
- if (prevState) action(machine.states[prevState]?.exit);
269
- action(transitionRef?.actions);
270
- const cleanup = effect(machine.states[nextState]?.effects);
271
- if (cleanup) effects.set(nextState, cleanup);
272
- if (prevState === INIT_STATE) {
273
- action(machine.entry);
274
- const cleanup = effect(machine.effects);
275
- if (cleanup) effects.set(INIT_STATE, cleanup);
276
- }
277
- action(machine.states[nextState]?.entry);
278
- }
41
+ //#region src/utils/use-forward-props-emits.ts
42
+ function useForwardPropsEmits(props, emit) {
43
+ const parsedProps = useForwardProps(props);
44
+ const emitsAsProps = emit ? useEmitAsProps(emit) : {};
45
+ return computed(() => ({
46
+ ...parsedProps.value,
47
+ ...emitsAsProps
279
48
  }));
280
- let status = MachineStatus.NotStarted;
281
- onMounted(() => {
282
- const started = status === MachineStatus.Started;
283
- status = MachineStatus.Started;
284
- debug(started ? "rehydrating..." : "initializing...");
285
- state.invoke(state.initial, INIT_STATE);
286
- });
287
- onBeforeUnmount(() => {
288
- status = MachineStatus.Stopped;
289
- debug("unmounting...");
290
- const fns = effects.values();
291
- for (const fn of fns) fn?.();
292
- effects = /* @__PURE__ */ new Map();
293
- action(machine.exit);
294
- });
295
- const send = (event) => {
296
- if (status !== MachineStatus.Started) return;
297
- previousEventRef.current = eventRef.current;
298
- eventRef.current = event;
299
- const currentState = state.get();
300
- const transition = choose(machine.states[currentState].on?.[event.type] ?? machine.on?.[event.type]);
301
- if (!transition) return;
302
- transitionRef = transition;
303
- const target = transition.target ?? currentState;
304
- debug("transition", event.type, transition.target || currentState, `(${transition.actions})`);
305
- const changed = target !== currentState;
306
- if (changed) state.set(target);
307
- else if (transition.reenter && !changed) state.invoke(currentState, currentState);
308
- else action(transition.actions);
309
- };
310
- machine.watch?.(getParams());
311
- return {
312
- state: getState(),
313
- send,
314
- context: ctx,
315
- prop,
316
- get scope() {
317
- return scope.value;
318
- },
319
- refs,
320
- computed: computed$1,
321
- event: getEvent(),
322
- getStatus: () => status
323
- };
324
49
  }
325
- function useProp(valueRef) {
326
- return function get(key) {
327
- return valueRef.value[key];
328
- };
329
- }
330
- const flush = (fn) => {
331
- nextTick().then(() => {
332
- fn();
333
- });
334
- };
335
50
 
336
51
  //#endregion
337
- export { mergeProps, normalizeProps, useMachine };
52
+ export { DEFAULT_ENVIRONMENT, DEFAULT_LOCALE, environment_provider_default as EnvironmentProvider, locale_provider_default as LocaleProvider, createContext, mergeProps, normalizeProps, useCollator, useEmitAsProps, useEnvironmentContext, useFilter, useForwardExpose, useForwardProps, useForwardPropsEmits, useLocaleContext, useMachine };
@@ -0,0 +1,30 @@
1
+ import { Machine, MachineSchema, Service, mergeProps as mergeProps$1 } from "@sprawlify/primitives/core";
2
+ import * as _sprawlify_primitives_types0 from "@sprawlify/primitives/types";
3
+ import * as Vue from "vue";
4
+ import { ComputedRef, Ref } from "vue";
5
+
6
+ //#region src/core/normalize-props.d.ts
7
+ type ReservedProps = {
8
+ key?: string | number | symbol | undefined;
9
+ ref?: Vue.VNodeRef | undefined;
10
+ };
11
+ type Attrs<T> = T & ReservedProps;
12
+ type PropTypes = Vue.NativeElements & {
13
+ element: Attrs<Vue.HTMLAttributes>;
14
+ style: Vue.CSSProperties;
15
+ };
16
+ declare const normalizeProps$1: _sprawlify_primitives_types0.NormalizeProps<PropTypes>;
17
+ //#endregion
18
+ //#region src/core/machine.d.ts
19
+ type MaybeRef$1<T> = T | Ref<T> | ComputedRef<T>;
20
+ declare function useMachine<T extends MachineSchema>(machine: Machine<T>, userProps?: MaybeRef$1<Partial<T["props"]>>): Service<T>;
21
+ //#endregion
22
+ //#region src/types.d.ts
23
+ type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
24
+ type Assign<T, U> = Omit<T, keyof U> & U;
25
+ type EmitFn<T> = <K extends keyof T>(event: K, ...args: T[K] extends any[] ? T[K] : never) => void;
26
+ type BooleanKey<T> = { [K in keyof T]: boolean extends NonNullable<T[K]> ? K : never }[keyof T];
27
+ type BooleanDefaults<T> = { [K in BooleanKey<T>]: undefined };
28
+ type MaybePromise<T> = T | Promise<T>;
29
+ //#endregion
30
+ export { Optional as a, PropTypes as c, MaybePromise as i, normalizeProps$1 as l, BooleanDefaults as n, mergeProps$1 as o, EmitFn as r, useMachine as s, Assign as t };