fluid-dnd
Version:
An agnostic drag and drop library to sort all kind of lists. With current support for vue, react and svelte
56 lines (55 loc) • 1.68 kB
JavaScript
import { useEffect, useRef, useState } from 'react';
// @ts-ignore
import { flushSync } from 'react-dom';
export function useReactListConfig(items, parent) {
const [itemsState, setItemsState] = useState(items);
const stateRef = useRef(itemsState);
useEffect(() => {
stateRef.current = itemsState;
}, [itemsState]);
function removeAtEvent(index, sync = false) {
const deletedItem = stateRef.current[index];
const removeCallback = () => {
setItemsState((prevItems) => [...prevItems.slice(0, index), ...prevItems.slice(index + 1)]);
};
if (sync) {
flushSync(removeCallback);
}
else {
removeCallback();
}
return deletedItem;
}
function insertEvent(index, value, sync = false) {
const insertCallback = () => {
setItemsState((prevItems) => {
return [...prevItems.slice(0, index), value, ...prevItems.slice(index)];
});
};
if (sync) {
flushSync(insertCallback);
}
else {
insertCallback();
}
}
function getLength() {
return itemsState.length;
}
function getValue(index) {
return itemsState[index];
}
function insertToListEmpty(config, index, value) {
import('../../core/events/insert').then(({ insertToListEmpty }) => {
insertToListEmpty(config, parent.current, index, value);
});
}
const actions = {
removeAtEvent,
insertEvent,
getLength,
getValue,
insertToListEmpty
};
return [itemsState, setItemsState, actions];
}