mirror of
https://github.com/Tria-plc/emaui.git
synced 2026-08-28 07:51:05 +00:00
106 lines
2.6 KiB
JavaScript
106 lines
2.6 KiB
JavaScript
'use client';
|
|
import { useState, useCallback, useMemo } from 'react';
|
|
|
|
function useListState(initialValue = []) {
|
|
const [state, setState] = useState(initialValue);
|
|
const append = useCallback((...items) => setState((current) => [...current, ...items]), []);
|
|
const prepend = useCallback((...items) => setState((current) => [...items, ...current]), []);
|
|
const insert = useCallback(
|
|
(index, ...items) => setState((current) => [...current.slice(0, index), ...items, ...current.slice(index)]),
|
|
[]
|
|
);
|
|
const apply = useCallback(
|
|
(fn) => setState((current) => current.map((item, index) => fn(item, index))),
|
|
[]
|
|
);
|
|
const remove = useCallback(
|
|
(...indices) => setState((current) => current.filter((_, index) => !indices.includes(index))),
|
|
[]
|
|
);
|
|
const pop = useCallback(
|
|
() => setState((current) => {
|
|
const cloned = [...current];
|
|
cloned.pop();
|
|
return cloned;
|
|
}),
|
|
[]
|
|
);
|
|
const shift = useCallback(
|
|
() => setState((current) => {
|
|
const cloned = [...current];
|
|
cloned.shift();
|
|
return cloned;
|
|
}),
|
|
[]
|
|
);
|
|
const reorder = useCallback(
|
|
({ from, to }) => setState((current) => {
|
|
const cloned = [...current];
|
|
const item = current[from];
|
|
cloned.splice(from, 1);
|
|
cloned.splice(to, 0, item);
|
|
return cloned;
|
|
}),
|
|
[]
|
|
);
|
|
const swap = useCallback(
|
|
({ from, to }) => setState((current) => {
|
|
const cloned = [...current];
|
|
const fromItem = cloned[from];
|
|
const toItem = cloned[to];
|
|
cloned.splice(to, 1, fromItem);
|
|
cloned.splice(from, 1, toItem);
|
|
return cloned;
|
|
}),
|
|
[]
|
|
);
|
|
const setItem = useCallback(
|
|
(index, item) => setState((current) => {
|
|
const cloned = [...current];
|
|
cloned[index] = item;
|
|
return cloned;
|
|
}),
|
|
[]
|
|
);
|
|
const setItemProp = useCallback(
|
|
(index, prop, value) => setState((current) => {
|
|
const cloned = [...current];
|
|
cloned[index] = { ...cloned[index], [prop]: value };
|
|
return cloned;
|
|
}),
|
|
[]
|
|
);
|
|
const applyWhere = useCallback(
|
|
(condition, fn) => setState(
|
|
(current) => current.map((item, index) => condition(item, index) ? fn(item, index) : item)
|
|
),
|
|
[]
|
|
);
|
|
const filter = useCallback((fn) => {
|
|
setState((current) => current.filter(fn));
|
|
}, []);
|
|
const handlers = useMemo(
|
|
() => ({
|
|
setState,
|
|
append,
|
|
prepend,
|
|
insert,
|
|
pop,
|
|
shift,
|
|
apply,
|
|
applyWhere,
|
|
remove,
|
|
reorder,
|
|
swap,
|
|
setItem,
|
|
setItemProp,
|
|
filter
|
|
}),
|
|
[]
|
|
);
|
|
return [state, handlers];
|
|
}
|
|
|
|
export { useListState };
|
|
//# sourceMappingURL=use-list-state.mjs.map
|