@sprawlify/react 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/dist/index.cjs ADDED
@@ -0,0 +1,384 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) {
13
+ __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ }
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+
27
+ //#endregion
28
+ let __sprawlify_primitives_core = require("@sprawlify/primitives/core");
29
+ let __sprawlify_primitives_utils = require("@sprawlify/primitives/utils");
30
+ let react = require("react");
31
+ react = __toESM(react);
32
+ let react_dom = require("react-dom");
33
+ let __sprawlify_primitives_types = require("@sprawlify/primitives/types");
34
+ let react_jsx_runtime = require("react/jsx-runtime");
35
+
36
+ //#region src/core/use-layout-effect.ts
37
+ const useSafeLayoutEffect = typeof globalThis.document !== "undefined" ? react.useLayoutEffect : react.useEffect;
38
+
39
+ //#endregion
40
+ //#region src/core/bindable.ts
41
+ function useBindable(props) {
42
+ const initial = props().value ?? props().defaultValue;
43
+ const eq = props().isEqual ?? Object.is;
44
+ const [initialValue] = (0, react.useState)(initial);
45
+ const [value, setValue] = (0, react.useState)(initialValue);
46
+ const controlled = props().value !== void 0;
47
+ const valueRef = (0, react.useRef)(value);
48
+ valueRef.current = controlled ? props().value : value;
49
+ const prevValue = (0, react.useRef)(valueRef.current);
50
+ useSafeLayoutEffect(() => {
51
+ prevValue.current = valueRef.current;
52
+ }, [value, props().value]);
53
+ const setFn = (value$1) => {
54
+ const prev = prevValue.current;
55
+ const next = (0, __sprawlify_primitives_utils.isFunction)(value$1) ? value$1(prev) : value$1;
56
+ if (props().debug) console.log(`[bindable > ${props().debug}] setValue`, {
57
+ next,
58
+ prev
59
+ });
60
+ if (!controlled) setValue(next);
61
+ if (!eq(next, prev)) props().onChange?.(next, prev);
62
+ };
63
+ function get() {
64
+ return controlled ? props().value : value;
65
+ }
66
+ return {
67
+ initial: initialValue,
68
+ ref: valueRef,
69
+ get,
70
+ set(value$1) {
71
+ (props().sync ? react_dom.flushSync : __sprawlify_primitives_utils.identity)(() => setFn(value$1));
72
+ },
73
+ invoke(nextValue, prevValue$1) {
74
+ props().onChange?.(nextValue, prevValue$1);
75
+ },
76
+ hash(value$1) {
77
+ return props().hash?.(value$1) ?? String(value$1);
78
+ }
79
+ };
80
+ }
81
+ useBindable.cleanup = (fn) => {
82
+ (0, react.useEffect)(() => fn, []);
83
+ };
84
+ useBindable.ref = (defaultValue) => {
85
+ const value = (0, react.useRef)(defaultValue);
86
+ return {
87
+ get: () => value.current,
88
+ set: (next) => {
89
+ value.current = next;
90
+ }
91
+ };
92
+ };
93
+
94
+ //#endregion
95
+ //#region src/core/refs.ts
96
+ function useRefs(refs) {
97
+ const ref = (0, react.useRef)(refs);
98
+ return {
99
+ get(key) {
100
+ return ref.current[key];
101
+ },
102
+ set(key, value) {
103
+ ref.current[key] = value;
104
+ }
105
+ };
106
+ }
107
+
108
+ //#endregion
109
+ //#region src/core/track.ts
110
+ const useTrack = (deps, effect) => {
111
+ const render = (0, react.useRef)(false);
112
+ const called = (0, react.useRef)(false);
113
+ (0, react.useEffect)(() => {
114
+ if (render.current && called.current) return effect();
115
+ called.current = true;
116
+ }, [...(deps ?? []).map((d) => typeof d === "function" ? d() : d)]);
117
+ (0, react.useEffect)(() => {
118
+ render.current = true;
119
+ return () => {
120
+ render.current = false;
121
+ };
122
+ }, []);
123
+ };
124
+
125
+ //#endregion
126
+ //#region src/core/machine.ts
127
+ function useMachine(machine, userProps = {}) {
128
+ const scope = (0, react.useMemo)(() => {
129
+ const { id, ids, getRootNode } = userProps;
130
+ return (0, __sprawlify_primitives_core.createScope)({
131
+ id,
132
+ ids,
133
+ getRootNode
134
+ });
135
+ }, [userProps]);
136
+ const debug = (...args) => {
137
+ if (machine.debug) console.log(...args);
138
+ };
139
+ const prop = useProp(machine.props?.({
140
+ props: (0, __sprawlify_primitives_utils.compact)(userProps),
141
+ scope
142
+ }) ?? userProps);
143
+ const context = machine.context?.({
144
+ prop,
145
+ bindable: useBindable,
146
+ scope,
147
+ flush,
148
+ getContext() {
149
+ return ctx;
150
+ },
151
+ getComputed() {
152
+ return computed;
153
+ },
154
+ getRefs() {
155
+ return refs;
156
+ },
157
+ getEvent() {
158
+ return getEvent();
159
+ }
160
+ });
161
+ const contextRef = useLiveRef(context);
162
+ const ctx = {
163
+ get(key) {
164
+ return contextRef.current?.[key].ref.current;
165
+ },
166
+ set(key, value) {
167
+ contextRef.current?.[key].set(value);
168
+ },
169
+ initial(key) {
170
+ return contextRef.current?.[key].initial;
171
+ },
172
+ hash(key) {
173
+ const current = contextRef.current?.[key].get();
174
+ return contextRef.current?.[key].hash(current);
175
+ }
176
+ };
177
+ const effects = (0, react.useRef)(/* @__PURE__ */ new Map());
178
+ const transitionRef = (0, react.useRef)(null);
179
+ const previousEventRef = (0, react.useRef)(null);
180
+ const eventRef = (0, react.useRef)({ type: "" });
181
+ const getEvent = () => ({
182
+ ...eventRef.current,
183
+ current() {
184
+ return eventRef.current;
185
+ },
186
+ previous() {
187
+ return previousEventRef.current;
188
+ }
189
+ });
190
+ const getState = () => ({
191
+ ...state,
192
+ matches(...values) {
193
+ return values.includes(state.ref.current);
194
+ },
195
+ hasTag(tag) {
196
+ return !!machine.states[state.ref.current]?.tags?.includes(tag);
197
+ }
198
+ });
199
+ const refs = useRefs(machine.refs?.({
200
+ prop,
201
+ context: ctx
202
+ }) ?? {});
203
+ const getParams = () => ({
204
+ state: getState(),
205
+ context: ctx,
206
+ event: getEvent(),
207
+ prop,
208
+ send,
209
+ action,
210
+ guard,
211
+ track: useTrack,
212
+ refs,
213
+ computed,
214
+ flush,
215
+ scope,
216
+ choose
217
+ });
218
+ const action = (keys) => {
219
+ const strs = (0, __sprawlify_primitives_utils.isFunction)(keys) ? keys(getParams()) : keys;
220
+ if (!strs) return;
221
+ const fns = strs.map((s) => {
222
+ const fn = machine.implementations?.actions?.[s];
223
+ if (!fn) (0, __sprawlify_primitives_utils.warn)(`[sprawlify-js] No implementation found for action "${JSON.stringify(s)}"`);
224
+ return fn;
225
+ });
226
+ for (const fn of fns) fn?.(getParams());
227
+ };
228
+ const guard = (str) => {
229
+ if ((0, __sprawlify_primitives_utils.isFunction)(str)) return str(getParams());
230
+ return machine.implementations?.guards?.[str](getParams());
231
+ };
232
+ const effect = (keys) => {
233
+ const strs = (0, __sprawlify_primitives_utils.isFunction)(keys) ? keys(getParams()) : keys;
234
+ if (!strs) return;
235
+ const fns = strs.map((s) => {
236
+ const fn = machine.implementations?.effects?.[s];
237
+ if (!fn) (0, __sprawlify_primitives_utils.warn)(`[sprawlify-js] No implementation found for effect "${JSON.stringify(s)}"`);
238
+ return fn;
239
+ });
240
+ const cleanups = [];
241
+ for (const fn of fns) {
242
+ const cleanup = fn?.(getParams());
243
+ if (cleanup) cleanups.push(cleanup);
244
+ }
245
+ return () => cleanups.forEach((fn) => fn?.());
246
+ };
247
+ const choose = (transitions) => {
248
+ return (0, __sprawlify_primitives_utils.toArray)(transitions).find((t) => {
249
+ let result = !t.guard;
250
+ if ((0, __sprawlify_primitives_utils.isString)(t.guard)) result = !!guard(t.guard);
251
+ else if ((0, __sprawlify_primitives_utils.isFunction)(t.guard)) result = t.guard(getParams());
252
+ return result;
253
+ });
254
+ };
255
+ const computed = (key) => {
256
+ (0, __sprawlify_primitives_utils.ensure)(machine.computed, () => `[sprawlify-js] No computed object found on machine`);
257
+ const fn = machine.computed[key];
258
+ return fn({
259
+ context: ctx,
260
+ event: getEvent(),
261
+ prop,
262
+ refs,
263
+ scope,
264
+ computed
265
+ });
266
+ };
267
+ const state = useBindable(() => ({
268
+ defaultValue: machine.initialState({ prop }),
269
+ onChange(nextState, prevState) {
270
+ if (prevState) {
271
+ effects.current.get(prevState)?.();
272
+ effects.current.delete(prevState);
273
+ }
274
+ if (prevState) action(machine.states[prevState]?.exit);
275
+ action(transitionRef.current?.actions);
276
+ const cleanup = effect(machine.states[nextState]?.effects);
277
+ if (cleanup) effects.current.set(nextState, cleanup);
278
+ if (prevState === __sprawlify_primitives_core.INIT_STATE) {
279
+ action(machine.entry);
280
+ const cleanup$1 = effect(machine.effects);
281
+ if (cleanup$1) effects.current.set(__sprawlify_primitives_core.INIT_STATE, cleanup$1);
282
+ }
283
+ action(machine.states[nextState]?.entry);
284
+ }
285
+ }));
286
+ const hydratedStateRef = (0, react.useRef)(void 0);
287
+ const statusRef = (0, react.useRef)(__sprawlify_primitives_core.MachineStatus.NotStarted);
288
+ useSafeLayoutEffect(() => {
289
+ queueMicrotask(() => {
290
+ const started = statusRef.current === __sprawlify_primitives_core.MachineStatus.Started;
291
+ statusRef.current = __sprawlify_primitives_core.MachineStatus.Started;
292
+ debug(started ? "rehydrating..." : "initializing...");
293
+ const initialState = hydratedStateRef.current ?? state.initial;
294
+ state.invoke(initialState, started ? state.get() : __sprawlify_primitives_core.INIT_STATE);
295
+ });
296
+ const fns = effects.current;
297
+ const currentState = state.ref.current;
298
+ return () => {
299
+ debug("unmounting...");
300
+ hydratedStateRef.current = currentState;
301
+ statusRef.current = __sprawlify_primitives_core.MachineStatus.Stopped;
302
+ fns.forEach((fn) => fn?.());
303
+ effects.current = /* @__PURE__ */ new Map();
304
+ transitionRef.current = null;
305
+ queueMicrotask(() => {
306
+ action(machine.exit);
307
+ });
308
+ };
309
+ }, []);
310
+ const getCurrentState = () => {
311
+ if ("ref" in state) return state.ref.current;
312
+ return state.get();
313
+ };
314
+ const send = (event) => {
315
+ queueMicrotask(() => {
316
+ if (statusRef.current !== __sprawlify_primitives_core.MachineStatus.Started) return;
317
+ previousEventRef.current = eventRef.current;
318
+ eventRef.current = event;
319
+ const currentState = getCurrentState();
320
+ const transition = choose(machine.states[currentState].on?.[event.type] ?? machine.on?.[event.type]);
321
+ if (!transition) return;
322
+ transitionRef.current = transition;
323
+ const target = transition.target ?? currentState;
324
+ debug("transition", event.type, transition.target || currentState, `(${transition.actions})`);
325
+ const changed = target !== currentState;
326
+ if (changed) (0, react_dom.flushSync)(() => state.set(target));
327
+ else if (transition.reenter && !changed) state.invoke(currentState, currentState);
328
+ else action(transition.actions ?? []);
329
+ });
330
+ };
331
+ machine.watch?.(getParams());
332
+ return {
333
+ state: getState(),
334
+ send,
335
+ context: ctx,
336
+ prop,
337
+ scope,
338
+ refs,
339
+ computed,
340
+ event: getEvent(),
341
+ getStatus: () => statusRef.current
342
+ };
343
+ }
344
+ function useLiveRef(value) {
345
+ const ref = (0, react.useRef)(value);
346
+ ref.current = value;
347
+ return ref;
348
+ }
349
+ function useProp(value) {
350
+ const ref = useLiveRef(value);
351
+ return function get(key) {
352
+ return ref.current[key];
353
+ };
354
+ }
355
+ function flush(fn) {
356
+ queueMicrotask(() => {
357
+ (0, react_dom.flushSync)(() => fn());
358
+ });
359
+ }
360
+
361
+ //#endregion
362
+ //#region src/core/normalize-props.ts
363
+ const normalizeProps = (0, __sprawlify_primitives_types.createNormalizer)((v) => v);
364
+
365
+ //#endregion
366
+ //#region src/core/portal.tsx
367
+ const Portal = (props) => {
368
+ const { children, container, disabled, getRootNode } = props;
369
+ if (typeof window === "undefined" || disabled) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react.Fragment, { children });
370
+ const doc = getRootNode?.().ownerDocument ?? document;
371
+ const mountNode = container?.current ?? doc.body;
372
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react.Fragment, { children: react.Children.map(children, (child) => (0, react_dom.createPortal)(child, mountNode)) });
373
+ };
374
+
375
+ //#endregion
376
+ exports.Portal = Portal;
377
+ Object.defineProperty(exports, 'mergeProps', {
378
+ enumerable: true,
379
+ get: function () {
380
+ return __sprawlify_primitives_core.mergeProps;
381
+ }
382
+ });
383
+ exports.normalizeProps = normalizeProps;
384
+ exports.useMachine = useMachine;
@@ -0,0 +1,25 @@
1
+ import { Machine, MachineSchema, Service, mergeProps } from "@sprawlify/primitives/core";
2
+ import * as _sprawlify_primitives_types0 from "@sprawlify/primitives/types";
3
+ import { CSSProperties, HTMLAttributes, JSX, PropsWithChildren, RefObject } from "react";
4
+
5
+ //#region src/core/machine.d.ts
6
+ declare function useMachine<T extends MachineSchema>(machine: Machine<T>, userProps?: Partial<T["props"]>): Service<T>;
7
+ //#endregion
8
+ //#region src/core/normalize-props.d.ts
9
+ type WithoutRef<T> = Omit<T, "ref">;
10
+ type ElementsWithoutRef = { [K in keyof JSX.IntrinsicElements]: WithoutRef<JSX.IntrinsicElements[K]> };
11
+ type PropTypes = ElementsWithoutRef & {
12
+ element: WithoutRef<HTMLAttributes<HTMLElement>>;
13
+ style: CSSProperties;
14
+ };
15
+ declare const normalizeProps: _sprawlify_primitives_types0.NormalizeProps<PropTypes>;
16
+ //#endregion
17
+ //#region src/core/portal.d.ts
18
+ interface PortalProps {
19
+ disabled?: boolean | undefined;
20
+ container?: RefObject<HTMLElement> | undefined;
21
+ getRootNode?: (() => ShadowRoot | Document | Node) | undefined;
22
+ }
23
+ declare const Portal: (props: PropsWithChildren<PortalProps>) => JSX.Element;
24
+ //#endregion
25
+ export { Portal, PortalProps, PropTypes, mergeProps, normalizeProps, useMachine };
@@ -0,0 +1,25 @@
1
+ import { Machine, MachineSchema, Service, mergeProps } from "@sprawlify/primitives/core";
2
+ import { CSSProperties, HTMLAttributes, JSX, PropsWithChildren, RefObject } from "react";
3
+ import * as _sprawlify_primitives_types0 from "@sprawlify/primitives/types";
4
+
5
+ //#region src/core/machine.d.ts
6
+ declare function useMachine<T extends MachineSchema>(machine: Machine<T>, userProps?: Partial<T["props"]>): Service<T>;
7
+ //#endregion
8
+ //#region src/core/normalize-props.d.ts
9
+ type WithoutRef<T> = Omit<T, "ref">;
10
+ type ElementsWithoutRef = { [K in keyof JSX.IntrinsicElements]: WithoutRef<JSX.IntrinsicElements[K]> };
11
+ type PropTypes = ElementsWithoutRef & {
12
+ element: WithoutRef<HTMLAttributes<HTMLElement>>;
13
+ style: CSSProperties;
14
+ };
15
+ declare const normalizeProps: _sprawlify_primitives_types0.NormalizeProps<PropTypes>;
16
+ //#endregion
17
+ //#region src/core/portal.d.ts
18
+ interface PortalProps {
19
+ disabled?: boolean | undefined;
20
+ container?: RefObject<HTMLElement> | undefined;
21
+ getRootNode?: (() => ShadowRoot | Document | Node) | undefined;
22
+ }
23
+ declare const Portal: (props: PropsWithChildren<PortalProps>) => JSX.Element;
24
+ //#endregion
25
+ export { Portal, PortalProps, PropTypes, mergeProps, normalizeProps, useMachine };
package/dist/index.mjs ADDED
@@ -0,0 +1,349 @@
1
+ import { INIT_STATE, MachineStatus, createScope, mergeProps } from "@sprawlify/primitives/core";
2
+ import { compact, ensure, identity, isFunction, isString, toArray, warn } from "@sprawlify/primitives/utils";
3
+ import * as React from "react";
4
+ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
5
+ import { createPortal, flushSync } from "react-dom";
6
+ import { createNormalizer } from "@sprawlify/primitives/types";
7
+ import { jsx } from "react/jsx-runtime";
8
+
9
+ //#region src/core/use-layout-effect.ts
10
+ const useSafeLayoutEffect = typeof globalThis.document !== "undefined" ? useLayoutEffect : useEffect;
11
+
12
+ //#endregion
13
+ //#region src/core/bindable.ts
14
+ function useBindable(props) {
15
+ const initial = props().value ?? props().defaultValue;
16
+ const eq = props().isEqual ?? Object.is;
17
+ const [initialValue] = useState(initial);
18
+ const [value, setValue] = useState(initialValue);
19
+ const controlled = props().value !== void 0;
20
+ const valueRef = useRef(value);
21
+ valueRef.current = controlled ? props().value : value;
22
+ const prevValue = useRef(valueRef.current);
23
+ useSafeLayoutEffect(() => {
24
+ prevValue.current = valueRef.current;
25
+ }, [value, props().value]);
26
+ const setFn = (value$1) => {
27
+ const prev = prevValue.current;
28
+ const next = isFunction(value$1) ? value$1(prev) : value$1;
29
+ if (props().debug) console.log(`[bindable > ${props().debug}] setValue`, {
30
+ next,
31
+ prev
32
+ });
33
+ if (!controlled) setValue(next);
34
+ if (!eq(next, prev)) props().onChange?.(next, prev);
35
+ };
36
+ function get() {
37
+ return controlled ? props().value : value;
38
+ }
39
+ return {
40
+ initial: initialValue,
41
+ ref: valueRef,
42
+ get,
43
+ set(value$1) {
44
+ (props().sync ? flushSync : identity)(() => setFn(value$1));
45
+ },
46
+ invoke(nextValue, prevValue$1) {
47
+ props().onChange?.(nextValue, prevValue$1);
48
+ },
49
+ hash(value$1) {
50
+ return props().hash?.(value$1) ?? String(value$1);
51
+ }
52
+ };
53
+ }
54
+ useBindable.cleanup = (fn) => {
55
+ useEffect(() => fn, []);
56
+ };
57
+ useBindable.ref = (defaultValue) => {
58
+ const value = useRef(defaultValue);
59
+ return {
60
+ get: () => value.current,
61
+ set: (next) => {
62
+ value.current = next;
63
+ }
64
+ };
65
+ };
66
+
67
+ //#endregion
68
+ //#region src/core/refs.ts
69
+ function useRefs(refs) {
70
+ const ref = useRef(refs);
71
+ return {
72
+ get(key) {
73
+ return ref.current[key];
74
+ },
75
+ set(key, value) {
76
+ ref.current[key] = value;
77
+ }
78
+ };
79
+ }
80
+
81
+ //#endregion
82
+ //#region src/core/track.ts
83
+ const useTrack = (deps, effect) => {
84
+ const render = useRef(false);
85
+ const called = useRef(false);
86
+ useEffect(() => {
87
+ if (render.current && called.current) return effect();
88
+ called.current = true;
89
+ }, [...(deps ?? []).map((d) => typeof d === "function" ? d() : d)]);
90
+ useEffect(() => {
91
+ render.current = true;
92
+ return () => {
93
+ render.current = false;
94
+ };
95
+ }, []);
96
+ };
97
+
98
+ //#endregion
99
+ //#region src/core/machine.ts
100
+ function useMachine(machine, userProps = {}) {
101
+ const scope = useMemo(() => {
102
+ const { id, ids, getRootNode } = userProps;
103
+ return createScope({
104
+ id,
105
+ ids,
106
+ getRootNode
107
+ });
108
+ }, [userProps]);
109
+ const debug = (...args) => {
110
+ if (machine.debug) console.log(...args);
111
+ };
112
+ const prop = useProp(machine.props?.({
113
+ props: compact(userProps),
114
+ scope
115
+ }) ?? userProps);
116
+ const context = machine.context?.({
117
+ prop,
118
+ bindable: useBindable,
119
+ scope,
120
+ flush,
121
+ getContext() {
122
+ return ctx;
123
+ },
124
+ getComputed() {
125
+ return computed;
126
+ },
127
+ getRefs() {
128
+ return refs;
129
+ },
130
+ getEvent() {
131
+ return getEvent();
132
+ }
133
+ });
134
+ const contextRef = useLiveRef(context);
135
+ const ctx = {
136
+ get(key) {
137
+ return contextRef.current?.[key].ref.current;
138
+ },
139
+ set(key, value) {
140
+ contextRef.current?.[key].set(value);
141
+ },
142
+ initial(key) {
143
+ return contextRef.current?.[key].initial;
144
+ },
145
+ hash(key) {
146
+ const current = contextRef.current?.[key].get();
147
+ return contextRef.current?.[key].hash(current);
148
+ }
149
+ };
150
+ const effects = useRef(/* @__PURE__ */ new Map());
151
+ const transitionRef = useRef(null);
152
+ const previousEventRef = useRef(null);
153
+ const eventRef = useRef({ type: "" });
154
+ const getEvent = () => ({
155
+ ...eventRef.current,
156
+ current() {
157
+ return eventRef.current;
158
+ },
159
+ previous() {
160
+ return previousEventRef.current;
161
+ }
162
+ });
163
+ const getState = () => ({
164
+ ...state,
165
+ matches(...values) {
166
+ return values.includes(state.ref.current);
167
+ },
168
+ hasTag(tag) {
169
+ return !!machine.states[state.ref.current]?.tags?.includes(tag);
170
+ }
171
+ });
172
+ const refs = useRefs(machine.refs?.({
173
+ prop,
174
+ context: ctx
175
+ }) ?? {});
176
+ const getParams = () => ({
177
+ state: getState(),
178
+ context: ctx,
179
+ event: getEvent(),
180
+ prop,
181
+ send,
182
+ action,
183
+ guard,
184
+ track: useTrack,
185
+ refs,
186
+ computed,
187
+ flush,
188
+ scope,
189
+ choose
190
+ });
191
+ const action = (keys) => {
192
+ const strs = isFunction(keys) ? keys(getParams()) : keys;
193
+ if (!strs) return;
194
+ const fns = strs.map((s) => {
195
+ const fn = machine.implementations?.actions?.[s];
196
+ if (!fn) warn(`[sprawlify-js] No implementation found for action "${JSON.stringify(s)}"`);
197
+ return fn;
198
+ });
199
+ for (const fn of fns) fn?.(getParams());
200
+ };
201
+ const guard = (str) => {
202
+ if (isFunction(str)) return str(getParams());
203
+ return machine.implementations?.guards?.[str](getParams());
204
+ };
205
+ const effect = (keys) => {
206
+ const strs = isFunction(keys) ? keys(getParams()) : keys;
207
+ if (!strs) return;
208
+ const fns = strs.map((s) => {
209
+ const fn = machine.implementations?.effects?.[s];
210
+ if (!fn) warn(`[sprawlify-js] No implementation found for effect "${JSON.stringify(s)}"`);
211
+ return fn;
212
+ });
213
+ const cleanups = [];
214
+ for (const fn of fns) {
215
+ const cleanup = fn?.(getParams());
216
+ if (cleanup) cleanups.push(cleanup);
217
+ }
218
+ return () => cleanups.forEach((fn) => fn?.());
219
+ };
220
+ const choose = (transitions) => {
221
+ return toArray(transitions).find((t) => {
222
+ let result = !t.guard;
223
+ if (isString(t.guard)) result = !!guard(t.guard);
224
+ else if (isFunction(t.guard)) result = t.guard(getParams());
225
+ return result;
226
+ });
227
+ };
228
+ const computed = (key) => {
229
+ ensure(machine.computed, () => `[sprawlify-js] No computed object found on machine`);
230
+ const fn = machine.computed[key];
231
+ return fn({
232
+ context: ctx,
233
+ event: getEvent(),
234
+ prop,
235
+ refs,
236
+ scope,
237
+ computed
238
+ });
239
+ };
240
+ const state = useBindable(() => ({
241
+ defaultValue: machine.initialState({ prop }),
242
+ onChange(nextState, prevState) {
243
+ if (prevState) {
244
+ effects.current.get(prevState)?.();
245
+ effects.current.delete(prevState);
246
+ }
247
+ if (prevState) action(machine.states[prevState]?.exit);
248
+ action(transitionRef.current?.actions);
249
+ const cleanup = effect(machine.states[nextState]?.effects);
250
+ if (cleanup) effects.current.set(nextState, cleanup);
251
+ if (prevState === INIT_STATE) {
252
+ action(machine.entry);
253
+ const cleanup$1 = effect(machine.effects);
254
+ if (cleanup$1) effects.current.set(INIT_STATE, cleanup$1);
255
+ }
256
+ action(machine.states[nextState]?.entry);
257
+ }
258
+ }));
259
+ const hydratedStateRef = useRef(void 0);
260
+ const statusRef = useRef(MachineStatus.NotStarted);
261
+ useSafeLayoutEffect(() => {
262
+ queueMicrotask(() => {
263
+ const started = statusRef.current === MachineStatus.Started;
264
+ statusRef.current = MachineStatus.Started;
265
+ debug(started ? "rehydrating..." : "initializing...");
266
+ const initialState = hydratedStateRef.current ?? state.initial;
267
+ state.invoke(initialState, started ? state.get() : INIT_STATE);
268
+ });
269
+ const fns = effects.current;
270
+ const currentState = state.ref.current;
271
+ return () => {
272
+ debug("unmounting...");
273
+ hydratedStateRef.current = currentState;
274
+ statusRef.current = MachineStatus.Stopped;
275
+ fns.forEach((fn) => fn?.());
276
+ effects.current = /* @__PURE__ */ new Map();
277
+ transitionRef.current = null;
278
+ queueMicrotask(() => {
279
+ action(machine.exit);
280
+ });
281
+ };
282
+ }, []);
283
+ const getCurrentState = () => {
284
+ if ("ref" in state) return state.ref.current;
285
+ return state.get();
286
+ };
287
+ const send = (event) => {
288
+ queueMicrotask(() => {
289
+ if (statusRef.current !== MachineStatus.Started) return;
290
+ previousEventRef.current = eventRef.current;
291
+ eventRef.current = event;
292
+ const currentState = getCurrentState();
293
+ const transition = choose(machine.states[currentState].on?.[event.type] ?? machine.on?.[event.type]);
294
+ if (!transition) return;
295
+ transitionRef.current = transition;
296
+ const target = transition.target ?? currentState;
297
+ debug("transition", event.type, transition.target || currentState, `(${transition.actions})`);
298
+ const changed = target !== currentState;
299
+ if (changed) flushSync(() => state.set(target));
300
+ else if (transition.reenter && !changed) state.invoke(currentState, currentState);
301
+ else action(transition.actions ?? []);
302
+ });
303
+ };
304
+ machine.watch?.(getParams());
305
+ return {
306
+ state: getState(),
307
+ send,
308
+ context: ctx,
309
+ prop,
310
+ scope,
311
+ refs,
312
+ computed,
313
+ event: getEvent(),
314
+ getStatus: () => statusRef.current
315
+ };
316
+ }
317
+ function useLiveRef(value) {
318
+ const ref = useRef(value);
319
+ ref.current = value;
320
+ return ref;
321
+ }
322
+ function useProp(value) {
323
+ const ref = useLiveRef(value);
324
+ return function get(key) {
325
+ return ref.current[key];
326
+ };
327
+ }
328
+ function flush(fn) {
329
+ queueMicrotask(() => {
330
+ flushSync(() => fn());
331
+ });
332
+ }
333
+
334
+ //#endregion
335
+ //#region src/core/normalize-props.ts
336
+ const normalizeProps = createNormalizer((v) => v);
337
+
338
+ //#endregion
339
+ //#region src/core/portal.tsx
340
+ const Portal = (props) => {
341
+ const { children, container, disabled, getRootNode } = props;
342
+ if (typeof window === "undefined" || disabled) return /* @__PURE__ */ jsx(React.Fragment, { children });
343
+ const doc = getRootNode?.().ownerDocument ?? document;
344
+ const mountNode = container?.current ?? doc.body;
345
+ return /* @__PURE__ */ jsx(React.Fragment, { children: React.Children.map(children, (child) => createPortal(child, mountNode)) });
346
+ };
347
+
348
+ //#endregion
349
+ export { Portal, mergeProps, normalizeProps, useMachine };
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@sprawlify/react",
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "description": "React wrapper for primitives.",
6
+ "author": "sprawlify <npm@sprawlify.com>",
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.mjs",
9
+ "types": "./dist/index.d.mts",
10
+ "exports": {
11
+ ".": {
12
+ "import": {
13
+ "types": "./dist/index.d.mts",
14
+ "default": "./dist/index.mjs"
15
+ },
16
+ "require": {
17
+ "types": "./dist/index.d.cts",
18
+ "default": "./dist/index.cjs"
19
+ }
20
+ }
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "dependencies": {
29
+ "@sprawlify/primitives": "0.0.1"
30
+ },
31
+ "peerDependencies": {
32
+ "react": ">=19.0.0",
33
+ "react-dom": ">=19.0.0"
34
+ },
35
+ "engines": {
36
+ "node": ">=24"
37
+ },
38
+ "license": "MIT",
39
+ "scripts": {
40
+ "build": "tsdown",
41
+ "typecheck": "tsc --noEmit",
42
+ "lint": "eslint src --fix"
43
+ }
44
+ }