@weser/dnd 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022-present Robin Weser
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,22 @@
1
+ # @weser/dnd
2
+
3
+ <img alt="npm version" src="https://badge.fury.io/js/@weser/dnd.svg"> <img alt="npm downloads" src="https://img.shields.io/npm/dm/@weser/dnd.svg"> <a href="https://bundlephobia.com/result?p=@weser/dnd@latest"><img alt="Bundlephobia" src="https://img.shields.io/bundlephobia/minzip/@weser/dnd.svg"></a>
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ # npm
9
+ npm i --save @weser/dnd
10
+ # yarn
11
+ yarn add @weser/dnd
12
+ # pnpm
13
+ pnpm add @weser/dnd
14
+ ```
15
+
16
+ ## Documentation
17
+
18
+ ## License
19
+
20
+ @weser/dnd is licensed under the [MIT License](http://opensource.org/licenses/MIT).<br>
21
+ Documentation is licensed under [Creative Common License](http://creativecommons.org/licenses/by/4.0/).<br>
22
+ Created with ♥ by [@robinweser](http://weser.io).
@@ -0,0 +1,25 @@
1
+ import { Dispatch, SetStateAction } from 'react';
2
+ import { Coords, ElementId, Data, Nullable } from './types.js';
3
+ export type DndListeners = {
4
+ onDrop?: (active: ElementId, over: Nullable<ElementId>) => void;
5
+ onDragStart?: () => void;
6
+ onDragEnd?: () => void;
7
+ onDragMove?: () => void;
8
+ onDragOver?: (over: ElementId, id: ElementId) => void;
9
+ };
10
+ export type DndContext = {
11
+ activeId: Nullable<ElementId>;
12
+ setActiveId: Dispatch<SetStateAction<Nullable<ElementId>>>;
13
+ activeOver: Nullable<ElementId>;
14
+ setActiveOver: Dispatch<SetStateAction<Nullable<ElementId>>>;
15
+ origin: Nullable<Coords>;
16
+ setOrigin: Dispatch<SetStateAction<Nullable<Coords>>>;
17
+ delta: Nullable<Coords>;
18
+ setDelta: Dispatch<SetStateAction<Nullable<Coords>>>;
19
+ data: Nullable<Data>;
20
+ setData: Dispatch<SetStateAction<Nullable<Data>>>;
21
+ dropzones: Record<ElementId, any>;
22
+ setDropzones: Dispatch<SetStateAction<Record<ElementId, any>>>;
23
+ } & DndListeners;
24
+ declare const _default: import("react").Context<Nullable<DndContext>>;
25
+ export default _default;
@@ -0,0 +1,3 @@
1
+ 'use client';
2
+ import { createContext } from 'react';
3
+ export default createContext(null);
@@ -0,0 +1,5 @@
1
+ import { PropsWithChildren } from 'react';
2
+ import { DndListeners } from './DndContext.js';
3
+ type Props = DndListeners;
4
+ export default function DndProvider({ children, onDrop, onDragStart, onDragEnd, onDragMove, onDragOver, }: PropsWithChildren<Props>): import("react").JSX.Element;
5
+ export {};
@@ -0,0 +1,31 @@
1
+ 'use client';
2
+ import { useState } from 'react';
3
+ import DndContext from './DndContext.js';
4
+ export default function DndProvider({ children, onDrop, onDragStart, onDragEnd, onDragMove, onDragOver, }) {
5
+ const [activeId, setActiveId] = useState(null);
6
+ const [activeOver, setActiveOver] = useState(null);
7
+ const [origin, setOrigin] = useState(null);
8
+ const [delta, setDelta] = useState(null);
9
+ const [data, setData] = useState(null);
10
+ const [dropzones, setDropzones] = useState([]);
11
+ const context = {
12
+ activeId,
13
+ setActiveId,
14
+ activeOver,
15
+ setActiveOver,
16
+ origin,
17
+ setOrigin,
18
+ delta,
19
+ setDelta,
20
+ data,
21
+ setData,
22
+ dropzones,
23
+ setDropzones,
24
+ onDrop,
25
+ onDragStart,
26
+ onDragEnd,
27
+ onDragMove,
28
+ onDragOver,
29
+ };
30
+ return <DndContext.Provider value={context}>{children}</DndContext.Provider>;
31
+ }
@@ -0,0 +1,13 @@
1
+ /// <reference types="react" />
2
+ export type T_Layer = {
3
+ id: string;
4
+ element: Object;
5
+ };
6
+ type LayerContext = {
7
+ layers: Array<T_Layer>;
8
+ addLayer: (layer: T_Layer) => void;
9
+ removeLayer: (id: T_Layer['id']) => void;
10
+ hasLayer: (id: T_Layer['id']) => boolean;
11
+ };
12
+ declare const _default: import("react").Context<LayerContext | null>;
13
+ export default _default;
@@ -0,0 +1,3 @@
1
+ 'use client';
2
+ import { createContext } from 'react';
3
+ export default createContext(null);
@@ -0,0 +1,8 @@
1
+ import { PropsWithChildren } from 'react';
2
+ import { T_Layer } from './LayerContext.js';
3
+ type Props = {
4
+ onLayerAdded?: (layers: Array<T_Layer>) => void;
5
+ onLayerRemoved?: (layers: Array<T_Layer>) => void;
6
+ };
7
+ export default function LayerContextProvider({ children, onLayerAdded, onLayerRemoved, }: PropsWithChildren<Props>): import("react").JSX.Element;
8
+ export {};
@@ -0,0 +1,36 @@
1
+ 'use client';
2
+ import { useState } from 'react';
3
+ import LayerContext from './LayerContext.js';
4
+ export default function LayerContextProvider({ children, onLayerAdded, onLayerRemoved, }) {
5
+ const [layers, setLayers] = useState([]);
6
+ function addLayer(layer) {
7
+ setLayers((prevLayers) => {
8
+ const filteredLayers = prevLayers.filter((item) => item.id !== layer.id);
9
+ const newLayers = [...filteredLayers, layer];
10
+ if (onLayerAdded) {
11
+ onLayerAdded(newLayers);
12
+ }
13
+ return newLayers;
14
+ });
15
+ }
16
+ function removeLayer(id) {
17
+ setLayers((prevLayers) => {
18
+ const newLayers = prevLayers.filter((item) => item.id !== id);
19
+ if (onLayerRemoved) {
20
+ onLayerRemoved(newLayers);
21
+ }
22
+ return newLayers;
23
+ });
24
+ }
25
+ function hasLayer(id) {
26
+ return layers.find((item) => item.id === id) !== undefined;
27
+ }
28
+ return (<LayerContext.Provider value={{
29
+ addLayer,
30
+ removeLayer,
31
+ hasLayer,
32
+ layers,
33
+ }}>
34
+ {children}
35
+ </LayerContext.Provider>);
36
+ }
@@ -0,0 +1,7 @@
1
+ export { default as DndContext } from './DndContext.js';
2
+ export { default as DndProvider } from './DndProvider.jsx';
3
+ export { default as useDndContext } from './useDndContext.js';
4
+ export { default as useDndState } from './useDndState.js';
5
+ export { default as useDraggable } from './useDraggable.js';
6
+ export { default as useDroppable } from './useDroppable.js';
7
+ export * from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { default as DndContext } from './DndContext.js';
2
+ export { default as DndProvider } from './DndProvider.jsx';
3
+ export { default as useDndContext } from './useDndContext.js';
4
+ export { default as useDndState } from './useDndState.js';
5
+ export { default as useDraggable } from './useDraggable.js';
6
+ export { default as useDroppable } from './useDroppable.js';
7
+ export * from './types.js';
@@ -0,0 +1,7 @@
1
+ export type Nullable<T> = T | null;
2
+ export type ElementId = string;
3
+ export type Data = Record<string, any>;
4
+ export type Coords = {
5
+ x: number;
6
+ y: number;
7
+ };
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export default function useClientSide(): boolean;
@@ -0,0 +1,6 @@
1
+ import { useEffect, useState } from 'react';
2
+ export default function useClientSide() {
3
+ const [isClientSide, setClientSide] = useState(false);
4
+ useEffect(() => setClientSide(true), []);
5
+ return isClientSide;
6
+ }
@@ -0,0 +1 @@
1
+ export default function useDndContext(): import("./DndContext.js").DndContext;
@@ -0,0 +1,10 @@
1
+ 'use client';
2
+ import { useContext } from 'react';
3
+ import DndContext from './DndContext.js';
4
+ export default function useDndContext() {
5
+ const context = useContext(DndContext);
6
+ if (!context) {
7
+ throw new Error("You're using dnd context outside of its provider.");
8
+ }
9
+ return context;
10
+ }
@@ -0,0 +1,8 @@
1
+ export default function useDndState(): {
2
+ isDragging: boolean;
3
+ active: import("./types.js").Nullable<string>;
4
+ over: import("./types.js").Nullable<string>;
5
+ origin: import("./types.js").Nullable<import("./types.js").Coords>;
6
+ delta: import("./types.js").Nullable<import("./types.js").Coords>;
7
+ data: import("./types.js").Nullable<import("./types.js").Data>;
8
+ };
@@ -0,0 +1,15 @@
1
+ 'use client';
2
+ import useDndContext from './useDndContext.js';
3
+ // TODO: use memo to prevent unnecessary rerenders
4
+ export default function useDndState() {
5
+ const { activeId, activeOver, origin, delta, data } = useDndContext();
6
+ const isDragging = activeId !== null;
7
+ return {
8
+ isDragging,
9
+ active: activeId,
10
+ over: activeOver,
11
+ origin,
12
+ delta,
13
+ data,
14
+ };
15
+ }
@@ -0,0 +1,17 @@
1
+ /// <reference types="react" />
2
+ import { Data, ElementId } from './types.js';
3
+ export default function useDraggable({ id, data, delay, disabled, }: {
4
+ id: ElementId;
5
+ data?: Data;
6
+ delay?: number;
7
+ disabled?: boolean;
8
+ }): {
9
+ isDragging: boolean;
10
+ attributes: {};
11
+ listeners: {};
12
+ transform: {
13
+ top: number;
14
+ left: number;
15
+ };
16
+ ref: import("react").RefObject<HTMLElement>;
17
+ };
@@ -0,0 +1,109 @@
1
+ import { useEffect, useRef } from 'react';
2
+ import useDndContext from './useDndContext.js';
3
+ export default function useDraggable({ id, data = {}, delay = 0, disabled = false, }) {
4
+ const { delta, origin, dropzones, activeId, activeOver, setActiveId, setActiveOver, setOrigin, setDelta, setData, onDrop, onDragStart, onDragEnd, onDragOver, onDragMove, } = useDndContext();
5
+ const delayRef = useRef(null);
6
+ const isDragging = activeId === id;
7
+ const transform = {
8
+ top: origin && delta ? origin.y + delta.y : 0,
9
+ left: origin && delta ? origin.x + delta.x : 0,
10
+ };
11
+ const ref = useRef(null);
12
+ const attributes = {};
13
+ function onPointerDown(e) {
14
+ setOrigin({
15
+ x: e.pageX,
16
+ y: e.pageY,
17
+ });
18
+ delayRef.current = window.setTimeout(() => {
19
+ setData(data);
20
+ setActiveId(id);
21
+ setDelta({
22
+ x: 0,
23
+ y: 0,
24
+ });
25
+ if (onDragStart) {
26
+ onDragStart();
27
+ }
28
+ delayRef.current = -1;
29
+ }, delay);
30
+ }
31
+ function onClickCapture(e) {
32
+ if (delayRef.current === -1) {
33
+ e.stopPropagation();
34
+ }
35
+ }
36
+ const listeners = {
37
+ // TODO: add touch events
38
+ onPointerDown,
39
+ onClickCapture,
40
+ };
41
+ useEffect(() => {
42
+ function onPointerUp(e) {
43
+ if (delayRef.current !== null) {
44
+ clearTimeout(delayRef.current);
45
+ delayRef.current = null;
46
+ }
47
+ else {
48
+ e.stopPropagation();
49
+ }
50
+ if (onDrop && activeId) {
51
+ onDrop(activeId, activeOver);
52
+ }
53
+ if (onDragEnd) {
54
+ onDragEnd();
55
+ }
56
+ setOrigin(null);
57
+ setActiveId(null);
58
+ setActiveOver(null);
59
+ setDelta(null);
60
+ setData(null);
61
+ }
62
+ document.addEventListener('pointerup', onPointerUp);
63
+ return () => document.removeEventListener('pointerup', onPointerUp);
64
+ }, [onDrop, activeId, activeOver, data]);
65
+ useEffect(() => {
66
+ // TODO: implement auto-scroll
67
+ function onPointerMove(e) {
68
+ if (origin) {
69
+ setDelta({
70
+ x: e.pageX - origin.x,
71
+ y: e.pageY - origin.y,
72
+ });
73
+ if (activeId === id) {
74
+ if (onDragMove) {
75
+ onDragMove();
76
+ }
77
+ if (ref.current) {
78
+ for (const id in dropzones) {
79
+ const target = dropzones[id];
80
+ // TODO: cache bounding client rect
81
+ // TODO: update on resize / scroll
82
+ const rect = target.getBoundingClientRect();
83
+ const collidesX = e.clientX >= rect.left && e.clientX <= rect.right;
84
+ const collidesY = e.clientY >= rect.top && e.clientY <= rect.bottom;
85
+ // TODO: more collision algorithms
86
+ if (collidesX && collidesY) {
87
+ if (onDragOver && id !== activeOver) {
88
+ onDragOver(activeId, id);
89
+ }
90
+ setActiveOver(id);
91
+ return;
92
+ }
93
+ }
94
+ }
95
+ setActiveOver(null);
96
+ }
97
+ }
98
+ }
99
+ document.addEventListener('pointermove', onPointerMove);
100
+ return () => document.removeEventListener('pointermove', onPointerMove);
101
+ }, [origin, dropzones, ref, activeId, activeOver]);
102
+ return {
103
+ isDragging,
104
+ attributes,
105
+ listeners: disabled ? {} : listeners,
106
+ transform,
107
+ ref,
108
+ };
109
+ }
@@ -0,0 +1,9 @@
1
+ /// <reference types="react" />
2
+ import { ElementId } from './types';
3
+ export default function useDroppable({ id, disabled, }: {
4
+ id: ElementId;
5
+ disabled?: boolean;
6
+ }): {
7
+ ref: import("react").RefObject<HTMLElement>;
8
+ isOver: boolean;
9
+ };
@@ -0,0 +1,34 @@
1
+ import { useEffect, useRef } from 'react';
2
+ import useDndContext from './useDndContext';
3
+ function objectFilter(obj, filter) {
4
+ const filteredObj = {};
5
+ for (const key in obj) {
6
+ const value = obj[key];
7
+ if (filter(value, key, obj)) {
8
+ filteredObj[key] = value;
9
+ }
10
+ }
11
+ return filteredObj;
12
+ }
13
+ export default function useDroppable({ id, disabled = false, }) {
14
+ const { activeOver, setDropzones } = useDndContext();
15
+ const ref = useRef(null);
16
+ const isOver = activeOver === id;
17
+ useEffect(() => {
18
+ if (ref.current) {
19
+ if (disabled) {
20
+ setDropzones((dropzones) => objectFilter(dropzones, (_, key) => key !== id));
21
+ }
22
+ else {
23
+ setDropzones((dropzones) => ({
24
+ ...dropzones,
25
+ [id]: ref.current,
26
+ }));
27
+ }
28
+ }
29
+ }, [ref, disabled]);
30
+ return {
31
+ ref,
32
+ isOver,
33
+ };
34
+ }
@@ -0,0 +1,2 @@
1
+ import { RefObject } from 'react';
2
+ export default function useLayer(visible: boolean): [RefObject<HTMLElement>, boolean];
@@ -0,0 +1,20 @@
1
+ 'use client';
2
+ import { useEffect, useId, useRef } from 'react';
3
+ import useLayerContext from './useLayerContext.js';
4
+ export default function useLayer(visible) {
5
+ const id = useId();
6
+ const ref = useRef(null);
7
+ const { layers, addLayer, removeLayer, hasLayer } = useLayerContext();
8
+ useEffect(() => {
9
+ if (visible) {
10
+ addLayer({ id, element: ref });
11
+ }
12
+ else {
13
+ if (hasLayer(id)) {
14
+ removeLayer(id);
15
+ }
16
+ }
17
+ }, [visible]);
18
+ const active = layers[layers.length - 1]?.id === id;
19
+ return [ref, active];
20
+ }
@@ -0,0 +1,6 @@
1
+ export default function useLayerContext(): {
2
+ layers: import("./LayerContext.js").T_Layer[];
3
+ addLayer: (layer: import("./LayerContext.js").T_Layer) => void;
4
+ removeLayer: (id: string) => void;
5
+ hasLayer: (id: string) => boolean;
6
+ };
@@ -0,0 +1,9 @@
1
+ import { useContext } from 'react';
2
+ import LayerContext from './LayerContext.js';
3
+ export default function useLayerContext() {
4
+ const context = useContext(LayerContext);
5
+ if (!context) {
6
+ throw new Error("You're using layer context outside of its provider.");
7
+ }
8
+ return context;
9
+ }
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@weser/dnd",
3
+ "version": "0.0.1",
4
+ "description": "React library for low-level drag'n'drop implementations",
5
+ "author": "Robin Weser <robin@weser.io>",
6
+ "license": "MIT",
7
+ "homepage": "https://github.com/robinweser/weser.git",
8
+ "repository": "https://github.com/robinweser/weser.git",
9
+ "type": "module",
10
+ "main": "dist/index.js",
11
+ "module": "dist/index.js",
12
+ "types": "dist/index.d.ts",
13
+ "sideEffects": false,
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "files": [
18
+ "LICENSE",
19
+ "README.md",
20
+ "dist/**"
21
+ ],
22
+ "browserslist": [
23
+ "IE >= 11",
24
+ "Firefox >= 60",
25
+ "Safari >= 11.1",
26
+ "Chrome >= 66",
27
+ "ChromeAndroid >= 66",
28
+ "iOS >= 11.3",
29
+ "Edge >= 15"
30
+ ],
31
+ "scripts": {
32
+ "setup": "pnpm build",
33
+ "clean": "rimraf dist",
34
+ "build": "tsc -b",
35
+ "dev": "pnpm build -w",
36
+ "test": "echo 1"
37
+ },
38
+ "keywords": [
39
+ "react",
40
+ "react-hook",
41
+ "react hooks",
42
+ "hooks",
43
+ "utils",
44
+ "dnd",
45
+ "dragdrop",
46
+ "drag'n'drop"
47
+ ],
48
+ "peerDependencies": {
49
+ "react": ">16.3.0"
50
+ },
51
+ "devDependencies": {
52
+ "@types/react": "^18.3.3",
53
+ "ava": "^6.1.3",
54
+ "react": "canary",
55
+ "rimraf": "^3.0.2",
56
+ "typescript": "^5.4.5"
57
+ },
58
+ "gitHead": "f8cd929768ab80c7c441f66770df2a95c33318a7"
59
+ }