From 75e538976e0ee8ed596293a5687d4a134944afa6 Mon Sep 17 00:00:00 2001 From: TheoryOfNekomata Date: Mon, 6 May 2024 10:49:05 +0800 Subject: [PATCH] Initial commit Add files from pridepack. --- .eslintrc | 9 ++++ .gitignore | 107 +++++++++++++++++++++++++++++++++++++++ LICENSE | 7 +++ package.json | 77 ++++++++++++++++++++++++++++ pridepack.json | 3 ++ src/event.ts | 37 ++++++++++++++ src/hooks/browser.ts | 16 ++++++ src/hooks/client-side.ts | 18 +++++++ src/hooks/form.ts | 94 ++++++++++++++++++++++++++++++++++ src/hooks/id.ts | 6 +++ src/index.ts | 4 ++ tsconfig.eslint.json | 21 ++++++++ tsconfig.json | 21 ++++++++ vitest.config.ts | 8 +++ 14 files changed, 428 insertions(+) create mode 100644 .eslintrc create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 package.json create mode 100644 pridepack.json create mode 100644 src/event.ts create mode 100644 src/hooks/browser.ts create mode 100644 src/hooks/client-side.ts create mode 100644 src/hooks/form.ts create mode 100644 src/hooks/id.ts create mode 100644 src/index.ts create mode 100644 tsconfig.eslint.json create mode 100644 tsconfig.json create mode 100644 vitest.config.ts diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 0000000..7d22244 --- /dev/null +++ b/.eslintrc @@ -0,0 +1,9 @@ +{ + "root": true, + "extends": [ + "lxsmnsyc/typescript/react" + ], + "parserOptions": { + "project": "./tsconfig.eslint.json" + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..53992de --- /dev/null +++ b/.gitignore @@ -0,0 +1,107 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# TypeScript v1 declaration files +typings/ + +# TypeScript cache +*.tsbuildinfo + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env +.env.production +.env.development + +# parcel-bundler cache (https://parceljs.org/) +.cache + +# Next.js build output +.next + +# Nuxt.js build / generate output +.nuxt +dist + +# Gatsby files +.cache/ +# Comment in the public line in if your project uses Gatsby and *not* Next.js +# https://nextjs.org/blog/next-9-1#public-directory-support +# public + +# vuepress build output +.vuepress/dist + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# TernJS port file +.tern-port + +.npmrc diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f24dd21 --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +MIT License Copyright (c) 2023 TheoryOfNekomata + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..86189e7 --- /dev/null +++ b/package.json @@ -0,0 +1,77 @@ +{ + "name": "@modal-sh/react-utils", + "version": "0.0.0", + "files": [ + "dist", + "src" + ], + "engines": { + "node": ">=12" + }, + "license": "MIT", + "keywords": [ + "pridepack" + ], + "devDependencies": { + "@storybook/react": "^7.3.2", + "@testing-library/jest-dom": "^5.16.5", + "@testing-library/react": "^13.4.0", + "@types/node": "^18.14.1", + "@types/react": "^18.2.18", + "eslint": "^8.35.0", + "eslint-config-lxsmnsyc": "^0.5.0", + "pridepack": "2.4.4", + "react": "^18.2.0", + "react-dom": "^18.2.0", + "react-test-renderer": "^18.2.0", + "tslib": "^2.5.0", + "typescript": "^4.9.5", + "vitest": "^0.28.1" + }, + "peerDependencies": { + "react": "^16.8 || ^17.0 || ^18.0", + "react-dom": "^16.8 || ^17.0 || ^18.0" + }, + "scripts": { + "prepublishOnly": "pridepack clean && pridepack build", + "build": "pridepack build", + "type-check": "pridepack check", + "lint": "pridepack lint", + "clean": "pridepack clean", + "watch": "pridepack watch", + "start": "pridepack start", + "dev": "pridepack dev", + "test": "vitest" + }, + "private": false, + "description": "Utilities for React.", + "repository": { + "url": "", + "type": "git" + }, + "homepage": "", + "bugs": { + "url": "" + }, + "author": "TheoryOfNekomata ", + "publishConfig": { + "access": "public" + }, + "types": "./dist/types/index.d.ts", + "main": "./dist/cjs/production/index.js", + "module": "./dist/esm/production/index.js", + "exports": { + ".": { + "development": { + "require": "./dist/cjs/development/index.js", + "import": "./dist/esm/development/index.js" + }, + "require": "./dist/cjs/production/index.js", + "import": "./dist/esm/production/index.js", + "types": "./dist/types/index.d.ts" + } + }, + "typesVersions": { + "*": {} + } +} diff --git a/pridepack.json b/pridepack.json new file mode 100644 index 0000000..841fb58 --- /dev/null +++ b/pridepack.json @@ -0,0 +1,3 @@ +{ + "target": "es2018" +} \ No newline at end of file diff --git a/src/event.ts b/src/event.ts new file mode 100644 index 0000000..a818c00 --- /dev/null +++ b/src/event.ts @@ -0,0 +1,37 @@ +export const delegateTriggerEvent = ( + eventName: string, + target: T, + value?: unknown, +) => { + if (typeof window === 'undefined') { + return; + } + + const TAG_NAME_ELEMENT_CONSTRUCTOR = { + 'INPUT': window.HTMLInputElement, + 'SELECT': window.HTMLSelectElement, + 'TEXTAREA': window.HTMLTextAreaElement, + } as const; + + const { + [target.tagName as keyof typeof TAG_NAME_ELEMENT_CONSTRUCTOR]: elementCtor, + } = TAG_NAME_ELEMENT_CONSTRUCTOR; + + if (!elementCtor) { + return; + } + + if (eventName === 'change') { + const nativeInputValueSetter = Object.getOwnPropertyDescriptor(elementCtor.prototype, 'value')?.set; + if (nativeInputValueSetter) { + if ( + (target.tagName === 'INPUT' && (target as unknown as HTMLInputElement).type !== 'file') + || target.tagName !== 'INPUT' + ) { + nativeInputValueSetter.call(target, value); + } + const simulatedEvent = new Event(eventName, {bubbles: true}); + target.dispatchEvent(simulatedEvent); + } + } +}; diff --git a/src/hooks/browser.ts b/src/hooks/browser.ts new file mode 100644 index 0000000..b215b4a --- /dev/null +++ b/src/hooks/browser.ts @@ -0,0 +1,16 @@ +import * as React from 'react'; + +export const useBrowser = () => { + const [browser, setBrowser] = React.useState(); + React.useEffect(() => { + const isFirefox = typeof (window as unknown as Record).InstallTrigger !== 'undefined'; + if (isFirefox) { + setBrowser('firefox'); + } else { + // TODO - detect other browsers + setBrowser('chrome'); + } + }, []); + + return React.useMemo(() => browser, [browser]); +}; diff --git a/src/hooks/client-side.ts b/src/hooks/client-side.ts new file mode 100644 index 0000000..77a8813 --- /dev/null +++ b/src/hooks/client-side.ts @@ -0,0 +1,18 @@ +import * as React from 'react'; + +export interface UseEnhancedOptions { + clientSide: boolean; + initial?: boolean; +} + +export const useClientSide = (options: UseEnhancedOptions) => { + const { clientSide: enhancedProp, initial = false } = options; + const [enhanced, setEnhanced] = React.useState(initial); + React.useEffect(() => { + setEnhanced(enhancedProp); + }, [enhancedProp]); + + return React.useMemo(() => ({ + clientSide: enhanced, + }), [enhanced]); +}; diff --git a/src/hooks/form.ts b/src/hooks/form.ts new file mode 100644 index 0000000..17cc3f5 --- /dev/null +++ b/src/hooks/form.ts @@ -0,0 +1,94 @@ +import * as React from 'react'; +import { delegateTriggerEvent } from '../event'; + +type ValueType = string | number | readonly string[]; + +interface HTMLElementWithValue extends HTMLElement { + value: ValueType; +} + +export interface UseProxyInputOptions< + ForwardedRef extends HTMLElementWithValue, + Value = ValueType, +> { + forwardedRef: React.Ref; + valueSetterFn: (value: Value) => void; + transformChangeHandlerArgs?: (value: Value) => ValueType; +} + +export const useProxyInput = < + TheValueType = ValueType, + ForwardedRefType extends HTMLElementWithValue = HTMLElementWithValue, + DefaultRefType extends HTMLElementWithValue = ForwardedRefType, +>(options: UseProxyInputOptions) => { + const { + forwardedRef, + valueSetterFn, + transformChangeHandlerArgs = (e) => e as ValueType, + } = options; + const defaultRef = React.useRef(null); + + React.useEffect(() => { + const { current: currentRaw } = defaultRef; + const current = currentRaw as unknown as ForwardedRefType; + const forwardedRefProxy = new Proxy(current, { + get(target, prop, receiver) { + return Reflect.get(target, prop, receiver) as unknown; + }, + set(target, prop, newValue, receiver) { + if (prop === 'value') { + const thisNewValue = newValue as TheValueType; + const actualNewValue = ( + Array.isArray(thisNewValue) ? thisNewValue.join('') : thisNewValue?.toString() ?? '' + ) as TheValueType; + valueSetterFn(actualNewValue); + current.value = actualNewValue as string; + return true; + } + return Reflect.set(target, prop, newValue, receiver); + }, + }) as unknown as ForwardedRefType; + + if (typeof forwardedRef === 'function') { + forwardedRef(forwardedRefProxy); + return; + } + + if (typeof forwardedRef === 'object' && forwardedRef) { + const mutableForwardedRef = forwardedRef as React.MutableRefObject; + mutableForwardedRef.current = forwardedRefProxy; + } + }); + + // todo Handle input event + + // do we need to expose this? or is defaultref enough? + // maybe we could attach the event listener to the defaultRef instead of exposing a handler (as + // long as target element exposes a ref) + + // why do we have to do all this? because we want to proxy event handlers to fallback elements. + // fallback elements ensure server-side compatibility--with this, we can serialize every value + // that can be inputted in every custom control. (see graceful degradation) + const handleChange = React.useCallback((e: TheValueType) => { + if (!(typeof defaultRef === 'object' && defaultRef)) { + return; + } + const { current: input } = defaultRef; + if (!input) { + return; + } + const transformedValue = transformChangeHandlerArgs(e); + valueSetterFn(e); + setTimeout(() => { + delegateTriggerEvent('change', input, transformedValue); + }); + }, [valueSetterFn, transformChangeHandlerArgs, defaultRef]); + + return React.useMemo(() => ({ + defaultRef, + handleChange, + }), [ + defaultRef, + handleChange, + ]); +}; diff --git a/src/hooks/id.ts b/src/hooks/id.ts new file mode 100644 index 0000000..c006644 --- /dev/null +++ b/src/hooks/id.ts @@ -0,0 +1,6 @@ +import * as React from 'react'; + +export const useFallbackId = (id?: string) => { + const defaultId = React.useId(); + return id || defaultId; +}; diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..46d8a33 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,4 @@ +export * from './hooks/browser'; +export * from './hooks/client-side'; +export * from './hooks/form'; +export * from './hooks/id'; diff --git a/tsconfig.eslint.json b/tsconfig.eslint.json new file mode 100644 index 0000000..16f2e87 --- /dev/null +++ b/tsconfig.eslint.json @@ -0,0 +1,21 @@ +{ + "exclude": ["node_modules"], + "include": ["src", "types", "test"], + "compilerOptions": { + "module": "ESNext", + "lib": ["DOM", "ESNext"], + "importHelpers": true, + "declaration": true, + "sourceMap": true, + "rootDir": "./", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "moduleResolution": "node", + "jsx": "react", + "esModuleInterop": true, + "target": "es2018" + } +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..0ed68f4 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,21 @@ +{ + "exclude": ["node_modules"], + "include": ["src", "types"], + "compilerOptions": { + "module": "ESNext", + "lib": ["DOM", "ESNext"], + "importHelpers": true, + "declaration": true, + "sourceMap": true, + "rootDir": "./src", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "moduleResolution": "node", + "jsx": "react", + "esModuleInterop": true, + "target": "es2018" + } +} diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..a104d21 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,8 @@ +/// + +export default ({ + test: { + global: true, + environment: 'jsdom', + }, +});