Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[hooks] feat: Created hooks library (WIP) #114

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/hooks/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
vite.config.ts
.eslintrc.cjs
node_modules
dist
21 changes: 21 additions & 0 deletions packages/hooks/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended-type-checked',
'plugin:@typescript-eslint/stylistic-type-checked'
],
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
project: ['./tsconfig.json'],
tsconfigRootDir: __dirname,
},
ignorePatterns: ['dist', '.eslintrc.cjs', 'tsup.config.ts'],
parser: '@typescript-eslint/parser',
plugins: ['react'],
rules: {
'@typescript-eslint/explicit-function-return-type': ['off']
},
}
26 changes: 26 additions & 0 deletions packages/hooks/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
.eslintcache

npm-debug.log*
yarn-debug.log*
yarn-error.log*

dist/**
59 changes: 59 additions & 0 deletions packages/hooks/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
{
"name": "@layer5/sistent-hooks",
"version": "0.0.0",
"description": "Reusable React Components",
"sideEffects": false,
"exports": {
".": {
"require": "./dist/index.js",
"import": "./dist/index.js",
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"main": "./dist/index.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"dist/**"
],
"scripts": {
"build": "NODE_ENV=production tsup",
"dev": "NODE_ENV=development tsup"
},
"dependencies": {
"@reduxjs/toolkit": "^1.9.5",
"@types/cytoscape": "^3.19.10",
"@types/react": "^18.2.21",
"cytoscape": "^3.26.0",
"notistack": "^3.0.1",
"react-redux": "^8.1.2",
"redux": "^4.2.1",
"rxjs": "^7.8.1",
"tsup": "^7.2.0",
"typescript": "^5.2.2"
},
"devDependencies": {
"@swc/core": "^1.3.96",
"@typescript-eslint/eslint-plugin": "^6.10.0",
"@typescript-eslint/parser": "^6.10.0",
"eslint": "^8.53.0",
"eslint-plugin-react": "^7.33.2",
"tsconfig": "workspace:^"
},
"optionalDependencies": {
"react": "^17.0.0 || ^18.0.0",
"react-dom": "^17.0.0 || ^18.0.0"
},
"publishConfig": {
"access": "public",
"exports": {
".": {
"require": "./dist/index.js",
"import": "./dist/index.js",
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
}
}
}
19 changes: 19 additions & 0 deletions packages/hooks/src/context/CytoscapeProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import cytoscape from 'cytoscape';
import React from 'react';

export interface CytoscapeContextInterface {
cytoscape: cytoscape.Core;
container: HTMLElement;
}

export const CytoscapeContext = React.createContext<CytoscapeContextInterface | null>(null);

export const CytoscapeProvider = CytoscapeContext.Provider;

export function useCytoscapeContext() {
const context = React.useContext(CytoscapeContext);
if (!context) {
throw new Error('useCytoscapeContext must be used within a CytoscapeContextProvider');
}
return context;
}
21 changes: 21 additions & 0 deletions packages/hooks/src/context/ReduxProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import React from 'react';
import { Provider } from 'react-redux';
import { store } from '../redux/store';

interface ReduxProviderProps {
children: React.ReactNode;
}

const ReduxContext = React.createContext({});

export function useRedux() {
return React.useContext(ReduxContext);
}

export function ReduxProvider({ children }: ReduxProviderProps): JSX.Element {
return (
<Provider store={store}>
<ReduxContext.Provider value={store}>{children}</ReduxContext.Provider>
</Provider>
);
}
15 changes: 15 additions & 0 deletions packages/hooks/src/context/useRedux.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState, store } from '../redux/store';

const ReduxContext = React.createContext(store);

export function useReduxState<T>(selector: (state: RootState) => T): T {
const store = React.useContext(ReduxContext);
return useSelector(selector);
}

export function useReduxDispatch(): AppDispatch {
const store = React.useContext(ReduxContext);
return useDispatch();
}
7 changes: 7 additions & 0 deletions packages/hooks/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export * from '.';
export { ReduxProvider } from './context/ReduxProvider';
export { useReduxDispatch, useReduxState } from './context/useRedux';
export { useDebounced } from './useDebounced';
export { useLocalStorage } from './useLocalStorage';
export { usePauseEvent } from './usePauseEvent';
export { useThrottledDragOver } from './useThrottledDragOver';
8 changes: 8 additions & 0 deletions packages/hooks/src/redux/store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { configureStore } from '@reduxjs/toolkit';

export const store = configureStore({
reducer: {}
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
7 changes: 7 additions & 0 deletions packages/hooks/src/useCytoscape.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import cytoscape from 'cytoscape';

import { useCytoscapeContext } from './context/CytoscapeProvider';

export function useCytoscape(): cytoscape.Core {
return useCytoscapeContext().cytoscape;
}
26 changes: 26 additions & 0 deletions packages/hooks/src/useDebounced.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import React from 'react';

export function useDebounced<T extends (...args: any[]) => void>(func: T, timeout = 500) {
const timerRef = React.useRef<number>();

React.useEffect(() => {
const cleanup = () => {
if (timerRef.current) {
clearTimeout(timerRef.current);
}
};

return cleanup;
}, []);

const debouncedFunction = (...args: Parameters<T>) => {
if (timerRef.current) {
clearTimeout(timerRef.current);
}
timerRef.current = window.setTimeout(() => {
func(...args);
}, timeout);
};

return debouncedFunction;
}
52 changes: 52 additions & 0 deletions packages/hooks/src/useDraggable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import React from 'react';

import { useCytoscapeContext } from './context/CytoscapeProvider';

export function useDraggable(
dragReference: React.RefObject<HTMLElement | null>,
componentReference: React.RefObject<HTMLElement | null>
) {
const context = useCytoscapeContext();
const [{ dx, dy }, setOffset] = React.useState({ dx: 0, dy: 0 });

React.useEffect(() => {
if (!dragReference.current || !componentReference.current || !context) {
throw new Error(`An error occurred while trying to drag.`);
}
const el = dragReference.current;

const handleMouseDown: EventListener = (event) => {
const startX = (event as MouseEvent).pageX - dx;
const startY = (event as MouseEvent).pageY - dy;

const handleMouseMove = (event: Event) => {
const newDx = (event as MouseEvent).pageX - startX;
const newDy = (event as MouseEvent).pageY - startY;
setOffset({ dx: newDx, dy: newDy });
};

document.addEventListener('mousemove', handleMouseMove);
document.addEventListener(
'mouseup',
() => {
document.removeEventListener('mousemove', handleMouseMove);
},
{ once: true }
);
};

el.addEventListener('mousedown', handleMouseDown);
el.addEventListener('mouseup', handleMouseDown);

return () => {
el.removeEventListener('mousedown', handleMouseDown);
el.removeEventListener('mouseup', handleMouseDown);
};
}, [dx, dy, dragReference, componentReference, context]);

React.useEffect(() => {
if (componentReference.current) {
componentReference.current.style.transform = `translate3d(${dx}px, ${dy}px, 0)`;
}
}, [componentReference, dx, dy]);
}
51 changes: 51 additions & 0 deletions packages/hooks/src/useFullScreen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import React from 'react';

import { useCytoscapeContext } from './context/CytoscapeProvider';

function toggleFullScreen(dom: HTMLElement) {
if (document.fullscreenElement !== dom) {
dom.requestFullscreen().catch((err) => {
console.error('Error attempting to enable full screen:', err);
});
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
}
}
}

export function useFullScreen(container?: HTMLElement | null): {
toggle: () => void;
isFullScreen: boolean;
} {
const context = useCytoscapeContext();
const [isFullScreen, setFullScreen] = React.useState<boolean>(false);
const [element, setElement] = React.useState<HTMLElement>(
container ? container : context.container
);

// const toggleState = () => setFullScreen((v) => !v)
const toggleState = React.useCallback(() => {
setFullScreen((prevState) => !prevState);
}, [setFullScreen]);

React.useEffect(() => {
const handleFullscreenChange = () => toggleState();
document.addEventListener('fullscreenchange', handleFullscreenChange);

return () => document.removeEventListener('fullscreenchange', handleFullscreenChange);
}, [toggleState]);

React.useEffect(() => {
setElement(container ?? context.container);
}, [container, context.container]);

const toggle = React.useCallback(() => {
toggleFullScreen(element);
}, [element]);

return {
toggle,
isFullScreen
};
}
15 changes: 15 additions & 0 deletions packages/hooks/src/useLocalStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import React from 'react';

export function useLocalStorage<T>(key: string, initialValue: T): [T, (newValue: T) => void] {
const [value, setValue] = React.useState<T>(() => {
const storedValue = localStorage.getItem(key);
return storedValue !== null ? JSON.parse(storedValue) : initialValue;
});

const setLocalStorageValue = (newValue: T) => {
localStorage.setItem(key, JSON.stringify(newValue));
setValue(newValue);
};

return [value, setLocalStorageValue];
}
Loading