Skip to content

Commit

Permalink
Merge pull request #45 from JoviDeCroock/chore/useContextSelectorPOC
Browse files Browse the repository at this point in the history
(chore) - performant context propagation
  • Loading branch information
JoviDeCroock authored Jul 22, 2019
2 parents 15f469d + c8c851c commit b503301
Show file tree
Hide file tree
Showing 23 changed files with 1,227 additions and 1,489 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,16 @@ So if you don't plan to target older browsers feel free to use this.
onSubmit your values get traversed however if the application doesn't know what your values are
it can't set anything as touched. This can be solved with passing `mapPropsToValues` or `initialValues`.


- I can't build

change the following in microbundle/dist/microbundle.js on line 731

```
mainFields: ['module', 'jsnext', 'main'],
only: ['tslib', 'use-context-selector']
```

## Credits

- [Microbundle](https://github.com/developit/microbundle)
Expand Down
2 changes: 1 addition & 1 deletion __tests__/components/ErrorMessage.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react';
import { act, cleanup, render } from 'react-testing-library';
import { act, cleanup, render } from '@testing-library/react';

import { ErrorMessage, Form } from '../../src';

Expand Down
2 changes: 1 addition & 1 deletion __tests__/components/Field.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

import * as React from 'react';
import { act, cleanup, fireEvent, render } from 'react-testing-library';
import { act, cleanup, fireEvent, render } from '@testing-library/react';

import { Field, Form } from '../../src';

Expand Down
2 changes: 1 addition & 1 deletion __tests__/components/FieldArray.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react';
import { act, cleanup, fireEvent, render } from 'react-testing-library';
import { act, cleanup, fireEvent, render } from '@testing-library/react';

import { Field, FieldArray, Form, useFormConnect } from '../../src';

Expand Down
2 changes: 1 addition & 1 deletion __tests__/components/Form.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react';
import { act, cleanup, render, wait } from 'react-testing-library';
import { act, cleanup, render, wait } from '@testing-library/react';
import { Form, useFormConnect } from '../../src';

const Component = () => (<p>Hi</p>);
Expand Down
2 changes: 1 addition & 1 deletion __tests__/hooks/hooks.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react';
import { act, cleanup, render } from 'react-testing-library';
import { act, cleanup, render } from '@testing-library/react';

import { useError, useField, useFieldArray, Form } from '../../src';

Expand Down
2 changes: 1 addition & 1 deletion __tests__/performance/ErrorMessage.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react';
import { act, cleanup, render } from 'react-testing-library';
import { act, cleanup, render } from '@testing-library/react';

import { ErrorMessage, Form } from '../../src';

Expand Down
2 changes: 1 addition & 1 deletion __tests__/performance/Field.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react';
import { act, cleanup, render } from 'react-testing-library';
import { act, cleanup, render } from '@testing-library/react';

import { Form, Field } from '../../src';

Expand Down
2 changes: 1 addition & 1 deletion __tests__/performance/FieldArray.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react';
import { act, cleanup, render } from 'react-testing-library';
import { act, cleanup, render } from '@testing-library/react';

import { Form, FieldArray } from '../../src';

Expand Down
51 changes: 26 additions & 25 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
{
"name": "hooked-form",
"version": "2.2.1",
"version": "2.3.0-alpha.0",
"description": "Forms done with React-Hooks",
"author": "jdecroock <[email protected]> (https://twitter.com/JoviDeC)",
"private": false,
"repository": "https://www.github.com/jovidecroock/hooked-form",
"sideEffects": false,
"scripts": {
"build": "rimraf dist && yarn build:es5 && yarn build:modern && yarn build:minified && yarn cleanup",
"build:minified": "microbundle --define process.env.NODE_ENV=production --name hookedForm --output dist/prod",
"build:es5": "microbundle --no-compress --name hookedForm --output dist/",
"build": "rimraf dist && node ./scripts/removeLine.js && yarn build:es5 && yarn build:modern && yarn build:minified && yarn cleanup",
"build:minified": "microbundle --jsx React.createElement --external react --define process.env.NODE_ENV=production --name hookedForm --output dist/prod",
"build:es5": "microbundle --jsx React.createElement --external react --no-compress --name hookedForm --output dist/",
"build:modern": "rollup -c && node ./scripts/sliceLicense.js",
"cleanup": "rimraf .rpt2_cache && rimraf .rts2_cache_cjs && rimraf .rts2_cache_umd && rimraf .rts2_cache_es",
"filesize": "bundlesize",
Expand Down Expand Up @@ -42,34 +42,35 @@
"@types/react": "16.8.2"
},
"devDependencies": {
"@ampproject/rollup-plugin-closure-compiler": "0.9.0",
"@types/jest": "24.0.13",
"@types/react": "16.8.8",
"@types/react-dom": "16.8.2",
"@testing-library/react": "8.0.5",
"@types/jest": "24.0.15",
"@types/react": "16.8.23",
"@types/react-dom": "16.8.4",
"codecov": "3.5.0",
"cross-env": "5.2.0",
"jest": "24.8.0",
"jest-cli": "24.8.0",
"microbundle": "0.11.0",
"microbundle": "^0.12.0-next.3",
"react": "16.9.0-alpha.0",
"react-dom": "16.9.0-alpha.0",
"react-testing-library": "7.0.1",
"rimraf": "2.6.3",
"rollup": "1.12.3",
"rollup-plugin-filesize": "6.0.1",
"rollup-plugin-node-resolve": "4.2.1",
"rollup-plugin-replace": "^2.2.0",
"rollup-plugin-terser": "4.0.4",
"rollup-plugin-typescript2": "0.20.1",
"rollup": "1.17.0",
"rollup-plugin-filesize": "6.1.1",
"rollup-plugin-node-resolve": "5.2.0",
"rollup-plugin-replace": "2.2.0",
"rollup-plugin-terser": "5.1.1",
"rollup-plugin-typescript2": "0.22.0",
"ts-jest": "24.0.2",
"tslib": "1.9.3",
"tslint": "5.12.1",
"tslib": "1.10.0",
"tslint": "5.18.0",
"tslint-config-airbnb": "5.11.1",
"tslint-config-prettier": "1.18.0",
"tslint-react": "3.6.0",
"typescript": "3.5.1"
"tslint-react": "4.0.0",
"typescript": "3.5.3"
},
"dependencies": {
"use-context-selector": "0.3.0"
},
"dependencies": {},
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
Expand Down Expand Up @@ -97,19 +98,19 @@
"bundlesize": [
{
"path": "./dist/prod/hooked-form.module.js",
"maxSize": "2.25 kB"
"maxSize": "2.5 kB"
},
{
"path": "./dist/prod/hooked-form.umd.js",
"maxSize": "2.25 kB"
"maxSize": "2.5 kB"
},
{
"path": "./dist/prod/hooked-form.js",
"maxSize": "2.25 kB"
"maxSize": "2.5 kB"
},
{
"path": "./dist/prod/hooked-form.modern.js",
"maxSize": "2 kB"
"maxSize": "2.25 kB"
}
]
}
16 changes: 9 additions & 7 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ import nodeResolve from 'rollup-plugin-node-resolve';
import filesize from 'rollup-plugin-filesize';
import typescript from 'typescript';
import typescriptPlugin from 'rollup-plugin-typescript2';
import compiler from '@ampproject/rollup-plugin-closure-compiler';
// import compiler from '@ampproject/rollup-plugin-closure-compiler';
import { terser } from 'rollup-plugin-terser';
import replace from 'rollup-plugin-replace';

const config = [
{
external: ['react', 'react-dom'],
input: 'src/index.ts',
output: {
file: 'dist/hooked-form.modern.js',
Expand All @@ -16,13 +17,14 @@ const config = [
},
plugins: [
nodeResolve({
mainFields: ['module'],
only: ['tslib']
mainFields: ['module', 'jsnext', 'main'],
only: ['tslib', 'use-context-selector']
}),
typescriptPlugin({ typescript, tsconfig: './tsconfig.json' }),
filesize(),
],
}, {
},
{
input: 'src/index.ts',
output: {
file: 'dist/prod/hooked-form.modern.js',
Expand All @@ -32,11 +34,11 @@ const config = [
plugins: [
replace({ 'process.env.NODE_ENV': JSON.stringify('production') }),
nodeResolve({
mainFields: ['module'],
only: ['tslib']
mainFields: ['module', 'jsnext', 'main'],
only: ['tslib', 'use-context-selector']
}),
typescriptPlugin({ typescript, tsconfig: './tsconfig.json', objectHashIgnoreUnknownHack: true }),
compiler({ compilation_level: 'ADVANCED_OPTIMIZATIONS' }),
// compiler({ compilation_level: 'ADVANCED_OPTIMIZATIONS' }),
terser({
sourcemap: true,
output: { comments: false },
Expand Down
15 changes: 15 additions & 0 deletions scripts/removeLine.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
var fs = require('fs');

const filename = `${process.cwd()}/node_modules/microbundle/dist/microbundle.js`;
const IGNORED_LINE = 647;

fs.readFile(filename, 'utf8', function(err, data) {
let lines = data.split('\n')
if (lines[IGNORED_LINE].includes('browser: options.target')) {
lines = lines.filter((x, i) => i !== IGNORED_LINE && !x.includes("browser: options.target !== 'node'"))
}
if (!lines[712].includes('fs.writeFileSync')) {
lines[712] = "fs.writeFileSync(path.resolve(options.cwd, 'mangle.json'), JSON.stringify(nameCache, null, 2));"
}
fs.writeFileSync(filename, lines.join('\n'))
})
4 changes: 2 additions & 2 deletions scripts/sliceLicense.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ const filename = `${process.cwd()}/dist/hooked-form.modern.js`;

fs.readFile(filename, 'utf8', function(err, data) {
const lines = data.split('\n');
const imports = lines.slice(0, 1);
const source = lines.slice(18);
const imports = lines.slice(0, 2);
const source = lines.slice(17);
const final = [...imports, ...source].join('\n');
fs.writeFile(filename, final, console.log);
});
5 changes: 2 additions & 3 deletions src/Error.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ const ErrorContainer: React.FC<FieldProps> = ({ component, fieldId }) => {
if (process.env.NODE_ENV !== 'production' && !component) {
throw new Error('The ErrorMessage needs a "component" property to function correctly.');
}
const error = useError(fieldId);
return React.useMemo(() => React.createElement(component, { error }), [error]);
return React.createElement(component, { error: useError(fieldId) });
};

export default React.memo(ErrorContainer, () => true);
export default ErrorContainer;
23 changes: 7 additions & 16 deletions src/Field.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as React from 'react';

import useField from './useField';

interface Props {
Expand All @@ -26,23 +25,15 @@ const FieldContainer: React.FC<FieldProps> = (

const {
0: actions,
1: { error, touched: isFieldTouched, value },
1: res,
} = useField(fieldId);

return React.useMemo(() =>
React.createElement(component, {
error,
ref: innerRef,
touched: isFieldTouched,
value,
...actions,
...rest,
}),
[
value, error, isFieldTouched,
...((watchableProps || defaultWatchables).map((key: string) => rest[key])),
],
);
return React.createElement(component, {
ref: innerRef,
...res,
...actions,
...rest,
});
};

export default React.memo(
Expand Down
9 changes: 3 additions & 6 deletions src/FieldArray.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,16 @@ const FieldArrayContainer: React.FC<FieldProps> = (
}
const {
0: actions,
1: { value, error },
1: res,
} = useFieldArray(fieldId);

const props = {
error,
fieldId,
value,
...res,
...actions,
};

return React.useMemo(() => component ?
React.createElement(component, props) :
render!(props), [value, error]);
return component ? React.createElement(component, props) : render!(props);
};

export default React.memo(FieldArrayContainer, () => true);
4 changes: 2 additions & 2 deletions src/helpers/context.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as React from 'react';
import { createContext } from 'use-context-selector';
import { FormHookContext } from '../types';

export const formContext = React.createContext<FormHookContext>({} as any);
export const formContext = createContext<FormHookContext>({} as any);
const { Provider } = formContext;
export { Provider };
12 changes: 6 additions & 6 deletions src/useError.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as React from 'react';
import { useContextSelector } from 'use-context-selector';
import { formContext } from './helpers/context';
import { get } from './helpers/operations';
import { FormHookContext } from './types';

export interface FieldInformation {
error: string;
Expand All @@ -10,9 +11,8 @@ export default function useError(fieldId: string): string | null {
if (process.env.NODE_ENV !== 'production' && (!fieldId || typeof fieldId !== 'string')) {
throw new Error('The Error needs a valid "fieldId" property to function correctly.');
}
const { errors } = React.useContext(formContext);
if (process.env.NODE_ENV !== 'production') {
React.useDebugValue(`${fieldId} Error: ${get(errors, fieldId)}`);
}
return React.useMemo(() => get(errors, fieldId), [errors]);
return useContextSelector(
formContext,
({ errors }: FormHookContext) => get(errors, fieldId),
);
}
19 changes: 9 additions & 10 deletions src/useField.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import * as React from 'react';
import { useContextSelector } from 'use-context-selector';
import { formContext } from './helpers/context';
import { get } from './helpers/operations';
import { FormHookContext } from './types';

export interface FieldOperations<T> {
onBlur: () => void;
Expand All @@ -25,13 +27,7 @@ export default function useField<T = any>(
throw new Error('The Field needs a valid "fieldId" property to function correctly.');
}
// Context
const { errors, values, setFieldValue, setFieldTouched, touched } = React.useContext(formContext);

if (process.env.NODE_ENV !== 'production') {
React.useDebugValue(`${fieldId} Value: ${get(values, fieldId)}`);
React.useDebugValue(`${fieldId} Touched: ${get(touched, fieldId)}`);
React.useDebugValue(`${fieldId} Error: ${get(errors, fieldId)}`);
}
const { setFieldValue, setFieldTouched } = React.useContext(formContext);

return [
{
Expand All @@ -47,9 +43,12 @@ export default function useField<T = any>(
setFieldValue,
},
{
error: React.useMemo(() => get(errors, fieldId), [errors]),
touched: React.useMemo(() => get(touched, fieldId), [touched]),
value: React.useMemo(() => get(values, fieldId) || '', [values]),
error: useContextSelector(
formContext, ({ errors }: FormHookContext) => get(errors, fieldId)),
touched: useContextSelector(
formContext, ({ touched }: FormHookContext) => get(touched, fieldId)),
value: useContextSelector(
formContext, ({ values }: FormHookContext) => get(values, fieldId) || ''),
},
];
}
Loading

0 comments on commit b503301

Please sign in to comment.