@sprawlify/vue 0.0.64 → 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.
@@ -0,0 +1,505 @@
1
+ import { INIT_STATE, MachineStatus, createScope, mergeProps as mergeProps$1 } 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 { Fragment, computed, createCommentVNode, createElementBlock, defineComponent, getCurrentInstance, inject, nextTick, onBeforeUnmount, onMounted, onUnmounted, openBlock, provide, ref, renderSlot, shallowRef, toValue, watch } from "vue";
5
+ import { getDocument, getWindow } from "@sprawlify/primitives/dom-query";
6
+ import { createCollator, createFilter, isRTL } from "@sprawlify/primitives/i18n-utils";
7
+
8
+ //#region src/core/normalize-props.ts
9
+ function toCase(txt) {
10
+ return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
11
+ }
12
+ const propMap = {
13
+ htmlFor: "for",
14
+ className: "class",
15
+ onDoubleClick: "onDblclick",
16
+ onChange: "onInput",
17
+ onFocus: "onFocusin",
18
+ onBlur: "onFocusout",
19
+ defaultValue: "value",
20
+ defaultChecked: "checked"
21
+ };
22
+ const preserveKeys = "viewBox,className,preserveAspectRatio,fillRule,clipPath,clipRule,strokeWidth,strokeLinecap,strokeLinejoin,strokeDasharray,strokeDashoffset,strokeMiterlimit".split(",");
23
+ function toVueProp(prop) {
24
+ if (prop in propMap) return propMap[prop];
25
+ if (prop.startsWith("on")) return `on${toCase(prop.substr(2))}`;
26
+ if (preserveKeys.includes(prop)) return prop;
27
+ return prop.toLowerCase();
28
+ }
29
+ const normalizeProps$1 = createNormalizer((props) => {
30
+ const normalized = {};
31
+ for (const key in props) {
32
+ const value = props[key];
33
+ if (key === "children") {
34
+ if (typeof value === "string") normalized["innerHTML"] = value;
35
+ else if (process.env.NODE_ENV !== "production" && value != null) console.warn("[Vue Normalize Prop] : avoid passing non-primitive value as `children`");
36
+ } else normalized[toVueProp(key)] = props[key];
37
+ }
38
+ return normalized;
39
+ });
40
+
41
+ //#endregion
42
+ //#region src/core/bindable.ts
43
+ function bindable(props) {
44
+ const initial = props().defaultValue ?? props().value;
45
+ const eq = props().isEqual ?? Object.is;
46
+ const v = shallowRef(initial);
47
+ const controlled = computed(() => props().value !== void 0);
48
+ return {
49
+ initial,
50
+ ref: shallowRef(controlled.value ? props().value : v.value),
51
+ get() {
52
+ return controlled.value ? props().value : v.value;
53
+ },
54
+ set(val) {
55
+ const prev = controlled.value ? props().value : v.value;
56
+ const next = isFunction(val) ? val(prev) : val;
57
+ if (props().debug) console.log(`[bindable > ${props().debug}] setValue`, {
58
+ next,
59
+ prev
60
+ });
61
+ if (!controlled.value) v.value = next;
62
+ if (!eq(next, prev)) props().onChange?.(next, prev);
63
+ },
64
+ invoke(nextValue, prevValue) {
65
+ props().onChange?.(nextValue, prevValue);
66
+ },
67
+ hash(value) {
68
+ return props().hash?.(value) ?? String(value);
69
+ }
70
+ };
71
+ }
72
+ bindable.cleanup = (fn) => {
73
+ onUnmounted(() => fn());
74
+ };
75
+ bindable.ref = (defaultValue) => {
76
+ let value = defaultValue;
77
+ return {
78
+ get: () => value,
79
+ set: (next) => {
80
+ value = next;
81
+ }
82
+ };
83
+ };
84
+
85
+ //#endregion
86
+ //#region src/core/refs.ts
87
+ function useRefs(refs) {
88
+ const ref = { current: refs };
89
+ return {
90
+ get(key) {
91
+ return ref.current[key];
92
+ },
93
+ set(key, value) {
94
+ ref.current[key] = value;
95
+ }
96
+ };
97
+ }
98
+
99
+ //#endregion
100
+ //#region src/core/track.ts
101
+ const useTrack = (deps, effect) => {
102
+ watch(() => [...deps.map((d) => d())], (current, previous) => {
103
+ let changed = false;
104
+ for (let i = 0; i < current.length; i++) if (!isEqual(previous[i], toValue(current[i]))) {
105
+ changed = true;
106
+ break;
107
+ }
108
+ if (changed) effect();
109
+ });
110
+ };
111
+
112
+ //#endregion
113
+ //#region src/core/machine.ts
114
+ function useMachine(machine, userProps = {}) {
115
+ const scope = computed(() => {
116
+ const { id, ids, getRootNode } = toValue(userProps);
117
+ return createScope({
118
+ id,
119
+ ids,
120
+ getRootNode
121
+ });
122
+ });
123
+ const debug = (...args) => {
124
+ if (machine.debug) console.log(...args);
125
+ };
126
+ const prop = useProp(computed(() => machine.props?.({
127
+ props: compact(toValue(userProps)),
128
+ get scope() {
129
+ return scope.value;
130
+ }
131
+ }) ?? toValue(userProps)));
132
+ const context = machine.context?.({
133
+ prop,
134
+ bindable,
135
+ get scope() {
136
+ return scope.value;
137
+ },
138
+ flush,
139
+ getContext() {
140
+ return ctx;
141
+ },
142
+ getComputed() {
143
+ return computed$1;
144
+ },
145
+ getRefs() {
146
+ return refs;
147
+ },
148
+ getEvent() {
149
+ return getEvent();
150
+ }
151
+ });
152
+ const ctx = {
153
+ get(key) {
154
+ return context[key]?.get();
155
+ },
156
+ set(key, value) {
157
+ context[key]?.set(value);
158
+ },
159
+ initial(key) {
160
+ return context[key]?.initial;
161
+ },
162
+ hash(key) {
163
+ const current = context[key]?.get();
164
+ return context[key]?.hash(current);
165
+ }
166
+ };
167
+ let effects = /* @__PURE__ */ new Map();
168
+ let transitionRef = null;
169
+ const previousEventRef = { current: null };
170
+ const eventRef = { current: { type: "" } };
171
+ const getEvent = () => ({
172
+ ...eventRef.current,
173
+ current() {
174
+ return eventRef.current;
175
+ },
176
+ previous() {
177
+ return previousEventRef.current;
178
+ }
179
+ });
180
+ const getState = () => ({
181
+ ...state,
182
+ matches(...values) {
183
+ const currentState = state.get();
184
+ return values.includes(currentState);
185
+ },
186
+ hasTag(tag) {
187
+ const currentState = state.get();
188
+ return !!machine.states[currentState]?.tags?.includes(tag);
189
+ }
190
+ });
191
+ const refs = useRefs(machine.refs?.({
192
+ prop,
193
+ context: ctx
194
+ }) ?? {});
195
+ const getParams = () => ({
196
+ state: getState(),
197
+ context: ctx,
198
+ event: getEvent(),
199
+ prop,
200
+ send,
201
+ action,
202
+ guard,
203
+ track: useTrack,
204
+ refs,
205
+ computed: computed$1,
206
+ flush,
207
+ get scope() {
208
+ return scope.value;
209
+ },
210
+ choose
211
+ });
212
+ const action = (keys) => {
213
+ const strs = isFunction(keys) ? keys(getParams()) : keys;
214
+ if (!strs) return;
215
+ const fns = strs.map((s) => {
216
+ const fn = machine.implementations?.actions?.[s];
217
+ if (!fn) warn(`[sprawlify-js] No implementation found for action "${JSON.stringify(s)}"`);
218
+ return fn;
219
+ });
220
+ for (const fn of fns) fn?.(getParams());
221
+ };
222
+ const guard = (str) => {
223
+ if (isFunction(str)) return str(getParams());
224
+ return machine.implementations?.guards?.[str](getParams());
225
+ };
226
+ const effect = (keys) => {
227
+ const strs = isFunction(keys) ? keys(getParams()) : keys;
228
+ if (!strs) return;
229
+ const fns = strs.map((s) => {
230
+ const fn = machine.implementations?.effects?.[s];
231
+ if (!fn) warn(`[sprawlify-js] No implementation found for effect "${JSON.stringify(s)}"`);
232
+ return fn;
233
+ });
234
+ const cleanups = [];
235
+ for (const fn of fns) {
236
+ const cleanup = fn?.(getParams());
237
+ if (cleanup) cleanups.push(cleanup);
238
+ }
239
+ return () => cleanups.forEach((fn) => fn?.());
240
+ };
241
+ const choose = (transitions) => {
242
+ return toArray(transitions).find((t) => {
243
+ let result = !t.guard;
244
+ if (isString(t.guard)) result = !!guard(t.guard);
245
+ else if (isFunction(t.guard)) result = t.guard(getParams());
246
+ return result;
247
+ });
248
+ };
249
+ const computed$1 = (key) => {
250
+ ensure(machine.computed, () => `[sprawlify-js] No computed object found on machine`);
251
+ const fn = machine.computed[key];
252
+ return fn({
253
+ context: ctx,
254
+ event: getEvent(),
255
+ prop,
256
+ refs,
257
+ get scope() {
258
+ return scope.value;
259
+ },
260
+ computed: computed$1
261
+ });
262
+ };
263
+ const state = bindable(() => ({
264
+ defaultValue: machine.initialState({ prop }),
265
+ onChange(nextState, prevState) {
266
+ if (prevState) {
267
+ effects.get(prevState)?.();
268
+ effects.delete(prevState);
269
+ }
270
+ if (prevState) action(machine.states[prevState]?.exit);
271
+ action(transitionRef?.actions);
272
+ const cleanup = effect(machine.states[nextState]?.effects);
273
+ if (cleanup) effects.set(nextState, cleanup);
274
+ if (prevState === INIT_STATE) {
275
+ action(machine.entry);
276
+ const cleanup = effect(machine.effects);
277
+ if (cleanup) effects.set(INIT_STATE, cleanup);
278
+ }
279
+ action(machine.states[nextState]?.entry);
280
+ }
281
+ }));
282
+ let status = MachineStatus.NotStarted;
283
+ onMounted(() => {
284
+ const started = status === MachineStatus.Started;
285
+ status = MachineStatus.Started;
286
+ debug(started ? "rehydrating..." : "initializing...");
287
+ state.invoke(state.initial, INIT_STATE);
288
+ });
289
+ onBeforeUnmount(() => {
290
+ status = MachineStatus.Stopped;
291
+ debug("unmounting...");
292
+ const fns = effects.values();
293
+ for (const fn of fns) fn?.();
294
+ effects = /* @__PURE__ */ new Map();
295
+ action(machine.exit);
296
+ });
297
+ const send = (event) => {
298
+ if (status !== MachineStatus.Started) return;
299
+ previousEventRef.current = eventRef.current;
300
+ eventRef.current = event;
301
+ const currentState = state.get();
302
+ const transition = choose(machine.states[currentState].on?.[event.type] ?? machine.on?.[event.type]);
303
+ if (!transition) return;
304
+ transitionRef = transition;
305
+ const target = transition.target ?? currentState;
306
+ debug("transition", event.type, transition.target || currentState, `(${transition.actions})`);
307
+ const changed = target !== currentState;
308
+ if (changed) state.set(target);
309
+ else if (transition.reenter && !changed) state.invoke(currentState, currentState);
310
+ else action(transition.actions);
311
+ };
312
+ machine.watch?.(getParams());
313
+ return {
314
+ state: getState(),
315
+ send,
316
+ context: ctx,
317
+ prop,
318
+ get scope() {
319
+ return scope.value;
320
+ },
321
+ refs,
322
+ computed: computed$1,
323
+ event: getEvent(),
324
+ getStatus: () => status
325
+ };
326
+ }
327
+ function useProp(valueRef) {
328
+ return function get(key) {
329
+ return valueRef.value[key];
330
+ };
331
+ }
332
+ const flush = (fn) => {
333
+ nextTick().then(() => {
334
+ fn();
335
+ });
336
+ };
337
+
338
+ //#endregion
339
+ //#region src/utils/run-if-fn.ts
340
+ const isFunction$1 = (value) => typeof value === "function";
341
+ const runIfFn = (valueOrFn, ...args) => isFunction$1(valueOrFn) ? valueOrFn(...args) : valueOrFn;
342
+
343
+ //#endregion
344
+ //#region src/utils/create-context.ts
345
+ const createContext = (id) => {
346
+ const contextId = Symbol(id);
347
+ const provider = (value) => provide(contextId, value);
348
+ const consumer = (fallback) => inject(contextId, fallback);
349
+ return [
350
+ provider,
351
+ consumer,
352
+ contextId
353
+ ];
354
+ };
355
+
356
+ //#endregion
357
+ //#region src/providers/environment/use-environment-context.ts
358
+ const [EnvironmentContextProvider, useEnvironmentContext] = createContext("EnvironmentContext");
359
+ const DEFAULT_ENVIRONMENT = computed(() => ({
360
+ getRootNode: () => document,
361
+ getDocument: () => document,
362
+ getWindow: () => window
363
+ }));
364
+
365
+ //#endregion
366
+ //#region src/providers/environment/environment-provider.vue?vue&type=script&setup=true&lang.ts
367
+ var environment_provider_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
368
+ __name: "environment-provider",
369
+ props: { value: {
370
+ type: Function,
371
+ required: false,
372
+ skipCheck: true
373
+ } },
374
+ setup(__props) {
375
+ const props = __props;
376
+ const spanRef = ref(null);
377
+ const getRootNode = () => runIfFn(props.value) ?? spanRef.value?.getRootNode() ?? document;
378
+ EnvironmentContextProvider(computed(() => ({
379
+ getRootNode,
380
+ getDocument: () => getDocument(getRootNode()),
381
+ getWindow: () => getWindow(getRootNode())
382
+ })));
383
+ return (_ctx, _cache) => {
384
+ return openBlock(), createElementBlock(Fragment, null, [renderSlot(_ctx.$slots, "default"), !props.value ? (openBlock(), createElementBlock("span", {
385
+ key: 0,
386
+ hidden: "",
387
+ ref_key: "spanRef",
388
+ ref: spanRef
389
+ }, null, 512)) : createCommentVNode("v-if", true)], 64);
390
+ };
391
+ }
392
+ });
393
+
394
+ //#endregion
395
+ //#region src/providers/environment/environment-provider.vue
396
+ var environment_provider_default = environment_provider_vue_vue_type_script_setup_true_lang_default;
397
+
398
+ //#endregion
399
+ //#region src/providers/locale/use-locale-context.ts
400
+ const DEFAULT_LOCALE = computed(() => ({
401
+ dir: "ltr",
402
+ locale: "en-US"
403
+ }));
404
+ const [LocaleContextProvider, useLocaleContext] = createContext("LocaleContext");
405
+
406
+ //#endregion
407
+ //#region src/providers/locale/locale-provider.vue?vue&type=script&setup=true&lang.ts
408
+ var locale_provider_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
409
+ __name: "locale-provider",
410
+ props: { locale: {
411
+ type: String,
412
+ required: true
413
+ } },
414
+ setup(__props) {
415
+ const props = __props;
416
+ LocaleContextProvider(computed(() => ({
417
+ locale: props.locale,
418
+ dir: isRTL(props.locale) ? "rtl" : "ltr"
419
+ })));
420
+ return (_ctx, _cache) => {
421
+ return renderSlot(_ctx.$slots, "default");
422
+ };
423
+ }
424
+ });
425
+
426
+ //#endregion
427
+ //#region src/providers/locale/locale-provider.vue
428
+ var locale_provider_default = locale_provider_vue_vue_type_script_setup_true_lang_default;
429
+
430
+ //#endregion
431
+ //#region src/providers/locale/use-collator.ts
432
+ function useCollator(propsOrFn = {}) {
433
+ const env = useLocaleContext();
434
+ return computed(() => {
435
+ const props = toValue(propsOrFn);
436
+ const locale = props.locale ?? env.value.locale;
437
+ const { locale: _, ...options } = props;
438
+ return createCollator(locale, options);
439
+ });
440
+ }
441
+
442
+ //#endregion
443
+ //#region src/providers/locale/use-filter.ts
444
+ function useFilter(props) {
445
+ const env = useLocaleContext(DEFAULT_LOCALE);
446
+ const locale = computed(() => props.locale ?? env.value.locale);
447
+ return computed(() => createFilter({
448
+ ...props,
449
+ locale: locale.value
450
+ }));
451
+ }
452
+
453
+ //#endregion
454
+ //#region src/utils/unref-element.ts
455
+ function unrefElement(elRef) {
456
+ const plain = toValue(elRef);
457
+ return plain?.$el ?? plain;
458
+ }
459
+
460
+ //#endregion
461
+ //#region src/utils/use-forward-expose.ts
462
+ const isElement = (el) => Object.prototype.hasOwnProperty.call(el, "nodeName") && typeof el.nodeName === "string";
463
+ function useForwardExpose() {
464
+ const instance = getCurrentInstance();
465
+ const currentRef = ref();
466
+ const currentElement = computed(() => {
467
+ return ["#text", "#comment"].includes(currentRef.value?.$el.nodeName) ? currentRef.value?.$el.nextElementSibling : unrefElement(currentRef);
468
+ });
469
+ const localExpose = Object.assign({}, instance.exposed);
470
+ const ret = {};
471
+ for (const key in instance.props) Object.defineProperty(ret, key, {
472
+ enumerable: true,
473
+ configurable: true,
474
+ get: () => instance.props[key]
475
+ });
476
+ if (Object.keys(localExpose).length > 0) for (const key in localExpose) Object.defineProperty(ret, key, {
477
+ enumerable: true,
478
+ configurable: true,
479
+ get: () => localExpose[key]
480
+ });
481
+ Object.defineProperty(ret, "$el", {
482
+ enumerable: true,
483
+ configurable: true,
484
+ get: () => instance.vnode.el
485
+ });
486
+ instance.exposed = ret;
487
+ function forwardRef(ref) {
488
+ currentRef.value = ref;
489
+ if (isElement(ref) || !ref) return;
490
+ Object.defineProperty(ret, "$el", {
491
+ enumerable: true,
492
+ configurable: true,
493
+ get: () => ref.$el
494
+ });
495
+ instance.exposed = ret;
496
+ }
497
+ return {
498
+ forwardRef,
499
+ currentRef,
500
+ currentElement
501
+ };
502
+ }
503
+
504
+ //#endregion
505
+ export { DEFAULT_LOCALE as a, DEFAULT_ENVIRONMENT as c, mergeProps$1 as d, useMachine as f, locale_provider_default as i, useEnvironmentContext as l, useFilter as n, useLocaleContext as o, normalizeProps$1 as p, useCollator as r, environment_provider_default as s, useForwardExpose as t, createContext as u };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sprawlify/vue",
3
- "version": "0.0.64",
3
+ "version": "0.0.65",
4
4
  "type": "module",
5
5
  "description": "Vue wrapper for primitives.",
6
6
  "author": "sprawlify <npm@sprawlify.com>",
@@ -11,6 +11,10 @@
11
11
  ".": {
12
12
  "types": "./dist/index.d.ts",
13
13
  "default": "./dist/index.js"
14
+ },
15
+ "./collapsible": {
16
+ "types": "./dist/components/collapsible/index.d.ts",
17
+ "default": "./dist/components/collapsible/index.js"
14
18
  }
15
19
  },
16
20
  "files": [
@@ -20,7 +24,7 @@
20
24
  "access": "public"
21
25
  },
22
26
  "dependencies": {
23
- "@sprawlify/primitives": "0.0.64"
27
+ "@sprawlify/primitives": "0.0.65"
24
28
  },
25
29
  "peerDependencies": {
26
30
  "vue": ">=3.0.0"