UNPKG

@devseed-ui/form

Version:
1,284 lines (1,130 loc) 46 kB
import styled, { css } from 'styled-components'; import { glsp, visuallyHidden, themeVal, rgba as rgba$1, disabled, stylizeFunction } from '@devseed-ui/theme-provider'; import React from 'react'; import T, { PropTypes } from 'prop-types'; import { iconDataURI, CollecticonTickSmall } from '@devseed-ui/collecticons'; import { shake } from '@devseed-ui/animation'; import { createOverlineStyles } from '@devseed-ui/typography'; var Form = /*#__PURE__*/styled.form.withConfig({ displayName: "form__Form", componentId: "sc-ovnwer-0" })(["display:grid;grid-template-rows:auto;grid-gap:", ";"], glsp()); var Form$1 = Form; function _extends$1() { _extends$1 = Object.assign || 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$1.apply(this, arguments); } 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 _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 _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } 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 _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."); } var _templateObject$4, _templateObject2$2, _templateObject3$2, _templateObject4; var _excluded$2 = ["children", "id", "name", "title", "type", "checked", "onChange", "value", "className", "textPlacement", "hideText"]; /** * Renders a FormCheckable component. * * @param {string} type Determines the type of input to render. Can be one of * `checkbox` or `radio` * @param {string} name (html prop) name to be used as `name` prop of * the element * @param {string} id (html prop) id to be used as `id` prop of the element * @param {string} title (html prop) Label's title attribute * @param {boolean} checked Whether or not the FormCheckable is checked * @param {func} onChange Change callback for the FormCheckable * @param {string} value Value for the underlying input element * @param {node} children Textual content * @param {string} textPlacement Where to position the text. `left` or `right` * of the control. Default to `right` */ var FormCheckableElement = function FormCheckableElement(props) { var children = props.children, id = props.id, name = props.name, title = props.title, type = props.type, checked = props.checked, onChange = props.onChange, value = props.value, className = props.className, textPlacement = props.textPlacement, hideText = props.hideText, rest = _objectWithoutProperties(props, _excluded$2); return /*#__PURE__*/React.createElement("label", _extends$1({ htmlFor: id, className: className, title: title }, rest), /*#__PURE__*/React.createElement("input", { type: type, name: name, id: id, value: value, checked: checked, onChange: onChange }), textPlacement === 'right' && /*#__PURE__*/React.createElement(FormCheckableControl, null), /*#__PURE__*/React.createElement(FormCheckableText, { hideText: hideText }, children), textPlacement === 'left' && /*#__PURE__*/React.createElement(FormCheckableControl, null)); }; FormCheckableElement.propTypes = { name: T.string.isRequired, id: T.string.isRequired, textPlacement: T.oneOf(['right', 'left']), hideText: T.bool, className: T.string, title: T.string, type: T.oneOf(['checkbox', 'radio']), checked: T.bool, children: T.node.isRequired, onChange: T.func, value: T.oneOfType([T.number, T.string]) }; FormCheckableElement.defaultProps = { textPlacement: 'right' }; var formCheckableWrapper = css(_templateObject$4 || (_templateObject$4 = _taggedTemplateLiteral(["\n display: inline-grid;\n gap: 0.5rem;\n font-size: 1rem;\n line-height: 1.5;\n cursor: pointer;\n justify-content: start;\n\n > * {\n grid-row: 1;\n }\n\n input {\n flex: none;\n }\n"]))); var FormCheckableText = /*#__PURE__*/styled.span.withConfig({ displayName: "checkable__FormCheckableText", componentId: "sc-1cpluk5-0" })(["line-height:1.5;", ""], function (_ref) { var hideText = _ref.hideText; return hideText && visuallyHidden(); }); var FormCheckableControl = /*#__PURE__*/styled.span.withConfig({ displayName: "checkable__FormCheckableControl", componentId: "sc-1cpluk5-1" })(["position:relative;transition:all 0.16s ease 0s;"]); var FormCheckable = /*#__PURE__*/styled(FormCheckableElement).withConfig({ displayName: "checkable__FormCheckable", componentId: "sc-1cpluk5-2" })(["", " input{", "}", "{display:flex;align-items:center;justify-content:center;margin:0.125rem 0;height:1.25rem;width:1.25rem;background:", ";line-height:1;border:", " solid ", ";border-radius:", ";&::before{transition:all 0.24s ease 0s;opacity:0;content:'';", "}}&:hover ", "{border-width:", ";border-color:", ";}", " input:focus ~ ", ",input:active ~ ", "{outline:0;border-width:", ";border-color:", ";}", " input:checked ~ ", "{&::before{opacity:1;}}&[disabled]{", "}"], formCheckableWrapper, visuallyHidden(), FormCheckableControl, themeVal('color.surface'), themeVal('layout.border'), rgba$1(themeVal('color.base'), 0.16), function (_ref2) { var type = _ref2.type; return type === 'checkbox' ? themeVal('shape.rounded') : themeVal('shape.ellipsoid'); }, function (_ref3) { var type = _ref3.type, theme = _ref3.theme; return type === 'checkbox' ? css(_templateObject2$2 || (_templateObject2$2 = _taggedTemplateLiteral(["\n background-image: url('", "');\n background-size: 1rem 1rem;\n height: 1rem;\n width: 1rem;\n background-repeat: no-repeat;\n "])), iconDataURI(CollecticonTickSmall, { color: theme.color.base })) : css(_templateObject3$2 || (_templateObject3$2 = _taggedTemplateLiteral(["\n height: 0.5rem;\n width: 0.5rem;\n background: ", ";\n border-radius: ", ";\n "])), themeVal('color.base'), themeVal('shape.ellipsoid')); }, FormCheckableControl, themeVal('layout.border'), rgba$1(themeVal('color.base'), 0.32), function (_ref4) { var invalid = _ref4.invalid; return invalid && css(_templateObject4 || (_templateObject4 = _taggedTemplateLiteral(["\n ", " {\n border-width: ", ";\n border-color: ", ";\n }\n &:hover\n ", ",\n &:focus\n ", ",\n &:active\n ", " {\n border-color: ", ";\n }\n "])), FormCheckableControl, themeVal('layout.border'), themeVal('color.danger'), FormCheckableControl, FormCheckableControl, FormCheckableControl, themeVal('color.danger')); }, FormCheckableControl, FormCheckableControl, themeVal('layout.border'), rgba$1(themeVal('color.base'), 0.64), function (_ref5) { var checked = _ref5.checked; return checked ? "".concat(FormCheckableControl, ",") : ''; }, FormCheckableControl, disabled()); var FormCheckableGroup = /*#__PURE__*/styled.div.withConfig({ displayName: "checkable__FormCheckableGroup", componentId: "sc-1cpluk5-3" })(["display:flex;flex-flow:row wrap;gap:0.5rem 1rem;"]); var _templateObject$3, _templateObject2$1, _templateObject3$1; var fontSizeMatrix = { small: '0.875rem', medium: '1rem', large: '1rem', xlarge: '1rem' }; var lineHeightMatrix = { small: '1.25rem', medium: '1.5rem', large: '1.5rem', xlarge: '1.5rem' }; var heightMatrix = { small: '1.5rem', medium: '2rem', large: '2.5rem', xlarge: '3rem' }; var paddingMatrix = { small: '0.125rem 0.5rem', medium: '0.25rem 0.5rem', large: '0.5rem 0.75rem', xlarge: '0.75rem 1rem' }; var createFormSkinStyles = function createFormSkinStyles(_ref) { var _ref$size = _ref.size, size = _ref$size === void 0 ? 'medium' : _ref$size, invalid = _ref.invalid, stressed = _ref.stressed; return css(_templateObject$3 || (_templateObject$3 = _taggedTemplateLiteral(["\n appearance: none;\n display: flex;\n width: auto;\n height: ", ";\n padding: ", ";\n border: ", " solid ", ";\n border-radius: ", ";\n background-color: ", ";\n font-family: inherit;\n font-size: ", ";\n line-height: ", ";\n color: ", ";\n transition: all 0.24s ease 0s;\n\n &::placeholder {\n opacity: 0.64;\n }\n\n &[disabled] {\n ", "\n }\n\n &[readonly] {\n cursor: text;\n color: ", ";\n }\n\n &:hover {\n border-color: ", ";\n }\n\n &:focus,\n &:active {\n outline: 0;\n border-color: ", ";\n }\n\n ", "\n\n ", "\n"])), heightMatrix[size], paddingMatrix[size], themeVal('layout.border'), themeVal('color.base-200a'), themeVal('shape.rounded'), themeVal('color.surface'), fontSizeMatrix[size], lineHeightMatrix[size], themeVal('type.base.color'), disabled(), rgba$1(themeVal('type.base.color'), 0.64), themeVal('color.base-300a'), themeVal('color.base-400a'), function () { return invalid && css(_templateObject2$1 || (_templateObject2$1 = _taggedTemplateLiteral(["\n border-color: ", ";\n &:hover,\n &:focus,\n &:active {\n border-color: ", ";\n }\n "])), themeVal('color.danger'), themeVal('color.danger')); }, function () { return stressed && css(_templateObject3$1 || (_templateObject3$1 = _taggedTemplateLiteral(["\n animation: ", " 0.5s linear;\n "])), shake); }); }; var createFormSkinStyles$1 = createFormSkinStyles; var FormInput = /*#__PURE__*/styled.input.withConfig({ displayName: "input__FormInput", componentId: "sc-52ed1q-0" })(["", ""], createFormSkinStyles$1); var FormInput$1 = FormInput; var _excluded$1 = ["children", "optional", "required", "hint"]; var LabelHint = /*#__PURE__*/styled.small.withConfig({ displayName: "label__LabelHint", componentId: "sc-eumonh-0" })(["font-weight:", ";font-size:0.75rem;line-height:1;color:", ";"], themeVal('type.base.weight'), rgba$1(themeVal('type.base.color'), 0.64)); var LabelStyled = /*#__PURE__*/styled.label.withConfig({ displayName: "label__LabelStyled", componentId: "sc-eumonh-1" })([""]); var LabelBase = function LabelBase(_ref) { var children = _ref.children, optional = _ref.optional, required = _ref.required, hint = _ref.hint, rest = _objectWithoutProperties(_ref, _excluded$1); var getHint = function getHint() { if (hint) return hint; if (required) return '(required)'; if (optional) return '(optional)'; }; var theHint = getHint(); return /*#__PURE__*/React.createElement(LabelStyled, rest, children, !!theHint && "\xA0" /* Non breaking space */ , !!theHint && /*#__PURE__*/React.createElement(LabelHint, null, theHint)); }; LabelBase.propTypes = { children: T.node, optional: T.bool, required: T.bool, hint: T.node }; var FormLabel = /*#__PURE__*/styled(LabelBase).withConfig({ displayName: "label__FormLabel", componentId: "sc-eumonh-2" })(["display:inline-flex;align-items:center;font-family:", ";font-weight:", ";font-size:1rem;line-height:1.5;min-width:0;&[for]{cursor:pointer;}"], themeVal('type.base.family'), themeVal('type.base.bold')); var FormLabel$1 = FormLabel; var _templateObject$2; var getPaddingValue = function getPaddingValue(size) { // horizontal padding if there are 2 values, otherwise it is the same for all // directions. var _paddingMatrix$size$s = paddingMatrix[size].split(' '), _paddingMatrix$size$s2 = _slicedToArray(_paddingMatrix$size$s, 2), v = _paddingMatrix$size$s2[0], h = _paddingMatrix$size$s2[1]; return h || v; }; var FormSelect = /*#__PURE__*/styled.select.withConfig({ displayName: "select__FormSelect", componentId: "sc-vhnur7-0" })(["", " cursor:pointer;line-height:1;background-image:", ";background-repeat:no-repeat;", " &::-ms-expand{display:none;}@-moz-document url-prefix(){&{text-overflow:'';text-indent:-2px;}}:-moz-focusring{color:transparent;text-shadow:0 0 0 ", ";}"], createFormSkinStyles$1, function (_ref) { var theme = _ref.theme; return "url('data:image/svg+xml;utf8,".concat(encodeURIComponent("<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"16px\" height=\"16px\" viewBox=\"0 0 16 16\"><polygon fill=\"".concat(theme.color.base, "\" points=\"12.586,4.586 8,9.172 3.414,4.586 2,6 8,12 14,6\" /></svg>")), "');"); }, function (_ref2) { var _ref2$size = _ref2.size, size = _ref2$size === void 0 ? 'medium' : _ref2$size; var p = getPaddingValue(size); return css(_templateObject$2 || (_templateObject$2 = _taggedTemplateLiteral(["\n background-position: calc(100% - ", ") center;\n /* padding + icons size + padding */\n padding-right: calc(1rem + ", " * 2);\n "])), p, p); }, themeVal('type.base.color')); var FormSelect$1 = FormSelect; var FormTextarea = /*#__PURE__*/styled.textarea.withConfig({ displayName: "textarea__FormTextarea", componentId: "sc-16thlyb-0" })(["", " height:auto;min-height:8rem;resize:none;"], createFormSkinStyles$1); var FormTextarea$1 = FormTextarea; function _extends() { _extends = Object.assign || 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 _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } /** * Create an error file out of errors.md for development and a simple web link to the full errors * in production mode. * @private */ var PolishedError = /*#__PURE__*/function (_Error) { _inheritsLoose(PolishedError, _Error); function PolishedError(code) { var _this; { _this = _Error.call(this, "An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#" + code + " for more information.") || this; } return _assertThisInitialized(_this); } return PolishedError; }( /*#__PURE__*/_wrapNativeSuper(Error)); function colorToInt(color) { return Math.round(color * 255); } function convertToInt(red, green, blue) { return colorToInt(red) + "," + colorToInt(green) + "," + colorToInt(blue); } function hslToRgb(hue, saturation, lightness, convert) { if (convert === void 0) { convert = convertToInt; } if (saturation === 0) { // achromatic return convert(lightness, lightness, lightness); } // formulae from https://en.wikipedia.org/wiki/HSL_and_HSV var huePrime = (hue % 360 + 360) % 360 / 60; var chroma = (1 - Math.abs(2 * lightness - 1)) * saturation; var secondComponent = chroma * (1 - Math.abs(huePrime % 2 - 1)); var red = 0; var green = 0; var blue = 0; if (huePrime >= 0 && huePrime < 1) { red = chroma; green = secondComponent; } else if (huePrime >= 1 && huePrime < 2) { red = secondComponent; green = chroma; } else if (huePrime >= 2 && huePrime < 3) { green = chroma; blue = secondComponent; } else if (huePrime >= 3 && huePrime < 4) { green = secondComponent; blue = chroma; } else if (huePrime >= 4 && huePrime < 5) { red = secondComponent; blue = chroma; } else if (huePrime >= 5 && huePrime < 6) { red = chroma; blue = secondComponent; } var lightnessModification = lightness - chroma / 2; var finalRed = red + lightnessModification; var finalGreen = green + lightnessModification; var finalBlue = blue + lightnessModification; return convert(finalRed, finalGreen, finalBlue); } var namedColorMap = { aliceblue: 'f0f8ff', antiquewhite: 'faebd7', aqua: '00ffff', aquamarine: '7fffd4', azure: 'f0ffff', beige: 'f5f5dc', bisque: 'ffe4c4', black: '000', blanchedalmond: 'ffebcd', blue: '0000ff', blueviolet: '8a2be2', brown: 'a52a2a', burlywood: 'deb887', cadetblue: '5f9ea0', chartreuse: '7fff00', chocolate: 'd2691e', coral: 'ff7f50', cornflowerblue: '6495ed', cornsilk: 'fff8dc', crimson: 'dc143c', cyan: '00ffff', darkblue: '00008b', darkcyan: '008b8b', darkgoldenrod: 'b8860b', darkgray: 'a9a9a9', darkgreen: '006400', darkgrey: 'a9a9a9', darkkhaki: 'bdb76b', darkmagenta: '8b008b', darkolivegreen: '556b2f', darkorange: 'ff8c00', darkorchid: '9932cc', darkred: '8b0000', darksalmon: 'e9967a', darkseagreen: '8fbc8f', darkslateblue: '483d8b', darkslategray: '2f4f4f', darkslategrey: '2f4f4f', darkturquoise: '00ced1', darkviolet: '9400d3', deeppink: 'ff1493', deepskyblue: '00bfff', dimgray: '696969', dimgrey: '696969', dodgerblue: '1e90ff', firebrick: 'b22222', floralwhite: 'fffaf0', forestgreen: '228b22', fuchsia: 'ff00ff', gainsboro: 'dcdcdc', ghostwhite: 'f8f8ff', gold: 'ffd700', goldenrod: 'daa520', gray: '808080', green: '008000', greenyellow: 'adff2f', grey: '808080', honeydew: 'f0fff0', hotpink: 'ff69b4', indianred: 'cd5c5c', indigo: '4b0082', ivory: 'fffff0', khaki: 'f0e68c', lavender: 'e6e6fa', lavenderblush: 'fff0f5', lawngreen: '7cfc00', lemonchiffon: 'fffacd', lightblue: 'add8e6', lightcoral: 'f08080', lightcyan: 'e0ffff', lightgoldenrodyellow: 'fafad2', lightgray: 'd3d3d3', lightgreen: '90ee90', lightgrey: 'd3d3d3', lightpink: 'ffb6c1', lightsalmon: 'ffa07a', lightseagreen: '20b2aa', lightskyblue: '87cefa', lightslategray: '789', lightslategrey: '789', lightsteelblue: 'b0c4de', lightyellow: 'ffffe0', lime: '0f0', limegreen: '32cd32', linen: 'faf0e6', magenta: 'f0f', maroon: '800000', mediumaquamarine: '66cdaa', mediumblue: '0000cd', mediumorchid: 'ba55d3', mediumpurple: '9370db', mediumseagreen: '3cb371', mediumslateblue: '7b68ee', mediumspringgreen: '00fa9a', mediumturquoise: '48d1cc', mediumvioletred: 'c71585', midnightblue: '191970', mintcream: 'f5fffa', mistyrose: 'ffe4e1', moccasin: 'ffe4b5', navajowhite: 'ffdead', navy: '000080', oldlace: 'fdf5e6', olive: '808000', olivedrab: '6b8e23', orange: 'ffa500', orangered: 'ff4500', orchid: 'da70d6', palegoldenrod: 'eee8aa', palegreen: '98fb98', paleturquoise: 'afeeee', palevioletred: 'db7093', papayawhip: 'ffefd5', peachpuff: 'ffdab9', peru: 'cd853f', pink: 'ffc0cb', plum: 'dda0dd', powderblue: 'b0e0e6', purple: '800080', rebeccapurple: '639', red: 'f00', rosybrown: 'bc8f8f', royalblue: '4169e1', saddlebrown: '8b4513', salmon: 'fa8072', sandybrown: 'f4a460', seagreen: '2e8b57', seashell: 'fff5ee', sienna: 'a0522d', silver: 'c0c0c0', skyblue: '87ceeb', slateblue: '6a5acd', slategray: '708090', slategrey: '708090', snow: 'fffafa', springgreen: '00ff7f', steelblue: '4682b4', tan: 'd2b48c', teal: '008080', thistle: 'd8bfd8', tomato: 'ff6347', turquoise: '40e0d0', violet: 'ee82ee', wheat: 'f5deb3', white: 'fff', whitesmoke: 'f5f5f5', yellow: 'ff0', yellowgreen: '9acd32' }; /** * Checks if a string is a CSS named color and returns its equivalent hex value, otherwise returns the original color. * @private */ function nameToHex(color) { if (typeof color !== 'string') return color; var normalizedColorName = color.toLowerCase(); return namedColorMap[normalizedColorName] ? "#" + namedColorMap[normalizedColorName] : color; } var hexRegex = /^#[a-fA-F0-9]{6}$/; var hexRgbaRegex = /^#[a-fA-F0-9]{8}$/; var reducedHexRegex = /^#[a-fA-F0-9]{3}$/; var reducedRgbaHexRegex = /^#[a-fA-F0-9]{4}$/; var rgbRegex = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i; var rgbaRegex = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*([-+]?[0-9]*[.]?[0-9]+)\s*\)$/i; var hslRegex = /^hsl\(\s*(\d{0,3}[.]?[0-9]+)\s*,\s*(\d{1,3}[.]?[0-9]?)%\s*,\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i; var hslaRegex = /^hsla\(\s*(\d{0,3}[.]?[0-9]+)\s*,\s*(\d{1,3}[.]?[0-9]?)%\s*,\s*(\d{1,3}[.]?[0-9]?)%\s*,\s*([-+]?[0-9]*[.]?[0-9]+)\s*\)$/i; /** * Returns an RgbColor or RgbaColor object. This utility function is only useful * if want to extract a color component. With the color util `toColorString` you * can convert a RgbColor or RgbaColor object back to a string. * * @example * // Assigns `{ red: 255, green: 0, blue: 0 }` to color1 * const color1 = parseToRgb('rgb(255, 0, 0)'); * // Assigns `{ red: 92, green: 102, blue: 112, alpha: 0.75 }` to color2 * const color2 = parseToRgb('hsla(210, 10%, 40%, 0.75)'); */ function parseToRgb(color) { if (typeof color !== 'string') { throw new PolishedError(3); } var normalizedColor = nameToHex(color); if (normalizedColor.match(hexRegex)) { return { red: parseInt("" + normalizedColor[1] + normalizedColor[2], 16), green: parseInt("" + normalizedColor[3] + normalizedColor[4], 16), blue: parseInt("" + normalizedColor[5] + normalizedColor[6], 16) }; } if (normalizedColor.match(hexRgbaRegex)) { var alpha = parseFloat((parseInt("" + normalizedColor[7] + normalizedColor[8], 16) / 255).toFixed(2)); return { red: parseInt("" + normalizedColor[1] + normalizedColor[2], 16), green: parseInt("" + normalizedColor[3] + normalizedColor[4], 16), blue: parseInt("" + normalizedColor[5] + normalizedColor[6], 16), alpha: alpha }; } if (normalizedColor.match(reducedHexRegex)) { return { red: parseInt("" + normalizedColor[1] + normalizedColor[1], 16), green: parseInt("" + normalizedColor[2] + normalizedColor[2], 16), blue: parseInt("" + normalizedColor[3] + normalizedColor[3], 16) }; } if (normalizedColor.match(reducedRgbaHexRegex)) { var _alpha = parseFloat((parseInt("" + normalizedColor[4] + normalizedColor[4], 16) / 255).toFixed(2)); return { red: parseInt("" + normalizedColor[1] + normalizedColor[1], 16), green: parseInt("" + normalizedColor[2] + normalizedColor[2], 16), blue: parseInt("" + normalizedColor[3] + normalizedColor[3], 16), alpha: _alpha }; } var rgbMatched = rgbRegex.exec(normalizedColor); if (rgbMatched) { return { red: parseInt("" + rgbMatched[1], 10), green: parseInt("" + rgbMatched[2], 10), blue: parseInt("" + rgbMatched[3], 10) }; } var rgbaMatched = rgbaRegex.exec(normalizedColor.substring(0, 50)); if (rgbaMatched) { return { red: parseInt("" + rgbaMatched[1], 10), green: parseInt("" + rgbaMatched[2], 10), blue: parseInt("" + rgbaMatched[3], 10), alpha: parseFloat("" + rgbaMatched[4]) }; } var hslMatched = hslRegex.exec(normalizedColor); if (hslMatched) { var hue = parseInt("" + hslMatched[1], 10); var saturation = parseInt("" + hslMatched[2], 10) / 100; var lightness = parseInt("" + hslMatched[3], 10) / 100; var rgbColorString = "rgb(" + hslToRgb(hue, saturation, lightness) + ")"; var hslRgbMatched = rgbRegex.exec(rgbColorString); if (!hslRgbMatched) { throw new PolishedError(4, normalizedColor, rgbColorString); } return { red: parseInt("" + hslRgbMatched[1], 10), green: parseInt("" + hslRgbMatched[2], 10), blue: parseInt("" + hslRgbMatched[3], 10) }; } var hslaMatched = hslaRegex.exec(normalizedColor.substring(0, 50)); if (hslaMatched) { var _hue = parseInt("" + hslaMatched[1], 10); var _saturation = parseInt("" + hslaMatched[2], 10) / 100; var _lightness = parseInt("" + hslaMatched[3], 10) / 100; var _rgbColorString = "rgb(" + hslToRgb(_hue, _saturation, _lightness) + ")"; var _hslRgbMatched = rgbRegex.exec(_rgbColorString); if (!_hslRgbMatched) { throw new PolishedError(4, normalizedColor, _rgbColorString); } return { red: parseInt("" + _hslRgbMatched[1], 10), green: parseInt("" + _hslRgbMatched[2], 10), blue: parseInt("" + _hslRgbMatched[3], 10), alpha: parseFloat("" + hslaMatched[4]) }; } throw new PolishedError(5); } /** * Reduces hex values if possible e.g. #ff8866 to #f86 * @private */ var reduceHexValue = function reduceHexValue(value) { if (value.length === 7 && value[1] === value[2] && value[3] === value[4] && value[5] === value[6]) { return "#" + value[1] + value[3] + value[5]; } return value; }; function numberToHex(value) { var hex = value.toString(16); return hex.length === 1 ? "0" + hex : hex; } /** * Returns a string value for the color. The returned result is the smallest possible hex notation. * * @example * // Styles as object usage * const styles = { * background: rgb(255, 205, 100), * background: rgb({ red: 255, green: 205, blue: 100 }), * } * * // styled-components usage * const div = styled.div` * background: ${rgb(255, 205, 100)}; * background: ${rgb({ red: 255, green: 205, blue: 100 })}; * ` * * // CSS in JS Output * * element { * background: "#ffcd64"; * background: "#ffcd64"; * } */ function rgb(value, green, blue) { if (typeof value === 'number' && typeof green === 'number' && typeof blue === 'number') { return reduceHexValue("#" + numberToHex(value) + numberToHex(green) + numberToHex(blue)); } else if (typeof value === 'object' && green === undefined && blue === undefined) { return reduceHexValue("#" + numberToHex(value.red) + numberToHex(value.green) + numberToHex(value.blue)); } throw new PolishedError(6); } /** * Returns a string value for the color. The returned result is the smallest possible rgba or hex notation. * * Can also be used to fade a color by passing a hex value or named CSS color along with an alpha value. * * @example * // Styles as object usage * const styles = { * background: rgba(255, 205, 100, 0.7), * background: rgba({ red: 255, green: 205, blue: 100, alpha: 0.7 }), * background: rgba(255, 205, 100, 1), * background: rgba('#ffffff', 0.4), * background: rgba('black', 0.7), * } * * // styled-components usage * const div = styled.div` * background: ${rgba(255, 205, 100, 0.7)}; * background: ${rgba({ red: 255, green: 205, blue: 100, alpha: 0.7 })}; * background: ${rgba(255, 205, 100, 1)}; * background: ${rgba('#ffffff', 0.4)}; * background: ${rgba('black', 0.7)}; * ` * * // CSS in JS Output * * element { * background: "rgba(255,205,100,0.7)"; * background: "rgba(255,205,100,0.7)"; * background: "#ffcd64"; * background: "rgba(255,255,255,0.4)"; * background: "rgba(0,0,0,0.7)"; * } */ function rgba(firstValue, secondValue, thirdValue, fourthValue) { if (typeof firstValue === 'string' && typeof secondValue === 'number') { var rgbValue = parseToRgb(firstValue); return "rgba(" + rgbValue.red + "," + rgbValue.green + "," + rgbValue.blue + "," + secondValue + ")"; } else if (typeof firstValue === 'number' && typeof secondValue === 'number' && typeof thirdValue === 'number' && typeof fourthValue === 'number') { return fourthValue >= 1 ? rgb(firstValue, secondValue, thirdValue) : "rgba(" + firstValue + "," + secondValue + "," + thirdValue + "," + fourthValue + ")"; } else if (typeof firstValue === 'object' && secondValue === undefined && thirdValue === undefined && fourthValue === undefined) { return firstValue.alpha >= 1 ? rgb(firstValue.red, firstValue.green, firstValue.blue) : "rgba(" + firstValue.red + "," + firstValue.green + "," + firstValue.blue + "," + firstValue.alpha + ")"; } throw new PolishedError(7); } // Type definitions taken from https://github.com/gcanti/flow-static-land/blob/master/src/Fun.js // eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-redeclare function curried(f, length, acc) { return function fn() { // eslint-disable-next-line prefer-rest-params var combined = acc.concat(Array.prototype.slice.call(arguments)); return combined.length >= length ? f.apply(this, combined) : curried(f, length, combined); }; } // eslint-disable-next-line no-redeclare function curry(f) { // eslint-disable-line no-redeclare return curried(f, f.length, []); } /** * Mixes the two provided colors together by calculating the average of each of the RGB components weighted to the first color by the provided weight. * * @example * // Styles as object usage * const styles = { * background: mix(0.5, '#f00', '#00f') * background: mix(0.25, '#f00', '#00f') * background: mix('0.5', 'rgba(255, 0, 0, 0.5)', '#00f') * } * * // styled-components usage * const div = styled.div` * background: ${mix(0.5, '#f00', '#00f')}; * background: ${mix(0.25, '#f00', '#00f')}; * background: ${mix('0.5', 'rgba(255, 0, 0, 0.5)', '#00f')}; * ` * * // CSS in JS Output * * element { * background: "#7f007f"; * background: "#3f00bf"; * background: "rgba(63, 0, 191, 0.75)"; * } */ function mix(weight, color, otherColor) { if (color === 'transparent') return otherColor; if (otherColor === 'transparent') return color; if (weight === 0) return otherColor; var parsedColor1 = parseToRgb(color); var color1 = _extends({}, parsedColor1, { alpha: typeof parsedColor1.alpha === 'number' ? parsedColor1.alpha : 1 }); var parsedColor2 = parseToRgb(otherColor); var color2 = _extends({}, parsedColor2, { alpha: typeof parsedColor2.alpha === 'number' ? parsedColor2.alpha : 1 }); // The formula is copied from the original Sass implementation: // http://sass-lang.com/documentation/Sass/Script/Functions.html#mix-instance_method var alphaDelta = color1.alpha - color2.alpha; var x = parseFloat(weight) * 2 - 1; var y = x * alphaDelta === -1 ? x : x + alphaDelta; var z = 1 + x * alphaDelta; var weight1 = (y / z + 1) / 2.0; var weight2 = 1 - weight1; var mixedColor = { red: Math.floor(color1.red * weight1 + color2.red * weight2), green: Math.floor(color1.green * weight1 + color2.green * weight2), blue: Math.floor(color1.blue * weight1 + color2.blue * weight2), alpha: color1.alpha * (parseFloat(weight) / 1.0) + color2.alpha * (1 - parseFloat(weight) / 1.0) }; return rgba(mixedColor); } // prettier-ignore var curriedMix = /*#__PURE__*/curry /* ::<number | string, string, string, string> */ (mix); /** * Shades a color by mixing it with black. `shade` can produce * hue shifts, where as `darken` manipulates the luminance channel and therefore * doesn't produce hue shifts. * * @example * // Styles as object usage * const styles = { * background: shade(0.25, '#00f') * } * * // styled-components usage * const div = styled.div` * background: ${shade(0.25, '#00f')}; * ` * * // CSS in JS Output * * element { * background: "#00003f"; * } */ function shade(percentage, color) { if (color === 'transparent') return color; return curriedMix(parseFloat(percentage), 'rgb(0, 0, 0)', color); } // prettier-ignore var curriedShade = /*#__PURE__*/curry /* ::<number | string, string, string> */ (shade); var _templateObject$1; var _shade = stylizeFunction(curriedShade); /** * Renders a FormSwitch component. * Under the hood this uses a checkbox * * @param {string} name (html prop) name to be used as `name` prop of * the checkbox * @param {string} id (html prop) id to be used as `id` prop of the checkbox * @param {string} title (html prop) Label's title attribute * @param {boolean} checked Whether or not the FormSwitch is checked * @param {func} onChange Change callback for the FormSwitch * @param {string} value Value for the underlying checkbox * @param {node} children Content of the label * @param {boolean} hideText Whether or not to visually hide the FormSwitch text * @param {string} textPlacement Where to position the text. `left` or `right` * of the toggle. */ var FormSwitchElement = function FormSwitchElement(props) { var children = props.children, id = props.id, name = props.name, title = props.title, checked = props.checked, onChange = props.onChange, value = props.value, className = props.className, hideText = props.hideText, textPlacement = props.textPlacement; return /*#__PURE__*/React.createElement("label", { htmlFor: id, className: className, title: title }, /*#__PURE__*/React.createElement("input", { type: "checkbox", name: name, id: id, value: value, checked: checked, onChange: onChange }), textPlacement === 'right' && /*#__PURE__*/React.createElement(FormOptionUi, null), /*#__PURE__*/React.createElement(FormOptionText, { hideText: hideText }, children), textPlacement === 'left' && /*#__PURE__*/React.createElement(FormOptionUi, null)); }; FormSwitchElement.propTypes = { name: T.string.isRequired, id: T.string.isRequired, textPlacement: T.oneOf(['right', 'left']), hideText: T.bool, className: T.string, title: T.string, checked: T.bool, children: T.node.isRequired, onChange: T.func, value: T.oneOfType([T.number, T.string]) }; FormSwitchElement.defaultProps = { textPlacement: 'left' }; /** * Form option extend. Common code to all form options. */ var formOption = css(_templateObject$1 || (_templateObject$1 = _taggedTemplateLiteral(["\n display: inline-grid;\n grid-template-columns: max-content;\n grid-auto-flow: column;\n grid-auto-columns: 1fr;\n grid-gap: 1rem;\n font-size: 0.875rem;\n line-height: 1.5;\n cursor: pointer;\n\n input {\n flex: none;\n margin-top: 0.3125rem; /* 5px */\n }\n"]))); var FormOptionText = /*#__PURE__*/styled.span.withConfig({ displayName: "switch__FormOptionText", componentId: "sc-rh9a5m-0" })(["line-height:1.5;", ""], function (_ref) { var hideText = _ref.hideText; return hideText && visuallyHidden(); }); var FormOptionUi = /*#__PURE__*/styled.span.withConfig({ displayName: "switch__FormOptionUi", componentId: "sc-rh9a5m-1" })(["flex:none;position:relative;transition:all 0.16s ease 0s;"]); var FormSwitch = /*#__PURE__*/styled(FormSwitchElement).withConfig({ displayName: "switch__FormSwitch", componentId: "sc-rh9a5m-2" })(["", " input{", "}", "{margin:0.375rem 0;width:2.25rem;height:0.75rem;border-radius:", ";background:", ";&::before{background-color:", ";box-shadow:", ";position:absolute;top:50%;left:0;z-index:2;content:'';height:1.25rem;width:1.25rem;border-radius:", ";transform:translate(0,-50%);transition:all 0.24s ease 0s;}}&:hover ", "::before{background-color:", ";}", " input:checked ~ ", "{background:", ";&::before{left:100%;transform:translate(-100%,-50%);}}"], formOption, visuallyHidden(), FormOptionUi, themeVal('shape.ellipsoid'), themeVal('color.base-300a'), themeVal('color.surface'), themeVal('boxShadow.elevationB'), themeVal('shape.ellipsoid'), /* sc-selector */ FormOptionUi, _shade(0.04, themeVal('color.surface-500')), function (_ref2) { var checked = _ref2.checked; return checked ? "".concat(FormOptionUi, ",") : ''; }, FormOptionUi, themeVal('color.link')); var FormSwitch$1 = FormSwitch; var FormFieldset = /*#__PURE__*/styled.fieldset.withConfig({ displayName: "fieldset__FormFieldset", componentId: "sc-1qku189-0" })(["background-color:", ";border-radius:", ";border:", " solid ", ";padding:0;"], themeVal('color.base-50a'), themeVal('shape.rounded'), themeVal('layout.border'), themeVal('color.base-100a')); var FormLegend = /*#__PURE__*/styled.legend.withConfig({ displayName: "fieldset__FormLegend", componentId: "sc-1qku189-1" })(["", " display:flex;align-items:center;width:100%;border:0;padding:0;"], createOverlineStyles); var FormFieldsetHeader = /*#__PURE__*/styled.div.withConfig({ displayName: "fieldset__FormFieldsetHeader", componentId: "sc-1qku189-2" })(["display:flex;flex-flow:wrap nowrap;justify-content:space-between;padding:", ";border-bottom:", " solid ", ";fieldset fieldset &{padding:", ";}"], glsp(0.75, 2), themeVal('layout.border'), themeVal('color.base-100a'), glsp(0.25, 1)); var FormFieldsetBody = /*#__PURE__*/styled.div.withConfig({ displayName: "fieldset__FormFieldsetBody", componentId: "sc-1qku189-3" })(["display:grid;grid-template-rows:auto;grid-gap:", ";padding:", ";fieldset fieldset &{padding:", ";}"], glsp(), glsp(2), glsp()); var _excluded = ["value", "max", "children"]; var _templateObject, _templateObject2, _templateObject3; var FormHelper = /*#__PURE__*/styled.div.withConfig({ displayName: "helper__FormHelper", componentId: "sc-1b93h35-0" })(["display:flex;flex-flow:row nowrap;justify-content:space-between;line-height:1.25rem;color:", ";"], themeVal('color.base-400')); var FormHelperMessage = /*#__PURE__*/styled.p.withConfig({ displayName: "helper__FormHelperMessage", componentId: "sc-1b93h35-1" })(["font-size:0.875rem;", ""], function (_ref) { var invalid = _ref.invalid; return invalid ? css(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n color: ", ";\n "])), themeVal('color.danger')) : ''; }); var renderFormHelperCounterColor = function renderFormHelperCounterColor(_ref2) { var currentVal = _ref2.currentVal, maxVal = _ref2.maxVal, warnAt = _ref2.warnAt; if (!currentVal || !maxVal) return; var warnLimit = warnAt || Math.floor(maxVal * 0.9); if (currentVal > maxVal) { return css(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral(["\n color: ", ";\n "])), themeVal('color.danger')); } else if (currentVal >= warnLimit) { return css(_templateObject3 || (_templateObject3 = _taggedTemplateLiteral(["\n color: ", ";\n "])), themeVal('color.warning')); } }; var FormHelperCounterSelf = /*#__PURE__*/styled.p.withConfig({ displayName: "helper__FormHelperCounterSelf", componentId: "sc-1b93h35-2" })(["font-size:0.75rem;padding-left:", ";margin-left:auto;", ""], glsp(), renderFormHelperCounterColor); var FormHelperCounter = function FormHelperCounter(props) { var value = props.value, max = props.max, children = props.children, rest = _objectWithoutProperties(props, _excluded); return /*#__PURE__*/React.createElement(FormHelperCounterSelf, _extends$1({ currentVal: value, maxVal: max }, rest), children || "".concat(value, " / ").concat(max)); }; FormHelperCounter.propTypes = { value: T.number, warnAt: T.number, max: T.number, children: T.node }; var FormGroup = /*#__PURE__*/styled.div.withConfig({ displayName: "group__FormGroup", componentId: "sc-13i8i0r-0" })(["display:grid;grid-template-rows:auto;grid-gap:", ";"], glsp(1 / 2)); var FormGroupHeader = /*#__PURE__*/styled.div.withConfig({ displayName: "group__FormGroupHeader", componentId: "sc-13i8i0r-1" })(["display:flex;flex-flow:wrap nowrap;justify-content:space-between;min-width:0;", ""], function (_ref) { var isHidden = _ref.isHidden; return isHidden && visuallyHidden(); }); var FormGroupBody = /*#__PURE__*/styled.div.withConfig({ displayName: "group__FormGroupBody", componentId: "sc-13i8i0r-2" })(["display:grid;grid-template-rows:auto;grid-gap:", ";"], glsp(1 / 4)); var FormGroupFooter = /*#__PURE__*/styled.div.withConfig({ displayName: "group__FormGroupFooter", componentId: "sc-13i8i0r-3" })([""]); /** * From group structure. * */ function FormGroupStructure(props) { var id = props.id, label = props.label, optional = props.optional, required = props.required, hint = props.hint, hideHeader = props.hideHeader, className = props.className, toolbar = props.toolbar, helper = props.helper, children = props.children, footerContent = props.footerContent; return /*#__PURE__*/React.createElement(FormGroup, { className: className }, /*#__PURE__*/React.createElement(FormGroupHeader, { isHidden: hideHeader }, /*#__PURE__*/React.createElement(FormLabel$1, { htmlFor: id, optional: optional, required: required, hint: hint }, label), toolbar), /*#__PURE__*/React.createElement(FormGroupBody, null, children, helper && /*#__PURE__*/React.createElement(FormHelper, null, helper)), footerContent && /*#__PURE__*/React.createElement(FormGroupFooter, null, footerContent)); } FormGroupStructure.propTypes = { id: PropTypes.string.isRequired, label: PropTypes.node.isRequired, optional: PropTypes.bool, required: PropTypes.bool, hint: PropTypes.node, hideHeader: PropTypes.bool, className: PropTypes.string, description: PropTypes.string, toolbar: PropTypes.node, helper: PropTypes.element, footerContent: PropTypes.node, children: PropTypes.node }; export { Form$1 as Form, FormCheckable, FormCheckableGroup, FormFieldset, FormFieldsetBody, FormFieldsetHeader, FormGroup, FormGroupBody, FormGroupFooter, FormGroupHeader, FormGroupStructure, FormHelper, FormHelperCounter, FormHelperMessage, FormInput$1 as FormInput, FormLabel$1 as FormLabel, FormLegend, FormSelect$1 as FormSelect, FormSwitch$1 as FormSwitch, FormTextarea$1 as FormTextarea, createFormSkinStyles$1 as createFormSkinStyles }; //# sourceMappingURL=index.es.js.map