1
This commit is contained in:
+9
@@ -0,0 +1,9 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014-present yiminghe
|
||||
|
||||
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 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.
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
# @rc-component/context
|
||||
|
||||
---
|
||||
|
||||
React way perf context selector
|
||||
|
||||
[![NPM version][npm-image]][npm-url] [![build status][github-actions-image]][github-actions-url] [![Codecov][codecov-image]][codecov-url] [![node version][node-image]][node-url] [![npm download][download-image]][download-url]
|
||||
|
||||
[npm-image]: http://img.shields.io/npm/v/@rc-component/context.svg?style=flat-square
|
||||
[npm-url]: http://npmjs.org/package/@rc-component/context
|
||||
[github-actions-image]: https://github.com/react-component/context/workflows/CI/badge.svg
|
||||
[github-actions-url]: https://github.com/react-component/context/actions
|
||||
[codecov-image]: https://img.shields.io/codecov/c/github/react-component/context/master.svg?style=flat-square
|
||||
[codecov-url]: https://app.codecov.io/gh/react-component/context
|
||||
[node-image]: https://img.shields.io/badge/node.js-%3E=_0.10-green.svg?style=flat-square
|
||||
[node-url]: http://nodejs.org/download/
|
||||
[download-image]: https://img.shields.io/npm/dm/@rc-component/context.svg?style=flat-square
|
||||
[download-url]: https://npmjs.org/package/@rc-component/context
|
||||
|
||||
## Development
|
||||
|
||||
```
|
||||
npm install
|
||||
npm start
|
||||
```
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import * as React from 'react';
|
||||
export type CompareProps<T extends React.ComponentType<any>> = (prevProps: Readonly<React.ComponentProps<T>>, nextProps: Readonly<React.ComponentProps<T>>) => boolean;
|
||||
/**
|
||||
* Create Immutable pair for `makeImmutable` and `responseImmutable`.
|
||||
*/
|
||||
export default function createImmutable(): {
|
||||
makeImmutable: <T extends React.ComponentType<any>>(Component: T, shouldTriggerRender?: CompareProps<T>) => T;
|
||||
responseImmutable: <T_1 extends React.ComponentType<any>>(Component: T_1, propsAreEqual?: CompareProps<T_1>) => T_1;
|
||||
useImmutableMark: () => number;
|
||||
};
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
|
||||
import { supportRef } from "@rc-component/util/es/ref";
|
||||
import * as React from 'react';
|
||||
/**
|
||||
* Create Immutable pair for `makeImmutable` and `responseImmutable`.
|
||||
*/
|
||||
export default function createImmutable() {
|
||||
const ImmutableContext = /*#__PURE__*/React.createContext(null);
|
||||
|
||||
/**
|
||||
* Get render update mark by `makeImmutable` root.
|
||||
* Do not deps on the return value as render times
|
||||
* but only use for `useMemo` or `useCallback` deps.
|
||||
*/
|
||||
function useImmutableMark() {
|
||||
return React.useContext(ImmutableContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapped Component will be marked as Immutable.
|
||||
* When Component parent trigger render,
|
||||
* it will notice children component (use with `responseImmutable`) node that parent has updated.
|
||||
* @param Component Passed Component
|
||||
* @param triggerRender Customize trigger `responseImmutable` children re-render logic. Default will always trigger re-render when this component re-render.
|
||||
*/
|
||||
function makeImmutable(Component, shouldTriggerRender) {
|
||||
const refAble = supportRef(Component);
|
||||
const ImmutableComponent = (props, ref) => {
|
||||
const refProps = refAble ? {
|
||||
ref
|
||||
} : {};
|
||||
const renderTimesRef = React.useRef(0);
|
||||
const prevProps = React.useRef(props);
|
||||
|
||||
// If parent has the context, we do not wrap it
|
||||
const mark = useImmutableMark();
|
||||
if (mark !== null) {
|
||||
return /*#__PURE__*/React.createElement(Component, _extends({}, props, refProps));
|
||||
}
|
||||
if (
|
||||
// Always trigger re-render if `shouldTriggerRender` is not provided
|
||||
!shouldTriggerRender || shouldTriggerRender(prevProps.current, props)) {
|
||||
renderTimesRef.current += 1;
|
||||
}
|
||||
prevProps.current = props;
|
||||
return /*#__PURE__*/React.createElement(ImmutableContext.Provider, {
|
||||
value: renderTimesRef.current
|
||||
}, /*#__PURE__*/React.createElement(Component, _extends({}, props, refProps)));
|
||||
};
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
ImmutableComponent.displayName = `ImmutableRoot(${Component.displayName || Component.name})`;
|
||||
}
|
||||
return refAble ? /*#__PURE__*/React.forwardRef(ImmutableComponent) : ImmutableComponent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapped Component with `React.memo`.
|
||||
* But will rerender when parent with `makeImmutable` rerender.
|
||||
*/
|
||||
function responseImmutable(Component, propsAreEqual) {
|
||||
const refAble = supportRef(Component);
|
||||
const ImmutableComponent = (props, ref) => {
|
||||
const refProps = refAble ? {
|
||||
ref
|
||||
} : {};
|
||||
useImmutableMark();
|
||||
return /*#__PURE__*/React.createElement(Component, _extends({}, props, refProps));
|
||||
};
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
ImmutableComponent.displayName = `ImmutableResponse(${Component.displayName || Component.name})`;
|
||||
}
|
||||
return /*#__PURE__*/React.memo(refAble ? /*#__PURE__*/React.forwardRef(ImmutableComponent) : ImmutableComponent, propsAreEqual);
|
||||
}
|
||||
return {
|
||||
makeImmutable,
|
||||
responseImmutable,
|
||||
useImmutableMark
|
||||
};
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
import * as React from 'react';
|
||||
export type Selector<ContextProps, SelectorValue = ContextProps> = (value: ContextProps) => SelectorValue;
|
||||
export type Trigger<ContextProps> = (value: ContextProps) => void;
|
||||
export type Listeners<ContextProps> = Set<Trigger<ContextProps>>;
|
||||
export interface Context<ContextProps> {
|
||||
getValue: () => ContextProps;
|
||||
listeners: Listeners<ContextProps>;
|
||||
}
|
||||
export interface ContextSelectorProviderProps<T> {
|
||||
value: T;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
export interface SelectorContext<ContextProps> {
|
||||
Context: React.Context<Context<ContextProps>>;
|
||||
Provider: React.ComponentType<ContextSelectorProviderProps<ContextProps>>;
|
||||
defaultValue?: ContextProps;
|
||||
}
|
||||
export declare function createContext<ContextProps>(defaultValue?: ContextProps): SelectorContext<ContextProps>;
|
||||
/** e.g. useSelect(userContext) => user */
|
||||
export declare function useContext<ContextProps>(holder: SelectorContext<ContextProps>): ContextProps;
|
||||
/** e.g. useSelect(userContext, user => user.name) => user.name */
|
||||
export declare function useContext<ContextProps, SelectorValue>(holder: SelectorContext<ContextProps>, selector: Selector<ContextProps, SelectorValue>): SelectorValue;
|
||||
/** e.g. useSelect(userContext, ['name', 'age']) => user { name, age } */
|
||||
export declare function useContext<ContextProps, SelectorValue extends Partial<ContextProps>>(holder: SelectorContext<ContextProps>, selector: (keyof ContextProps)[]): SelectorValue;
|
||||
/** e.g. useSelect(userContext, 'name') => user.name */
|
||||
export declare function useContext<ContextProps, PropName extends keyof ContextProps>(holder: SelectorContext<ContextProps>, selector: PropName): ContextProps[PropName];
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
import useEvent from "@rc-component/util/es/hooks/useEvent";
|
||||
import useLayoutEffect from "@rc-component/util/es/hooks/useLayoutEffect";
|
||||
import isEqual from "@rc-component/util/es/isEqual";
|
||||
import * as React from 'react';
|
||||
import { unstable_batchedUpdates } from 'react-dom';
|
||||
export function createContext(defaultValue) {
|
||||
const Context = /*#__PURE__*/React.createContext(undefined);
|
||||
const Provider = ({
|
||||
value,
|
||||
children
|
||||
}) => {
|
||||
const valueRef = React.useRef(value);
|
||||
valueRef.current = value;
|
||||
const [context] = React.useState(() => ({
|
||||
getValue: () => valueRef.current,
|
||||
listeners: new Set()
|
||||
}));
|
||||
useLayoutEffect(() => {
|
||||
unstable_batchedUpdates(() => {
|
||||
context.listeners.forEach(listener => {
|
||||
listener(value);
|
||||
});
|
||||
});
|
||||
}, [value]);
|
||||
return /*#__PURE__*/React.createElement(Context.Provider, {
|
||||
value: context
|
||||
}, children);
|
||||
};
|
||||
return {
|
||||
Context,
|
||||
Provider,
|
||||
defaultValue
|
||||
};
|
||||
}
|
||||
|
||||
/** e.g. useSelect(userContext) => user */
|
||||
|
||||
/** e.g. useSelect(userContext, user => user.name) => user.name */
|
||||
|
||||
/** e.g. useSelect(userContext, ['name', 'age']) => user { name, age } */
|
||||
|
||||
/** e.g. useSelect(userContext, 'name') => user.name */
|
||||
|
||||
export function useContext(holder, selector) {
|
||||
const eventSelector = useEvent(typeof selector === 'function' ? selector : ctx => {
|
||||
if (selector === undefined) {
|
||||
return ctx;
|
||||
}
|
||||
if (!Array.isArray(selector)) {
|
||||
return ctx[selector];
|
||||
}
|
||||
const obj = {};
|
||||
selector.forEach(key => {
|
||||
obj[key] = ctx[key];
|
||||
});
|
||||
return obj;
|
||||
});
|
||||
const context = React.useContext(holder?.Context);
|
||||
const {
|
||||
listeners,
|
||||
getValue
|
||||
} = context || {};
|
||||
const valueRef = React.useRef();
|
||||
valueRef.current = eventSelector(context ? getValue() : holder?.defaultValue);
|
||||
const [, forceUpdate] = React.useState({});
|
||||
useLayoutEffect(() => {
|
||||
if (!context) {
|
||||
return;
|
||||
}
|
||||
function trigger(nextValue) {
|
||||
const nextSelectorValue = eventSelector(nextValue);
|
||||
if (!isEqual(valueRef.current, nextSelectorValue, true)) {
|
||||
forceUpdate({});
|
||||
}
|
||||
}
|
||||
listeners.add(trigger);
|
||||
return () => {
|
||||
listeners.delete(trigger);
|
||||
};
|
||||
}, [context]);
|
||||
return valueRef.current;
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
/// <reference types="react" />
|
||||
import type { SelectorContext } from './context';
|
||||
import { createContext, useContext } from './context';
|
||||
import createImmutable from './Immutable';
|
||||
declare const makeImmutable: <T extends import("react").ComponentType<any>>(Component: T, shouldTriggerRender?: import("./Immutable").CompareProps<T>) => T, responseImmutable: <T extends import("react").ComponentType<any>>(Component: T, propsAreEqual?: import("./Immutable").CompareProps<T>) => T, useImmutableMark: () => number;
|
||||
export { createContext, useContext, createImmutable, makeImmutable, responseImmutable, useImmutableMark, };
|
||||
export type { SelectorContext };
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import { createContext, useContext } from "./context";
|
||||
import createImmutable from "./Immutable";
|
||||
|
||||
// For legacy usage, we export it directly
|
||||
const {
|
||||
makeImmutable,
|
||||
responseImmutable,
|
||||
useImmutableMark
|
||||
} = createImmutable();
|
||||
export { createContext, useContext, createImmutable, makeImmutable, responseImmutable, useImmutableMark };
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import * as React from 'react';
|
||||
export type CompareProps<T extends React.ComponentType<any>> = (prevProps: Readonly<React.ComponentProps<T>>, nextProps: Readonly<React.ComponentProps<T>>) => boolean;
|
||||
/**
|
||||
* Create Immutable pair for `makeImmutable` and `responseImmutable`.
|
||||
*/
|
||||
export default function createImmutable(): {
|
||||
makeImmutable: <T extends React.ComponentType<any>>(Component: T, shouldTriggerRender?: CompareProps<T>) => T;
|
||||
responseImmutable: <T_1 extends React.ComponentType<any>>(Component: T_1, propsAreEqual?: CompareProps<T_1>) => T_1;
|
||||
useImmutableMark: () => number;
|
||||
};
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = createImmutable;
|
||||
var _ref = require("@rc-component/util/lib/ref");
|
||||
var React = _interopRequireWildcard(require("react"));
|
||||
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
|
||||
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
|
||||
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
|
||||
/**
|
||||
* Create Immutable pair for `makeImmutable` and `responseImmutable`.
|
||||
*/
|
||||
function createImmutable() {
|
||||
const ImmutableContext = /*#__PURE__*/React.createContext(null);
|
||||
|
||||
/**
|
||||
* Get render update mark by `makeImmutable` root.
|
||||
* Do not deps on the return value as render times
|
||||
* but only use for `useMemo` or `useCallback` deps.
|
||||
*/
|
||||
function useImmutableMark() {
|
||||
return React.useContext(ImmutableContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapped Component will be marked as Immutable.
|
||||
* When Component parent trigger render,
|
||||
* it will notice children component (use with `responseImmutable`) node that parent has updated.
|
||||
* @param Component Passed Component
|
||||
* @param triggerRender Customize trigger `responseImmutable` children re-render logic. Default will always trigger re-render when this component re-render.
|
||||
*/
|
||||
function makeImmutable(Component, shouldTriggerRender) {
|
||||
const refAble = (0, _ref.supportRef)(Component);
|
||||
const ImmutableComponent = (props, ref) => {
|
||||
const refProps = refAble ? {
|
||||
ref
|
||||
} : {};
|
||||
const renderTimesRef = React.useRef(0);
|
||||
const prevProps = React.useRef(props);
|
||||
|
||||
// If parent has the context, we do not wrap it
|
||||
const mark = useImmutableMark();
|
||||
if (mark !== null) {
|
||||
return /*#__PURE__*/React.createElement(Component, _extends({}, props, refProps));
|
||||
}
|
||||
if (
|
||||
// Always trigger re-render if `shouldTriggerRender` is not provided
|
||||
!shouldTriggerRender || shouldTriggerRender(prevProps.current, props)) {
|
||||
renderTimesRef.current += 1;
|
||||
}
|
||||
prevProps.current = props;
|
||||
return /*#__PURE__*/React.createElement(ImmutableContext.Provider, {
|
||||
value: renderTimesRef.current
|
||||
}, /*#__PURE__*/React.createElement(Component, _extends({}, props, refProps)));
|
||||
};
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
ImmutableComponent.displayName = `ImmutableRoot(${Component.displayName || Component.name})`;
|
||||
}
|
||||
return refAble ? /*#__PURE__*/React.forwardRef(ImmutableComponent) : ImmutableComponent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapped Component with `React.memo`.
|
||||
* But will rerender when parent with `makeImmutable` rerender.
|
||||
*/
|
||||
function responseImmutable(Component, propsAreEqual) {
|
||||
const refAble = (0, _ref.supportRef)(Component);
|
||||
const ImmutableComponent = (props, ref) => {
|
||||
const refProps = refAble ? {
|
||||
ref
|
||||
} : {};
|
||||
useImmutableMark();
|
||||
return /*#__PURE__*/React.createElement(Component, _extends({}, props, refProps));
|
||||
};
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
ImmutableComponent.displayName = `ImmutableResponse(${Component.displayName || Component.name})`;
|
||||
}
|
||||
return /*#__PURE__*/React.memo(refAble ? /*#__PURE__*/React.forwardRef(ImmutableComponent) : ImmutableComponent, propsAreEqual);
|
||||
}
|
||||
return {
|
||||
makeImmutable,
|
||||
responseImmutable,
|
||||
useImmutableMark
|
||||
};
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
import * as React from 'react';
|
||||
export type Selector<ContextProps, SelectorValue = ContextProps> = (value: ContextProps) => SelectorValue;
|
||||
export type Trigger<ContextProps> = (value: ContextProps) => void;
|
||||
export type Listeners<ContextProps> = Set<Trigger<ContextProps>>;
|
||||
export interface Context<ContextProps> {
|
||||
getValue: () => ContextProps;
|
||||
listeners: Listeners<ContextProps>;
|
||||
}
|
||||
export interface ContextSelectorProviderProps<T> {
|
||||
value: T;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
export interface SelectorContext<ContextProps> {
|
||||
Context: React.Context<Context<ContextProps>>;
|
||||
Provider: React.ComponentType<ContextSelectorProviderProps<ContextProps>>;
|
||||
defaultValue?: ContextProps;
|
||||
}
|
||||
export declare function createContext<ContextProps>(defaultValue?: ContextProps): SelectorContext<ContextProps>;
|
||||
/** e.g. useSelect(userContext) => user */
|
||||
export declare function useContext<ContextProps>(holder: SelectorContext<ContextProps>): ContextProps;
|
||||
/** e.g. useSelect(userContext, user => user.name) => user.name */
|
||||
export declare function useContext<ContextProps, SelectorValue>(holder: SelectorContext<ContextProps>, selector: Selector<ContextProps, SelectorValue>): SelectorValue;
|
||||
/** e.g. useSelect(userContext, ['name', 'age']) => user { name, age } */
|
||||
export declare function useContext<ContextProps, SelectorValue extends Partial<ContextProps>>(holder: SelectorContext<ContextProps>, selector: (keyof ContextProps)[]): SelectorValue;
|
||||
/** e.g. useSelect(userContext, 'name') => user.name */
|
||||
export declare function useContext<ContextProps, PropName extends keyof ContextProps>(holder: SelectorContext<ContextProps>, selector: PropName): ContextProps[PropName];
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createContext = createContext;
|
||||
exports.useContext = useContext;
|
||||
var _useEvent = _interopRequireDefault(require("@rc-component/util/lib/hooks/useEvent"));
|
||||
var _useLayoutEffect = _interopRequireDefault(require("@rc-component/util/lib/hooks/useLayoutEffect"));
|
||||
var _isEqual = _interopRequireDefault(require("@rc-component/util/lib/isEqual"));
|
||||
var React = _interopRequireWildcard(require("react"));
|
||||
var _reactDom = require("react-dom");
|
||||
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
|
||||
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
function createContext(defaultValue) {
|
||||
const Context = /*#__PURE__*/React.createContext(undefined);
|
||||
const Provider = ({
|
||||
value,
|
||||
children
|
||||
}) => {
|
||||
const valueRef = React.useRef(value);
|
||||
valueRef.current = value;
|
||||
const [context] = React.useState(() => ({
|
||||
getValue: () => valueRef.current,
|
||||
listeners: new Set()
|
||||
}));
|
||||
(0, _useLayoutEffect.default)(() => {
|
||||
(0, _reactDom.unstable_batchedUpdates)(() => {
|
||||
context.listeners.forEach(listener => {
|
||||
listener(value);
|
||||
});
|
||||
});
|
||||
}, [value]);
|
||||
return /*#__PURE__*/React.createElement(Context.Provider, {
|
||||
value: context
|
||||
}, children);
|
||||
};
|
||||
return {
|
||||
Context,
|
||||
Provider,
|
||||
defaultValue
|
||||
};
|
||||
}
|
||||
|
||||
/** e.g. useSelect(userContext) => user */
|
||||
|
||||
/** e.g. useSelect(userContext, user => user.name) => user.name */
|
||||
|
||||
/** e.g. useSelect(userContext, ['name', 'age']) => user { name, age } */
|
||||
|
||||
/** e.g. useSelect(userContext, 'name') => user.name */
|
||||
|
||||
function useContext(holder, selector) {
|
||||
const eventSelector = (0, _useEvent.default)(typeof selector === 'function' ? selector : ctx => {
|
||||
if (selector === undefined) {
|
||||
return ctx;
|
||||
}
|
||||
if (!Array.isArray(selector)) {
|
||||
return ctx[selector];
|
||||
}
|
||||
const obj = {};
|
||||
selector.forEach(key => {
|
||||
obj[key] = ctx[key];
|
||||
});
|
||||
return obj;
|
||||
});
|
||||
const context = React.useContext(holder?.Context);
|
||||
const {
|
||||
listeners,
|
||||
getValue
|
||||
} = context || {};
|
||||
const valueRef = React.useRef();
|
||||
valueRef.current = eventSelector(context ? getValue() : holder?.defaultValue);
|
||||
const [, forceUpdate] = React.useState({});
|
||||
(0, _useLayoutEffect.default)(() => {
|
||||
if (!context) {
|
||||
return;
|
||||
}
|
||||
function trigger(nextValue) {
|
||||
const nextSelectorValue = eventSelector(nextValue);
|
||||
if (!(0, _isEqual.default)(valueRef.current, nextSelectorValue, true)) {
|
||||
forceUpdate({});
|
||||
}
|
||||
}
|
||||
listeners.add(trigger);
|
||||
return () => {
|
||||
listeners.delete(trigger);
|
||||
};
|
||||
}, [context]);
|
||||
return valueRef.current;
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
/// <reference types="react" />
|
||||
import type { SelectorContext } from './context';
|
||||
import { createContext, useContext } from './context';
|
||||
import createImmutable from './Immutable';
|
||||
declare const makeImmutable: <T extends import("react").ComponentType<any>>(Component: T, shouldTriggerRender?: import("./Immutable").CompareProps<T>) => T, responseImmutable: <T extends import("react").ComponentType<any>>(Component: T, propsAreEqual?: import("./Immutable").CompareProps<T>) => T, useImmutableMark: () => number;
|
||||
export { createContext, useContext, createImmutable, makeImmutable, responseImmutable, useImmutableMark, };
|
||||
export type { SelectorContext };
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "createContext", {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return _context.createContext;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "createImmutable", {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return _Immutable.default;
|
||||
}
|
||||
});
|
||||
exports.responseImmutable = exports.makeImmutable = void 0;
|
||||
Object.defineProperty(exports, "useContext", {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return _context.useContext;
|
||||
}
|
||||
});
|
||||
exports.useImmutableMark = void 0;
|
||||
var _context = require("./context");
|
||||
var _Immutable = _interopRequireDefault(require("./Immutable"));
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
// For legacy usage, we export it directly
|
||||
const {
|
||||
makeImmutable,
|
||||
responseImmutable,
|
||||
useImmutableMark
|
||||
} = (0, _Immutable.default)();
|
||||
exports.useImmutableMark = useImmutableMark;
|
||||
exports.responseImmutable = responseImmutable;
|
||||
exports.makeImmutable = makeImmutable;
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
{
|
||||
"name": "@rc-component/context",
|
||||
"version": "2.0.1",
|
||||
"description": "React way perf context selector",
|
||||
"keywords": [
|
||||
"react",
|
||||
"react-component",
|
||||
"context"
|
||||
],
|
||||
"homepage": "http://github.com/react-component/context",
|
||||
"bugs": {
|
||||
"url": "http://github.com/react-component/context/issues"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git@github.com:react-component/context.git"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "",
|
||||
"main": "./lib/index",
|
||||
"module": "./es/index",
|
||||
"files": [
|
||||
"lib",
|
||||
"es"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "dumi build",
|
||||
"compile": "father build",
|
||||
"coverage": "father test --coverage",
|
||||
"lint": "eslint src/ docs/ --ext .tsx,.ts,.jsx,.js",
|
||||
"now-build": "npm run build",
|
||||
"prepublishOnly": "npm run compile && rc-np",
|
||||
"start": "dumi dev",
|
||||
"test": "rc-test",
|
||||
"tsc": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@rc-component/util": "^1.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rc-component/father-plugin": "^2.0.2",
|
||||
"@rc-component/np": "^1.0.4",
|
||||
"@types/jest": "^29.5.0",
|
||||
"@types/node": "^24.5.2",
|
||||
"@types/react": "^18.0.0",
|
||||
"@types/react-dom": "^18.0.0",
|
||||
"@types/warning": "^3.0.0",
|
||||
"@umijs/fabric": "^4.0.0",
|
||||
"cross-env": "^7.0.3",
|
||||
"dumi": "^2.0.15",
|
||||
"eslint": "^8.54.0",
|
||||
"eslint-plugin-jest": "^28.2.0",
|
||||
"eslint-plugin-unicorn": "^52.0.0",
|
||||
"father": "^4.0.0",
|
||||
"rc-test": "^7.0.14",
|
||||
"react": "^18.0.0",
|
||||
"react-dom": "^18.0.0",
|
||||
"typescript": "^5.0.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.9.0",
|
||||
"react-dom": ">=16.9.0"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user