"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.FontSizePicker = void 0;
var _i18n = require("@wordpress/i18n");
var _icons = require("@wordpress/icons");
var _element = require("@wordpress/element");
var _button = require("../button");
var _rangeControl = _interopRequireDefault(require("../range-control"));
var _flex = require("../flex");
var _unitControl = _interopRequireWildcard(require("../unit-control"));
var _visuallyHidden = require("../visually-hidden");
var _utils = require("./utils");
var _styles = require("./styles");
var _spacer = require("../spacer");
var _fontSizePickerSelect = _interopRequireDefault(require("./font-size-picker-select"));
var _fontSizePickerToggleGroup = _interopRequireDefault(require("./font-size-picker-toggle-group"));
var _constants = require("./constants");
var _jsxRuntime = require("react/jsx-runtime");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
/**
 * External dependencies
 */

/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const DEFAULT_UNITS = ['px', 'em', 'rem', 'vw', 'vh'];
const UnforwardedFontSizePicker = (props, ref) => {
  const {
    __next40pxDefaultSize = false,
    fallbackFontSize,
    fontSizes = [],
    disableCustomFontSizes = false,
    onChange,
    size = 'default',
    units: unitsProp = DEFAULT_UNITS,
    value,
    withSlider = false,
    withReset = true
  } = props;
  const units = (0, _unitControl.useCustomUnits)({
    availableUnits: unitsProp
  });
  const shouldUseSelectControl = fontSizes.length > 5;
  const selectedFontSize = fontSizes.find(fontSize => fontSize.size === value);
  const isCustomValue = !!value && !selectedFontSize;
  const [showCustomValueControl, setShowCustomValueControl] = (0, _element.useState)(!disableCustomFontSizes && isCustomValue);
  const headerHint = (0, _element.useMemo)(() => {
    if (showCustomValueControl) {
      return (0, _i18n.__)('Custom');
    }
    if (!shouldUseSelectControl) {
      if (selectedFontSize) {
        return selectedFontSize.name || _constants.T_SHIRT_NAMES[fontSizes.indexOf(selectedFontSize)];
      }
      return '';
    }
    const commonUnit = (0, _utils.getCommonSizeUnit)(fontSizes);
    if (commonUnit) {
      return `(${commonUnit})`;
    }
    return '';
  }, [showCustomValueControl, shouldUseSelectControl, selectedFontSize, fontSizes]);
  if (fontSizes.length === 0 && disableCustomFontSizes) {
    return null;
  }

  // If neither the value or first font size is a string, then FontSizePicker
  // operates in a legacy "unitless" mode where UnitControl can only be used
  // to select px values and onChange() is always called with number values.
  const hasUnits = typeof value === 'string' || typeof fontSizes[0]?.size === 'string';
  const [valueQuantity, valueUnit] = (0, _unitControl.parseQuantityAndUnitFromRawValue)(value, units);
  const isValueUnitRelative = !!valueUnit && ['em', 'rem', 'vw', 'vh'].includes(valueUnit);
  const isDisabled = value === undefined;
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_styles.Container, {
    ref: ref,
    className: "components-font-size-picker",
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_visuallyHidden.VisuallyHidden, {
      as: "legend",
      children: (0, _i18n.__)('Font size')
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_spacer.Spacer, {
      children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_styles.Header, {
        className: "components-font-size-picker__header",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_styles.HeaderLabel, {
          "aria-label": `${(0, _i18n.__)('Size')} ${headerHint || ''}`,
          children: [(0, _i18n.__)('Size'), headerHint && /*#__PURE__*/(0, _jsxRuntime.jsx)(_styles.HeaderHint, {
            className: "components-font-size-picker__header__hint",
            children: headerHint
          })]
        }), !disableCustomFontSizes && /*#__PURE__*/(0, _jsxRuntime.jsx)(_styles.HeaderToggle, {
          label: showCustomValueControl ? (0, _i18n.__)('Use size preset') : (0, _i18n.__)('Set custom size'),
          icon: _icons.settings,
          onClick: () => {
            setShowCustomValueControl(!showCustomValueControl);
          },
          isPressed: showCustomValueControl,
          size: "small"
        })]
      })
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      children: [!!fontSizes.length && shouldUseSelectControl && !showCustomValueControl && /*#__PURE__*/(0, _jsxRuntime.jsx)(_fontSizePickerSelect.default, {
        __next40pxDefaultSize: __next40pxDefaultSize,
        fontSizes: fontSizes,
        value: value,
        disableCustomFontSizes: disableCustomFontSizes,
        size: size,
        onChange: newValue => {
          if (newValue === undefined) {
            onChange?.(undefined);
          } else {
            onChange?.(hasUnits ? newValue : Number(newValue), fontSizes.find(fontSize => fontSize.size === newValue));
          }
        },
        onSelectCustom: () => setShowCustomValueControl(true)
      }), !shouldUseSelectControl && !showCustomValueControl && /*#__PURE__*/(0, _jsxRuntime.jsx)(_fontSizePickerToggleGroup.default, {
        fontSizes: fontSizes,
        value: value,
        __next40pxDefaultSize: __next40pxDefaultSize,
        size: size,
        onChange: newValue => {
          if (newValue === undefined) {
            onChange?.(undefined);
          } else {
            onChange?.(hasUnits ? newValue : Number(newValue), fontSizes.find(fontSize => fontSize.size === newValue));
          }
        }
      }), !disableCustomFontSizes && showCustomValueControl && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_flex.Flex, {
        className: "components-font-size-picker__custom-size-control",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_flex.FlexItem, {
          isBlock: true,
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_unitControl.default, {
            __next40pxDefaultSize: __next40pxDefaultSize,
            label: (0, _i18n.__)('Custom'),
            labelPosition: "top",
            hideLabelFromVision: true,
            value: value,
            onChange: newValue => {
              if (newValue === undefined) {
                onChange?.(undefined);
              } else {
                onChange?.(hasUnits ? newValue : parseInt(newValue, 10));
              }
            },
            size: size,
            units: hasUnits ? units : [],
            min: 0
          })
        }), withSlider && /*#__PURE__*/(0, _jsxRuntime.jsx)(_flex.FlexItem, {
          isBlock: true,
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_spacer.Spacer, {
            marginX: 2,
            marginBottom: 0,
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_rangeControl.default, {
              __nextHasNoMarginBottom: true,
              __next40pxDefaultSize: __next40pxDefaultSize,
              className: "components-font-size-picker__custom-input",
              label: (0, _i18n.__)('Custom Size'),
              hideLabelFromVision: true,
              value: valueQuantity,
              initialPosition: fallbackFontSize,
              withInputField: false,
              onChange: newValue => {
                if (newValue === undefined) {
                  onChange?.(undefined);
                } else if (hasUnits) {
                  onChange?.(newValue + (valueUnit !== null && valueUnit !== void 0 ? valueUnit : 'px'));
                } else {
                  onChange?.(newValue);
                }
              },
              min: 0,
              max: isValueUnitRelative ? 10 : 100,
              step: isValueUnitRelative ? 0.1 : 1
            })
          })
        }), withReset && /*#__PURE__*/(0, _jsxRuntime.jsx)(_flex.FlexItem, {
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_button.Button, {
            disabled: isDisabled,
            accessibleWhenDisabled: true,
            onClick: () => {
              onChange?.(undefined);
            },
            variant: "secondary",
            __next40pxDefaultSize: true,
            size: size === '__unstable-large' || props.__next40pxDefaultSize ? 'default' : 'small',
            children: (0, _i18n.__)('Reset')
          })
        })]
      })]
    })]
  });
};
const FontSizePicker = exports.FontSizePicker = (0, _element.forwardRef)(UnforwardedFontSizePicker);
var _default = exports.default = FontSizePicker;
//# sourceMappingURL=index.js.map