UNPKG

@coko/client

Version:

Client side common code for coko apps

148 lines (147 loc) 10.7 kB
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireWildcard(require("react")); var _styledComponents = _interopRequireDefault(require("styled-components")); var _propTypes = _interopRequireDefault(require("prop-types")); var _toolkit = require("../../toolkit"); var _index = require("../../index"); var _theme = _interopRequireDefault(require("../../theme")); var _excluded = ["alignment", "children", "focusableContent", "id", "toggle", "position"]; var _templateObject, _templateObject2; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } 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); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } var PopupContainer = _styledComponents["default"].div(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n background: ", ";\n border: 1px solid ", ";\n border-radius: 10px;\n display: ", ";\n\n ", "\n padding: ", ";\n position: absolute;\n\n z-index: 1000;\n"])), _theme["default"].colorBackground, _theme["default"].colorBorder, function (_ref) { var visible = _ref.visible; return visible ? 'block' : 'none'; }, function (props) { var position = props.position, alignment = props.alignment; switch ("".concat(position, "/").concat(alignment)) { case 'block-start/start': return "inset-block-end: 100%; inset-inline-start: 0; margin-block-end: ".concat(props.theme.gridUnit, ";"); case 'block-start/end': return "inset-block-end: 100%; inset-inline-end: 0; margin-block-end: ".concat(props.theme.gridUnit, ";"); case 'block-end/start': return "inset-block-start: 100%; inset-inline-start: 0; margin-block-start: ".concat(props.theme.gridUnit, ";"); case 'block-end/end': return "inset-block-start: 100%; inset-inline-end: 0; margin-block-start: ".concat(props.theme.gridUnit, ";"); case 'inline-start/start': return "inset-inline-end: 100%; inset-block-start: 0; margin-inline-end: ".concat(props.theme.gridUnit, ";"); case 'inline-start/end': return "inset-inline-end: 100%; inset-block-end: 0; margin-inline-end: ".concat(props.theme.gridUnit, ";"); case 'inline-end/start': return "inset-inline-start: 100%; inset-block-start: 0; margin-inline-start: ".concat(props.theme.gridUnit, ";"); case 'inline-end/end': return "inset-inline-start: 100%; inset-block-end: 0; margin-inline-start: ".concat(props.theme.gridUnit, ";"); default: return "inset-block-end: 100%; inset-inline-start: 0; margin-block-end: ".concat(props.theme.gridUnit, ";"); } }, (0, _toolkit.grid)(5)); var Wrapper = _styledComponents["default"].div(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral(["\n display: inline-block;\n position: relative;\n"]))); var Popup = function Popup(_ref2) { var alignment = _ref2.alignment, children = _ref2.children, focusableContent = _ref2.focusableContent, id = _ref2.id, toggle = _ref2.toggle, position = _ref2.position, rest = _objectWithoutProperties(_ref2, _excluded); var WrapperRef = (0, _react.useRef)(null); var popupRef = (0, _react.useRef)(null); var _useState = (0, _react.useState)([]), _useState2 = _slicedToArray(_useState, 2), focusableElements = _useState2[0], setFocusableElements = _useState2[1]; var _useState3 = (0, _react.useState)(false), _useState4 = _slicedToArray(_useState3, 2), visible = _useState4[0], setVisible = _useState4[1]; var onClickToggle = function onClickToggle() { setVisible(!visible); }; (0, _react.useEffect)(function () { if (visible && focusableElements.length > 0) { // focusing the first focusable element of the popup focusableElements[0].focus(); } }, [visible]); (0, _react.useEffect)(function () { if (popupRef.current) { var focusableContentSelector = focusableContent.join(', '); setFocusableElements(popupRef.current.querySelectorAll(focusableContentSelector)); } }, [children]); var handleKeyDown = function handleKeyDown(e) { var isEscapePress = e.key === 'Escape' || e.keyCode === 27; var isTabPressed = e.key === 'Tab' || e.keyCode === 9; if (!isTabPressed && !isEscapePress) return; if (isEscapePress) { popupRef.current.previousElementSibling.focus(); setVisible(false); } var firstFocusableElement = focusableElements[0]; var lastFocusableElement = focusableElements[focusableElements.length - 1]; if (e.shiftKey) { if (document.activeElement === firstFocusableElement) { lastFocusableElement.focus(); e.preventDefault(); } } else if (document.activeElement === lastFocusableElement) { firstFocusableElement.focus(); e.preventDefault(); } }; var handleBlur = function handleBlur(e) { // when clicking outside the popup wrapper close the popup if (!WrapperRef.current.contains(e.relatedTarget)) { setVisible(false); } }; return /*#__PURE__*/_react["default"].createElement(Wrapper, { ref: WrapperRef }, /*#__PURE__*/(0, _react.cloneElement)(toggle, { onClick: onClickToggle, 'aria-controls': id, 'aria-expanded': visible, 'aria-haspopup': 'dialog' }), /*#__PURE__*/_react["default"].createElement(PopupContainer, _extends({ alignment: alignment, id: id, onBlur: handleBlur, onKeyDown: handleKeyDown, position: position, ref: popupRef, tabIndex: "0", visible: visible }, rest), children)); }; Popup.propTypes = { alignment: _propTypes["default"].oneOf(['start', 'end']), id: _propTypes["default"].string, focusableContent: _propTypes["default"].arrayOf(_propTypes["default"].string), toggle: _propTypes["default"].element.isRequired, position: _propTypes["default"].oneOf(['block-start', 'block-end', 'inline-start', 'inline-end']) }; Popup.defaultProps = { id: (0, _index.uuid)(), focusableContent: ['a[href]', 'area[href]', 'input:not([disabled]):not([type=hidden])', 'select:not([disabled])', 'textarea:not([disabled])', 'button:not([disabled])', 'object', 'embed', '[tabindex]:not([tabindex="-1"])', 'audio[controls]', 'video[controls]', '[contenteditable]:not([contenteditable="false"])'], position: 'block-start', alignment: 'start' }; var _default = Popup; exports["default"] = _default;