neue Homepage auf react basis

This commit is contained in:
2026-08-07 21:39:30 +02:00
parent 164bdd19ad
commit ee89442c04
52191 changed files with 1230242 additions and 58 deletions
+91
View File
@@ -0,0 +1,91 @@
import { Store } from "./Store.mjs";
/**
* A Store that supports controlled state keys, non-reactive values and provides utility methods for React.
*/
export declare class ReactStore<State extends object, Context = Record<string, never>, Selectors extends Record<string, SelectorFunction<State>> = Record<string, never>> extends Store<State> {
/**
* Creates a new ReactStore instance.
*
* @param state Initial state of the store.
* @param context Non-reactive context values.
* @param selectors Optional selectors for use with `useState`.
*/
constructor(state: State, context?: Context, selectors?: Selectors);
/**
* Non-reactive values such as refs, callbacks, etc.
*/
readonly context: Context;
private selectors;
/**
* Synchronizes a single external value into the store.
*
* Note that the while the value in `state` is updated immediately, the value returned
* by `useState` is updated before the next render (similarly to React's `useState`).
*/
useSyncedValue<Key extends keyof State, Value extends State[Key]>(key: keyof State, value: Value): void;
/**
* Synchronizes a single external value into the store and
* cleans it up (sets to `undefined`) on unmount.
*
* Note that the while the value in `state` is updated immediately, the value returned
* by `useState` is updated before the next render (similarly to React's `useState`).
*/
useSyncedValueWithCleanup<Key extends KeysAllowingUndefined<State>>(key: Key, value: State[Key]): void;
/**
* Synchronizes multiple external values into the store.
*
* Note that the while the values in `state` are updated immediately, the values returned
* by `useState` are updated before the next render (similarly to React's `useState`).
*/
useSyncedValues(statePart: Partial<State>): void;
/**
* Registers a controllable prop pair (`controlled`, `defaultValue`) for a specific key. If `controlled`
* is non-undefined, the store's state at `key` is updated to match `controlled`.
*/
useControlledProp<Key extends keyof State, Value extends State[Key]>(key: keyof State, controlled: Value | undefined): void;
/** Gets the current value from the store using a selector with the provided key.
*
* @param key Key of the selector to use.
*/
select<Key extends keyof Selectors>(key: Key, ...args: SelectorArgs<Selectors[Key]>): ReturnType<Selectors[Key]>;
/**
* Returns a value from the store's state using a selector function.
* Used to subscribe to specific parts of the state.
* This methods causes a rerender whenever the selected state changes.
*
* @param key Key of the selector to use.
*/
useState<Key extends keyof Selectors>(key: Key, ...args: SelectorArgs<Selectors[Key]>): ReturnType<Selectors[Key]>;
/**
* Wraps a function with `useStableCallback` to ensure it has a stable reference
* and assigns it to the context.
*
* @param key Key of the event callback. Must be a function in the context.
* @param fn Function to assign.
*/
useContextCallback<Key extends ContextFunctionKeys<Context>>(key: Key, fn: ContextFunction<Context, Key> | undefined): void;
/**
* Returns a stable setter function for a specific key in the store's state.
* It's commonly used to pass as a ref callback to React elements.
*
* @param key Key of the state to set.
*/
useStateSetter<const Key extends keyof State, Value extends State[Key]>(key: keyof State): (v: Value) => void;
/**
* Observes changes derived from the store's selectors and calls the listener when the selected value changes.
*
* @param key Key of the selector to observe.
* @param listener Listener function called when the selector result changes.
*/
observe<Key extends keyof Selectors>(selector: Key, listener: (newValue: ReturnType<Selectors[Key]>, oldValue: ReturnType<Selectors[Key]>, store: this) => void): () => void;
observe<Selector extends ObserveSelector<State>>(selector: Selector, listener: (newValue: ReturnType<Selector>, oldValue: ReturnType<Selector>, store: this) => void): () => void;
}
type MaybeCallable = (...args: any[]) => any;
type ContextFunctionKeys<Context> = { [Key in keyof Context]-?: Extract<Context[Key], MaybeCallable> extends never ? never : Key }[keyof Context];
type ContextFunction<Context, Key extends keyof Context> = Extract<Context[Key], MaybeCallable>;
type KeysAllowingUndefined<State> = { [Key in keyof State]-?: undefined extends State[Key] ? Key : never }[keyof State];
type ObserveSelector<State> = (state: State) => any;
type SelectorFunction<State> = (state: State, ...args: any[]) => any;
type Tail<T extends readonly any[]> = T extends readonly [any, ...infer Rest] ? Rest : [];
type SelectorArgs<Selector> = Selector extends ((...params: infer Params) => any) ? Tail<Params> : never;
export {};
+91
View File
@@ -0,0 +1,91 @@
import { Store } from "./Store.js";
/**
* A Store that supports controlled state keys, non-reactive values and provides utility methods for React.
*/
export declare class ReactStore<State extends object, Context = Record<string, never>, Selectors extends Record<string, SelectorFunction<State>> = Record<string, never>> extends Store<State> {
/**
* Creates a new ReactStore instance.
*
* @param state Initial state of the store.
* @param context Non-reactive context values.
* @param selectors Optional selectors for use with `useState`.
*/
constructor(state: State, context?: Context, selectors?: Selectors);
/**
* Non-reactive values such as refs, callbacks, etc.
*/
readonly context: Context;
private selectors;
/**
* Synchronizes a single external value into the store.
*
* Note that the while the value in `state` is updated immediately, the value returned
* by `useState` is updated before the next render (similarly to React's `useState`).
*/
useSyncedValue<Key extends keyof State, Value extends State[Key]>(key: keyof State, value: Value): void;
/**
* Synchronizes a single external value into the store and
* cleans it up (sets to `undefined`) on unmount.
*
* Note that the while the value in `state` is updated immediately, the value returned
* by `useState` is updated before the next render (similarly to React's `useState`).
*/
useSyncedValueWithCleanup<Key extends KeysAllowingUndefined<State>>(key: Key, value: State[Key]): void;
/**
* Synchronizes multiple external values into the store.
*
* Note that the while the values in `state` are updated immediately, the values returned
* by `useState` are updated before the next render (similarly to React's `useState`).
*/
useSyncedValues(statePart: Partial<State>): void;
/**
* Registers a controllable prop pair (`controlled`, `defaultValue`) for a specific key. If `controlled`
* is non-undefined, the store's state at `key` is updated to match `controlled`.
*/
useControlledProp<Key extends keyof State, Value extends State[Key]>(key: keyof State, controlled: Value | undefined): void;
/** Gets the current value from the store using a selector with the provided key.
*
* @param key Key of the selector to use.
*/
select<Key extends keyof Selectors>(key: Key, ...args: SelectorArgs<Selectors[Key]>): ReturnType<Selectors[Key]>;
/**
* Returns a value from the store's state using a selector function.
* Used to subscribe to specific parts of the state.
* This methods causes a rerender whenever the selected state changes.
*
* @param key Key of the selector to use.
*/
useState<Key extends keyof Selectors>(key: Key, ...args: SelectorArgs<Selectors[Key]>): ReturnType<Selectors[Key]>;
/**
* Wraps a function with `useStableCallback` to ensure it has a stable reference
* and assigns it to the context.
*
* @param key Key of the event callback. Must be a function in the context.
* @param fn Function to assign.
*/
useContextCallback<Key extends ContextFunctionKeys<Context>>(key: Key, fn: ContextFunction<Context, Key> | undefined): void;
/**
* Returns a stable setter function for a specific key in the store's state.
* It's commonly used to pass as a ref callback to React elements.
*
* @param key Key of the state to set.
*/
useStateSetter<const Key extends keyof State, Value extends State[Key]>(key: keyof State): (v: Value) => void;
/**
* Observes changes derived from the store's selectors and calls the listener when the selected value changes.
*
* @param key Key of the selector to observe.
* @param listener Listener function called when the selector result changes.
*/
observe<Key extends keyof Selectors>(selector: Key, listener: (newValue: ReturnType<Selectors[Key]>, oldValue: ReturnType<Selectors[Key]>, store: this) => void): () => void;
observe<Selector extends ObserveSelector<State>>(selector: Selector, listener: (newValue: ReturnType<Selector>, oldValue: ReturnType<Selector>, store: this) => void): () => void;
}
type MaybeCallable = (...args: any[]) => any;
type ContextFunctionKeys<Context> = { [Key in keyof Context]-?: Extract<Context[Key], MaybeCallable> extends never ? never : Key }[keyof Context];
type ContextFunction<Context, Key extends keyof Context> = Extract<Context[Key], MaybeCallable>;
type KeysAllowingUndefined<State> = { [Key in keyof State]-?: undefined extends State[Key] ? Key : never }[keyof State];
type ObserveSelector<State> = (state: State) => any;
type SelectorFunction<State> = (state: State, ...args: any[]) => any;
type Tail<T extends readonly any[]> = T extends readonly [any, ...infer Rest] ? Rest : [];
type SelectorArgs<Selector> = Selector extends ((...params: infer Params) => any) ? Tail<Params> : never;
export {};
+209
View File
@@ -0,0 +1,209 @@
"use strict";
/* False positives - ESLint thinks we're calling a hook from a class component. */
/* eslint-disable react-hooks/rules-of-hooks */
'use client';
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ReactStore = void 0;
var React = _interopRequireWildcard(require("react"));
var _Store = require("./Store");
var _useStore = require("./useStore");
var _useStableCallback = require("../useStableCallback");
var _useIsoLayoutEffect = require("../useIsoLayoutEffect");
var _empty = require("../empty");
/**
* A Store that supports controlled state keys, non-reactive values and provides utility methods for React.
*/
class ReactStore extends _Store.Store {
/**
* Creates a new ReactStore instance.
*
* @param state Initial state of the store.
* @param context Non-reactive context values.
* @param selectors Optional selectors for use with `useState`.
*/
constructor(state, context = {}, selectors) {
super(state);
this.context = context;
this.selectors = selectors;
}
/**
* Non-reactive values such as refs, callbacks, etc.
*/
/**
* Synchronizes a single external value into the store.
*
* Note that the while the value in `state` is updated immediately, the value returned
* by `useState` is updated before the next render (similarly to React's `useState`).
*/
useSyncedValue(key, value) {
React.useDebugValue(key);
// eslint-disable-next-line consistent-this
const store = this;
(0, _useIsoLayoutEffect.useIsoLayoutEffect)(() => {
if (store.state[key] !== value) {
store.set(key, value);
}
}, [store, key, value]);
}
/**
* Synchronizes a single external value into the store and
* cleans it up (sets to `undefined`) on unmount.
*
* Note that the while the value in `state` is updated immediately, the value returned
* by `useState` is updated before the next render (similarly to React's `useState`).
*/
useSyncedValueWithCleanup(key, value) {
// eslint-disable-next-line consistent-this
const store = this;
(0, _useIsoLayoutEffect.useIsoLayoutEffect)(() => {
if (store.state[key] !== value) {
store.set(key, value);
}
return () => {
store.set(key, undefined);
};
}, [store, key, value]);
}
/**
* Synchronizes multiple external values into the store.
*
* Note that the while the values in `state` are updated immediately, the values returned
* by `useState` are updated before the next render (similarly to React's `useState`).
*/
useSyncedValues(statePart) {
// eslint-disable-next-line consistent-this
const store = this;
if (process.env.NODE_ENV !== 'production') {
// Check that an object with the same shape is passed on every render
React.useDebugValue(statePart, p => Object.keys(p));
const keys = React.useRef(Object.keys(statePart)).current;
const nextKeys = Object.keys(statePart);
if (keys.length !== nextKeys.length || keys.some((key, index) => key !== nextKeys[index])) {
console.error('ReactStore.useSyncedValues expects the same prop keys on every render. Keys should be stable.');
}
}
const dependencies = Object.values(statePart);
(0, _useIsoLayoutEffect.useIsoLayoutEffect)(() => {
store.update(statePart);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [store, ...dependencies]);
}
/**
* Registers a controllable prop pair (`controlled`, `defaultValue`) for a specific key. If `controlled`
* is non-undefined, the store's state at `key` is updated to match `controlled`.
*/
useControlledProp(key, controlled) {
React.useDebugValue(key);
// eslint-disable-next-line consistent-this
const store = this;
const isControlled = controlled !== undefined;
(0, _useIsoLayoutEffect.useIsoLayoutEffect)(() => {
if (isControlled && !Object.is(store.state[key], controlled)) {
// Set the internal state to match the controlled value.
store.setState({
...store.state,
[key]: controlled
});
}
}, [store, key, controlled, isControlled]);
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line
const cache = this.controlledValues ??= new Map();
if (!cache.has(key)) {
cache.set(key, isControlled);
}
const previouslyControlled = cache.get(key);
if (previouslyControlled !== undefined && previouslyControlled !== isControlled) {
console.error(`A component is changing the ${isControlled ? '' : 'un'}controlled state of ${key.toString()} to be ${isControlled ? 'un' : ''}controlled. Elements should not switch from uncontrolled to controlled (or vice versa).`);
}
}
}
/** Gets the current value from the store using a selector with the provided key.
*
* @param key Key of the selector to use.
*/
select(key, a1, a2, a3) {
const selector = this.selectors[key];
return selector(this.state, a1, a2, a3);
}
/**
* Returns a value from the store's state using a selector function.
* Used to subscribe to specific parts of the state.
* This methods causes a rerender whenever the selected state changes.
*
* @param key Key of the selector to use.
*/
useState(key, a1, a2, a3) {
React.useDebugValue(key);
return (0, _useStore.useStore)(this, this.selectors[key], a1, a2, a3);
}
/**
* Wraps a function with `useStableCallback` to ensure it has a stable reference
* and assigns it to the context.
*
* @param key Key of the event callback. Must be a function in the context.
* @param fn Function to assign.
*/
useContextCallback(key, fn) {
React.useDebugValue(key);
const stableFunction = (0, _useStableCallback.useStableCallback)(fn ?? _empty.NOOP);
this.context[key] = stableFunction;
}
/**
* Returns a stable setter function for a specific key in the store's state.
* It's commonly used to pass as a ref callback to React elements.
*
* @param key Key of the state to set.
*/
useStateSetter(key) {
const ref = React.useRef(undefined);
if (ref.current === undefined) {
ref.current = value => {
this.set(key, value);
};
}
return ref.current;
}
/**
* Observes changes derived from the store's selectors and calls the listener when the selected value changes.
*
* @param key Key of the selector to observe.
* @param listener Listener function called when the selector result changes.
*/
observe(selector, listener) {
let selectFn;
if (typeof selector === 'function') {
selectFn = selector;
} else {
selectFn = this.selectors[selector];
}
let prevValue = selectFn(this.state);
listener(prevValue, prevValue, this);
return this.subscribe(nextState => {
const nextValue = selectFn(nextState);
if (!Object.is(prevValue, nextValue)) {
const oldValue = prevValue;
prevValue = nextValue;
listener(nextValue, oldValue, this);
}
});
}
}
exports.ReactStore = ReactStore;
+203
View File
@@ -0,0 +1,203 @@
/* False positives - ESLint thinks we're calling a hook from a class component. */
/* eslint-disable react-hooks/rules-of-hooks */
'use client';
import * as React from 'react';
import { Store } from "./Store.mjs";
import { useStore } from "./useStore.mjs";
import { useStableCallback } from "../useStableCallback.mjs";
import { useIsoLayoutEffect } from "../useIsoLayoutEffect.mjs";
import { NOOP } from "../empty.mjs";
/**
* A Store that supports controlled state keys, non-reactive values and provides utility methods for React.
*/
export class ReactStore extends Store {
/**
* Creates a new ReactStore instance.
*
* @param state Initial state of the store.
* @param context Non-reactive context values.
* @param selectors Optional selectors for use with `useState`.
*/
constructor(state, context = {}, selectors) {
super(state);
this.context = context;
this.selectors = selectors;
}
/**
* Non-reactive values such as refs, callbacks, etc.
*/
/**
* Synchronizes a single external value into the store.
*
* Note that the while the value in `state` is updated immediately, the value returned
* by `useState` is updated before the next render (similarly to React's `useState`).
*/
useSyncedValue(key, value) {
React.useDebugValue(key);
// eslint-disable-next-line consistent-this
const store = this;
useIsoLayoutEffect(() => {
if (store.state[key] !== value) {
store.set(key, value);
}
}, [store, key, value]);
}
/**
* Synchronizes a single external value into the store and
* cleans it up (sets to `undefined`) on unmount.
*
* Note that the while the value in `state` is updated immediately, the value returned
* by `useState` is updated before the next render (similarly to React's `useState`).
*/
useSyncedValueWithCleanup(key, value) {
// eslint-disable-next-line consistent-this
const store = this;
useIsoLayoutEffect(() => {
if (store.state[key] !== value) {
store.set(key, value);
}
return () => {
store.set(key, undefined);
};
}, [store, key, value]);
}
/**
* Synchronizes multiple external values into the store.
*
* Note that the while the values in `state` are updated immediately, the values returned
* by `useState` are updated before the next render (similarly to React's `useState`).
*/
useSyncedValues(statePart) {
// eslint-disable-next-line consistent-this
const store = this;
if (process.env.NODE_ENV !== 'production') {
// Check that an object with the same shape is passed on every render
React.useDebugValue(statePart, p => Object.keys(p));
const keys = React.useRef(Object.keys(statePart)).current;
const nextKeys = Object.keys(statePart);
if (keys.length !== nextKeys.length || keys.some((key, index) => key !== nextKeys[index])) {
console.error('ReactStore.useSyncedValues expects the same prop keys on every render. Keys should be stable.');
}
}
const dependencies = Object.values(statePart);
useIsoLayoutEffect(() => {
store.update(statePart);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [store, ...dependencies]);
}
/**
* Registers a controllable prop pair (`controlled`, `defaultValue`) for a specific key. If `controlled`
* is non-undefined, the store's state at `key` is updated to match `controlled`.
*/
useControlledProp(key, controlled) {
React.useDebugValue(key);
// eslint-disable-next-line consistent-this
const store = this;
const isControlled = controlled !== undefined;
useIsoLayoutEffect(() => {
if (isControlled && !Object.is(store.state[key], controlled)) {
// Set the internal state to match the controlled value.
store.setState({
...store.state,
[key]: controlled
});
}
}, [store, key, controlled, isControlled]);
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line
const cache = this.controlledValues ??= new Map();
if (!cache.has(key)) {
cache.set(key, isControlled);
}
const previouslyControlled = cache.get(key);
if (previouslyControlled !== undefined && previouslyControlled !== isControlled) {
console.error(`A component is changing the ${isControlled ? '' : 'un'}controlled state of ${key.toString()} to be ${isControlled ? 'un' : ''}controlled. Elements should not switch from uncontrolled to controlled (or vice versa).`);
}
}
}
/** Gets the current value from the store using a selector with the provided key.
*
* @param key Key of the selector to use.
*/
select(key, a1, a2, a3) {
const selector = this.selectors[key];
return selector(this.state, a1, a2, a3);
}
/**
* Returns a value from the store's state using a selector function.
* Used to subscribe to specific parts of the state.
* This methods causes a rerender whenever the selected state changes.
*
* @param key Key of the selector to use.
*/
useState(key, a1, a2, a3) {
React.useDebugValue(key);
return useStore(this, this.selectors[key], a1, a2, a3);
}
/**
* Wraps a function with `useStableCallback` to ensure it has a stable reference
* and assigns it to the context.
*
* @param key Key of the event callback. Must be a function in the context.
* @param fn Function to assign.
*/
useContextCallback(key, fn) {
React.useDebugValue(key);
const stableFunction = useStableCallback(fn ?? NOOP);
this.context[key] = stableFunction;
}
/**
* Returns a stable setter function for a specific key in the store's state.
* It's commonly used to pass as a ref callback to React elements.
*
* @param key Key of the state to set.
*/
useStateSetter(key) {
const ref = React.useRef(undefined);
if (ref.current === undefined) {
ref.current = value => {
this.set(key, value);
};
}
return ref.current;
}
/**
* Observes changes derived from the store's selectors and calls the listener when the selected value changes.
*
* @param key Key of the selector to observe.
* @param listener Listener function called when the selector result changes.
*/
observe(selector, listener) {
let selectFn;
if (typeof selector === 'function') {
selectFn = selector;
} else {
selectFn = this.selectors[selector];
}
let prevValue = selectFn(this.state);
listener(prevValue, prevValue, this);
return this.subscribe(nextState => {
const nextValue = selectFn(nextState);
if (!Object.is(prevValue, nextValue)) {
const oldValue = prevValue;
prevValue = nextValue;
listener(nextValue, oldValue, this);
}
});
}
}
+58
View File
@@ -0,0 +1,58 @@
type Listener<T> = (state: T) => void;
/**
* A data store implementation that allows subscribing to state changes and updating the state.
* It uses an observer pattern to notify subscribers when the state changes.
*/
export declare class Store<State> {
/**
* The current state of the store.
* This property is updated immediately when the state changes as a result of calling {@link setState}, {@link update}, or {@link set}.
* To subscribe to state changes, use the {@link useState} method. The value returned by {@link useState} is updated after the component renders (similarly to React's useState).
* The values can be used directly (to avoid subscribing to the store) in effects or event handlers.
*
* Do not modify properties in state directly. Instead, use the provided methods to ensure proper state management and listener notification.
*/
state: State;
private listeners;
private updateTick;
constructor(state: State);
/**
* Registers a listener that will be called whenever the store's state changes.
*
* @param fn The listener function to be called on state changes.
* @returns A function to unsubscribe the listener.
*/
subscribe: (fn: Listener<State>) => () => void;
/**
* Returns the current state of the store.
*/
getSnapshot: () => State;
/**
* Updates the entire store's state and notifies all registered listeners.
*
* @param newState The new state to set for the store.
*/
setState(newState: State): void;
/**
* Merges the provided changes into the current state and notifies listeners if there are changes.
*
* @param changes An object containing the changes to apply to the current state.
*/
update(changes: Partial<State>): void;
/**
* Sets a specific key in the store's state to a new value and notifies listeners if the value has changed.
*
* @param key The key in the store's state to update.
* @param value The new value to set for the specified key.
*/
set<T>(key: keyof State, value: T): void;
/**
* Gives the state a new reference and updates all registered listeners.
*/
notifyAll(): void;
use<F extends (...args: any) => any>(selector: F, ...args: SelectorArgs<F>): ReturnType<F>;
}
export type ReadonlyStore<State> = Pick<Store<State>, 'getSnapshot' | 'subscribe' | 'state'>;
type SelectorArgs<Selector> = Selector extends ((...params: infer Params) => any) ? Tail<Params> : never;
type Tail<T extends readonly any[]> = T extends readonly [any, ...infer Rest] ? Rest : [];
export {};
+58
View File
@@ -0,0 +1,58 @@
type Listener<T> = (state: T) => void;
/**
* A data store implementation that allows subscribing to state changes and updating the state.
* It uses an observer pattern to notify subscribers when the state changes.
*/
export declare class Store<State> {
/**
* The current state of the store.
* This property is updated immediately when the state changes as a result of calling {@link setState}, {@link update}, or {@link set}.
* To subscribe to state changes, use the {@link useState} method. The value returned by {@link useState} is updated after the component renders (similarly to React's useState).
* The values can be used directly (to avoid subscribing to the store) in effects or event handlers.
*
* Do not modify properties in state directly. Instead, use the provided methods to ensure proper state management and listener notification.
*/
state: State;
private listeners;
private updateTick;
constructor(state: State);
/**
* Registers a listener that will be called whenever the store's state changes.
*
* @param fn The listener function to be called on state changes.
* @returns A function to unsubscribe the listener.
*/
subscribe: (fn: Listener<State>) => () => void;
/**
* Returns the current state of the store.
*/
getSnapshot: () => State;
/**
* Updates the entire store's state and notifies all registered listeners.
*
* @param newState The new state to set for the store.
*/
setState(newState: State): void;
/**
* Merges the provided changes into the current state and notifies listeners if there are changes.
*
* @param changes An object containing the changes to apply to the current state.
*/
update(changes: Partial<State>): void;
/**
* Sets a specific key in the store's state to a new value and notifies listeners if the value has changed.
*
* @param key The key in the store's state to update.
* @param value The new value to set for the specified key.
*/
set<T>(key: keyof State, value: T): void;
/**
* Gives the state a new reference and updates all registered listeners.
*/
notifyAll(): void;
use<F extends (...args: any) => any>(selector: F, ...args: SelectorArgs<F>): ReturnType<F>;
}
export type ReadonlyStore<State> = Pick<Store<State>, 'getSnapshot' | 'subscribe' | 'state'>;
type SelectorArgs<Selector> = Selector extends ((...params: infer Params) => any) ? Tail<Params> : never;
type Tail<T extends readonly any[]> = T extends readonly [any, ...infer Rest] ? Rest : [];
export {};
+118
View File
@@ -0,0 +1,118 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Store = void 0;
var _useStore = require("./useStore");
/**
* A data store implementation that allows subscribing to state changes and updating the state.
* It uses an observer pattern to notify subscribers when the state changes.
*/
class Store {
/**
* The current state of the store.
* This property is updated immediately when the state changes as a result of calling {@link setState}, {@link update}, or {@link set}.
* To subscribe to state changes, use the {@link useState} method. The value returned by {@link useState} is updated after the component renders (similarly to React's useState).
* The values can be used directly (to avoid subscribing to the store) in effects or event handlers.
*
* Do not modify properties in state directly. Instead, use the provided methods to ensure proper state management and listener notification.
*/
// Internal state to handle recursive `setState()` calls
constructor(state) {
this.state = state;
this.listeners = new Set();
this.updateTick = 0;
}
/**
* Registers a listener that will be called whenever the store's state changes.
*
* @param fn The listener function to be called on state changes.
* @returns A function to unsubscribe the listener.
*/
subscribe = fn => {
this.listeners.add(fn);
return () => {
this.listeners.delete(fn);
};
};
/**
* Returns the current state of the store.
*/
getSnapshot = () => {
return this.state;
};
/**
* Updates the entire store's state and notifies all registered listeners.
*
* @param newState The new state to set for the store.
*/
setState(newState) {
if (this.state === newState) {
return;
}
this.state = newState;
this.updateTick += 1;
const currentTick = this.updateTick;
for (const listener of this.listeners) {
if (currentTick !== this.updateTick) {
// If the tick has changed, a recursive `setState` call has been made,
// and it has already notified all listeners.
return;
}
listener(newState);
}
}
/**
* Merges the provided changes into the current state and notifies listeners if there are changes.
*
* @param changes An object containing the changes to apply to the current state.
*/
update(changes) {
for (const key in changes) {
if (!Object.is(this.state[key], changes[key])) {
this.setState({
...this.state,
...changes
});
return;
}
}
}
/**
* Sets a specific key in the store's state to a new value and notifies listeners if the value has changed.
*
* @param key The key in the store's state to update.
* @param value The new value to set for the specified key.
*/
set(key, value) {
if (!Object.is(this.state[key], value)) {
this.setState({
...this.state,
[key]: value
});
}
}
/**
* Gives the state a new reference and updates all registered listeners.
*/
notifyAll() {
const newState = {
...this.state
};
this.setState(newState);
}
use(selector, a1, a2, a3) {
// eslint-disable-next-line react-hooks/rules-of-hooks
return (0, _useStore.useStore)(this, selector, a1, a2, a3);
}
}
exports.Store = Store;
+111
View File
@@ -0,0 +1,111 @@
import { useStore } from "./useStore.mjs";
/**
* A data store implementation that allows subscribing to state changes and updating the state.
* It uses an observer pattern to notify subscribers when the state changes.
*/
export class Store {
/**
* The current state of the store.
* This property is updated immediately when the state changes as a result of calling {@link setState}, {@link update}, or {@link set}.
* To subscribe to state changes, use the {@link useState} method. The value returned by {@link useState} is updated after the component renders (similarly to React's useState).
* The values can be used directly (to avoid subscribing to the store) in effects or event handlers.
*
* Do not modify properties in state directly. Instead, use the provided methods to ensure proper state management and listener notification.
*/
// Internal state to handle recursive `setState()` calls
constructor(state) {
this.state = state;
this.listeners = new Set();
this.updateTick = 0;
}
/**
* Registers a listener that will be called whenever the store's state changes.
*
* @param fn The listener function to be called on state changes.
* @returns A function to unsubscribe the listener.
*/
subscribe = fn => {
this.listeners.add(fn);
return () => {
this.listeners.delete(fn);
};
};
/**
* Returns the current state of the store.
*/
getSnapshot = () => {
return this.state;
};
/**
* Updates the entire store's state and notifies all registered listeners.
*
* @param newState The new state to set for the store.
*/
setState(newState) {
if (this.state === newState) {
return;
}
this.state = newState;
this.updateTick += 1;
const currentTick = this.updateTick;
for (const listener of this.listeners) {
if (currentTick !== this.updateTick) {
// If the tick has changed, a recursive `setState` call has been made,
// and it has already notified all listeners.
return;
}
listener(newState);
}
}
/**
* Merges the provided changes into the current state and notifies listeners if there are changes.
*
* @param changes An object containing the changes to apply to the current state.
*/
update(changes) {
for (const key in changes) {
if (!Object.is(this.state[key], changes[key])) {
this.setState({
...this.state,
...changes
});
return;
}
}
}
/**
* Sets a specific key in the store's state to a new value and notifies listeners if the value has changed.
*
* @param key The key in the store's state to update.
* @param value The new value to set for the specified key.
*/
set(key, value) {
if (!Object.is(this.state[key], value)) {
this.setState({
...this.state,
[key]: value
});
}
}
/**
* Gives the state a new reference and updates all registered listeners.
*/
notifyAll() {
const newState = {
...this.state
};
this.setState(newState);
}
use(selector, a1, a2, a3) {
// eslint-disable-next-line react-hooks/rules-of-hooks
return useStore(this, selector, a1, a2, a3);
}
}
+62
View File
@@ -0,0 +1,62 @@
import * as React from 'react';
import { Store } from "./Store.mjs";
/**
* Minimal shape of a store owner (such as a Base UI popup handle) that exposes a live store to
* inspect. Typed structurally so this dev utility stays decoupled from the component packages'
* handle types. The exposed store is loosely typed on purpose: handles narrow it for their public
* API, but at runtime it is a full `Store`, which the inspector casts to internally.
*/
export interface StoreOwner {
readonly store: object;
subscribeStore?(listener: () => void): () => void;
}
interface StoreInspectorBaseProps {
/**
* Additional data to display in the inspector.
*/
additionalData?: any;
/**
* Title to display in the panel header.
*/
title?: string | undefined;
/**
* Whether the inspector panel should be open by default.
* @default false
*/
defaultOpen?: boolean | undefined;
}
export type StoreInspectorProps = StoreInspectorBaseProps & ({
/**
* Instance of the store to inspect.
*/
store: Store<any>;
handle?: undefined;
} | {
/**
* A store owner (such as a Base UI popup handle) whose live `store` is inspected.
*/
handle: StoreOwner;
store?: undefined;
});
/**
* A tool to inspect the state of a Store in a floating panel.
* This is intended for development and debugging purposes.
*/
export declare function StoreInspector(props: StoreInspectorProps): import("react/jsx-runtime").JSX.Element;
interface PanelProps {
anchorElement: HTMLElement | null;
store: Store<any>;
title?: string | undefined;
additionalData?: any;
open: boolean;
onClose?: (() => void) | undefined;
}
export declare function StoreInspectorPanel({
anchorElement,
store,
title,
additionalData,
open,
onClose
}: PanelProps): React.ReactPortal | null;
export {};
+62
View File
@@ -0,0 +1,62 @@
import * as React from 'react';
import { Store } from "./Store.js";
/**
* Minimal shape of a store owner (such as a Base UI popup handle) that exposes a live store to
* inspect. Typed structurally so this dev utility stays decoupled from the component packages'
* handle types. The exposed store is loosely typed on purpose: handles narrow it for their public
* API, but at runtime it is a full `Store`, which the inspector casts to internally.
*/
export interface StoreOwner {
readonly store: object;
subscribeStore?(listener: () => void): () => void;
}
interface StoreInspectorBaseProps {
/**
* Additional data to display in the inspector.
*/
additionalData?: any;
/**
* Title to display in the panel header.
*/
title?: string | undefined;
/**
* Whether the inspector panel should be open by default.
* @default false
*/
defaultOpen?: boolean | undefined;
}
export type StoreInspectorProps = StoreInspectorBaseProps & ({
/**
* Instance of the store to inspect.
*/
store: Store<any>;
handle?: undefined;
} | {
/**
* A store owner (such as a Base UI popup handle) whose live `store` is inspected.
*/
handle: StoreOwner;
store?: undefined;
});
/**
* A tool to inspect the state of a Store in a floating panel.
* This is intended for development and debugging purposes.
*/
export declare function StoreInspector(props: StoreInspectorProps): import("react/jsx-runtime").JSX.Element;
interface PanelProps {
anchorElement: HTMLElement | null;
store: Store<any>;
title?: string | undefined;
additionalData?: any;
open: boolean;
onClose?: (() => void) | undefined;
}
export declare function StoreInspectorPanel({
anchorElement,
store,
title,
additionalData,
open,
onClose
}: PanelProps): React.ReactPortal | null;
export {};
+579
View File
@@ -0,0 +1,579 @@
"use strict";
'use client';
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.StoreInspector = StoreInspector;
exports.StoreInspectorPanel = StoreInspectorPanel;
var React = _interopRequireWildcard(require("react"));
var ReactDOM = _interopRequireWildcard(require("react-dom"));
var _dom = require("@floating-ui/utils/dom");
var _shim = require("use-sync-external-store/shim");
var _mergeCleanups = require("../mergeCleanups");
var _owner = require("../owner");
var _addEventListener = require("../addEventListener");
var _useForcedRerendering = require("../useForcedRerendering");
var _useStableCallback = require("../useStableCallback");
var _useAnimationFrame = require("../useAnimationFrame");
var _useIsoLayoutEffect = require("../useIsoLayoutEffect");
var _useTimeout = require("../useTimeout");
var _empty = require("../empty");
var _jsxRuntime = require("react/jsx-runtime");
var _style, _FileJson, _SquareTerminal, _h, _h2, _h3, _CloseIcon, _div, _svg, _svg2, _svg3;
const STYLES = `
.baseui-store-inspector-trigger {
all: unset;
width: 32px;
height: 32px;
display: inline-flex;
align-items: center;
justify-content: center;
color: oklch(0.651 0.078 264);
}
.baseui-store-inspector-trigger:hover,
.baseui-store-inspector-trigger:focus-visible {
opacity: 0.8;
}
.baseui-store-inspector-content {
background: #101010;
flex: 1 1 auto;
min-height: 0;
overflow: auto;
padding-bottom: 12px;
scrollbar-width: thin;
padding: 8px;
border-radius: 4px;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.baseui-store-inspector-content h3 {
text-transform: uppercase;
font-weight: bold;
}
.baseui-store-inspector-content pre {
margin: 0 0 16px 0;
}
.baseui-store-inspector-content pre:last-child {
margin-bottom: 0;
}
.baseui-store-inspector-root {
position: fixed;
background: oklch(0.34 0.036 264);
color: #fff;
z-index: 1000;
font-size: 12px;
padding: 8px;
border-radius: 8px;
display: flex;
flex-direction: column;
box-sizing: border-box;
max-width: 50vw;
color-scheme: dark;
overflow: clip;
box-shadow:
0 10px 15px -3px oklch(12% 9% 264deg / 8%),
0 4px 6px -4px oklch(12% 9% 264deg / 8%);
}
.baseui-store-inspector-header {
display: flex;
align-items: center;
cursor: move;
-webkit-user-select: none;
user-select: none;
touch-action: none;
padding: 4px 8px 8px 8px;
gap: 8px;
h2 {
font-size: 16px;
flex-grow: 1;
}
}
.baseui-store-inspector-header button {
all: unset;
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
cursor: default;
}
.baseui-store-inspector-header button:hover,
.baseui-store-inspector-header button:focus-visible {
opacity: 0.8;
}
.baseui-store-inspector-resize-handle {
position: absolute;
width: 8px;
height: 8px;
right: -4px;
bottom: -4px;
cursor: se-resize;
background: linear-gradient(135deg, transparent 50%, rgba(255, 255, 255, 0.25) 50%);
border-radius: 2px;
}
`;
function getTarget(event) {
if ('composedPath' in event) {
return event.composedPath()[0];
}
return event.target;
}
/**
* Minimal shape of a store owner (such as a Base UI popup handle) that exposes a live store to
* inspect. Typed structurally so this dev utility stays decoupled from the component packages'
* handle types. The exposed store is loosely typed on purpose: handles narrow it for their public
* API, but at runtime it is a full `Store`, which the inspector casts to internally.
*/
/**
* A tool to inspect the state of a Store in a floating panel.
* This is intended for development and debugging purposes.
*/
function StoreInspector(props) {
const {
title,
additionalData,
defaultOpen = false
} = props;
const store = useStoreInspectorStore(props);
const [open, setOpen] = React.useState(defaultOpen);
const triggerRef = React.useRef(null);
return /*#__PURE__*/(0, _jsxRuntime.jsxs)(React.Fragment, {
children: [_style || (_style = /*#__PURE__*/(0, _jsxRuntime.jsx)("style", {
href: "baseui-store-inspector",
precedence: "default",
children: STYLES
})), /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
ref: triggerRef,
className: "baseui-store-inspector-trigger",
type: "button",
onClick: event => {
event.preventDefault();
event.stopPropagation();
setOpen(o => !o);
},
title: "Toggle store inspector",
"aria-hidden": true,
children: _FileJson || (_FileJson = /*#__PURE__*/(0, _jsxRuntime.jsx)(FileJson, {}))
}), /*#__PURE__*/(0, _jsxRuntime.jsx)(StoreInspectorPanel, {
anchorElement: triggerRef.current,
open: open,
store: store,
title: title,
additionalData: additionalData,
onClose: () => setOpen(false)
})]
});
}
function useStoreInspectorStore(props) {
const handle = props.handle;
const store = props.store;
const subscribe = React.useCallback(listener => {
return handle?.subscribeStore?.(listener) ?? _empty.NOOP;
}, [handle]);
const getSnapshot = React.useCallback(() => {
// A handle exposes a narrowed store view for its public API; at runtime it is a full `Store`.
return store ?? handle?.store;
}, [handle, store]);
return (0, _shim.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
}
function StoreInspectorPanel({
anchorElement,
store,
title,
additionalData,
open,
onClose
}) {
const rerender = (0, _useForcedRerendering.useForcedRerendering)();
const rerenderTimeout = (0, _useTimeout.useTimeout)();
// Update when state changes
(0, _useIsoLayoutEffect.useIsoLayoutEffect)(() => {
const unsubscribe = store.subscribe(() => {
rerenderTimeout.start(1, () => rerender());
});
return unsubscribe;
}, [store, rerender, rerenderTimeout]);
const logToConsole = (0, _useStableCallback.useStableCallback)(() => {
const data = {
state: store.state
};
if (Object.keys(store.context ?? {}).length > 0) {
data.context = store.context;
}
if (additionalData !== undefined) {
data.additionalData = additionalData;
}
// eslint-disable-next-line no-console
console.log(data);
});
if (typeof document === 'undefined') {
return null;
}
const doc = (0, _owner.ownerDocument)(anchorElement);
const content = /*#__PURE__*/(0, _jsxRuntime.jsxs)(Window, {
title: title ?? 'Store Inspector',
onClose: onClose,
headerActions: /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
type: "button",
onClick: logToConsole,
title: "Log to console",
children: _SquareTerminal || (_SquareTerminal = /*#__PURE__*/(0, _jsxRuntime.jsx)(SquareTerminal, {}))
}),
children: [_h || (_h = /*#__PURE__*/(0, _jsxRuntime.jsx)("h3", {
children: "State"
})), /*#__PURE__*/(0, _jsxRuntime.jsx)("pre", {
children: JSON.stringify(store.state, getStringifyReplacer(), 2)
}), Object.keys(store.context ?? {}).length > 0 && /*#__PURE__*/(0, _jsxRuntime.jsxs)(React.Fragment, {
children: [_h2 || (_h2 = /*#__PURE__*/(0, _jsxRuntime.jsx)("h3", {
children: "Context"
})), /*#__PURE__*/(0, _jsxRuntime.jsx)("pre", {
children: JSON.stringify(store.context, getStringifyReplacer(), 2)
})]
}), additionalData !== undefined && /*#__PURE__*/(0, _jsxRuntime.jsxs)(React.Fragment, {
children: [_h3 || (_h3 = /*#__PURE__*/(0, _jsxRuntime.jsx)("h3", {
children: "Additional data"
})), /*#__PURE__*/(0, _jsxRuntime.jsx)("pre", {
children: JSON.stringify(additionalData, getStringifyReplacer(), 2)
})]
})]
});
return open ? /*#__PURE__*/ReactDOM.createPortal(content, doc.body) : null;
}
function getStringifyReplacer() {
const ancestors = [];
return function replacer(_, value) {
if ((0, _dom.isElement)(value)) {
return `Element(${value.tagName.toLowerCase()}${value.id ? `#${value.id}` : ''})`;
}
if (value === undefined) {
return '[undefined]';
}
if (value instanceof Map) {
return Array.from(value.entries());
}
if (value instanceof Set) {
return Array.from(value);
}
if (typeof value !== 'object' || value === null) {
return value;
}
// `this` is the object that value is contained in,
// i.e., its direct parent.
while (ancestors.length > 0 && ancestors.at(-1) !== this) {
ancestors.pop();
}
if (ancestors.includes(value)) {
return '[circular reference]';
}
ancestors.push(value);
return value;
};
}
/**
* A reusable draggable and resizable window component.
* Handles all the pointer events for dragging and resizing internally.
*/
function Window({
title,
onClose,
children,
headerActions
}) {
const rootRef = React.useRef(null);
const headerRef = React.useRef(null);
const resizeHandleRef = React.useRef(null);
const raf = (0, _useAnimationFrame.useAnimationFrame)();
const minWidth = 160;
const minHeight = 52;
// Track position when user drags the window
const [position, setPosition] = React.useState(null);
const dragStateRef = React.useRef(null);
// Track size when user resizes the window
const [size, setSize] = React.useState(null);
const resizeStateRef = React.useRef(null);
(0, _useIsoLayoutEffect.useIsoLayoutEffect)(() => {
if (position != null) {
return;
}
const el = rootRef.current;
if (!el) {
return;
}
setPosition({
left: 8,
top: 8
});
}, [position]);
const onPointerDown = (0, _useStableCallback.useStableCallback)(event => {
if (!headerRef.current || !rootRef.current) {
return;
}
const target = getTarget(event.nativeEvent);
if (target && target.closest('button')) {
return;
}
const currentPos = position ?? {
left: 8,
top: 8
};
dragStateRef.current = {
dragging: true,
startX: event.clientX,
startY: event.clientY,
startLeft: currentPos.left,
startTop: currentPos.top
};
try {
headerRef.current.setPointerCapture(event.pointerId);
} catch {
void 0;
}
event.preventDefault();
});
const endDrag = (0, _useStableCallback.useStableCallback)(event => {
if (headerRef.current && event) {
try {
headerRef.current.releasePointerCapture(event.pointerId);
} catch {
void 0;
}
}
if (dragStateRef.current) {
dragStateRef.current.dragging = false;
}
});
const onPointerMove = (0, _useStableCallback.useStableCallback)(event => {
const state = dragStateRef.current;
if (!state || !state.dragging) {
return;
}
const nextLeft = state.startLeft + (event.clientX - state.startX);
const nextTop = Math.max(0, state.startTop + (event.clientY - state.startY));
raf.request(() => {
setPosition({
left: nextLeft,
top: nextTop
});
});
});
const onResizePointerDown = (0, _useStableCallback.useStableCallback)(event => {
if (!rootRef.current) {
return;
}
const rect = rootRef.current.getBoundingClientRect();
const currentSize = size ?? {
width: rect.width,
height: rect.height
};
const currentLeft = position?.left ?? rect.left;
const currentTop = position?.top ?? rect.top;
const win = (0, _owner.ownerWindow)(rootRef.current);
const maxWidth = Math.max(100, win.innerWidth - currentLeft);
const maxHeight = Math.max(80, win.innerHeight - currentTop);
resizeStateRef.current = {
resizing: true,
startX: event.clientX,
startY: event.clientY,
startWidth: currentSize.width,
startHeight: currentSize.height,
minWidth,
minHeight,
maxWidth,
maxHeight
};
try {
event.currentTarget?.setPointerCapture?.(event.pointerId);
} catch {
void 0;
}
event.preventDefault();
});
const onResizePointerMove = (0, _useStableCallback.useStableCallback)(event => {
const state = resizeStateRef.current;
if (!state || !state.resizing) {
return;
}
const dx = event.clientX - state.startX;
const dy = event.clientY - state.startY;
const nextWidth = Math.min(state.maxWidth, Math.max(state.minWidth, state.startWidth + dx));
const nextHeight = Math.min(state.maxHeight, Math.max(state.minHeight, state.startHeight + dy));
raf.request(() => {
setSize({
width: nextWidth,
height: nextHeight
});
});
});
const endResize = (0, _useStableCallback.useStableCallback)(event => {
if (event) {
try {
getTarget(event)?.releasePointerCapture?.(event.pointerId);
} catch {
void 0;
}
}
if (resizeStateRef.current) {
resizeStateRef.current.resizing = false;
}
});
// Bind/unbind global listeners for dragging and resizing
(0, _useIsoLayoutEffect.useIsoLayoutEffect)(() => {
const win = (0, _owner.ownerWindow)(rootRef.current);
const move = event => {
onPointerMove(event);
onResizePointerMove(event);
};
const up = event => {
endDrag(event);
endResize(event);
};
return (0, _mergeCleanups.mergeCleanups)((0, _addEventListener.addEventListener)(win, 'pointermove', move), (0, _addEventListener.addEventListener)(win, 'pointerup', up), (0, _addEventListener.addEventListener)(win, 'pointercancel', up));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Compute window style once per render
const style = {};
let win = null;
if (rootRef.current) {
win = (0, _owner.ownerWindow)(rootRef.current);
} else if (typeof window !== 'undefined') {
win = window;
}
const viewportMax = win ? Math.max(0, win.innerHeight - 16) : undefined;
if (position) {
style.top = position.top;
style.left = position.left;
style.right = 'auto';
style.position = 'fixed';
if (size?.width != null) {
style.width = size.width;
}
if (size?.height != null) {
style.height = size.height;
}
style.maxHeight = win ? Math.max(0, win.innerHeight - position.top - 8) : undefined;
} else {
if (size?.width != null) {
style.width = size.width;
}
if (size?.height != null) {
style.height = size.height;
}
style.maxHeight = viewportMax;
}
return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
ref: rootRef,
className: "baseui-store-inspector-root",
style: style,
children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
ref: headerRef,
className: "baseui-store-inspector-header",
onPointerDown: onPointerDown,
children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("h2", {
children: title
}), headerActions, /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
type: "button",
onClick: onClose,
title: "Close window",
children: _CloseIcon || (_CloseIcon = /*#__PURE__*/(0, _jsxRuntime.jsx)(CloseIcon, {}))
})]
}), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
className: "baseui-store-inspector-content",
children: children
}), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
ref: resizeHandleRef,
onPointerDown: onResizePointerDown,
style: {
position: 'relative'
},
children: _div || (_div = /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
className: "baseui-store-inspector-resize-handle"
}))
})]
});
}
function CloseIcon() {
return _svg || (_svg = /*#__PURE__*/(0, _jsxRuntime.jsxs)("svg", {
width: "24",
height: "24",
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
strokeWidth: "2",
strokeLinecap: "round",
strokeLinejoin: "round",
children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("circle", {
cx: "12",
cy: "12",
r: "10"
}), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "m15 9-6 6"
}), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "m9 9 6 6"
})]
}));
}
function FileJson() {
return _svg2 || (_svg2 = /*#__PURE__*/(0, _jsxRuntime.jsxs)("svg", {
width: "24",
height: "24",
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
strokeWidth: "2",
strokeLinecap: "round",
strokeLinejoin: "round",
children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"
}), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M14 2v4a2 2 0 0 0 2 2h4"
}), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1"
}), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1"
})]
}));
}
function SquareTerminal() {
return _svg3 || (_svg3 = /*#__PURE__*/(0, _jsxRuntime.jsxs)("svg", {
width: "24",
height: "24",
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
strokeWidth: "2",
strokeLinecap: "round",
strokeLinejoin: "round",
children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "m7 11 2-2-2-2"
}), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M11 13h4"
}), /*#__PURE__*/(0, _jsxRuntime.jsx)("rect", {
width: "18",
height: "18",
x: "3",
y: "3",
rx: "2",
ry: "2"
})]
}));
}
+572
View File
@@ -0,0 +1,572 @@
'use client';
var _style, _FileJson, _SquareTerminal, _h, _h2, _h3, _CloseIcon, _div, _svg, _svg2, _svg3;
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { isElement } from '@floating-ui/utils/dom';
import { useSyncExternalStore } from 'use-sync-external-store/shim';
import { mergeCleanups } from "../mergeCleanups.mjs";
import { ownerDocument, ownerWindow } from "../owner.mjs";
import { addEventListener } from "../addEventListener.mjs";
import { useForcedRerendering } from "../useForcedRerendering.mjs";
import { useStableCallback } from "../useStableCallback.mjs";
import { useAnimationFrame } from "../useAnimationFrame.mjs";
import { useIsoLayoutEffect } from "../useIsoLayoutEffect.mjs";
import { useTimeout } from "../useTimeout.mjs";
import { NOOP } from "../empty.mjs";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const STYLES = `
.baseui-store-inspector-trigger {
all: unset;
width: 32px;
height: 32px;
display: inline-flex;
align-items: center;
justify-content: center;
color: oklch(0.651 0.078 264);
}
.baseui-store-inspector-trigger:hover,
.baseui-store-inspector-trigger:focus-visible {
opacity: 0.8;
}
.baseui-store-inspector-content {
background: #101010;
flex: 1 1 auto;
min-height: 0;
overflow: auto;
padding-bottom: 12px;
scrollbar-width: thin;
padding: 8px;
border-radius: 4px;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.baseui-store-inspector-content h3 {
text-transform: uppercase;
font-weight: bold;
}
.baseui-store-inspector-content pre {
margin: 0 0 16px 0;
}
.baseui-store-inspector-content pre:last-child {
margin-bottom: 0;
}
.baseui-store-inspector-root {
position: fixed;
background: oklch(0.34 0.036 264);
color: #fff;
z-index: 1000;
font-size: 12px;
padding: 8px;
border-radius: 8px;
display: flex;
flex-direction: column;
box-sizing: border-box;
max-width: 50vw;
color-scheme: dark;
overflow: clip;
box-shadow:
0 10px 15px -3px oklch(12% 9% 264deg / 8%),
0 4px 6px -4px oklch(12% 9% 264deg / 8%);
}
.baseui-store-inspector-header {
display: flex;
align-items: center;
cursor: move;
-webkit-user-select: none;
user-select: none;
touch-action: none;
padding: 4px 8px 8px 8px;
gap: 8px;
h2 {
font-size: 16px;
flex-grow: 1;
}
}
.baseui-store-inspector-header button {
all: unset;
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
cursor: default;
}
.baseui-store-inspector-header button:hover,
.baseui-store-inspector-header button:focus-visible {
opacity: 0.8;
}
.baseui-store-inspector-resize-handle {
position: absolute;
width: 8px;
height: 8px;
right: -4px;
bottom: -4px;
cursor: se-resize;
background: linear-gradient(135deg, transparent 50%, rgba(255, 255, 255, 0.25) 50%);
border-radius: 2px;
}
`;
function getTarget(event) {
if ('composedPath' in event) {
return event.composedPath()[0];
}
return event.target;
}
/**
* Minimal shape of a store owner (such as a Base UI popup handle) that exposes a live store to
* inspect. Typed structurally so this dev utility stays decoupled from the component packages'
* handle types. The exposed store is loosely typed on purpose: handles narrow it for their public
* API, but at runtime it is a full `Store`, which the inspector casts to internally.
*/
/**
* A tool to inspect the state of a Store in a floating panel.
* This is intended for development and debugging purposes.
*/
export function StoreInspector(props) {
const {
title,
additionalData,
defaultOpen = false
} = props;
const store = useStoreInspectorStore(props);
const [open, setOpen] = React.useState(defaultOpen);
const triggerRef = React.useRef(null);
return /*#__PURE__*/_jsxs(React.Fragment, {
children: [_style || (_style = /*#__PURE__*/_jsx("style", {
href: "baseui-store-inspector",
precedence: "default",
children: STYLES
})), /*#__PURE__*/_jsx("button", {
ref: triggerRef,
className: "baseui-store-inspector-trigger",
type: "button",
onClick: event => {
event.preventDefault();
event.stopPropagation();
setOpen(o => !o);
},
title: "Toggle store inspector",
"aria-hidden": true,
children: _FileJson || (_FileJson = /*#__PURE__*/_jsx(FileJson, {}))
}), /*#__PURE__*/_jsx(StoreInspectorPanel, {
anchorElement: triggerRef.current,
open: open,
store: store,
title: title,
additionalData: additionalData,
onClose: () => setOpen(false)
})]
});
}
function useStoreInspectorStore(props) {
const handle = props.handle;
const store = props.store;
const subscribe = React.useCallback(listener => {
return handle?.subscribeStore?.(listener) ?? NOOP;
}, [handle]);
const getSnapshot = React.useCallback(() => {
// A handle exposes a narrowed store view for its public API; at runtime it is a full `Store`.
return store ?? handle?.store;
}, [handle, store]);
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
}
export function StoreInspectorPanel({
anchorElement,
store,
title,
additionalData,
open,
onClose
}) {
const rerender = useForcedRerendering();
const rerenderTimeout = useTimeout();
// Update when state changes
useIsoLayoutEffect(() => {
const unsubscribe = store.subscribe(() => {
rerenderTimeout.start(1, () => rerender());
});
return unsubscribe;
}, [store, rerender, rerenderTimeout]);
const logToConsole = useStableCallback(() => {
const data = {
state: store.state
};
if (Object.keys(store.context ?? {}).length > 0) {
data.context = store.context;
}
if (additionalData !== undefined) {
data.additionalData = additionalData;
}
// eslint-disable-next-line no-console
console.log(data);
});
if (typeof document === 'undefined') {
return null;
}
const doc = ownerDocument(anchorElement);
const content = /*#__PURE__*/_jsxs(Window, {
title: title ?? 'Store Inspector',
onClose: onClose,
headerActions: /*#__PURE__*/_jsx("button", {
type: "button",
onClick: logToConsole,
title: "Log to console",
children: _SquareTerminal || (_SquareTerminal = /*#__PURE__*/_jsx(SquareTerminal, {}))
}),
children: [_h || (_h = /*#__PURE__*/_jsx("h3", {
children: "State"
})), /*#__PURE__*/_jsx("pre", {
children: JSON.stringify(store.state, getStringifyReplacer(), 2)
}), Object.keys(store.context ?? {}).length > 0 && /*#__PURE__*/_jsxs(React.Fragment, {
children: [_h2 || (_h2 = /*#__PURE__*/_jsx("h3", {
children: "Context"
})), /*#__PURE__*/_jsx("pre", {
children: JSON.stringify(store.context, getStringifyReplacer(), 2)
})]
}), additionalData !== undefined && /*#__PURE__*/_jsxs(React.Fragment, {
children: [_h3 || (_h3 = /*#__PURE__*/_jsx("h3", {
children: "Additional data"
})), /*#__PURE__*/_jsx("pre", {
children: JSON.stringify(additionalData, getStringifyReplacer(), 2)
})]
})]
});
return open ? /*#__PURE__*/ReactDOM.createPortal(content, doc.body) : null;
}
function getStringifyReplacer() {
const ancestors = [];
return function replacer(_, value) {
if (isElement(value)) {
return `Element(${value.tagName.toLowerCase()}${value.id ? `#${value.id}` : ''})`;
}
if (value === undefined) {
return '[undefined]';
}
if (value instanceof Map) {
return Array.from(value.entries());
}
if (value instanceof Set) {
return Array.from(value);
}
if (typeof value !== 'object' || value === null) {
return value;
}
// `this` is the object that value is contained in,
// i.e., its direct parent.
while (ancestors.length > 0 && ancestors.at(-1) !== this) {
ancestors.pop();
}
if (ancestors.includes(value)) {
return '[circular reference]';
}
ancestors.push(value);
return value;
};
}
/**
* A reusable draggable and resizable window component.
* Handles all the pointer events for dragging and resizing internally.
*/
function Window({
title,
onClose,
children,
headerActions
}) {
const rootRef = React.useRef(null);
const headerRef = React.useRef(null);
const resizeHandleRef = React.useRef(null);
const raf = useAnimationFrame();
const minWidth = 160;
const minHeight = 52;
// Track position when user drags the window
const [position, setPosition] = React.useState(null);
const dragStateRef = React.useRef(null);
// Track size when user resizes the window
const [size, setSize] = React.useState(null);
const resizeStateRef = React.useRef(null);
useIsoLayoutEffect(() => {
if (position != null) {
return;
}
const el = rootRef.current;
if (!el) {
return;
}
setPosition({
left: 8,
top: 8
});
}, [position]);
const onPointerDown = useStableCallback(event => {
if (!headerRef.current || !rootRef.current) {
return;
}
const target = getTarget(event.nativeEvent);
if (target && target.closest('button')) {
return;
}
const currentPos = position ?? {
left: 8,
top: 8
};
dragStateRef.current = {
dragging: true,
startX: event.clientX,
startY: event.clientY,
startLeft: currentPos.left,
startTop: currentPos.top
};
try {
headerRef.current.setPointerCapture(event.pointerId);
} catch {
void 0;
}
event.preventDefault();
});
const endDrag = useStableCallback(event => {
if (headerRef.current && event) {
try {
headerRef.current.releasePointerCapture(event.pointerId);
} catch {
void 0;
}
}
if (dragStateRef.current) {
dragStateRef.current.dragging = false;
}
});
const onPointerMove = useStableCallback(event => {
const state = dragStateRef.current;
if (!state || !state.dragging) {
return;
}
const nextLeft = state.startLeft + (event.clientX - state.startX);
const nextTop = Math.max(0, state.startTop + (event.clientY - state.startY));
raf.request(() => {
setPosition({
left: nextLeft,
top: nextTop
});
});
});
const onResizePointerDown = useStableCallback(event => {
if (!rootRef.current) {
return;
}
const rect = rootRef.current.getBoundingClientRect();
const currentSize = size ?? {
width: rect.width,
height: rect.height
};
const currentLeft = position?.left ?? rect.left;
const currentTop = position?.top ?? rect.top;
const win = ownerWindow(rootRef.current);
const maxWidth = Math.max(100, win.innerWidth - currentLeft);
const maxHeight = Math.max(80, win.innerHeight - currentTop);
resizeStateRef.current = {
resizing: true,
startX: event.clientX,
startY: event.clientY,
startWidth: currentSize.width,
startHeight: currentSize.height,
minWidth,
minHeight,
maxWidth,
maxHeight
};
try {
event.currentTarget?.setPointerCapture?.(event.pointerId);
} catch {
void 0;
}
event.preventDefault();
});
const onResizePointerMove = useStableCallback(event => {
const state = resizeStateRef.current;
if (!state || !state.resizing) {
return;
}
const dx = event.clientX - state.startX;
const dy = event.clientY - state.startY;
const nextWidth = Math.min(state.maxWidth, Math.max(state.minWidth, state.startWidth + dx));
const nextHeight = Math.min(state.maxHeight, Math.max(state.minHeight, state.startHeight + dy));
raf.request(() => {
setSize({
width: nextWidth,
height: nextHeight
});
});
});
const endResize = useStableCallback(event => {
if (event) {
try {
getTarget(event)?.releasePointerCapture?.(event.pointerId);
} catch {
void 0;
}
}
if (resizeStateRef.current) {
resizeStateRef.current.resizing = false;
}
});
// Bind/unbind global listeners for dragging and resizing
useIsoLayoutEffect(() => {
const win = ownerWindow(rootRef.current);
const move = event => {
onPointerMove(event);
onResizePointerMove(event);
};
const up = event => {
endDrag(event);
endResize(event);
};
return mergeCleanups(addEventListener(win, 'pointermove', move), addEventListener(win, 'pointerup', up), addEventListener(win, 'pointercancel', up));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Compute window style once per render
const style = {};
let win = null;
if (rootRef.current) {
win = ownerWindow(rootRef.current);
} else if (typeof window !== 'undefined') {
win = window;
}
const viewportMax = win ? Math.max(0, win.innerHeight - 16) : undefined;
if (position) {
style.top = position.top;
style.left = position.left;
style.right = 'auto';
style.position = 'fixed';
if (size?.width != null) {
style.width = size.width;
}
if (size?.height != null) {
style.height = size.height;
}
style.maxHeight = win ? Math.max(0, win.innerHeight - position.top - 8) : undefined;
} else {
if (size?.width != null) {
style.width = size.width;
}
if (size?.height != null) {
style.height = size.height;
}
style.maxHeight = viewportMax;
}
return /*#__PURE__*/_jsxs("div", {
ref: rootRef,
className: "baseui-store-inspector-root",
style: style,
children: [/*#__PURE__*/_jsxs("div", {
ref: headerRef,
className: "baseui-store-inspector-header",
onPointerDown: onPointerDown,
children: [/*#__PURE__*/_jsx("h2", {
children: title
}), headerActions, /*#__PURE__*/_jsx("button", {
type: "button",
onClick: onClose,
title: "Close window",
children: _CloseIcon || (_CloseIcon = /*#__PURE__*/_jsx(CloseIcon, {}))
})]
}), /*#__PURE__*/_jsx("div", {
className: "baseui-store-inspector-content",
children: children
}), /*#__PURE__*/_jsx("div", {
ref: resizeHandleRef,
onPointerDown: onResizePointerDown,
style: {
position: 'relative'
},
children: _div || (_div = /*#__PURE__*/_jsx("div", {
className: "baseui-store-inspector-resize-handle"
}))
})]
});
}
function CloseIcon() {
return _svg || (_svg = /*#__PURE__*/_jsxs("svg", {
width: "24",
height: "24",
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
strokeWidth: "2",
strokeLinecap: "round",
strokeLinejoin: "round",
children: [/*#__PURE__*/_jsx("circle", {
cx: "12",
cy: "12",
r: "10"
}), /*#__PURE__*/_jsx("path", {
d: "m15 9-6 6"
}), /*#__PURE__*/_jsx("path", {
d: "m9 9 6 6"
})]
}));
}
function FileJson() {
return _svg2 || (_svg2 = /*#__PURE__*/_jsxs("svg", {
width: "24",
height: "24",
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
strokeWidth: "2",
strokeLinecap: "round",
strokeLinejoin: "round",
children: [/*#__PURE__*/_jsx("path", {
d: "M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"
}), /*#__PURE__*/_jsx("path", {
d: "M14 2v4a2 2 0 0 0 2 2h4"
}), /*#__PURE__*/_jsx("path", {
d: "M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1"
}), /*#__PURE__*/_jsx("path", {
d: "M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1"
})]
}));
}
function SquareTerminal() {
return _svg3 || (_svg3 = /*#__PURE__*/_jsxs("svg", {
width: "24",
height: "24",
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
strokeWidth: "2",
strokeLinecap: "round",
strokeLinejoin: "round",
children: [/*#__PURE__*/_jsx("path", {
d: "m7 11 2-2-2-2"
}), /*#__PURE__*/_jsx("path", {
d: "M11 13h4"
}), /*#__PURE__*/_jsx("rect", {
width: "18",
height: "18",
x: "3",
y: "3",
rx: "2",
ry: "2"
})]
}));
}
+41
View File
@@ -0,0 +1,41 @@
import type { Selector } from 'reselect';
type Fn = (...args: any[]) => any;
/**
* The NoOptionalParams type is a utility type that checks if a function has optional or default parameters.
* If the function has optional or default parameters, it returns a string literal type with an error message.
* Otherwise, it returns the original function type.
*
* This is used to enforce that the combiner function passed to createSelector does not have optional or default parameters,
* as memoization relies on the Function.length property, which does not account for optional or default parameters.
*/
type NoOptionalParams<F extends Fn> = Parameters<F> extends Required<Parameters<F>> ? F : 'Combiner cannot have optional or default parameters because memoization relies on Function.length';
export type CreateSelectorFunction = <const Args extends any[], const Selectors extends ReadonlyArray<Selector<any>>, const Combiner extends (...args: readonly [...ReturnTypes<Selectors>, ...Args]) => any>(...items: [...Selectors, NoOptionalParams<Combiner>]) => (...args: Selectors['length'] extends 0 ? MergeParams<ReturnTypes<Selectors>, Parameters<Combiner>> : [StateFromSelectorList<Selectors>, ...MergeParams<ReturnTypes<Selectors>, Parameters<Combiner>>]) => ReturnType<Combiner>;
type StateFromSelectorList<Selectors extends readonly any[]> = Selectors extends [f: infer F, ...other: infer R] ? StateFromSelector<F> extends StateFromSelectorList<R> ? StateFromSelector<F> : StateFromSelectorList<R> : {};
type StateFromSelector<T> = T extends ((first: infer F, ...args: any[]) => any) ? F : never;
type DropFirst<T> = T extends [any, ...infer Xs] ? Xs : [];
type ReturnTypes<FunctionsArray extends readonly Fn[]> = { [Index in keyof FunctionsArray]: FunctionsArray[Index] extends FunctionsArray[number] ? ReturnType<FunctionsArray[Index]> : never };
type MergeParams<STypes extends readonly unknown[], CTypes extends readonly unknown[]> = STypes['length'] extends 0 ? CTypes : MergeParams<DropFirst<STypes>, DropFirst<CTypes>>;
/**
* Creates a selector function that can be used to derive values from the store's state.
*
* The combiner function can have up to three additional parameters, but it **cannot have optional or default parameters**.
*
* This function accepts up to six functions and combines them into a single selector function.
* The resulting selector will take the state from the combined selectors and any additional parameters required by the combiner.
*
* The return type of the resulting selector is determined by the return type of the combiner function.
*
* @example
* const selector = createSelector(
* (state) => state.disabled
* );
*
* @example
* const selector = createSelector(
* (state) => state.disabled,
* (state) => state.open,
* (disabled, open) => ({ disabled, open })
* );
*/
export declare const createSelector: CreateSelectorFunction;
export {};
+41
View File
@@ -0,0 +1,41 @@
import type { Selector } from 'reselect';
type Fn = (...args: any[]) => any;
/**
* The NoOptionalParams type is a utility type that checks if a function has optional or default parameters.
* If the function has optional or default parameters, it returns a string literal type with an error message.
* Otherwise, it returns the original function type.
*
* This is used to enforce that the combiner function passed to createSelector does not have optional or default parameters,
* as memoization relies on the Function.length property, which does not account for optional or default parameters.
*/
type NoOptionalParams<F extends Fn> = Parameters<F> extends Required<Parameters<F>> ? F : 'Combiner cannot have optional or default parameters because memoization relies on Function.length';
export type CreateSelectorFunction = <const Args extends any[], const Selectors extends ReadonlyArray<Selector<any>>, const Combiner extends (...args: readonly [...ReturnTypes<Selectors>, ...Args]) => any>(...items: [...Selectors, NoOptionalParams<Combiner>]) => (...args: Selectors['length'] extends 0 ? MergeParams<ReturnTypes<Selectors>, Parameters<Combiner>> : [StateFromSelectorList<Selectors>, ...MergeParams<ReturnTypes<Selectors>, Parameters<Combiner>>]) => ReturnType<Combiner>;
type StateFromSelectorList<Selectors extends readonly any[]> = Selectors extends [f: infer F, ...other: infer R] ? StateFromSelector<F> extends StateFromSelectorList<R> ? StateFromSelector<F> : StateFromSelectorList<R> : {};
type StateFromSelector<T> = T extends ((first: infer F, ...args: any[]) => any) ? F : never;
type DropFirst<T> = T extends [any, ...infer Xs] ? Xs : [];
type ReturnTypes<FunctionsArray extends readonly Fn[]> = { [Index in keyof FunctionsArray]: FunctionsArray[Index] extends FunctionsArray[number] ? ReturnType<FunctionsArray[Index]> : never };
type MergeParams<STypes extends readonly unknown[], CTypes extends readonly unknown[]> = STypes['length'] extends 0 ? CTypes : MergeParams<DropFirst<STypes>, DropFirst<CTypes>>;
/**
* Creates a selector function that can be used to derive values from the store's state.
*
* The combiner function can have up to three additional parameters, but it **cannot have optional or default parameters**.
*
* This function accepts up to six functions and combines them into a single selector function.
* The resulting selector will take the state from the combined selectors and any additional parameters required by the combiner.
*
* The return type of the resulting selector is determined by the return type of the combiner function.
*
* @example
* const selector = createSelector(
* (state) => state.disabled
* );
*
* @example
* const selector = createSelector(
* (state) => state.disabled,
* (state) => state.open,
* (disabled, open) => ({ disabled, open })
* );
*/
export declare const createSelector: CreateSelectorFunction;
export {};
+89
View File
@@ -0,0 +1,89 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createSelector = void 0;
var _formatErrorMessage2 = _interopRequireDefault(require("../formatErrorMessage.js"));
/**
* The NoOptionalParams type is a utility type that checks if a function has optional or default parameters.
* If the function has optional or default parameters, it returns a string literal type with an error message.
* Otherwise, it returns the original function type.
*
* This is used to enforce that the combiner function passed to createSelector does not have optional or default parameters,
* as memoization relies on the Function.length property, which does not account for optional or default parameters.
*/
/**
* Creates a selector function that can be used to derive values from the store's state.
*
* The combiner function can have up to three additional parameters, but it **cannot have optional or default parameters**.
*
* This function accepts up to six functions and combines them into a single selector function.
* The resulting selector will take the state from the combined selectors and any additional parameters required by the combiner.
*
* The return type of the resulting selector is determined by the return type of the combiner function.
*
* @example
* const selector = createSelector(
* (state) => state.disabled
* );
*
* @example
* const selector = createSelector(
* (state) => state.disabled,
* (state) => state.open,
* (disabled, open) => ({ disabled, open })
* );
*/
/* eslint-disable id-denylist */
const createSelector = (a, b, c, d, e, f, ...other) => {
if (other.length > 0) {
throw new Error(process.env.NODE_ENV !== "production" ? 'Unsupported number of selectors' : (0, _formatErrorMessage2.default)(1));
}
let selector;
if (a && b && c && d && e && f) {
selector = (state, a1, a2, a3) => {
const va = a(state, a1, a2, a3);
const vb = b(state, a1, a2, a3);
const vc = c(state, a1, a2, a3);
const vd = d(state, a1, a2, a3);
const ve = e(state, a1, a2, a3);
return f(va, vb, vc, vd, ve, a1, a2, a3);
};
} else if (a && b && c && d && e) {
selector = (state, a1, a2, a3) => {
const va = a(state, a1, a2, a3);
const vb = b(state, a1, a2, a3);
const vc = c(state, a1, a2, a3);
const vd = d(state, a1, a2, a3);
return e(va, vb, vc, vd, a1, a2, a3);
};
} else if (a && b && c && d) {
selector = (state, a1, a2, a3) => {
const va = a(state, a1, a2, a3);
const vb = b(state, a1, a2, a3);
const vc = c(state, a1, a2, a3);
return d(va, vb, vc, a1, a2, a3);
};
} else if (a && b && c) {
selector = (state, a1, a2, a3) => {
const va = a(state, a1, a2, a3);
const vb = b(state, a1, a2, a3);
return c(va, vb, a1, a2, a3);
};
} else if (a && b) {
selector = (state, a1, a2, a3) => {
const va = a(state, a1, a2, a3);
return b(va, a1, a2, a3);
};
} else if (a) {
selector = a;
} else {
throw /* minify-error-disabled */new Error('Missing arguments');
}
return selector;
};
/* eslint-enable id-denylist */
exports.createSelector = createSelector;
+81
View File
@@ -0,0 +1,81 @@
import _formatErrorMessage from "../formatErrorMessage.mjs";
/**
* The NoOptionalParams type is a utility type that checks if a function has optional or default parameters.
* If the function has optional or default parameters, it returns a string literal type with an error message.
* Otherwise, it returns the original function type.
*
* This is used to enforce that the combiner function passed to createSelector does not have optional or default parameters,
* as memoization relies on the Function.length property, which does not account for optional or default parameters.
*/
/**
* Creates a selector function that can be used to derive values from the store's state.
*
* The combiner function can have up to three additional parameters, but it **cannot have optional or default parameters**.
*
* This function accepts up to six functions and combines them into a single selector function.
* The resulting selector will take the state from the combined selectors and any additional parameters required by the combiner.
*
* The return type of the resulting selector is determined by the return type of the combiner function.
*
* @example
* const selector = createSelector(
* (state) => state.disabled
* );
*
* @example
* const selector = createSelector(
* (state) => state.disabled,
* (state) => state.open,
* (disabled, open) => ({ disabled, open })
* );
*/
/* eslint-disable id-denylist */
export const createSelector = (a, b, c, d, e, f, ...other) => {
if (other.length > 0) {
throw new Error(process.env.NODE_ENV !== "production" ? 'Unsupported number of selectors' : _formatErrorMessage(1));
}
let selector;
if (a && b && c && d && e && f) {
selector = (state, a1, a2, a3) => {
const va = a(state, a1, a2, a3);
const vb = b(state, a1, a2, a3);
const vc = c(state, a1, a2, a3);
const vd = d(state, a1, a2, a3);
const ve = e(state, a1, a2, a3);
return f(va, vb, vc, vd, ve, a1, a2, a3);
};
} else if (a && b && c && d && e) {
selector = (state, a1, a2, a3) => {
const va = a(state, a1, a2, a3);
const vb = b(state, a1, a2, a3);
const vc = c(state, a1, a2, a3);
const vd = d(state, a1, a2, a3);
return e(va, vb, vc, vd, a1, a2, a3);
};
} else if (a && b && c && d) {
selector = (state, a1, a2, a3) => {
const va = a(state, a1, a2, a3);
const vb = b(state, a1, a2, a3);
const vc = c(state, a1, a2, a3);
return d(va, vb, vc, a1, a2, a3);
};
} else if (a && b && c) {
selector = (state, a1, a2, a3) => {
const va = a(state, a1, a2, a3);
const vb = b(state, a1, a2, a3);
return c(va, vb, a1, a2, a3);
};
} else if (a && b) {
selector = (state, a1, a2, a3) => {
const va = a(state, a1, a2, a3);
return b(va, a1, a2, a3);
};
} else if (a) {
selector = a;
} else {
throw /* minify-error-disabled */new Error('Missing arguments');
}
return selector;
};
/* eslint-enable id-denylist */
@@ -0,0 +1,2 @@
import type { CreateSelectorFunction } from "./createSelector.mjs";
export declare const createSelectorMemoized: CreateSelectorFunction;
@@ -0,0 +1,2 @@
import type { CreateSelectorFunction } from "./createSelector.js";
export declare const createSelectorMemoized: CreateSelectorFunction;
+85
View File
@@ -0,0 +1,85 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createSelectorMemoized = void 0;
var _formatErrorMessage2 = _interopRequireDefault(require("../formatErrorMessage.js"));
var _reselect = require("reselect");
/* eslint-disable no-underscore-dangle */ // __cacheKey__
const reselectCreateSelector = (0, _reselect.createSelectorCreator)({
memoize: _reselect.lruMemoize,
memoizeOptions: {
maxSize: 1,
equalityCheck: Object.is
}
});
const createSelectorMemoized = (...selectors) => {
const cache = new WeakMap();
let nextCacheId = 1;
const combiner = selectors[selectors.length - 1];
const nSelectors = selectors.length - 1 || 1;
// (s1, s2, ..., sN, a1, a2, a3) => { ... }
const argsLength = combiner.length - nSelectors;
if (argsLength > 3) {
throw new Error(process.env.NODE_ENV !== "production" ? 'Unsupported number of arguments' : (0, _formatErrorMessage2.default)(2));
}
const selector = (state, a1, a2, a3) => {
let cacheKey = state.__cacheKey__;
if (!cacheKey) {
cacheKey = {
id: nextCacheId
};
state.__cacheKey__ = cacheKey;
nextCacheId += 1;
}
let fn = cache.get(cacheKey);
if (!fn) {
let reselectArgs = selectors;
const selectorArgs = [undefined, undefined, undefined];
switch (argsLength) {
case 0:
break;
case 1:
{
reselectArgs = [...selectors.slice(0, -1), () => selectorArgs[0], combiner];
break;
}
case 2:
{
reselectArgs = [...selectors.slice(0, -1), () => selectorArgs[0], () => selectorArgs[1], combiner];
break;
}
case 3:
{
reselectArgs = [...selectors.slice(0, -1), () => selectorArgs[0], () => selectorArgs[1], () => selectorArgs[2], combiner];
break;
}
default:
throw new Error(process.env.NODE_ENV !== "production" ? 'Unsupported number of arguments' : (0, _formatErrorMessage2.default)(2));
}
fn = reselectCreateSelector(...reselectArgs);
fn.selectorArgs = selectorArgs;
cache.set(cacheKey, fn);
}
fn.selectorArgs[0] = a1;
fn.selectorArgs[1] = a2;
fn.selectorArgs[2] = a3;
switch (argsLength) {
case 0:
return fn(state);
case 1:
return fn(state, a1);
case 2:
return fn(state, a1, a2);
case 3:
return fn(state, a1, a2, a3);
default:
throw /* minify-error-disabled */new Error('unreachable');
}
};
return selector;
};
exports.createSelectorMemoized = createSelectorMemoized;
+77
View File
@@ -0,0 +1,77 @@
import _formatErrorMessage from "../formatErrorMessage.mjs";
import { lruMemoize, createSelectorCreator } from 'reselect';
/* eslint-disable no-underscore-dangle */ // __cacheKey__
const reselectCreateSelector = createSelectorCreator({
memoize: lruMemoize,
memoizeOptions: {
maxSize: 1,
equalityCheck: Object.is
}
});
export const createSelectorMemoized = (...selectors) => {
const cache = new WeakMap();
let nextCacheId = 1;
const combiner = selectors[selectors.length - 1];
const nSelectors = selectors.length - 1 || 1;
// (s1, s2, ..., sN, a1, a2, a3) => { ... }
const argsLength = combiner.length - nSelectors;
if (argsLength > 3) {
throw new Error(process.env.NODE_ENV !== "production" ? 'Unsupported number of arguments' : _formatErrorMessage(2));
}
const selector = (state, a1, a2, a3) => {
let cacheKey = state.__cacheKey__;
if (!cacheKey) {
cacheKey = {
id: nextCacheId
};
state.__cacheKey__ = cacheKey;
nextCacheId += 1;
}
let fn = cache.get(cacheKey);
if (!fn) {
let reselectArgs = selectors;
const selectorArgs = [undefined, undefined, undefined];
switch (argsLength) {
case 0:
break;
case 1:
{
reselectArgs = [...selectors.slice(0, -1), () => selectorArgs[0], combiner];
break;
}
case 2:
{
reselectArgs = [...selectors.slice(0, -1), () => selectorArgs[0], () => selectorArgs[1], combiner];
break;
}
case 3:
{
reselectArgs = [...selectors.slice(0, -1), () => selectorArgs[0], () => selectorArgs[1], () => selectorArgs[2], combiner];
break;
}
default:
throw new Error(process.env.NODE_ENV !== "production" ? 'Unsupported number of arguments' : _formatErrorMessage(2));
}
fn = reselectCreateSelector(...reselectArgs);
fn.selectorArgs = selectorArgs;
cache.set(cacheKey, fn);
}
fn.selectorArgs[0] = a1;
fn.selectorArgs[1] = a2;
fn.selectorArgs[2] = a3;
switch (argsLength) {
case 0:
return fn(state);
case 1:
return fn(state, a1);
case 2:
return fn(state, a1, a2);
case 3:
return fn(state, a1, a2, a3);
default:
throw /* minify-error-disabled */new Error('unreachable');
}
};
return selector;
};
+6
View File
@@ -0,0 +1,6 @@
export * from "./createSelector.mjs";
export * from "./createSelectorMemoized.mjs";
export * from "./useStore.mjs";
export * from "./Store.mjs";
export * from "./ReactStore.mjs";
export * from "./StoreInspector.mjs";
+6
View File
@@ -0,0 +1,6 @@
export * from "./createSelector.js";
export * from "./createSelectorMemoized.js";
export * from "./useStore.js";
export * from "./Store.js";
export * from "./ReactStore.js";
export * from "./StoreInspector.js";
+71
View File
@@ -0,0 +1,71 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createSelector = require("./createSelector");
Object.keys(_createSelector).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _createSelector[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _createSelector[key];
}
});
});
var _createSelectorMemoized = require("./createSelectorMemoized");
Object.keys(_createSelectorMemoized).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _createSelectorMemoized[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _createSelectorMemoized[key];
}
});
});
var _useStore = require("./useStore");
Object.keys(_useStore).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _useStore[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _useStore[key];
}
});
});
var _Store = require("./Store");
Object.keys(_Store).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _Store[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _Store[key];
}
});
});
var _ReactStore = require("./ReactStore");
Object.keys(_ReactStore).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _ReactStore[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _ReactStore[key];
}
});
});
var _StoreInspector = require("./StoreInspector");
Object.keys(_StoreInspector).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _StoreInspector[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _StoreInspector[key];
}
});
});
+6
View File
@@ -0,0 +1,6 @@
export * from "./createSelector.mjs";
export * from "./createSelectorMemoized.mjs";
export * from "./useStore.mjs";
export * from "./Store.mjs";
export * from "./ReactStore.mjs";
export * from "./StoreInspector.mjs";
+21
View File
@@ -0,0 +1,21 @@
import { Instance } from "../fastHooks.mjs";
import type { ReadonlyStore } from "./Store.mjs";
export declare function useStore<State, Value>(store: ReadonlyStore<State>, selector: (state: State) => Value): Value;
export declare function useStore<State, Value, A1>(store: ReadonlyStore<State>, selector: (state: State, a1: A1) => Value, a1: A1): Value;
export declare function useStore<State, Value, A1, A2>(store: ReadonlyStore<State>, selector: (state: State, a1: A1, a2: A2) => Value, a1: A1, a2: A2): Value;
export declare function useStore<State, Value, A1, A2, A3>(store: ReadonlyStore<State>, selector: (state: State, a1: A1, a2: A2, a3: A3) => Value, a1: A1, a2: A2, a3: A3): Value;
export type StoreInstance = Instance & {
syncIndex: number;
syncTick: number;
syncHooks: {
store: any;
selector: Function;
a1: unknown;
a2: unknown;
a3: unknown;
value: unknown;
}[];
didChangeStore: boolean;
subscribe: (onStoreChange: any) => () => void;
getSnapshot: () => unknown;
};
+21
View File
@@ -0,0 +1,21 @@
import { Instance } from "../fastHooks.js";
import type { ReadonlyStore } from "./Store.js";
export declare function useStore<State, Value>(store: ReadonlyStore<State>, selector: (state: State) => Value): Value;
export declare function useStore<State, Value, A1>(store: ReadonlyStore<State>, selector: (state: State, a1: A1) => Value, a1: A1): Value;
export declare function useStore<State, Value, A1, A2>(store: ReadonlyStore<State>, selector: (state: State, a1: A1, a2: A2) => Value, a1: A1, a2: A2): Value;
export declare function useStore<State, Value, A1, A2, A3>(store: ReadonlyStore<State>, selector: (state: State, a1: A1, a2: A2, a3: A3) => Value, a1: A1, a2: A2, a3: A3): Value;
export type StoreInstance = Instance & {
syncIndex: number;
syncTick: number;
syncHooks: {
store: any;
selector: Function;
a1: unknown;
a2: unknown;
a3: unknown;
value: unknown;
}[];
didChangeStore: boolean;
subscribe: (onStoreChange: any) => () => void;
getSnapshot: () => unknown;
};
+113
View File
@@ -0,0 +1,113 @@
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useStore = useStore;
var React = _interopRequireWildcard(require("react"));
var _shim = require("use-sync-external-store/shim");
var _withSelector = require("use-sync-external-store/shim/with-selector");
var _reactVersion = require("../reactVersion");
var _fastHooks = require("../fastHooks");
/* We need to import the shim because React 17 does not support the `useSyncExternalStore` API.
* More info: https://github.com/mui/mui-x/issues/18303#issuecomment-2958392341 */
/* Some tests fail in R18 with the raw useSyncExternalStore. It may be possible to make it work
* but for now we only enable it for R19+. */
const canUseRawUseSyncExternalStore = (0, _reactVersion.isReactVersionAtLeast)(19);
const useStoreImplementation = canUseRawUseSyncExternalStore ? useStoreFast : useStoreLegacy;
function useStore(store, selector, a1, a2, a3) {
return useStoreImplementation(store, selector, a1, a2, a3);
}
function useStoreR19(store, selector, a1, a2, a3) {
const getSelection = React.useCallback(() => selector(store.getSnapshot(), a1, a2, a3), [store, selector, a1, a2, a3]);
return (0, _shim.useSyncExternalStore)(store.subscribe, getSelection, getSelection);
}
(0, _fastHooks.register)({
before(instance) {
instance.syncIndex = 0;
if (!instance.didInitialize) {
instance.syncTick = 1;
instance.syncHooks = [];
instance.didChangeStore = true;
instance.getSnapshot = () => {
let didChange = false;
for (let i = 0; i < instance.syncHooks.length; i += 1) {
const hook = instance.syncHooks[i];
const value = hook.selector(hook.store.state, hook.a1, hook.a2, hook.a3);
if (!Object.is(hook.value, value)) {
didChange = true;
hook.value = value;
}
}
if (didChange) {
instance.syncTick += 1;
}
return instance.syncTick;
};
}
},
after(instance) {
if (instance.syncHooks.length > 0) {
if (instance.didChangeStore) {
instance.didChangeStore = false;
instance.subscribe = onStoreChange => {
const stores = new Set();
for (const hook of instance.syncHooks) {
stores.add(hook.store);
}
const unsubscribes = [];
for (const store of stores) {
unsubscribes.push(store.subscribe(onStoreChange));
}
return () => {
for (const unsubscribe of unsubscribes) {
unsubscribe();
}
};
};
}
// eslint-disable-next-line react-hooks/rules-of-hooks
(0, _shim.useSyncExternalStore)(instance.subscribe, instance.getSnapshot, instance.getSnapshot);
}
}
});
function useStoreFast(store, selector, a1, a2, a3) {
const instance = (0, _fastHooks.getInstance)();
if (!instance) {
// eslint-disable-next-line react-hooks/rules-of-hooks
return useStoreR19(store, selector, a1, a2, a3);
}
const index = instance.syncIndex;
instance.syncIndex += 1;
let hook;
if (!instance.didInitialize) {
hook = {
store,
selector,
a1,
a2,
a3,
value: selector(store.getSnapshot(), a1, a2, a3)
};
instance.syncHooks.push(hook);
} else {
hook = instance.syncHooks[index];
if (hook.store !== store || hook.selector !== selector || !Object.is(hook.a1, a1) || !Object.is(hook.a2, a2) || !Object.is(hook.a3, a3)) {
if (hook.store !== store) {
instance.didChangeStore = true;
}
hook.store = store;
hook.selector = selector;
hook.a1 = a1;
hook.a2 = a2;
hook.a3 = a3;
hook.value = selector(store.getSnapshot(), a1, a2, a3);
}
}
return hook.value;
}
function useStoreLegacy(store, selector, a1, a2, a3) {
return (0, _withSelector.useSyncExternalStoreWithSelector)(store.subscribe, store.getSnapshot, store.getSnapshot, state => selector(state, a1, a2, a3));
}
+105
View File
@@ -0,0 +1,105 @@
import * as React from 'react';
/* We need to import the shim because React 17 does not support the `useSyncExternalStore` API.
* More info: https://github.com/mui/mui-x/issues/18303#issuecomment-2958392341 */
import { useSyncExternalStore } from 'use-sync-external-store/shim';
import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector';
import { isReactVersionAtLeast } from "../reactVersion.mjs";
import { register, getInstance } from "../fastHooks.mjs";
/* Some tests fail in R18 with the raw useSyncExternalStore. It may be possible to make it work
* but for now we only enable it for R19+. */
const canUseRawUseSyncExternalStore = isReactVersionAtLeast(19);
const useStoreImplementation = canUseRawUseSyncExternalStore ? useStoreFast : useStoreLegacy;
export function useStore(store, selector, a1, a2, a3) {
return useStoreImplementation(store, selector, a1, a2, a3);
}
function useStoreR19(store, selector, a1, a2, a3) {
const getSelection = React.useCallback(() => selector(store.getSnapshot(), a1, a2, a3), [store, selector, a1, a2, a3]);
return useSyncExternalStore(store.subscribe, getSelection, getSelection);
}
register({
before(instance) {
instance.syncIndex = 0;
if (!instance.didInitialize) {
instance.syncTick = 1;
instance.syncHooks = [];
instance.didChangeStore = true;
instance.getSnapshot = () => {
let didChange = false;
for (let i = 0; i < instance.syncHooks.length; i += 1) {
const hook = instance.syncHooks[i];
const value = hook.selector(hook.store.state, hook.a1, hook.a2, hook.a3);
if (!Object.is(hook.value, value)) {
didChange = true;
hook.value = value;
}
}
if (didChange) {
instance.syncTick += 1;
}
return instance.syncTick;
};
}
},
after(instance) {
if (instance.syncHooks.length > 0) {
if (instance.didChangeStore) {
instance.didChangeStore = false;
instance.subscribe = onStoreChange => {
const stores = new Set();
for (const hook of instance.syncHooks) {
stores.add(hook.store);
}
const unsubscribes = [];
for (const store of stores) {
unsubscribes.push(store.subscribe(onStoreChange));
}
return () => {
for (const unsubscribe of unsubscribes) {
unsubscribe();
}
};
};
}
// eslint-disable-next-line react-hooks/rules-of-hooks
useSyncExternalStore(instance.subscribe, instance.getSnapshot, instance.getSnapshot);
}
}
});
function useStoreFast(store, selector, a1, a2, a3) {
const instance = getInstance();
if (!instance) {
// eslint-disable-next-line react-hooks/rules-of-hooks
return useStoreR19(store, selector, a1, a2, a3);
}
const index = instance.syncIndex;
instance.syncIndex += 1;
let hook;
if (!instance.didInitialize) {
hook = {
store,
selector,
a1,
a2,
a3,
value: selector(store.getSnapshot(), a1, a2, a3)
};
instance.syncHooks.push(hook);
} else {
hook = instance.syncHooks[index];
if (hook.store !== store || hook.selector !== selector || !Object.is(hook.a1, a1) || !Object.is(hook.a2, a2) || !Object.is(hook.a3, a3)) {
if (hook.store !== store) {
instance.didChangeStore = true;
}
hook.store = store;
hook.selector = selector;
hook.a1 = a1;
hook.a2 = a2;
hook.a3 = a3;
hook.value = selector(store.getSnapshot(), a1, a2, a3);
}
}
return hook.value;
}
function useStoreLegacy(store, selector, a1, a2, a3) {
return useSyncExternalStoreWithSelector(store.subscribe, store.getSnapshot, store.getSnapshot, state => selector(state, a1, a2, a3));
}