UNPKG

@enact/core

Version:

Enact is an open source JavaScript framework containing everything you need to create a fast, scalable mobile or web application.

184 lines (171 loc) 8.22 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.functionalKind = exports["default"] = void 0; var _react = require("react"); var _useHandlers = _interopRequireDefault(require("../useHandlers")); var _util = require("../util"); var _computed = _interopRequireDefault(require("./computed")); var _styles = _interopRequireDefault(require("./styles")); var _util2 = require("./util"); function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* * Provides the {@link core/kind.functionalKind} method to create components * * @module core/kind * @exports functionalKind */ // Fallback context when none is specified. var NoContext = /*#__PURE__*/(0, _react.createContext)(null); /* * @callback RenderFunction * @memberof core/kind * @param {Object<string, any>} props * @param {Object<string, any>} context * @returns React.Element|null */ /* * @callback ComputedPropFunction * @memberof core/kind * @param {Object<string, any>} props * @param {Object<string, any>} context * @returns any */ /* * @callback HandlerFunction * @memberof core/kind * @param {any} event * @param {Object<string, any>} props * @param {Object<string, any>} context */ /* * Configuration for CSS class name mapping * * @typedef {Object} StylesBlock * @memberof core/kind * @property {Object.<string, string>} css The CSS of the component * @property {String} [className] The className of the component * @property {Boolean|String|String[]} [publicClassNames] Specifies which class names are overridable. * If this value is `true`, all the class names of the component CSS will become public. */ /* * @typedef {Object} KindConfig * @memberof core/kind * @property {String} [name] The name of the component * @property {Object.<string, Function>} [propTypes] Specifies expected props * @property {Object.<string, any>} [defaultProps] Sets the default props * @property {Object} [contextType] Specifies context type * @property {StylesBlock} [styles] Configures styles * @property {Object.<string, HandlerFunction>} [handlers] Adds event handlers * @property {Object.<string, ComputedPropFunction>} [computed] Adds computed properties * @property {RenderFunction} useRender The useRender function */ /* * Creates a new component with some helpful declarative syntactic sugar. * * Example: * ``` * import css from './Button.module.less'; * // Return a functional component * const Button = functionalKind({ * name: 'Button', * // expect color and onClick properties but neither required * propTypes: { * color: PropTypes.string * }, * // if no color is provided, it'll be green * defaultProps: { * color: 'green' * }, * // expect backgroundColor via context * contextType: React.createContext({ backgroundColor }), * // configure styles with the static className to merge with user className * styles: { * // include the CSS modules map so 'button' can be resolved to the local name * css, * className: 'button' * }, * // add event handlers that are cached between calls to prevent recreating each call. Any * // handlers are added to the props passed to `useRender()`. See core/handle. * handlers: { * onKeyDown: (evt, props) => { .... } * }, * // add some computed properties, these are added to props passed to `useRender()` * computed: { * // border color will be the color prepended by 'light' * borderColor: ({color}) => 'light' + color, * // background color will be the contextual background color if specified * color: ({color}, context) => context.backgroundColor || color * }, * // Render the thing, already! * useRender: ({color, borderColor, children, ...rest}) => ( * <button * {...rest} * style={{backgroundColor: color, borderColor}} * > * {children} * </button> * ) * }); /* * Creates a new functional component with declarative syntactic sugar. * * @function * @template Props * @param {KindConfig} config Component configuration * @returns {Component<Props>} * @memberof core/kind * @private */ var functionalKind = exports.functionalKind = function functionalKind(config) { var cfgComputed = config.computed, _config$contextType = config.contextType, contextType = _config$contextType === void 0 ? NoContext : _config$contextType, defaultProps = config.defaultProps, handlers = config.handlers, name = config.name, propTypes = config.propTypes, useRender = config.useRender, cfgStyles = config.styles; var renderStyles = cfgStyles ? (0, _styles["default"])(cfgStyles) : false; var renderComputed = cfgComputed ? (0, _computed["default"])(cfgComputed) : false; var renderKind = function renderKind(props, context) { if (renderStyles) props = renderStyles(props, context); if (renderComputed) props = renderComputed(props, context); return useRender(props, context); // eslint-disable-line react-hooks/rules-of-hooks }; var defaultPropKeys = defaultProps ? Object.keys(defaultProps) : null; var handlerKeys = handlers ? Object.keys(handlers) : null; var _Component = function Component(props) { // Hooks must always be called unconditionally and in the same order. // useContext only accepts Context and never suspends (unlike use(), which can suspend on Promises and break SSR). var ctx = (0, _react.useContext)(contextType); var boundHandlers = (0, _useHandlers["default"])(handlers, props, ctx); // Merge incoming props with bound handlers. var merged = _objectSpread(_objectSpread({}, props), boundHandlers); // Apply defaultProps manually so functional components // receive defaults even when React's own defaultProps is set. (0, _util.applyDefaultProps)(merged, defaultProps, defaultPropKeys); (0, _util.checkPropTypes)(_Component, merged); return renderKind(merged, ctx); }; if (name) _Component.displayName = name; if (propTypes) _Component.propTypes = propTypes; if (defaultProps) _Component.defaultProps = defaultProps; // Expose computed map in DEV for easier testability. if (process.env.NODE_ENV !== "production" && cfgComputed) _Component.computed = cfgComputed; // ── inline ────────────────────────────────────────────────────────────── // A synchronous, hook-free path for calling the component logic outside // of the React render cycle (e.g. in tests or server-side utilities). _Component.inline = function (props, context) { var updated = (0, _util.applyDefaultProps)(_objectSpread({}, props), defaultProps, defaultPropKeys); return renderKind((0, _util2.bindInlineHandlers)(updated, handlers, handlerKeys, context), context); }; return _Component; }; var _default = exports["default"] = functionalKind;