0.2.0 - Mid migration

This commit is contained in:
Daniel Mason 2022-04-25 14:47:15 +12:00
parent 139e6a915e
commit 7e38fdbd7d
42393 changed files with 5358157 additions and 62 deletions

View file

@ -0,0 +1,19 @@
Copyright (c) 2017-present James Kyle <me@thejameskyle.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 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.

View file

@ -0,0 +1,99 @@
# create-react-context
> Polyfill for the [proposed React context API](https://github.com/reactjs/rfcs/pull/2)
## Install
```sh
yarn add create-react-context
```
You'll need to also have `react` and `prop-types` installed.
## API
```js
const Context = createReactContext(defaultValue);
// <Context.Provider value={providedValue}>{children}</Context.Provider>
// ...
// <Context.Consumer>{value => children}</Context.Consumer>
```
## Example
```js
// @flow
import React, { type Node } from 'react';
import createReactContext, { type Context } from 'create-react-context';
type Theme = 'light' | 'dark';
// Pass a default theme to ensure type correctness
const ThemeContext: Context<Theme> = createReactContext('light');
class ThemeToggler extends React.Component<
{ children: Node },
{ theme: Theme }
> {
state = { theme: 'light' };
render() {
return (
// Pass the current context value to the Provider's `value` prop.
// Changes are detected using strict comparison (Object.is)
<ThemeContext.Provider value={this.state.theme}>
<button
onClick={() => {
this.setState(state => ({
theme: state.theme === 'light' ? 'dark' : 'light'
}));
}}
>
Toggle theme
</button>
{this.props.children}
</ThemeContext.Provider>
);
}
}
class Title extends React.Component<{ children: Node }> {
render() {
return (
// The Consumer uses a render prop API. Avoids conflicts in the
// props namespace.
<ThemeContext.Consumer>
{theme => (
<h1 style={{ color: theme === 'light' ? '#000' : '#fff' }}>
{this.props.children}
</h1>
)}
</ThemeContext.Consumer>
);
}
}
```
## Compatibility
This package only "ponyfills" the `React.createContext` API, not other
unrelated React 16+ APIs. If you are using a version of React <16, keep
in mind that you can only use features available in that version.
For example, you cannot pass children types aren't valid pre React 16:
```js
<Context.Provider>
<div/>
<div/>
</Context.Provider>
```
It will throw `A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.` because `<Context.Provider>` can only receive a single child element. To fix the error just wrap everyting in a single `<div>`:
```js
<Context.Provider>
<div>
<div/>
<div/>
</div>
</Context.Provider>
```

View file

@ -0,0 +1,196 @@
'use strict';
exports.__esModule = true;
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _gud = require('gud');
var _gud2 = _interopRequireDefault(_gud);
var _warning = require('warning');
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var MAX_SIGNED_31_BIT_INT = 1073741823;
// Inlined Object.is polyfill.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
function objectIs(x, y) {
if (x === y) {
return x !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
function createEventEmitter(value) {
var handlers = [];
return {
on: function on(handler) {
handlers.push(handler);
},
off: function off(handler) {
handlers = handlers.filter(function (h) {
return h !== handler;
});
},
get: function get() {
return value;
},
set: function set(newValue, changedBits) {
value = newValue;
handlers.forEach(function (handler) {
return handler(value, changedBits);
});
}
};
}
function onlyChild(children) {
return Array.isArray(children) ? children[0] : children;
}
function createReactContext(defaultValue, calculateChangedBits) {
var _Provider$childContex, _Consumer$contextType;
var contextProp = '__create-react-context-' + (0, _gud2.default)() + '__';
var Provider = function (_Component) {
_inherits(Provider, _Component);
function Provider() {
var _temp, _this, _ret;
_classCallCheck(this, Provider);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.emitter = createEventEmitter(_this.props.value), _temp), _possibleConstructorReturn(_this, _ret);
}
Provider.prototype.getChildContext = function getChildContext() {
var _ref;
return _ref = {}, _ref[contextProp] = this.emitter, _ref;
};
Provider.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.props.value !== nextProps.value) {
var oldValue = this.props.value;
var newValue = nextProps.value;
var changedBits = void 0;
if (objectIs(oldValue, newValue)) {
changedBits = 0; // No change
} else {
changedBits = typeof calculateChangedBits === 'function' ? calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
if (process.env.NODE_ENV !== 'production') {
(0, _warning2.default)((changedBits & MAX_SIGNED_31_BIT_INT) === changedBits, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits);
}
changedBits |= 0;
if (changedBits !== 0) {
this.emitter.set(nextProps.value, changedBits);
}
}
}
};
Provider.prototype.render = function render() {
return this.props.children;
};
return Provider;
}(_react.Component);
Provider.childContextTypes = (_Provider$childContex = {}, _Provider$childContex[contextProp] = _propTypes2.default.object.isRequired, _Provider$childContex);
var Consumer = function (_Component2) {
_inherits(Consumer, _Component2);
function Consumer() {
var _temp2, _this2, _ret2;
_classCallCheck(this, Consumer);
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return _ret2 = (_temp2 = (_this2 = _possibleConstructorReturn(this, _Component2.call.apply(_Component2, [this].concat(args))), _this2), _this2.state = {
value: _this2.getValue()
}, _this2.onUpdate = function (newValue, changedBits) {
var observedBits = _this2.observedBits | 0;
if ((observedBits & changedBits) !== 0) {
_this2.setState({ value: _this2.getValue() });
}
}, _temp2), _possibleConstructorReturn(_this2, _ret2);
}
Consumer.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var observedBits = nextProps.observedBits;
this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT // Subscribe to all changes by default
: observedBits;
};
Consumer.prototype.componentDidMount = function componentDidMount() {
if (this.context[contextProp]) {
this.context[contextProp].on(this.onUpdate);
}
var observedBits = this.props.observedBits;
this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT // Subscribe to all changes by default
: observedBits;
};
Consumer.prototype.componentWillUnmount = function componentWillUnmount() {
if (this.context[contextProp]) {
this.context[contextProp].off(this.onUpdate);
}
};
Consumer.prototype.getValue = function getValue() {
if (this.context[contextProp]) {
return this.context[contextProp].get();
} else {
return defaultValue;
}
};
Consumer.prototype.render = function render() {
return onlyChild(this.props.children)(this.state.value);
};
return Consumer;
}(_react.Component);
Consumer.contextTypes = (_Consumer$contextType = {}, _Consumer$contextType[contextProp] = _propTypes2.default.object, _Consumer$contextType);
return {
Provider: Provider,
Consumer: Consumer
};
}
exports.default = createReactContext;
module.exports = exports['default'];

View file

@ -0,0 +1,23 @@
import * as React from 'react';
export default function createReactContext<T>(
defaultValue: T,
calculateChangedBits?: (prev: T, next: T) => number
): Context<T>;
type RenderFn<T> = (value: T) => React.ReactNode;
export type Context<T> = {
Provider: React.ComponentClass<ProviderProps<T>>;
Consumer: React.ComponentClass<ConsumerProps<T>>;
};
export type ProviderProps<T> = {
value: T;
children: React.ReactNode;
};
export type ConsumerProps<T> = {
children: RenderFn<T> | [RenderFn<T>];
observedBits?: number;
};

View file

@ -0,0 +1,16 @@
'use strict';
exports.__esModule = true;
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _implementation = require('./implementation');
var _implementation2 = _interopRequireDefault(_implementation);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _react2.default.createContext || _implementation2.default;
module.exports = exports['default'];

View file

@ -0,0 +1,31 @@
// @flow
import { Component, type Node } from 'react';
type RenderFn<T> = (value: T) => Node;
export type ProviderProps<T> = {
value: T,
children?: Node
};
export type ConsumerProps<T> = {
children: RenderFn<T> | [RenderFn<T>],
observedBits?: number
};
export type ConsumerState<T> = {
value: T
};
export type Provider<T> = Component<ProviderProps<T>>;
export type Consumer<T> = Component<ConsumerProps<T>, ConsumerState<T>>;
export type Context<T> = {
Provider: Class<Provider<T>>,
Consumer: Class<Consumer<T>>
};
declare export default function createReactContext<T>(
defaultValue: T,
calculateChangedBits?: (prev: T, next: T) => number
): Context<T>;

View file

@ -0,0 +1,70 @@
{
"name": "@hypnosphi/create-react-context",
"publishConfig": {
"access": "public"
},
"version": "0.3.1",
"description": "Polyfill for the proposed React context API",
"main": "lib/index.js",
"typings": "lib/index.d.ts",
"repository": "https://github.com/thejameskyle/create-react-context",
"author": "James Kyle <me@thejameskyle.com>",
"license": "MIT",
"keywords": [
"react",
"context",
"contextTypes",
"polyfill",
"ponyfill"
],
"files": [
"lib"
],
"scripts": {
"test": "jest",
"flow": "flow",
"format": "prettier --write '**/*.{js,md,json,js.flow,d.ts}'",
"build": "babel src -d lib --copy-files --ignore __tests__",
"prepublish": "yarn build",
"commit": "lint-staged"
},
"dependencies": {
"gud": "^1.0.0",
"warning": "^4.0.3"
},
"peerDependencies": {
"prop-types": "^15.0.0",
"react": ">=0.14.0"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-env": "^1.6.1",
"babel-preset-flow": "^6.23.0",
"babel-preset-react": "^6.24.1",
"enzyme": "^3.2.0",
"enzyme-adapter-react-16": "^1.1.0",
"enzyme-to-json": "^3.2.2",
"flow-bin": "^0.60.1",
"husky": "^0.14.3",
"jest": "^21.2.1",
"lint-staged": "^6.0.0",
"prettier": "^1.9.1",
"prop-types": "^15.6.0",
"raf": "^3.4.0",
"react": "^16.2.0",
"react-dom": "^16.2.0"
},
"lint-staged": {
"*.{js,md,json,js.flow,d.ts}": [
"prettier --write",
"git add"
]
},
"jest": {
"snapshotSerializers": [
"enzyme-to-json/serializer"
]
}
}