UNPKG

@enact/ui

Version:

A collection of simplified unstyled cross-platform UI components for Enact

161 lines (156 loc) 7.22 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; exports.useSlots = useSlots; var _react = require("react"); var _warning = _interopRequireDefault(require("warning")); var _excluded = ["children"]; 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); } function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; } // ** WARNING ** This is an intentional but likely dangerous hack necessary to clone a child while // omitting the `slot` property. It relies on the black box structure of a React element which could // change breaking this code. Without it, the slot property will cascade to a DOM node causing a // React warning. function cloneElement(child, index) { var newProps = Object.assign({}, child.props); delete newProps.slot; newProps.key = "slot-".concat(index); return /*#__PURE__*/(0, _react.createElement)(child.type, newProps); } function distributeChild(child, index, slots, props) { var c, slot; var hasSlot = function hasSlot(name) { return slots.indexOf(name) !== -1; }; if (! /*#__PURE__*/(0, _react.isValidElement)(child)) { return false; } else if (child.props.slot) { var hasUserSlot = hasSlot(slot = child.props.slot); process.env.NODE_ENV !== "production" ? (0, _warning["default"])(hasUserSlot, 'The slot "%s" specified on %s does not exist', child.props.slot, typeof child.type === 'string' ? child.type : child.type.name || child.type.displayName || 'component') : void 0; if (hasUserSlot) { c = cloneElement(child, index); } } else if (hasSlot(slot = child.type.defaultSlot)) { c = child; } else if (hasSlot(slot = child.type)) { var propNames = Object.keys(child.props); if (propNames.length === 1 && propNames[0] === 'children') { c = child.props.children; } else { c = child; } } if (c) { var prop = props[slot]; if (prop) { if (Array.isArray(prop)) { prop.push(c); } else { prop = [prop, c]; } } else { prop = c; } props[slot] = prop; return true; } return false; } function distribute(_ref) { var children = _ref.children, slots = _objectWithoutProperties(_ref, _excluded); var slotNames = Object.keys(slots); var props = { children: children }; if (slotNames.length > 0) { var remaining = []; _react.Children.forEach(children, function (child, index) { if (!distributeChild(child, index, slotNames, props)) { remaining.push(child); } }); // we need to retain the children prop so that it can overwrite the value from props if the // author spreads the return of useSlots over props props.children = remaining.length === 0 ? null : remaining; } slotNames.forEach(function (slot) { if (slots[slot] === undefined) { // eslint-disable-line no-undefined delete slots[slot]; } }); // We handle fallback here (rather than at the props initialization) because distributeChild // will append to existing props and we want the distributed value to override the fallback // value. return _objectSpread(_objectSpread({}, slots), props); } /** * Configuration for `useSlots` * * @typedef {Object} useSlotsConfig * @memberof ui/Slottable * @property {Object} [slots] An object mapping slot names to default values. It must contain a * `children` key with an array of elements to be distributed into slots. * @private */ /** * Distributes `children` into the configured `slots`. * * `useSlots` iterates over all the `children` in `props` and distributes any children based on * the following rules: * * * If the child has a `slot` property matching a valid slot, or * * If the component for the child has the `defaultSlot` static member matching a valid slot, or * * If the child component's type is a string matching a valid slot. * * When a child matches one of the above rules, it is removed from children and inserted into a prop * matching the name of the slot. * * *Special Conditions* * * * If multiple children match the same slot, the destination prop will be an array of children. * * If a value exists on `props` but not as a slot within `children`, the prop value is used as a * fallback. * * If a value exists both on `props` and as a slot within `children`, the slot value(s) replaces * the prop value. * * ``` * function Component ({after, before, children, label, ...rest}) { * const slots = useSlots({after, before, children, label}); * * return ( * <div {...rest} aria-label={label}> * <span class="before">{slots.before}</span> * {slots.children} * <span class="after">{slots.after}</span> * </div> * ); * } * * <Component label="descriptive label"> * <Icon slot="before">star</Icon> * Some other content * <Icon slot="after">flag</Icon> * </Component> * ``` * * @param {useSlotsConfig} config Configuration options * @returns {Object} A object whose keys are the slot names and values are the nodes from * `children`. If any nodes were not assigned to a slot, they will be returned in * the `children` prop. If no nodes remain, the `children` prop will be omitted. * @memberof ui/Slottable * @private */ function useSlots(slots) { return distribute(slots); } var _default = exports["default"] = useSlots;