Procházet zdrojové kódy

Initial commit

Add files from pridepack.
master
TheoryOfNekomata před 6 měsíci
revize
75e538976e
14 změnil soubory, kde provedl 428 přidání a 0 odebrání
  1. +9
    -0
      .eslintrc
  2. +107
    -0
      .gitignore
  3. +7
    -0
      LICENSE
  4. +77
    -0
      package.json
  5. +3
    -0
      pridepack.json
  6. +37
    -0
      src/event.ts
  7. +16
    -0
      src/hooks/browser.ts
  8. +18
    -0
      src/hooks/client-side.ts
  9. +94
    -0
      src/hooks/form.ts
  10. +6
    -0
      src/hooks/id.ts
  11. +4
    -0
      src/index.ts
  12. +21
    -0
      tsconfig.eslint.json
  13. +21
    -0
      tsconfig.json
  14. +8
    -0
      vitest.config.ts

+ 9
- 0
.eslintrc Zobrazit soubor

@@ -0,0 +1,9 @@
{
"root": true,
"extends": [
"lxsmnsyc/typescript/react"
],
"parserOptions": {
"project": "./tsconfig.eslint.json"
}
}

+ 107
- 0
.gitignore Zobrazit soubor

@@ -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

+ 7
- 0
LICENSE Zobrazit soubor

@@ -0,0 +1,7 @@
MIT License Copyright (c) 2023 TheoryOfNekomata <allan.crisostomo@outlook.com>

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.

+ 77
- 0
package.json Zobrazit soubor

@@ -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 <allan.crisostomo@outlook.com>",
"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": {
"*": {}
}
}

+ 3
- 0
pridepack.json Zobrazit soubor

@@ -0,0 +1,3 @@
{
"target": "es2018"
}

+ 37
- 0
src/event.ts Zobrazit soubor

@@ -0,0 +1,37 @@
export const delegateTriggerEvent = <T extends HTMLElement>(
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);
}
}
};

+ 16
- 0
src/hooks/browser.ts Zobrazit soubor

@@ -0,0 +1,16 @@
import * as React from 'react';

export const useBrowser = () => {
const [browser, setBrowser] = React.useState<string>();
React.useEffect(() => {
const isFirefox = typeof (window as unknown as Record<string, unknown>).InstallTrigger !== 'undefined';
if (isFirefox) {
setBrowser('firefox');
} else {
// TODO - detect other browsers
setBrowser('chrome');
}
}, []);

return React.useMemo(() => browser, [browser]);
};

+ 18
- 0
src/hooks/client-side.ts Zobrazit soubor

@@ -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]);
};

+ 94
- 0
src/hooks/form.ts Zobrazit soubor

@@ -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<ForwardedRef>;
valueSetterFn: (value: Value) => void;
transformChangeHandlerArgs?: (value: Value) => ValueType;
}

export const useProxyInput = <
TheValueType = ValueType,
ForwardedRefType extends HTMLElementWithValue = HTMLElementWithValue,
DefaultRefType extends HTMLElementWithValue = ForwardedRefType,
>(options: UseProxyInputOptions<ForwardedRefType, TheValueType>) => {
const {
forwardedRef,
valueSetterFn,
transformChangeHandlerArgs = (e) => e as ValueType,
} = options;
const defaultRef = React.useRef<DefaultRefType>(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<ForwardedRefType>;
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,
]);
};

+ 6
- 0
src/hooks/id.ts Zobrazit soubor

@@ -0,0 +1,6 @@
import * as React from 'react';

export const useFallbackId = (id?: string) => {
const defaultId = React.useId();
return id || defaultId;
};

+ 4
- 0
src/index.ts Zobrazit soubor

@@ -0,0 +1,4 @@
export * from './hooks/browser';
export * from './hooks/client-side';
export * from './hooks/form';
export * from './hooks/id';

+ 21
- 0
tsconfig.eslint.json Zobrazit soubor

@@ -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"
}
}

+ 21
- 0
tsconfig.json Zobrazit soubor

@@ -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"
}
}

+ 8
- 0
vitest.config.ts Zobrazit soubor

@@ -0,0 +1,8 @@
/// <reference types="vitest" />

export default ({
test: {
global: true,
environment: 'jsdom',
},
});

Načítá se…
Zrušit
Uložit