Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@zag-js/react

Package Overview
Dependencies
Maintainers
1
Versions
1089
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@zag-js/react - npm Package Compare versions

Comparing version
1.34.1
to
1.35.0
+12
dist/bindable.d.mts
import { BindableParams, Bindable } from '@zag-js/core';
declare function useBindable<T>(props: () => BindableParams<T>): Bindable<T>;
declare namespace useBindable {
var cleanup: (fn: VoidFunction) => void;
var ref: <T>(defaultValue: T) => {
get: () => T;
set: (next: T) => void;
};
}
export { useBindable };
import { BindableParams, Bindable } from '@zag-js/core';
declare function useBindable<T>(props: () => BindableParams<T>): Bindable<T>;
declare namespace useBindable {
var cleanup: (fn: VoidFunction) => void;
var ref: <T>(defaultValue: T) => {
get: () => T;
set: (next: T) => void;
};
}
export { useBindable };
"use strict";
"use client";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/bindable.ts
var bindable_exports = {};
__export(bindable_exports, {
useBindable: () => useBindable
});
module.exports = __toCommonJS(bindable_exports);
var import_utils = require("@zag-js/utils");
var import_react = require("react");
var import_react_dom = require("react-dom");
var import_use_layout_effect = require("./use-layout-effect.cjs");
function useBindable(props) {
const initial = props().value ?? props().defaultValue;
const eq = props().isEqual ?? Object.is;
const [initialValue] = (0, import_react.useState)(initial);
const [value, setValue] = (0, import_react.useState)(initialValue);
const controlled = props().value !== void 0;
const valueRef = (0, import_react.useRef)(value);
valueRef.current = controlled ? props().value : value;
const prevValue = (0, import_react.useRef)(valueRef.current);
(0, import_use_layout_effect.useSafeLayoutEffect)(() => {
prevValue.current = valueRef.current;
}, [value, props().value]);
const setFn = (value2) => {
const prev = prevValue.current;
const next = (0, import_utils.isFunction)(value2) ? value2(prev) : value2;
if (props().debug) {
console.log(`[bindable > ${props().debug}] setValue`, { next, prev });
}
if (!controlled) setValue(next);
if (!eq(next, prev)) {
props().onChange?.(next, prev);
}
};
function get() {
return controlled ? props().value : value;
}
return {
initial: initialValue,
ref: valueRef,
get,
set(value2) {
const exec = props().sync ? import_react_dom.flushSync : import_utils.identity;
exec(() => setFn(value2));
},
invoke(nextValue, prevValue2) {
props().onChange?.(nextValue, prevValue2);
},
hash(value2) {
return props().hash?.(value2) ?? String(value2);
}
};
}
useBindable.cleanup = (fn) => {
(0, import_react.useEffect)(() => fn, []);
};
useBindable.ref = (defaultValue) => {
const value = (0, import_react.useRef)(defaultValue);
return {
get: () => value.current,
set: (next) => {
value.current = next;
}
};
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
useBindable
});
"use client";
// src/bindable.ts
import { identity, isFunction } from "@zag-js/utils";
import { useEffect, useRef, useState } from "react";
import { flushSync } from "react-dom";
import { useSafeLayoutEffect } from "./use-layout-effect.mjs";
function useBindable(props) {
const initial = props().value ?? props().defaultValue;
const eq = props().isEqual ?? Object.is;
const [initialValue] = useState(initial);
const [value, setValue] = useState(initialValue);
const controlled = props().value !== void 0;
const valueRef = useRef(value);
valueRef.current = controlled ? props().value : value;
const prevValue = useRef(valueRef.current);
useSafeLayoutEffect(() => {
prevValue.current = valueRef.current;
}, [value, props().value]);
const setFn = (value2) => {
const prev = prevValue.current;
const next = isFunction(value2) ? value2(prev) : value2;
if (props().debug) {
console.log(`[bindable > ${props().debug}] setValue`, { next, prev });
}
if (!controlled) setValue(next);
if (!eq(next, prev)) {
props().onChange?.(next, prev);
}
};
function get() {
return controlled ? props().value : value;
}
return {
initial: initialValue,
ref: valueRef,
get,
set(value2) {
const exec = props().sync ? flushSync : identity;
exec(() => setFn(value2));
},
invoke(nextValue, prevValue2) {
props().onChange?.(nextValue, prevValue2);
},
hash(value2) {
return props().hash?.(value2) ?? String(value2);
}
};
}
useBindable.cleanup = (fn) => {
useEffect(() => fn, []);
};
useBindable.ref = (defaultValue) => {
const value = useRef(defaultValue);
return {
get: () => value.current,
set: (next) => {
value.current = next;
}
};
};
export {
useBindable
};
import { MachineSchema, Machine, Service } from '@zag-js/core';
declare function useMachine<T extends MachineSchema>(machine: Machine<T>, userProps?: Partial<T["props"]>): Service<T>;
export { useMachine };
import { MachineSchema, Machine, Service } from '@zag-js/core';
declare function useMachine<T extends MachineSchema>(machine: Machine<T>, userProps?: Partial<T["props"]>): Service<T>;
export { useMachine };
"use strict";
"use client";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/machine.ts
var machine_exports = {};
__export(machine_exports, {
useMachine: () => useMachine
});
module.exports = __toCommonJS(machine_exports);
var import_core = require("@zag-js/core");
var import_utils = require("@zag-js/utils");
var import_react = require("react");
var import_react_dom = require("react-dom");
var import_bindable = require("./bindable.cjs");
var import_refs = require("./refs.cjs");
var import_track = require("./track.cjs");
var import_use_layout_effect = require("./use-layout-effect.cjs");
function useMachine(machine, userProps = {}) {
const scope = (0, import_react.useMemo)(() => {
const { id, ids, getRootNode } = userProps;
return (0, import_core.createScope)({ id, ids, getRootNode });
}, [userProps]);
const debug = (...args) => {
if (machine.debug) console.log(...args);
};
const props = machine.props?.({ props: (0, import_utils.compact)(userProps), scope }) ?? userProps;
const prop = useProp(props);
const context = machine.context?.({
prop,
bindable: import_bindable.useBindable,
scope,
flush,
getContext() {
return ctx;
},
getComputed() {
return computed;
},
getRefs() {
return refs;
},
getEvent() {
return getEvent();
}
});
const contextRef = useLiveRef(context);
const ctx = {
get(key) {
return contextRef.current?.[key].ref.current;
},
set(key, value) {
contextRef.current?.[key].set(value);
},
initial(key) {
return contextRef.current?.[key].initial;
},
hash(key) {
const current = contextRef.current?.[key].get();
return contextRef.current?.[key].hash(current);
}
};
const effects = (0, import_react.useRef)(/* @__PURE__ */ new Map());
const transitionRef = (0, import_react.useRef)(null);
const previousEventRef = (0, import_react.useRef)(null);
const eventRef = (0, import_react.useRef)({ type: "" });
const getEvent = () => ({
...eventRef.current,
current() {
return eventRef.current;
},
previous() {
return previousEventRef.current;
}
});
const getState = () => ({
...state,
matches(...values) {
return values.some((value) => (0, import_core.matchesState)(state.ref.current, value));
},
hasTag(tag) {
return (0, import_core.hasTag)(machine, state.ref.current, tag);
}
});
const refs = (0, import_refs.useRefs)(machine.refs?.({ prop, context: ctx }) ?? {});
const getParams = () => ({
state: getState(),
context: ctx,
event: getEvent(),
prop,
send,
action,
guard,
track: import_track.useTrack,
refs,
computed,
flush,
scope,
choose
});
const action = (keys) => {
const strs = (0, import_utils.isFunction)(keys) ? keys(getParams()) : keys;
if (!strs) return;
const fns = strs.map((s) => {
const fn = machine.implementations?.actions?.[s];
if (!fn) (0, import_utils.warn)(`[zag-js] No implementation found for action "${JSON.stringify(s)}"`);
return fn;
});
for (const fn of fns) {
fn?.(getParams());
}
};
const guard = (str) => {
if ((0, import_utils.isFunction)(str)) return str(getParams());
return machine.implementations?.guards?.[str](getParams());
};
const effect = (keys) => {
const strs = (0, import_utils.isFunction)(keys) ? keys(getParams()) : keys;
if (!strs) return;
const fns = strs.map((s) => {
const fn = machine.implementations?.effects?.[s];
if (!fn) (0, import_utils.warn)(`[zag-js] No implementation found for effect "${JSON.stringify(s)}"`);
return fn;
});
const cleanups = [];
for (const fn of fns) {
const cleanup = fn?.(getParams());
if (cleanup) cleanups.push(cleanup);
}
return () => cleanups.forEach((fn) => fn?.());
};
const choose = (transitions) => {
return (0, import_utils.toArray)(transitions).find((t) => {
let result = !t.guard;
if ((0, import_utils.isString)(t.guard)) result = !!guard(t.guard);
else if ((0, import_utils.isFunction)(t.guard)) result = t.guard(getParams());
return result;
});
};
const computed = (key) => {
(0, import_utils.ensure)(machine.computed, () => `[zag-js] No computed object found on machine`);
const fn = machine.computed[key];
return fn({
context: ctx,
event: getEvent(),
prop,
refs,
scope,
computed
});
};
const state = (0, import_bindable.useBindable)(() => ({
defaultValue: (0, import_core.resolveStateValue)(machine, machine.initialState({ prop })),
onChange(nextState, prevState) {
const { exiting, entering } = (0, import_core.getExitEnterStates)(machine, prevState, nextState, transitionRef.current?.reenter);
exiting.forEach((item) => {
const exitEffects = effects.current.get(item.path);
exitEffects?.();
effects.current.delete(item.path);
});
exiting.forEach((item) => {
action(item.state?.exit);
});
action(transitionRef.current?.actions);
entering.forEach((item) => {
const cleanup = effect(item.state?.effects);
if (cleanup) effects.current.set(item.path, cleanup);
});
if (prevState === import_core.INIT_STATE) {
action(machine.entry);
const cleanup = effect(machine.effects);
if (cleanup) effects.current.set(import_core.INIT_STATE, cleanup);
}
entering.forEach((item) => {
action(item.state?.entry);
});
}
}));
const hydratedStateRef = (0, import_react.useRef)(void 0);
const statusRef = (0, import_react.useRef)(import_core.MachineStatus.NotStarted);
(0, import_use_layout_effect.useSafeLayoutEffect)(() => {
queueMicrotask(() => {
const started = statusRef.current === import_core.MachineStatus.Started;
statusRef.current = import_core.MachineStatus.Started;
debug(started ? "rehydrating..." : "initializing...");
const initialState = hydratedStateRef.current ?? state.initial;
state.invoke(initialState, started ? state.get() : import_core.INIT_STATE);
});
const fns = effects.current;
const currentState = state.ref.current;
return () => {
debug("unmounting...");
hydratedStateRef.current = currentState;
statusRef.current = import_core.MachineStatus.Stopped;
fns.forEach((fn) => fn?.());
effects.current = /* @__PURE__ */ new Map();
transitionRef.current = null;
queueMicrotask(() => {
action(machine.exit);
});
};
}, []);
const getCurrentState = () => {
if ("ref" in state) return state.ref.current;
return state.get();
};
const send = (event) => {
queueMicrotask(() => {
if (statusRef.current !== import_core.MachineStatus.Started) return;
previousEventRef.current = eventRef.current;
eventRef.current = event;
let currentState = getCurrentState();
const { transitions, source } = (0, import_core.findTransition)(machine, currentState, event.type);
const transition = choose(transitions);
if (!transition) return;
transitionRef.current = transition;
const target = (0, import_core.resolveStateValue)(machine, transition.target ?? currentState, source);
debug("transition", event.type, transition.target || currentState, `(${transition.actions})`);
const changed = target !== currentState;
if (changed) {
(0, import_react_dom.flushSync)(() => state.set(target));
} else if (transition.reenter) {
state.invoke(currentState, currentState);
} else {
action(transition.actions ?? []);
}
});
};
machine.watch?.(getParams());
return {
state: getState(),
send,
context: ctx,
prop,
scope,
refs,
computed,
event: getEvent(),
getStatus: () => statusRef.current
};
}
function useLiveRef(value) {
const ref = (0, import_react.useRef)(value);
ref.current = value;
return ref;
}
function useProp(value) {
const ref = useLiveRef(value);
return function get(key) {
return ref.current[key];
};
}
function flush(fn) {
queueMicrotask(() => {
(0, import_react_dom.flushSync)(() => fn());
});
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
useMachine
});
"use client";
// src/machine.ts
import {
createScope,
findTransition,
getExitEnterStates,
hasTag,
INIT_STATE,
MachineStatus,
matchesState,
resolveStateValue
} from "@zag-js/core";
import { compact, ensure, isFunction, isString, toArray, warn } from "@zag-js/utils";
import { useMemo, useRef } from "react";
import { flushSync } from "react-dom";
import { useBindable } from "./bindable.mjs";
import { useRefs } from "./refs.mjs";
import { useTrack } from "./track.mjs";
import { useSafeLayoutEffect } from "./use-layout-effect.mjs";
function useMachine(machine, userProps = {}) {
const scope = useMemo(() => {
const { id, ids, getRootNode } = userProps;
return createScope({ id, ids, getRootNode });
}, [userProps]);
const debug = (...args) => {
if (machine.debug) console.log(...args);
};
const props = machine.props?.({ props: compact(userProps), scope }) ?? userProps;
const prop = useProp(props);
const context = machine.context?.({
prop,
bindable: useBindable,
scope,
flush,
getContext() {
return ctx;
},
getComputed() {
return computed;
},
getRefs() {
return refs;
},
getEvent() {
return getEvent();
}
});
const contextRef = useLiveRef(context);
const ctx = {
get(key) {
return contextRef.current?.[key].ref.current;
},
set(key, value) {
contextRef.current?.[key].set(value);
},
initial(key) {
return contextRef.current?.[key].initial;
},
hash(key) {
const current = contextRef.current?.[key].get();
return contextRef.current?.[key].hash(current);
}
};
const effects = useRef(/* @__PURE__ */ new Map());
const transitionRef = useRef(null);
const previousEventRef = useRef(null);
const eventRef = useRef({ type: "" });
const getEvent = () => ({
...eventRef.current,
current() {
return eventRef.current;
},
previous() {
return previousEventRef.current;
}
});
const getState = () => ({
...state,
matches(...values) {
return values.some((value) => matchesState(state.ref.current, value));
},
hasTag(tag) {
return hasTag(machine, state.ref.current, tag);
}
});
const refs = useRefs(machine.refs?.({ prop, context: ctx }) ?? {});
const getParams = () => ({
state: getState(),
context: ctx,
event: getEvent(),
prop,
send,
action,
guard,
track: useTrack,
refs,
computed,
flush,
scope,
choose
});
const action = (keys) => {
const strs = isFunction(keys) ? keys(getParams()) : keys;
if (!strs) return;
const fns = strs.map((s) => {
const fn = machine.implementations?.actions?.[s];
if (!fn) warn(`[zag-js] No implementation found for action "${JSON.stringify(s)}"`);
return fn;
});
for (const fn of fns) {
fn?.(getParams());
}
};
const guard = (str) => {
if (isFunction(str)) return str(getParams());
return machine.implementations?.guards?.[str](getParams());
};
const effect = (keys) => {
const strs = isFunction(keys) ? keys(getParams()) : keys;
if (!strs) return;
const fns = strs.map((s) => {
const fn = machine.implementations?.effects?.[s];
if (!fn) warn(`[zag-js] No implementation found for effect "${JSON.stringify(s)}"`);
return fn;
});
const cleanups = [];
for (const fn of fns) {
const cleanup = fn?.(getParams());
if (cleanup) cleanups.push(cleanup);
}
return () => cleanups.forEach((fn) => fn?.());
};
const choose = (transitions) => {
return toArray(transitions).find((t) => {
let result = !t.guard;
if (isString(t.guard)) result = !!guard(t.guard);
else if (isFunction(t.guard)) result = t.guard(getParams());
return result;
});
};
const computed = (key) => {
ensure(machine.computed, () => `[zag-js] No computed object found on machine`);
const fn = machine.computed[key];
return fn({
context: ctx,
event: getEvent(),
prop,
refs,
scope,
computed
});
};
const state = useBindable(() => ({
defaultValue: resolveStateValue(machine, machine.initialState({ prop })),
onChange(nextState, prevState) {
const { exiting, entering } = getExitEnterStates(machine, prevState, nextState, transitionRef.current?.reenter);
exiting.forEach((item) => {
const exitEffects = effects.current.get(item.path);
exitEffects?.();
effects.current.delete(item.path);
});
exiting.forEach((item) => {
action(item.state?.exit);
});
action(transitionRef.current?.actions);
entering.forEach((item) => {
const cleanup = effect(item.state?.effects);
if (cleanup) effects.current.set(item.path, cleanup);
});
if (prevState === INIT_STATE) {
action(machine.entry);
const cleanup = effect(machine.effects);
if (cleanup) effects.current.set(INIT_STATE, cleanup);
}
entering.forEach((item) => {
action(item.state?.entry);
});
}
}));
const hydratedStateRef = useRef(void 0);
const statusRef = useRef(MachineStatus.NotStarted);
useSafeLayoutEffect(() => {
queueMicrotask(() => {
const started = statusRef.current === MachineStatus.Started;
statusRef.current = MachineStatus.Started;
debug(started ? "rehydrating..." : "initializing...");
const initialState = hydratedStateRef.current ?? state.initial;
state.invoke(initialState, started ? state.get() : INIT_STATE);
});
const fns = effects.current;
const currentState = state.ref.current;
return () => {
debug("unmounting...");
hydratedStateRef.current = currentState;
statusRef.current = MachineStatus.Stopped;
fns.forEach((fn) => fn?.());
effects.current = /* @__PURE__ */ new Map();
transitionRef.current = null;
queueMicrotask(() => {
action(machine.exit);
});
};
}, []);
const getCurrentState = () => {
if ("ref" in state) return state.ref.current;
return state.get();
};
const send = (event) => {
queueMicrotask(() => {
if (statusRef.current !== MachineStatus.Started) return;
previousEventRef.current = eventRef.current;
eventRef.current = event;
let currentState = getCurrentState();
const { transitions, source } = findTransition(machine, currentState, event.type);
const transition = choose(transitions);
if (!transition) return;
transitionRef.current = transition;
const target = resolveStateValue(machine, transition.target ?? currentState, source);
debug("transition", event.type, transition.target || currentState, `(${transition.actions})`);
const changed = target !== currentState;
if (changed) {
flushSync(() => state.set(target));
} else if (transition.reenter) {
state.invoke(currentState, currentState);
} else {
action(transition.actions ?? []);
}
});
};
machine.watch?.(getParams());
return {
state: getState(),
send,
context: ctx,
prop,
scope,
refs,
computed,
event: getEvent(),
getStatus: () => statusRef.current
};
}
function useLiveRef(value) {
const ref = useRef(value);
ref.current = value;
return ref;
}
function useProp(value) {
const ref = useLiveRef(value);
return function get(key) {
return ref.current[key];
};
}
function flush(fn) {
queueMicrotask(() => {
flushSync(() => fn());
});
}
export {
useMachine
};
import * as _zag_js_types from '@zag-js/types';
import { JSX, HTMLAttributes, CSSProperties } from 'react';
type WithoutRef<T> = Omit<T, "ref">;
type ElementsWithoutRef = {
[K in keyof JSX.IntrinsicElements]: WithoutRef<JSX.IntrinsicElements[K]>;
};
type PropTypes = ElementsWithoutRef & {
element: WithoutRef<HTMLAttributes<HTMLElement>>;
style: CSSProperties;
};
declare const normalizeProps: _zag_js_types.NormalizeProps<PropTypes>;
export { type PropTypes, normalizeProps };
import * as _zag_js_types from '@zag-js/types';
import { JSX, HTMLAttributes, CSSProperties } from 'react';
type WithoutRef<T> = Omit<T, "ref">;
type ElementsWithoutRef = {
[K in keyof JSX.IntrinsicElements]: WithoutRef<JSX.IntrinsicElements[K]>;
};
type PropTypes = ElementsWithoutRef & {
element: WithoutRef<HTMLAttributes<HTMLElement>>;
style: CSSProperties;
};
declare const normalizeProps: _zag_js_types.NormalizeProps<PropTypes>;
export { type PropTypes, normalizeProps };
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/normalize-props.ts
var normalize_props_exports = {};
__export(normalize_props_exports, {
normalizeProps: () => normalizeProps
});
module.exports = __toCommonJS(normalize_props_exports);
var import_types = require("@zag-js/types");
var normalizeProps = (0, import_types.createNormalizer)((v) => v);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
normalizeProps
});
// src/normalize-props.ts
import { createNormalizer } from "@zag-js/types";
var normalizeProps = createNormalizer((v) => v);
export {
normalizeProps
};
import { PropsWithChildren, RefObject, JSX } from 'react';
interface PortalProps {
disabled?: boolean | undefined;
container?: RefObject<HTMLElement> | undefined;
getRootNode?: (() => ShadowRoot | Document | Node) | undefined;
}
declare const Portal: (props: PropsWithChildren<PortalProps>) => JSX.Element;
export { Portal, type PortalProps };
import { PropsWithChildren, RefObject, JSX } from 'react';
interface PortalProps {
disabled?: boolean | undefined;
container?: RefObject<HTMLElement> | undefined;
getRootNode?: (() => ShadowRoot | Document | Node) | undefined;
}
declare const Portal: (props: PropsWithChildren<PortalProps>) => JSX.Element;
export { Portal, type PortalProps };
"use strict";
"use client";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/portal.tsx
var portal_exports = {};
__export(portal_exports, {
Portal: () => Portal
});
module.exports = __toCommonJS(portal_exports);
var React = __toESM(require("react"));
var import_react_dom = require("react-dom");
var import_jsx_runtime = require("react/jsx-runtime");
var Portal = (props) => {
const { children, container, disabled, getRootNode } = props;
const isServer = typeof window === "undefined";
if (isServer || disabled) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(React.Fragment, { children });
const doc = getRootNode?.().ownerDocument ?? document;
const mountNode = container?.current ?? doc.body;
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(React.Fragment, { children: React.Children.map(children, (child) => (0, import_react_dom.createPortal)(child, mountNode)) });
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Portal
});
"use client";
// src/portal.tsx
import * as React from "react";
import { createPortal } from "react-dom";
import { jsx } from "react/jsx-runtime";
var Portal = (props) => {
const { children, container, disabled, getRootNode } = props;
const isServer = typeof window === "undefined";
if (isServer || disabled) return /* @__PURE__ */ jsx(React.Fragment, { children });
const doc = getRootNode?.().ownerDocument ?? document;
const mountNode = container?.current ?? doc.body;
return /* @__PURE__ */ jsx(React.Fragment, { children: React.Children.map(children, (child) => createPortal(child, mountNode)) });
};
export {
Portal
};
declare function useRefs<T>(refs: T): {
get<K extends keyof T>(key: K): T[K];
set<K extends keyof T>(key: K, value: T[K]): void;
};
export { useRefs };
declare function useRefs<T>(refs: T): {
get<K extends keyof T>(key: K): T[K];
set<K extends keyof T>(key: K, value: T[K]): void;
};
export { useRefs };
"use strict";
"use client";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/refs.ts
var refs_exports = {};
__export(refs_exports, {
useRefs: () => useRefs
});
module.exports = __toCommonJS(refs_exports);
var import_react = require("react");
function useRefs(refs) {
const ref = (0, import_react.useRef)(refs);
return {
get(key) {
return ref.current[key];
},
set(key, value) {
ref.current[key] = value;
}
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
useRefs
});
"use client";
// src/refs.ts
import { useRef } from "react";
function useRefs(refs) {
const ref = useRef(refs);
return {
get(key) {
return ref.current[key];
},
set(key, value) {
ref.current[key] = value;
}
};
}
export {
useRefs
};
declare const useTrack: (deps: any[], effect: VoidFunction) => void;
export { useTrack };
declare const useTrack: (deps: any[], effect: VoidFunction) => void;
export { useTrack };
"use strict";
"use client";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/track.ts
var track_exports = {};
__export(track_exports, {
useTrack: () => useTrack
});
module.exports = __toCommonJS(track_exports);
var import_react = require("react");
var useTrack = (deps, effect) => {
const render = (0, import_react.useRef)(false);
const called = (0, import_react.useRef)(false);
(0, import_react.useEffect)(() => {
const mounted = render.current;
const run = mounted && called.current;
if (run) return effect();
called.current = true;
}, [...(deps ?? []).map((d) => typeof d === "function" ? d() : d)]);
(0, import_react.useEffect)(() => {
render.current = true;
return () => {
render.current = false;
};
}, []);
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
useTrack
});
"use client";
// src/track.ts
import { useEffect, useRef } from "react";
var useTrack = (deps, effect) => {
const render = useRef(false);
const called = useRef(false);
useEffect(() => {
const mounted = render.current;
const run = mounted && called.current;
if (run) return effect();
called.current = true;
}, [...(deps ?? []).map((d) => typeof d === "function" ? d() : d)]);
useEffect(() => {
render.current = true;
return () => {
render.current = false;
};
}, []);
};
export {
useTrack
};
import { useLayoutEffect } from 'react';
declare const useSafeLayoutEffect: typeof useLayoutEffect;
export { useSafeLayoutEffect };
import { useLayoutEffect } from 'react';
declare const useSafeLayoutEffect: typeof useLayoutEffect;
export { useSafeLayoutEffect };
"use strict";
"use client";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/use-layout-effect.ts
var use_layout_effect_exports = {};
__export(use_layout_effect_exports, {
useSafeLayoutEffect: () => useSafeLayoutEffect
});
module.exports = __toCommonJS(use_layout_effect_exports);
var import_react = require("react");
var useSafeLayoutEffect = typeof globalThis.document !== "undefined" ? import_react.useLayoutEffect : import_react.useEffect;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
useSafeLayoutEffect
});
"use client";
// src/use-layout-effect.ts
import { useEffect, useLayoutEffect } from "react";
var useSafeLayoutEffect = typeof globalThis.document !== "undefined" ? useLayoutEffect : useEffect;
export {
useSafeLayoutEffect
};
+4
-24

@@ -1,26 +0,6 @@

import { MachineSchema, Machine, Service } from '@zag-js/core';
export { mergeProps } from '@zag-js/core';
import { JSX, HTMLAttributes, CSSProperties, PropsWithChildren, RefObject } from 'react';
export { useSyncExternalStore } from 'react';
import * as _zag_js_types from '@zag-js/types';
declare function useMachine<T extends MachineSchema>(machine: Machine<T>, userProps?: Partial<T["props"]>): Service<T>;
type WithoutRef<T> = Omit<T, "ref">;
type ElementsWithoutRef = {
[K in keyof JSX.IntrinsicElements]: WithoutRef<JSX.IntrinsicElements[K]>;
};
type PropTypes = ElementsWithoutRef & {
element: WithoutRef<HTMLAttributes<HTMLElement>>;
style: CSSProperties;
};
declare const normalizeProps: _zag_js_types.NormalizeProps<PropTypes>;
interface PortalProps {
disabled?: boolean | undefined;
container?: RefObject<HTMLElement> | undefined;
getRootNode?: (() => ShadowRoot | Document | Node) | undefined;
}
declare const Portal: (props: PropsWithChildren<PortalProps>) => JSX.Element;
export { Portal, type PortalProps, type PropTypes, normalizeProps, useMachine };
export { useMachine } from './machine.mjs';
export { PropTypes, normalizeProps } from './normalize-props.mjs';
export { Portal, PortalProps } from './portal.mjs';
import '@zag-js/types';

@@ -1,26 +0,6 @@

import { MachineSchema, Machine, Service } from '@zag-js/core';
export { mergeProps } from '@zag-js/core';
import { JSX, HTMLAttributes, CSSProperties, PropsWithChildren, RefObject } from 'react';
export { useSyncExternalStore } from 'react';
import * as _zag_js_types from '@zag-js/types';
declare function useMachine<T extends MachineSchema>(machine: Machine<T>, userProps?: Partial<T["props"]>): Service<T>;
type WithoutRef<T> = Omit<T, "ref">;
type ElementsWithoutRef = {
[K in keyof JSX.IntrinsicElements]: WithoutRef<JSX.IntrinsicElements[K]>;
};
type PropTypes = ElementsWithoutRef & {
element: WithoutRef<HTMLAttributes<HTMLElement>>;
style: CSSProperties;
};
declare const normalizeProps: _zag_js_types.NormalizeProps<PropTypes>;
interface PortalProps {
disabled?: boolean | undefined;
container?: RefObject<HTMLElement> | undefined;
getRootNode?: (() => ShadowRoot | Document | Node) | undefined;
}
declare const Portal: (props: PropsWithChildren<PortalProps>) => JSX.Element;
export { Portal, type PortalProps, type PropTypes, normalizeProps, useMachine };
export { useMachine } from './machine.js';
export { PropTypes, normalizeProps } from './normalize-props.js';
export { Portal, PortalProps } from './portal.js';
import '@zag-js/types';

@@ -1,377 +0,40 @@

"use client";
'use strict';
var core = require('@zag-js/core');
var React = require('react');
var utils = require('@zag-js/utils');
var reactDom = require('react-dom');
var types = require('@zag-js/types');
var jsxRuntime = require('react/jsx-runtime');
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
n.default = e;
return Object.freeze(n);
}
return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var React__namespace = /*#__PURE__*/_interopNamespace(React);
// src/index.ts
var useSafeLayoutEffect = typeof globalThis.document !== "undefined" ? React.useLayoutEffect : React.useEffect;
// src/bindable.ts
function useBindable(props) {
const initial = props().value ?? props().defaultValue;
const eq = props().isEqual ?? Object.is;
const [initialValue] = React.useState(initial);
const [value, setValue] = React.useState(initialValue);
const controlled = props().value !== void 0;
const valueRef = React.useRef(value);
valueRef.current = controlled ? props().value : value;
const prevValue = React.useRef(valueRef.current);
useSafeLayoutEffect(() => {
prevValue.current = valueRef.current;
}, [value, props().value]);
const setFn = (value2) => {
const prev = prevValue.current;
const next = utils.isFunction(value2) ? value2(prev) : value2;
if (props().debug) {
console.log(`[bindable > ${props().debug}] setValue`, { next, prev });
}
if (!controlled) setValue(next);
if (!eq(next, prev)) {
props().onChange?.(next, prev);
}
};
function get() {
return controlled ? props().value : value;
}
return {
initial: initialValue,
ref: valueRef,
get,
set(value2) {
const exec = props().sync ? reactDom.flushSync : utils.identity;
exec(() => setFn(value2));
},
invoke(nextValue, prevValue2) {
props().onChange?.(nextValue, prevValue2);
},
hash(value2) {
return props().hash?.(value2) ?? String(value2);
}
};
}
useBindable.cleanup = (fn) => {
React.useEffect(() => fn, []);
};
useBindable.ref = (defaultValue) => {
const value = React.useRef(defaultValue);
return {
get: () => value.current,
set: (next) => {
value.current = next;
}
};
};
function useRefs(refs) {
const ref = React.useRef(refs);
return {
get(key) {
return ref.current[key];
},
set(key, value) {
ref.current[key] = value;
}
};
}
var useTrack = (deps, effect) => {
const render = React.useRef(false);
const called = React.useRef(false);
React.useEffect(() => {
const mounted = render.current;
const run = mounted && called.current;
if (run) return effect();
called.current = true;
}, [...(deps ?? []).map((d) => typeof d === "function" ? d() : d)]);
React.useEffect(() => {
render.current = true;
return () => {
render.current = false;
};
}, []);
};
// src/machine.ts
function useMachine(machine, userProps = {}) {
const scope = React.useMemo(() => {
const { id, ids, getRootNode } = userProps;
return core.createScope({ id, ids, getRootNode });
}, [userProps]);
const debug = (...args) => {
if (machine.debug) console.log(...args);
};
const props = machine.props?.({ props: utils.compact(userProps), scope }) ?? userProps;
const prop = useProp(props);
const context = machine.context?.({
prop,
bindable: useBindable,
scope,
flush,
getContext() {
return ctx;
},
getComputed() {
return computed;
},
getRefs() {
return refs;
},
getEvent() {
return getEvent();
}
});
const contextRef = useLiveRef(context);
const ctx = {
get(key) {
return contextRef.current?.[key].ref.current;
},
set(key, value) {
contextRef.current?.[key].set(value);
},
initial(key) {
return contextRef.current?.[key].initial;
},
hash(key) {
const current = contextRef.current?.[key].get();
return contextRef.current?.[key].hash(current);
}
};
const effects = React.useRef(/* @__PURE__ */ new Map());
const transitionRef = React.useRef(null);
const previousEventRef = React.useRef(null);
const eventRef = React.useRef({ type: "" });
const getEvent = () => ({
...eventRef.current,
current() {
return eventRef.current;
},
previous() {
return previousEventRef.current;
}
});
const getState = () => ({
...state,
matches(...values) {
return values.includes(state.ref.current);
},
hasTag(tag) {
return !!machine.states[state.ref.current]?.tags?.includes(tag);
}
});
const refs = useRefs(machine.refs?.({ prop, context: ctx }) ?? {});
const getParams = () => ({
state: getState(),
context: ctx,
event: getEvent(),
prop,
send,
action,
guard,
track: useTrack,
refs,
computed,
flush,
scope,
choose
});
const action = (keys) => {
const strs = utils.isFunction(keys) ? keys(getParams()) : keys;
if (!strs) return;
const fns = strs.map((s) => {
const fn = machine.implementations?.actions?.[s];
if (!fn) utils.warn(`[zag-js] No implementation found for action "${JSON.stringify(s)}"`);
return fn;
});
for (const fn of fns) {
fn?.(getParams());
}
};
const guard = (str) => {
if (utils.isFunction(str)) return str(getParams());
return machine.implementations?.guards?.[str](getParams());
};
const effect = (keys) => {
const strs = utils.isFunction(keys) ? keys(getParams()) : keys;
if (!strs) return;
const fns = strs.map((s) => {
const fn = machine.implementations?.effects?.[s];
if (!fn) utils.warn(`[zag-js] No implementation found for effect "${JSON.stringify(s)}"`);
return fn;
});
const cleanups = [];
for (const fn of fns) {
const cleanup = fn?.(getParams());
if (cleanup) cleanups.push(cleanup);
}
return () => cleanups.forEach((fn) => fn?.());
};
const choose = (transitions) => {
return utils.toArray(transitions).find((t) => {
let result = !t.guard;
if (utils.isString(t.guard)) result = !!guard(t.guard);
else if (utils.isFunction(t.guard)) result = t.guard(getParams());
return result;
});
};
const computed = (key) => {
utils.ensure(machine.computed, () => `[zag-js] No computed object found on machine`);
const fn = machine.computed[key];
return fn({
context: ctx,
event: getEvent(),
prop,
refs,
scope,
computed
});
};
const state = useBindable(() => ({
defaultValue: machine.initialState({ prop }),
onChange(nextState, prevState) {
if (prevState) {
const exitEffects = effects.current.get(prevState);
exitEffects?.();
effects.current.delete(prevState);
}
if (prevState) {
action(machine.states[prevState]?.exit);
}
action(transitionRef.current?.actions);
const cleanup = effect(machine.states[nextState]?.effects);
if (cleanup) effects.current.set(nextState, cleanup);
if (prevState === core.INIT_STATE) {
action(machine.entry);
const cleanup2 = effect(machine.effects);
if (cleanup2) effects.current.set(core.INIT_STATE, cleanup2);
}
action(machine.states[nextState]?.entry);
}
}));
const hydratedStateRef = React.useRef(void 0);
const statusRef = React.useRef(core.MachineStatus.NotStarted);
useSafeLayoutEffect(() => {
queueMicrotask(() => {
const started = statusRef.current === core.MachineStatus.Started;
statusRef.current = core.MachineStatus.Started;
debug(started ? "rehydrating..." : "initializing...");
const initialState = hydratedStateRef.current ?? state.initial;
state.invoke(initialState, started ? state.get() : core.INIT_STATE);
});
const fns = effects.current;
const currentState = state.ref.current;
return () => {
debug("unmounting...");
hydratedStateRef.current = currentState;
statusRef.current = core.MachineStatus.Stopped;
fns.forEach((fn) => fn?.());
effects.current = /* @__PURE__ */ new Map();
transitionRef.current = null;
queueMicrotask(() => {
action(machine.exit);
});
};
}, []);
const getCurrentState = () => {
if ("ref" in state) return state.ref.current;
return state.get();
};
const send = (event) => {
queueMicrotask(() => {
if (statusRef.current !== core.MachineStatus.Started) return;
previousEventRef.current = eventRef.current;
eventRef.current = event;
let currentState = getCurrentState();
const transitions = (
// @ts-ignore
machine.states[currentState].on?.[event.type] ?? // @ts-ignore
machine.on?.[event.type]
);
const transition = choose(transitions);
if (!transition) return;
transitionRef.current = transition;
const target = transition.target ?? currentState;
debug("transition", event.type, transition.target || currentState, `(${transition.actions})`);
const changed = target !== currentState;
if (changed) {
reactDom.flushSync(() => state.set(target));
} else if (transition.reenter && !changed) {
state.invoke(currentState, currentState);
} else {
action(transition.actions ?? []);
}
});
};
machine.watch?.(getParams());
return {
state: getState(),
send,
context: ctx,
prop,
scope,
refs,
computed,
event: getEvent(),
getStatus: () => statusRef.current
};
}
function useLiveRef(value) {
const ref = React.useRef(value);
ref.current = value;
return ref;
}
function useProp(value) {
const ref = useLiveRef(value);
return function get(key) {
return ref.current[key];
};
}
function flush(fn) {
queueMicrotask(() => {
reactDom.flushSync(() => fn());
});
}
var normalizeProps = types.createNormalizer((v) => v);
var Portal = (props) => {
const { children, container, disabled, getRootNode } = props;
const isServer = typeof window === "undefined";
if (isServer || disabled) return /* @__PURE__ */ jsxRuntime.jsx(React__namespace.Fragment, { children });
const doc = getRootNode?.().ownerDocument ?? document;
const mountNode = container?.current ?? doc.body;
return /* @__PURE__ */ jsxRuntime.jsx(React__namespace.Fragment, { children: React__namespace.Children.map(children, (child) => reactDom.createPortal(child, mountNode)) });
};
Object.defineProperty(exports, "mergeProps", {
enumerable: true,
get: function () { return core.mergeProps; }
var index_exports = {};
__export(index_exports, {
mergeProps: () => import_core.mergeProps,
useSyncExternalStore: () => import_react.useSyncExternalStore
});
Object.defineProperty(exports, "useSyncExternalStore", {
enumerable: true,
get: function () { return React.useSyncExternalStore; }
module.exports = __toCommonJS(index_exports);
var import_core = require("@zag-js/core");
var import_react = require("react");
__reExport(index_exports, require("./machine.cjs"), module.exports);
__reExport(index_exports, require("./normalize-props.cjs"), module.exports);
__reExport(index_exports, require("./portal.cjs"), module.exports);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
mergeProps,
useSyncExternalStore,
...require("./machine.cjs"),
...require("./normalize-props.cjs"),
...require("./portal.cjs")
});
exports.Portal = Portal;
exports.normalizeProps = normalizeProps;
exports.useMachine = useMachine;

@@ -1,348 +0,10 @@

"use client";
import { createScope, MachineStatus, INIT_STATE } from '@zag-js/core';
export { mergeProps } from '@zag-js/core';
import * as React from 'react';
import { useMemo, useRef, useState, useLayoutEffect, useEffect } from 'react';
export { useSyncExternalStore } from 'react';
import { compact, ensure, isFunction, warn, toArray, isString, identity } from '@zag-js/utils';
import { flushSync, createPortal } from 'react-dom';
import { createNormalizer } from '@zag-js/types';
import { jsx } from 'react/jsx-runtime';
// src/index.ts
var useSafeLayoutEffect = typeof globalThis.document !== "undefined" ? useLayoutEffect : useEffect;
// src/bindable.ts
function useBindable(props) {
const initial = props().value ?? props().defaultValue;
const eq = props().isEqual ?? Object.is;
const [initialValue] = useState(initial);
const [value, setValue] = useState(initialValue);
const controlled = props().value !== void 0;
const valueRef = useRef(value);
valueRef.current = controlled ? props().value : value;
const prevValue = useRef(valueRef.current);
useSafeLayoutEffect(() => {
prevValue.current = valueRef.current;
}, [value, props().value]);
const setFn = (value2) => {
const prev = prevValue.current;
const next = isFunction(value2) ? value2(prev) : value2;
if (props().debug) {
console.log(`[bindable > ${props().debug}] setValue`, { next, prev });
}
if (!controlled) setValue(next);
if (!eq(next, prev)) {
props().onChange?.(next, prev);
}
};
function get() {
return controlled ? props().value : value;
}
return {
initial: initialValue,
ref: valueRef,
get,
set(value2) {
const exec = props().sync ? flushSync : identity;
exec(() => setFn(value2));
},
invoke(nextValue, prevValue2) {
props().onChange?.(nextValue, prevValue2);
},
hash(value2) {
return props().hash?.(value2) ?? String(value2);
}
};
}
useBindable.cleanup = (fn) => {
useEffect(() => fn, []);
import { mergeProps } from "@zag-js/core";
import { useSyncExternalStore } from "react";
export * from "./machine.mjs";
export * from "./normalize-props.mjs";
export * from "./portal.mjs";
export {
mergeProps,
useSyncExternalStore
};
useBindable.ref = (defaultValue) => {
const value = useRef(defaultValue);
return {
get: () => value.current,
set: (next) => {
value.current = next;
}
};
};
function useRefs(refs) {
const ref = useRef(refs);
return {
get(key) {
return ref.current[key];
},
set(key, value) {
ref.current[key] = value;
}
};
}
var useTrack = (deps, effect) => {
const render = useRef(false);
const called = useRef(false);
useEffect(() => {
const mounted = render.current;
const run = mounted && called.current;
if (run) return effect();
called.current = true;
}, [...(deps ?? []).map((d) => typeof d === "function" ? d() : d)]);
useEffect(() => {
render.current = true;
return () => {
render.current = false;
};
}, []);
};
// src/machine.ts
function useMachine(machine, userProps = {}) {
const scope = useMemo(() => {
const { id, ids, getRootNode } = userProps;
return createScope({ id, ids, getRootNode });
}, [userProps]);
const debug = (...args) => {
if (machine.debug) console.log(...args);
};
const props = machine.props?.({ props: compact(userProps), scope }) ?? userProps;
const prop = useProp(props);
const context = machine.context?.({
prop,
bindable: useBindable,
scope,
flush,
getContext() {
return ctx;
},
getComputed() {
return computed;
},
getRefs() {
return refs;
},
getEvent() {
return getEvent();
}
});
const contextRef = useLiveRef(context);
const ctx = {
get(key) {
return contextRef.current?.[key].ref.current;
},
set(key, value) {
contextRef.current?.[key].set(value);
},
initial(key) {
return contextRef.current?.[key].initial;
},
hash(key) {
const current = contextRef.current?.[key].get();
return contextRef.current?.[key].hash(current);
}
};
const effects = useRef(/* @__PURE__ */ new Map());
const transitionRef = useRef(null);
const previousEventRef = useRef(null);
const eventRef = useRef({ type: "" });
const getEvent = () => ({
...eventRef.current,
current() {
return eventRef.current;
},
previous() {
return previousEventRef.current;
}
});
const getState = () => ({
...state,
matches(...values) {
return values.includes(state.ref.current);
},
hasTag(tag) {
return !!machine.states[state.ref.current]?.tags?.includes(tag);
}
});
const refs = useRefs(machine.refs?.({ prop, context: ctx }) ?? {});
const getParams = () => ({
state: getState(),
context: ctx,
event: getEvent(),
prop,
send,
action,
guard,
track: useTrack,
refs,
computed,
flush,
scope,
choose
});
const action = (keys) => {
const strs = isFunction(keys) ? keys(getParams()) : keys;
if (!strs) return;
const fns = strs.map((s) => {
const fn = machine.implementations?.actions?.[s];
if (!fn) warn(`[zag-js] No implementation found for action "${JSON.stringify(s)}"`);
return fn;
});
for (const fn of fns) {
fn?.(getParams());
}
};
const guard = (str) => {
if (isFunction(str)) return str(getParams());
return machine.implementations?.guards?.[str](getParams());
};
const effect = (keys) => {
const strs = isFunction(keys) ? keys(getParams()) : keys;
if (!strs) return;
const fns = strs.map((s) => {
const fn = machine.implementations?.effects?.[s];
if (!fn) warn(`[zag-js] No implementation found for effect "${JSON.stringify(s)}"`);
return fn;
});
const cleanups = [];
for (const fn of fns) {
const cleanup = fn?.(getParams());
if (cleanup) cleanups.push(cleanup);
}
return () => cleanups.forEach((fn) => fn?.());
};
const choose = (transitions) => {
return toArray(transitions).find((t) => {
let result = !t.guard;
if (isString(t.guard)) result = !!guard(t.guard);
else if (isFunction(t.guard)) result = t.guard(getParams());
return result;
});
};
const computed = (key) => {
ensure(machine.computed, () => `[zag-js] No computed object found on machine`);
const fn = machine.computed[key];
return fn({
context: ctx,
event: getEvent(),
prop,
refs,
scope,
computed
});
};
const state = useBindable(() => ({
defaultValue: machine.initialState({ prop }),
onChange(nextState, prevState) {
if (prevState) {
const exitEffects = effects.current.get(prevState);
exitEffects?.();
effects.current.delete(prevState);
}
if (prevState) {
action(machine.states[prevState]?.exit);
}
action(transitionRef.current?.actions);
const cleanup = effect(machine.states[nextState]?.effects);
if (cleanup) effects.current.set(nextState, cleanup);
if (prevState === INIT_STATE) {
action(machine.entry);
const cleanup2 = effect(machine.effects);
if (cleanup2) effects.current.set(INIT_STATE, cleanup2);
}
action(machine.states[nextState]?.entry);
}
}));
const hydratedStateRef = useRef(void 0);
const statusRef = useRef(MachineStatus.NotStarted);
useSafeLayoutEffect(() => {
queueMicrotask(() => {
const started = statusRef.current === MachineStatus.Started;
statusRef.current = MachineStatus.Started;
debug(started ? "rehydrating..." : "initializing...");
const initialState = hydratedStateRef.current ?? state.initial;
state.invoke(initialState, started ? state.get() : INIT_STATE);
});
const fns = effects.current;
const currentState = state.ref.current;
return () => {
debug("unmounting...");
hydratedStateRef.current = currentState;
statusRef.current = MachineStatus.Stopped;
fns.forEach((fn) => fn?.());
effects.current = /* @__PURE__ */ new Map();
transitionRef.current = null;
queueMicrotask(() => {
action(machine.exit);
});
};
}, []);
const getCurrentState = () => {
if ("ref" in state) return state.ref.current;
return state.get();
};
const send = (event) => {
queueMicrotask(() => {
if (statusRef.current !== MachineStatus.Started) return;
previousEventRef.current = eventRef.current;
eventRef.current = event;
let currentState = getCurrentState();
const transitions = (
// @ts-ignore
machine.states[currentState].on?.[event.type] ?? // @ts-ignore
machine.on?.[event.type]
);
const transition = choose(transitions);
if (!transition) return;
transitionRef.current = transition;
const target = transition.target ?? currentState;
debug("transition", event.type, transition.target || currentState, `(${transition.actions})`);
const changed = target !== currentState;
if (changed) {
flushSync(() => state.set(target));
} else if (transition.reenter && !changed) {
state.invoke(currentState, currentState);
} else {
action(transition.actions ?? []);
}
});
};
machine.watch?.(getParams());
return {
state: getState(),
send,
context: ctx,
prop,
scope,
refs,
computed,
event: getEvent(),
getStatus: () => statusRef.current
};
}
function useLiveRef(value) {
const ref = useRef(value);
ref.current = value;
return ref;
}
function useProp(value) {
const ref = useLiveRef(value);
return function get(key) {
return ref.current[key];
};
}
function flush(fn) {
queueMicrotask(() => {
flushSync(() => fn());
});
}
var normalizeProps = createNormalizer((v) => v);
var Portal = (props) => {
const { children, container, disabled, getRootNode } = props;
const isServer = typeof window === "undefined";
if (isServer || disabled) return /* @__PURE__ */ jsx(React.Fragment, { children });
const doc = getRootNode?.().ownerDocument ?? document;
const mountNode = container?.current ?? doc.body;
return /* @__PURE__ */ jsx(React.Fragment, { children: React.Children.map(children, (child) => createPortal(child, mountNode)) });
};
export { Portal, normalizeProps, useMachine };
{
"name": "@zag-js/react",
"version": "1.34.1",
"version": "1.35.0",
"description": "The react wrapper for zag",

@@ -28,6 +28,6 @@ "keywords": [

"dependencies": {
"@zag-js/core": "1.34.1",
"@zag-js/store": "1.34.1",
"@zag-js/types": "1.34.1",
"@zag-js/utils": "1.34.1"
"@zag-js/core": "1.35.0",
"@zag-js/store": "1.35.0",
"@zag-js/types": "1.35.0",
"@zag-js/utils": "1.35.0"
},

@@ -34,0 +34,0 @@ "devDependencies": {