Group.mjs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. "use client";
  2. import { jsx } from 'react/jsx-runtime';
  3. import { invariant } from 'motion-utils';
  4. import { forwardRef, useRef, useEffect } from 'react';
  5. import { ReorderContext } from '../../context/ReorderContext.mjs';
  6. import { motion } from '../../render/components/motion/proxy.mjs';
  7. import { useConstant } from '../../utils/use-constant.mjs';
  8. import { checkReorder } from './utils/check-reorder.mjs';
  9. function ReorderGroupComponent({ children, as = "ul", axis = "y", onReorder, values, ...props }, externalRef) {
  10. const Component = useConstant(() => motion[as]);
  11. const order = [];
  12. const isReordering = useRef(false);
  13. invariant(Boolean(values), "Reorder.Group must be provided a values prop");
  14. const context = {
  15. axis,
  16. registerItem: (value, layout) => {
  17. // If the entry was already added, update it rather than adding it again
  18. const idx = order.findIndex((entry) => value === entry.value);
  19. if (idx !== -1) {
  20. order[idx].layout = layout[axis];
  21. }
  22. else {
  23. order.push({ value: value, layout: layout[axis] });
  24. }
  25. order.sort(compareMin);
  26. },
  27. updateOrder: (item, offset, velocity) => {
  28. if (isReordering.current)
  29. return;
  30. const newOrder = checkReorder(order, item, offset, velocity);
  31. if (order !== newOrder) {
  32. isReordering.current = true;
  33. onReorder(newOrder
  34. .map(getValue)
  35. .filter((value) => values.indexOf(value) !== -1));
  36. }
  37. },
  38. };
  39. useEffect(() => {
  40. isReordering.current = false;
  41. });
  42. return (jsx(Component, { ...props, ref: externalRef, ignoreStrict: true, children: jsx(ReorderContext.Provider, { value: context, children: children }) }));
  43. }
  44. const ReorderGroup = /*@__PURE__*/ forwardRef(ReorderGroupComponent);
  45. function getValue(item) {
  46. return item.value;
  47. }
  48. function compareMin(a, b) {
  49. return a.layout.min - b.layout.min;
  50. }
  51. export { ReorderGroup, ReorderGroupComponent };