@sprawlify/react 0.0.2 → 0.0.3

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,499 @@
1
+ import { t as createContext$1 } from "./create-context-fSIoyq0R.mjs";
2
+ import { INIT_STATE, MachineStatus, createScope, mergeProps, mergeProps as mergeProps$1 } from "@sprawlify/primitives/core";
3
+ import { compact, ensure, identity, isFunction, isString, toArray, warn } from "@sprawlify/primitives/utils";
4
+ import * as React$1 from "react";
5
+ import { Children, cloneElement, createElement, forwardRef, isValidElement, memo, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
6
+ import { createPortal, flushSync } from "react-dom";
7
+ import { createNormalizer } from "@sprawlify/primitives/types";
8
+ import { jsx, jsxs } from "react/jsx-runtime";
9
+ import { getDocument, getWindow } from "@sprawlify/primitives/dom-query";
10
+ import { createCollator, createFilter, isRTL } from "@sprawlify/primitives/i18n-utils";
11
+
12
+ //#region src/core/use-layout-effect.ts
13
+ const useSafeLayoutEffect = typeof globalThis.document !== "undefined" ? useLayoutEffect : useEffect;
14
+
15
+ //#endregion
16
+ //#region src/core/bindable.ts
17
+ function useBindable(props) {
18
+ const initial = props().value ?? props().defaultValue;
19
+ const eq = props().isEqual ?? Object.is;
20
+ const [initialValue] = useState(initial);
21
+ const [value, setValue] = useState(initialValue);
22
+ const controlled = props().value !== void 0;
23
+ const valueRef = useRef(value);
24
+ valueRef.current = controlled ? props().value : value;
25
+ const prevValue = useRef(valueRef.current);
26
+ useSafeLayoutEffect(() => {
27
+ prevValue.current = valueRef.current;
28
+ }, [value, props().value]);
29
+ const setFn = (value$1) => {
30
+ const prev = prevValue.current;
31
+ const next = isFunction(value$1) ? value$1(prev) : value$1;
32
+ if (props().debug) console.log(`[bindable > ${props().debug}] setValue`, {
33
+ next,
34
+ prev
35
+ });
36
+ if (!controlled) setValue(next);
37
+ if (!eq(next, prev)) props().onChange?.(next, prev);
38
+ };
39
+ function get() {
40
+ return controlled ? props().value : value;
41
+ }
42
+ return {
43
+ initial: initialValue,
44
+ ref: valueRef,
45
+ get,
46
+ set(value$1) {
47
+ (props().sync ? flushSync : identity)(() => setFn(value$1));
48
+ },
49
+ invoke(nextValue, prevValue$1) {
50
+ props().onChange?.(nextValue, prevValue$1);
51
+ },
52
+ hash(value$1) {
53
+ return props().hash?.(value$1) ?? String(value$1);
54
+ }
55
+ };
56
+ }
57
+ useBindable.cleanup = (fn) => {
58
+ useEffect(() => fn, []);
59
+ };
60
+ useBindable.ref = (defaultValue) => {
61
+ const value = useRef(defaultValue);
62
+ return {
63
+ get: () => value.current,
64
+ set: (next) => {
65
+ value.current = next;
66
+ }
67
+ };
68
+ };
69
+
70
+ //#endregion
71
+ //#region src/core/refs.ts
72
+ function useRefs(refs) {
73
+ const ref = useRef(refs);
74
+ return {
75
+ get(key) {
76
+ return ref.current[key];
77
+ },
78
+ set(key, value) {
79
+ ref.current[key] = value;
80
+ }
81
+ };
82
+ }
83
+
84
+ //#endregion
85
+ //#region src/core/track.ts
86
+ const useTrack = (deps, effect) => {
87
+ const render = useRef(false);
88
+ const called = useRef(false);
89
+ useEffect(() => {
90
+ if (render.current && called.current) return effect();
91
+ called.current = true;
92
+ }, [...(deps ?? []).map((d) => typeof d === "function" ? d() : d)]);
93
+ useEffect(() => {
94
+ render.current = true;
95
+ return () => {
96
+ render.current = false;
97
+ };
98
+ }, []);
99
+ };
100
+
101
+ //#endregion
102
+ //#region src/core/machine.ts
103
+ function useMachine(machine, userProps = {}) {
104
+ const scope = useMemo(() => {
105
+ const { id, ids, getRootNode } = userProps;
106
+ return createScope({
107
+ id,
108
+ ids,
109
+ getRootNode
110
+ });
111
+ }, [userProps]);
112
+ const debug = (...args) => {
113
+ if (machine.debug) console.log(...args);
114
+ };
115
+ const prop = useProp(machine.props?.({
116
+ props: compact(userProps),
117
+ scope
118
+ }) ?? userProps);
119
+ const context = machine.context?.({
120
+ prop,
121
+ bindable: useBindable,
122
+ scope,
123
+ flush,
124
+ getContext() {
125
+ return ctx;
126
+ },
127
+ getComputed() {
128
+ return computed;
129
+ },
130
+ getRefs() {
131
+ return refs;
132
+ },
133
+ getEvent() {
134
+ return getEvent();
135
+ }
136
+ });
137
+ const contextRef = useLiveRef(context);
138
+ const ctx = {
139
+ get(key) {
140
+ return contextRef.current?.[key].ref.current;
141
+ },
142
+ set(key, value) {
143
+ contextRef.current?.[key].set(value);
144
+ },
145
+ initial(key) {
146
+ return contextRef.current?.[key].initial;
147
+ },
148
+ hash(key) {
149
+ const current = contextRef.current?.[key].get();
150
+ return contextRef.current?.[key].hash(current);
151
+ }
152
+ };
153
+ const effects = useRef(/* @__PURE__ */ new Map());
154
+ const transitionRef = useRef(null);
155
+ const previousEventRef = useRef(null);
156
+ const eventRef = useRef({ type: "" });
157
+ const getEvent = () => ({
158
+ ...eventRef.current,
159
+ current() {
160
+ return eventRef.current;
161
+ },
162
+ previous() {
163
+ return previousEventRef.current;
164
+ }
165
+ });
166
+ const getState = () => ({
167
+ ...state,
168
+ matches(...values) {
169
+ return values.includes(state.ref.current);
170
+ },
171
+ hasTag(tag) {
172
+ return !!machine.states[state.ref.current]?.tags?.includes(tag);
173
+ }
174
+ });
175
+ const refs = useRefs(machine.refs?.({
176
+ prop,
177
+ context: ctx
178
+ }) ?? {});
179
+ const getParams = () => ({
180
+ state: getState(),
181
+ context: ctx,
182
+ event: getEvent(),
183
+ prop,
184
+ send,
185
+ action,
186
+ guard,
187
+ track: useTrack,
188
+ refs,
189
+ computed,
190
+ flush,
191
+ scope,
192
+ choose
193
+ });
194
+ const action = (keys) => {
195
+ const strs = isFunction(keys) ? keys(getParams()) : keys;
196
+ if (!strs) return;
197
+ const fns = strs.map((s) => {
198
+ const fn = machine.implementations?.actions?.[s];
199
+ if (!fn) warn(`[sprawlify-js] No implementation found for action "${JSON.stringify(s)}"`);
200
+ return fn;
201
+ });
202
+ for (const fn of fns) fn?.(getParams());
203
+ };
204
+ const guard = (str) => {
205
+ if (isFunction(str)) return str(getParams());
206
+ return machine.implementations?.guards?.[str](getParams());
207
+ };
208
+ const effect = (keys) => {
209
+ const strs = isFunction(keys) ? keys(getParams()) : keys;
210
+ if (!strs) return;
211
+ const fns = strs.map((s) => {
212
+ const fn = machine.implementations?.effects?.[s];
213
+ if (!fn) warn(`[sprawlify-js] No implementation found for effect "${JSON.stringify(s)}"`);
214
+ return fn;
215
+ });
216
+ const cleanups = [];
217
+ for (const fn of fns) {
218
+ const cleanup = fn?.(getParams());
219
+ if (cleanup) cleanups.push(cleanup);
220
+ }
221
+ return () => cleanups.forEach((fn) => fn?.());
222
+ };
223
+ const choose = (transitions) => {
224
+ return toArray(transitions).find((t) => {
225
+ let result = !t.guard;
226
+ if (isString(t.guard)) result = !!guard(t.guard);
227
+ else if (isFunction(t.guard)) result = t.guard(getParams());
228
+ return result;
229
+ });
230
+ };
231
+ const computed = (key) => {
232
+ ensure(machine.computed, () => `[sprawlify-js] No computed object found on machine`);
233
+ const fn = machine.computed[key];
234
+ return fn({
235
+ context: ctx,
236
+ event: getEvent(),
237
+ prop,
238
+ refs,
239
+ scope,
240
+ computed
241
+ });
242
+ };
243
+ const state = useBindable(() => ({
244
+ defaultValue: machine.initialState({ prop }),
245
+ onChange(nextState, prevState) {
246
+ if (prevState) {
247
+ effects.current.get(prevState)?.();
248
+ effects.current.delete(prevState);
249
+ }
250
+ if (prevState) action(machine.states[prevState]?.exit);
251
+ action(transitionRef.current?.actions);
252
+ const cleanup = effect(machine.states[nextState]?.effects);
253
+ if (cleanup) effects.current.set(nextState, cleanup);
254
+ if (prevState === INIT_STATE) {
255
+ action(machine.entry);
256
+ const cleanup$1 = effect(machine.effects);
257
+ if (cleanup$1) effects.current.set(INIT_STATE, cleanup$1);
258
+ }
259
+ action(machine.states[nextState]?.entry);
260
+ }
261
+ }));
262
+ const hydratedStateRef = useRef(void 0);
263
+ const statusRef = useRef(MachineStatus.NotStarted);
264
+ useSafeLayoutEffect(() => {
265
+ queueMicrotask(() => {
266
+ const started = statusRef.current === MachineStatus.Started;
267
+ statusRef.current = MachineStatus.Started;
268
+ debug(started ? "rehydrating..." : "initializing...");
269
+ const initialState = hydratedStateRef.current ?? state.initial;
270
+ state.invoke(initialState, started ? state.get() : INIT_STATE);
271
+ });
272
+ const fns = effects.current;
273
+ const currentState = state.ref.current;
274
+ return () => {
275
+ debug("unmounting...");
276
+ hydratedStateRef.current = currentState;
277
+ statusRef.current = MachineStatus.Stopped;
278
+ fns.forEach((fn) => fn?.());
279
+ effects.current = /* @__PURE__ */ new Map();
280
+ transitionRef.current = null;
281
+ queueMicrotask(() => {
282
+ action(machine.exit);
283
+ });
284
+ };
285
+ }, []);
286
+ const getCurrentState = () => {
287
+ if ("ref" in state) return state.ref.current;
288
+ return state.get();
289
+ };
290
+ const send = (event) => {
291
+ queueMicrotask(() => {
292
+ if (statusRef.current !== MachineStatus.Started) return;
293
+ previousEventRef.current = eventRef.current;
294
+ eventRef.current = event;
295
+ const currentState = getCurrentState();
296
+ const transition = choose(machine.states[currentState].on?.[event.type] ?? machine.on?.[event.type]);
297
+ if (!transition) return;
298
+ transitionRef.current = transition;
299
+ const target = transition.target ?? currentState;
300
+ debug("transition", event.type, transition.target || currentState, `(${transition.actions})`);
301
+ const changed = target !== currentState;
302
+ if (changed) flushSync(() => state.set(target));
303
+ else if (transition.reenter && !changed) state.invoke(currentState, currentState);
304
+ else action(transition.actions ?? []);
305
+ });
306
+ };
307
+ machine.watch?.(getParams());
308
+ return {
309
+ state: getState(),
310
+ send,
311
+ context: ctx,
312
+ prop,
313
+ scope,
314
+ refs,
315
+ computed,
316
+ event: getEvent(),
317
+ getStatus: () => statusRef.current
318
+ };
319
+ }
320
+ function useLiveRef(value) {
321
+ const ref = useRef(value);
322
+ ref.current = value;
323
+ return ref;
324
+ }
325
+ function useProp(value) {
326
+ const ref = useLiveRef(value);
327
+ return function get(key) {
328
+ return ref.current[key];
329
+ };
330
+ }
331
+ function flush(fn) {
332
+ queueMicrotask(() => {
333
+ flushSync(() => fn());
334
+ });
335
+ }
336
+
337
+ //#endregion
338
+ //#region src/core/normalize-props.ts
339
+ const normalizeProps = createNormalizer((v) => v);
340
+
341
+ //#endregion
342
+ //#region src/core/portal.tsx
343
+ const Portal = (props) => {
344
+ const { children, container, disabled, getRootNode } = props;
345
+ if (typeof window === "undefined" || disabled) return /* @__PURE__ */ jsx(React$1.Fragment, { children });
346
+ const doc = getRootNode?.().ownerDocument ?? document;
347
+ const mountNode = container?.current ?? doc.body;
348
+ return /* @__PURE__ */ jsx(React$1.Fragment, { children: React$1.Children.map(children, (child) => createPortal(child, mountNode)) });
349
+ };
350
+
351
+ //#endregion
352
+ //#region src/utils/run-if-fn.ts
353
+ const isFunction$1 = (value) => typeof value === "function";
354
+ const runIfFn = (valueOrFn, ...args) => isFunction$1(valueOrFn) ? valueOrFn(...args) : valueOrFn;
355
+
356
+ //#endregion
357
+ //#region src/providers/environment/use-environment-context.ts
358
+ const [EnvironmentContextProvider, useEnvironmentContext] = createContext$1({
359
+ name: "EnvironmentContext",
360
+ hookName: "useEnvironmentContext",
361
+ providerName: "<EnvironmentProvider />",
362
+ strict: false,
363
+ defaultValue: {
364
+ getRootNode: () => document,
365
+ getDocument: () => document,
366
+ getWindow: () => window
367
+ }
368
+ });
369
+
370
+ //#endregion
371
+ //#region src/providers/environment/environment-provider.tsx
372
+ const EnvironmentProvider = (props) => {
373
+ const { value, children } = props;
374
+ const [spanRef, setSpanRef] = useState();
375
+ const getRootNode = useMemo(() => {
376
+ return () => runIfFn(value) ?? spanRef?.getRootNode() ?? document;
377
+ }, [value, spanRef]);
378
+ return /* @__PURE__ */ jsxs(EnvironmentContextProvider, {
379
+ value: useMemo(() => ({
380
+ getRootNode,
381
+ getWindow: () => getWindow(getRootNode()),
382
+ getDocument: () => getDocument(getRootNode())
383
+ }), [getRootNode]),
384
+ children: [children, !value && /* @__PURE__ */ jsx("span", {
385
+ hidden: true,
386
+ ref: setSpanRef
387
+ })]
388
+ });
389
+ };
390
+
391
+ //#endregion
392
+ //#region src/providers/locale/use-locale-context.ts
393
+ const [LocaleContextProvider, useLocaleContext] = createContext$1({
394
+ name: "LocaleContext",
395
+ hookName: "useLocaleContext",
396
+ providerName: "<LocaleProvider />",
397
+ strict: false,
398
+ defaultValue: {
399
+ dir: "ltr",
400
+ locale: "en-US"
401
+ }
402
+ });
403
+
404
+ //#endregion
405
+ //#region src/providers/locale/locale-provider.tsx
406
+ const LocaleProvider = (props) => {
407
+ const { children, locale } = props;
408
+ return /* @__PURE__ */ jsx(LocaleContextProvider, {
409
+ value: {
410
+ locale,
411
+ dir: isRTL(locale) ? "rtl" : "ltr"
412
+ },
413
+ children
414
+ });
415
+ };
416
+
417
+ //#endregion
418
+ //#region src/providers/locale/use-collator.ts
419
+ function useCollator(props = {}) {
420
+ const env = useLocaleContext();
421
+ const locale = props.locale ?? env.locale;
422
+ return useMemo(() => {
423
+ const { locale: _, ...options } = props;
424
+ return createCollator(locale, options);
425
+ }, [locale, props]);
426
+ }
427
+
428
+ //#endregion
429
+ //#region src/providers/locale/use-filter.ts
430
+ function useFilter(props) {
431
+ const env = useLocaleContext();
432
+ const locale = props.locale ?? env.locale;
433
+ return useMemo(() => createFilter({
434
+ ...props,
435
+ locale
436
+ }), [locale, props]);
437
+ }
438
+
439
+ //#endregion
440
+ //#region src/utils/compose-refs.ts
441
+ function composeRefs(...refs) {
442
+ return (node) => {
443
+ const cleanUps = [];
444
+ for (const ref of refs) if (typeof ref === "function") {
445
+ const cb = ref(node);
446
+ if (typeof cb === "function") cleanUps.push(cb);
447
+ } else if (ref) ref.current = node;
448
+ if (cleanUps.length) return () => {
449
+ for (const cleanUp of cleanUps) cleanUp();
450
+ };
451
+ };
452
+ }
453
+
454
+ //#endregion
455
+ //#region src/components/factory.ts
456
+ function getRef(element) {
457
+ let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
458
+ let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
459
+ if (mayWarn) return element.ref;
460
+ getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
461
+ mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
462
+ if (mayWarn) return element.props.ref;
463
+ return element.props.ref || element.ref;
464
+ }
465
+ const withAsChild = (Component) => {
466
+ const Comp = memo(forwardRef((props, ref) => {
467
+ const { asChild, children, ...restProps } = props;
468
+ if (!asChild) return createElement(Component, {
469
+ ...restProps,
470
+ ref
471
+ }, children);
472
+ if (!isValidElement(children)) return null;
473
+ const onlyChild = Children.only(children);
474
+ const childRef = getRef(onlyChild);
475
+ return cloneElement(onlyChild, {
476
+ ...mergeProps(restProps, onlyChild.props),
477
+ ref: ref ? composeRefs(ref, childRef) : childRef
478
+ });
479
+ }));
480
+ Comp.displayName = typeof Component === "string" ? Component : Component.displayName || Component.name;
481
+ return Comp;
482
+ };
483
+ const jsxFactory = () => {
484
+ const cache = /* @__PURE__ */ new Map();
485
+ return new Proxy(withAsChild, {
486
+ apply(_target, _thisArg, argArray) {
487
+ return withAsChild(argArray[0]);
488
+ },
489
+ get(_, element) {
490
+ const asElement = element;
491
+ if (!cache.has(asElement)) cache.set(asElement, withAsChild(asElement));
492
+ return cache.get(asElement);
493
+ }
494
+ });
495
+ };
496
+ const sprawlify = jsxFactory();
497
+
498
+ //#endregion
499
+ export { LocaleProvider as a, useEnvironmentContext as c, normalizeProps as d, useMachine as f, useCollator as i, mergeProps$1 as l, sprawlify as n, useLocaleContext as o, useFilter as r, EnvironmentProvider as s, jsxFactory as t, Portal as u };