Skip to content

Commit

Permalink
Useless react wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
PuruVJ committed Dec 21, 2024
1 parent 21746b5 commit 677cd41
Show file tree
Hide file tree
Showing 23 changed files with 3,166 additions and 2,700 deletions.
1 change: 1 addition & 0 deletions packages/core/src/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ export const axis = unstable_definePlugin((value: 'x' | 'y') => {
export const applyUserSelectHack = unstable_definePlugin((value: boolean = true) => {
return {
name: 'neodrag:applyUserSelectHack',
cancelable: false,

setup() {
return {
Expand Down
10 changes: 8 additions & 2 deletions packages/core/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,22 @@ export function listen(
el.addEventListener(type, listener, options);
}

function camel_to_kebab(str: string): string {
return str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
}

export function set_node_key_style<T extends keyof CSSStyleDeclaration>(
node: HTMLElement | SVGElement,
key: T,
value: CSSStyleDeclaration[T],
) {
node.style.setProperty(key.toString(), value?.toString() ?? '');
const kebabKey = camel_to_kebab(key.toString());
node.style.setProperty(kebabKey, value?.toString() ?? '');
}

export function get_node_style(node: HTMLElement | SVGElement, key: keyof CSSStyleDeclaration) {
return node.style.getPropertyValue(key.toString());
const kebabKey = camel_to_kebab(key.toString());
return node.style.getPropertyValue(kebabKey);
}

export function set_node_dataset(node: HTMLElement | SVGElement, key: string, value: unknown) {
Expand Down
6 changes: 1 addition & 5 deletions packages/core/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,10 @@
"compilerOptions": {
"module": "ES2022",
"target": "ESNext",
"declaration": true,
"emitDeclarationOnly": true,
"declarationDir": "dist/",
"noEmit": true,
"strict": true,
"lib": ["ES2023.Array", "DOM"],
"esModuleInterop": true,
"moduleResolution": "bundler",
"isolatedDeclarations": false,
"allowImportingTsExtensions": true,
"types": ["vitest/globals"]
},
Expand Down
13 changes: 5 additions & 8 deletions packages/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,12 @@
"files": [
"dist/*"
],
"sideEffects": false,
"sideEffects": true,
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": {
"production": "./dist/min/index.js",
"development": "./dist/index.js"
},
"default": "./dist/min/index.js"
"import": "./dist/index.js",
"default": "./dist/index.js"
},
"./package.json": "./package.json"
},
Expand Down Expand Up @@ -45,11 +42,11 @@
"homepage": "https://github.com/PuruVJ/neodrag/tree/main/packages/react#readme",
"scripts": {
"compile": "tsup",
"compile:watch": "tsup --watch",
"compile:watch": "turbo watch compile",
"pub": "pnpm compile && pnpm publish --no-git-checks --access public",
"pub:dry": "pnpm compile && pnpm publish --dry-run --no-git-checks --access public"
},
"devDependencies": {
"dependencies": {
"@neodrag/core": "workspace:*"
}
}
114 changes: 26 additions & 88 deletions packages/react/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,100 +1,38 @@
import { DragEventData, draggable, DragOptions } from '@neodrag/core';
import React, { useEffect, useRef, useState } from 'react';
import { createDraggable } from '@neodrag/core';
import { type Plugin } from '@neodrag/core/plugins';
import { useEffect, useRef } from 'react';

type DragState = DragEventData;
const { draggable, instances } = createDraggable();

type HandleCancelType =
| string
| HTMLElement
| React.RefObject<HTMLElement>
| (React.RefObject<HTMLElement> | HTMLElement)[]
| undefined;

function unwrap_handle_cancel(
val: HandleCancelType,
): string | HTMLElement | HTMLElement[] | undefined {
if (val == undefined || typeof val === 'string' || val instanceof HTMLElement) return val;
if ('current' in val) return val.current!;

if (Array.isArray(val)) {
// It can only be an array now
return val.map((v) => (v instanceof HTMLElement ? v : v.current!));
}
}

type ReactDragOptions = Omit<DragOptions, 'handle' | 'cancel'> & {
handle?: HandleCancelType;
cancel?: HandleCancelType;
};

export function useDraggable<RefType extends HTMLElement = HTMLDivElement>(
nodeRef: React.RefObject<RefType>,
options: ReactDragOptions = {},
export function useDraggable(
ref: React.RefObject<HTMLElement | SVGElement>,
plugins: Plugin[] = [],
) {
const update_ref = useRef<(options: DragOptions) => void>();

const [isDragging, set_is_dragging] = useState(false);
const [dragState, set_drag_state] = useState<DragState>();

let { onDragStart, onDrag, onDragEnd, handle, cancel } = options;

let new_handle = unwrap_handle_cancel(handle);
let new_cancel = unwrap_handle_cancel(cancel);

function call_event(arg: DragState, cb: DragOptions['onDrag']) {
set_drag_state(arg);
cb?.(arg);
}

function custom_on_drag_start(arg: DragState) {
set_is_dragging(true);
call_event(arg, onDragStart);
}

function custom_on_drag(arg: DragState) {
call_event(arg, onDrag);
}

function custom_on_drag_end(arg: DragState) {
set_is_dragging(false);
call_event(arg, onDragEnd);
}
const instance = useRef<ReturnType<typeof draggable>>();
const pluginsRef = useRef(plugins);

// Use a separate effect for initialization and cleanup
useEffect(() => {
if (typeof window === 'undefined') return;
const node = nodeRef.current;
if (!node) return;

// Update callbacks
({ onDragStart, onDrag, onDragEnd } = options);

const { update, destroy } = draggable(node, {
...options,
handle: new_handle,
cancel: new_cancel,
onDragStart: custom_on_drag_start,
onDrag: custom_on_drag,
onDragEnd: custom_on_drag_end,
});
if (!ref.current) return;

update_ref.current = update;
instance.current = draggable(ref.current, plugins);
pluginsRef.current = plugins;

return destroy;
}, []);
return () => {
instance.current?.destroy();
instance.current = undefined;
};
}, []); // Empty deps - only run on mount/unmount

// Use a separate effect for plugin updates
useEffect(() => {
update_ref.current?.({
...options,
handle: unwrap_handle_cancel(handle),
cancel: unwrap_handle_cancel(cancel),
onDragStart: custom_on_drag_start,
onDrag: custom_on_drag,
onDragEnd: custom_on_drag_end,
});
}, [options]);
// Skip the initial mount since that's handled above
if (!instance.current || plugins === pluginsRef.current) return;

return { isDragging, dragState };
instance.current.update(plugins);
pluginsRef.current = plugins;
}, [plugins]); // Only run when plugins change
}

export type { DragAxis, DragBounds, DragBoundsCoords, DragEventData } from '@neodrag/core';
export type { ReactDragOptions as DragOptions };
export * from '@neodrag/core/plugins';
export { instances };
20 changes: 6 additions & 14 deletions packages/react/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,22 +1,14 @@
{
"compilerOptions": {
"module": "ESNext",
"target": "ESNext",
"useDefineForClassFields": true,
"declarationDir": "./dist",
"declaration": true,
"emitDeclarationOnly": true,
"lib": ["DOM", "ESNext"],
"allowJs": false,
"skipLibCheck": false,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"declarationDir": "dist",
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx"
"esModuleInterop": true,
"moduleResolution": "Bundler",
"composite": true
},
"include": ["./src"]
"files": ["./src/index.ts"]
}
13 changes: 11 additions & 2 deletions packages/react/tsup.config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
import { core_config } from '../config';
import { defineConfig } from 'tsup';

export default core_config({});
export default defineConfig([
{
entry: [`./src/index.ts`],
format: 'esm',
dts: { resolve: true },
external: ['react', '@neodrag/core'],
clean: true,
treeshake: 'smallest',
},
]);
21 changes: 20 additions & 1 deletion playground/react/.gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
.DS_Store
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
50 changes: 50 additions & 0 deletions playground/react/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# React + TypeScript + Vite

This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.

Currently, two official plugins are available:

- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh

## Expanding the ESLint configuration

If you are developing a production application, we recommend updating the configuration to enable type aware lint rules:

- Configure the top-level `parserOptions` property like this:

```js
export default tseslint.config({
languageOptions: {
// other options...
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
},
})
```

- Replace `tseslint.configs.recommended` to `tseslint.configs.recommendedTypeChecked` or `tseslint.configs.strictTypeChecked`
- Optionally add `...tseslint.configs.stylisticTypeChecked`
- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and update the config:

```js
// eslint.config.js
import react from 'eslint-plugin-react'

export default tseslint.config({
// Set the react version
settings: { react: { version: '18.3' } },
plugins: {
// Add the react plugin
react,
},
rules: {
// other rules...
// Enable its recommended rules
...react.configs.recommended.rules,
...react.configs['jsx-runtime'].rules,
},
})
```
21 changes: 10 additions & 11 deletions playground/react/index.html
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/src/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
16 changes: 10 additions & 6 deletions playground/react/package.json
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
{
"name": "react-demo",
"name": "react",
"private": true,
"version": "0.0.1",
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"build": "tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1",
"@neodrag/react": "workspace:*"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.2.1",
"typescript": "^5.3.3",
"vite": "^5.0.10"
"@types/react": "^18.3.17",
"@types/react-dom": "^18.3.5",
"@vitejs/plugin-react": "^4.3.4",
"vite": "^6.0.3"
}
}
Loading

0 comments on commit 677cd41

Please sign in to comment.