"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = ShadowsEditPanel;
var _clsx = _interopRequireDefault(require("clsx"));
var _components = require("@wordpress/components");
var _i18n = require("@wordpress/i18n");
var _blockEditor = require("@wordpress/block-editor");
var _icons = require("@wordpress/icons");
var _element = require("@wordpress/element");
var _lockUnlock = require("../../lock-unlock");
var _subtitle = _interopRequireDefault(require("./subtitle"));
var _header = _interopRequireDefault(require("./header"));
var _shadowsPanel = require("./shadows-panel");
var _shadowUtils = require("./shadow-utils");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * External dependencies
 */

/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const {
  useGlobalSetting
} = (0, _lockUnlock.unlock)(_blockEditor.privateApis);
const {
  Menu
} = (0, _lockUnlock.unlock)(_components.privateApis);
const customShadowMenuItems = [{
  label: (0, _i18n.__)('Rename'),
  action: 'rename'
}, {
  label: (0, _i18n.__)('Delete'),
  action: 'delete'
}];
const presetShadowMenuItems = [{
  label: (0, _i18n.__)('Reset'),
  action: 'reset'
}];
function ShadowsEditPanel() {
  const {
    goBack,
    params: {
      category,
      slug
    }
  } = (0, _components.useNavigator)();
  const [shadows, setShadows] = useGlobalSetting(`shadow.presets.${category}`);
  (0, _element.useEffect)(() => {
    const hasCurrentShadow = shadows?.some(shadow => shadow.slug === slug);
    // If the shadow being edited doesn't exist anymore in the global styles setting, navigate back
    // to prevent the user from editing a non-existent shadow entry.
    // This can happen, for example:
    // - when the user deletes the shadow
    // - when the user resets the styles while editing a custom shadow
    //
    // The check on the slug is necessary to prevent a double back navigation when the user triggers
    // a backward navigation by interacting with the screen's UI.
    if (!!slug && !hasCurrentShadow) {
      goBack();
    }
  }, [shadows, slug, goBack]);
  const [baseShadows] = useGlobalSetting(`shadow.presets.${category}`, undefined, 'base');
  const [selectedShadow, setSelectedShadow] = (0, _element.useState)(() => (shadows || []).find(shadow => shadow.slug === slug));
  const baseSelectedShadow = (0, _element.useMemo)(() => (baseShadows || []).find(b => b.slug === slug), [baseShadows, slug]);
  const [isConfirmDialogVisible, setIsConfirmDialogVisible] = (0, _element.useState)(false);
  const [isRenameModalVisible, setIsRenameModalVisible] = (0, _element.useState)(false);
  const [shadowName, setShadowName] = (0, _element.useState)(selectedShadow.name);
  if (!category || !slug) {
    return null;
  }
  const onShadowChange = shadow => {
    setSelectedShadow({
      ...selectedShadow,
      shadow
    });
    const updatedShadows = shadows.map(s => s.slug === slug ? {
      ...selectedShadow,
      shadow
    } : s);
    setShadows(updatedShadows);
  };
  const onMenuClick = action => {
    if (action === 'reset') {
      const updatedShadows = shadows.map(s => s.slug === slug ? baseSelectedShadow : s);
      setSelectedShadow(baseSelectedShadow);
      setShadows(updatedShadows);
    } else if (action === 'delete') {
      setIsConfirmDialogVisible(true);
    } else if (action === 'rename') {
      setIsRenameModalVisible(true);
    }
  };
  const handleShadowDelete = () => {
    setShadows(shadows.filter(s => s.slug !== slug));
  };
  const handleShadowRename = newName => {
    if (!newName) {
      return;
    }
    const updatedShadows = shadows.map(s => s.slug === slug ? {
      ...selectedShadow,
      name: newName
    } : s);
    setSelectedShadow({
      ...selectedShadow,
      name: newName
    });
    setShadows(updatedShadows);
  };
  return !selectedShadow ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_header.default, {
    title: ""
  }) : /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalHStack, {
      justify: "space-between",
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_header.default, {
        title: selectedShadow.name
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.FlexItem, {
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalSpacer, {
          marginTop: 2,
          marginBottom: 0,
          paddingX: 4,
          children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(Menu, {
            children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(Menu.TriggerButton, {
              render: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
                size: "small",
                icon: _icons.moreVertical,
                label: (0, _i18n.__)('Menu')
              })
            }), /*#__PURE__*/(0, _jsxRuntime.jsx)(Menu.Popover, {
              children: (category === 'custom' ? customShadowMenuItems : presetShadowMenuItems).map(item => /*#__PURE__*/(0, _jsxRuntime.jsx)(Menu.Item, {
                onClick: () => onMenuClick(item.action),
                disabled: item.action === 'reset' && selectedShadow.shadow === baseSelectedShadow.shadow,
                children: /*#__PURE__*/(0, _jsxRuntime.jsx)(Menu.ItemLabel, {
                  children: item.label
                })
              }, item.action))
            })]
          })
        })
      })]
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: "edit-site-global-styles-screen",
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(ShadowsPreview, {
        shadow: selectedShadow.shadow
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(ShadowEditor, {
        shadow: selectedShadow.shadow,
        onChange: onShadowChange
      })]
    }), isConfirmDialogVisible && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalConfirmDialog, {
      isOpen: true,
      onConfirm: () => {
        handleShadowDelete();
        setIsConfirmDialogVisible(false);
      },
      onCancel: () => {
        setIsConfirmDialogVisible(false);
      },
      confirmButtonText: (0, _i18n.__)('Delete'),
      size: "medium",
      children: (0, _i18n.sprintf)(/* translators: %s: Name of the shadow preset. */
      (0, _i18n.__)('Are you sure you want to delete "%s" shadow preset?'), selectedShadow.name)
    }), isRenameModalVisible && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Modal, {
      title: (0, _i18n.__)('Rename'),
      onRequestClose: () => setIsRenameModalVisible(false),
      size: "small",
      children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("form", {
        onSubmit: event => {
          event.preventDefault();
          handleShadowRename(shadowName);
          setIsRenameModalVisible(false);
        },
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalInputControl, {
          __next40pxDefaultSize: true,
          autoComplete: "off",
          label: (0, _i18n.__)('Name'),
          placeholder: (0, _i18n.__)('Shadow name'),
          value: shadowName,
          onChange: value => setShadowName(value)
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalSpacer, {
          marginBottom: 6
        }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.Flex, {
          className: "block-editor-shadow-edit-modal__actions",
          justify: "flex-end",
          expanded: false,
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.FlexItem, {
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
              __next40pxDefaultSize: true,
              variant: "tertiary",
              onClick: () => setIsRenameModalVisible(false),
              children: (0, _i18n.__)('Cancel')
            })
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.FlexItem, {
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
              __next40pxDefaultSize: true,
              variant: "primary",
              type: "submit",
              children: (0, _i18n.__)('Save')
            })
          })]
        })]
      })
    })]
  });
}
function ShadowsPreview({
  shadow
}) {
  const shadowStyle = {
    boxShadow: shadow
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalSpacer, {
    marginBottom: 4,
    marginTop: -2,
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalHStack, {
      align: "center",
      justify: "center",
      className: "edit-site-global-styles__shadow-preview-panel",
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "edit-site-global-styles__shadow-preview-block",
        style: shadowStyle
      })
    })
  });
}
function ShadowEditor({
  shadow,
  onChange
}) {
  const addShadowButtonRef = (0, _element.useRef)();
  const shadowParts = (0, _element.useMemo)(() => (0, _shadowUtils.getShadowParts)(shadow), [shadow]);
  const onChangeShadowPart = (index, part) => {
    const newShadowParts = [...shadowParts];
    newShadowParts[index] = part;
    onChange(newShadowParts.join(', '));
  };
  const onAddShadowPart = () => {
    onChange([...shadowParts, _shadowsPanel.defaultShadow].join(', '));
  };
  const onRemoveShadowPart = index => {
    onChange(shadowParts.filter((p, i) => i !== index).join(', '));
    addShadowButtonRef.current.focus();
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalVStack, {
      spacing: 2,
      children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalHStack, {
        justify: "space-between",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Flex, {
          align: "center",
          className: "edit-site-global-styles__shadows-panel__title",
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_subtitle.default, {
            level: 3,
            children: (0, _i18n.__)('Shadows')
          })
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.FlexItem, {
          className: "edit-site-global-styles__shadows-panel__options-container",
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
            size: "small",
            icon: _icons.plus,
            label: (0, _i18n.__)('Add shadow'),
            onClick: () => {
              onAddShadowPart();
            },
            ref: addShadowButtonRef
          })
        })]
      })
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalSpacer, {}), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalItemGroup, {
      isBordered: true,
      isSeparated: true,
      children: shadowParts.map((part, index) => /*#__PURE__*/(0, _jsxRuntime.jsx)(ShadowItem, {
        shadow: part,
        onChange: value => onChangeShadowPart(index, value),
        canRemove: shadowParts.length > 1,
        onRemove: () => onRemoveShadowPart(index)
      }, index))
    })]
  });
}
function ShadowItem({
  shadow,
  onChange,
  canRemove,
  onRemove
}) {
  const popoverProps = {
    placement: 'left-start',
    offset: 36,
    shift: true
  };
  const shadowObj = (0, _element.useMemo)(() => (0, _shadowUtils.shadowStringToObject)(shadow), [shadow]);
  const onShadowChange = newShadow => {
    onChange((0, _shadowUtils.shadowObjectToString)(newShadow));
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Dropdown, {
    popoverProps: popoverProps,
    className: "edit-site-global-styles__shadow-editor__dropdown",
    renderToggle: ({
      onToggle,
      isOpen
    }) => {
      const toggleProps = {
        onClick: onToggle,
        className: (0, _clsx.default)('edit-site-global-styles__shadow-editor__dropdown-toggle', {
          'is-open': isOpen
        }),
        'aria-expanded': isOpen
      };
      const removeButtonProps = {
        onClick: () => {
          if (isOpen) {
            onToggle();
          }
          onRemove();
        },
        className: (0, _clsx.default)('edit-site-global-styles__shadow-editor__remove-button', {
          'is-open': isOpen
        }),
        label: (0, _i18n.__)('Remove shadow')
      };
      return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
          __next40pxDefaultSize: true,
          icon: _icons.shadow,
          ...toggleProps,
          children: shadowObj.inset ? (0, _i18n.__)('Inner shadow') : (0, _i18n.__)('Drop shadow')
        }), canRemove && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
          size: "small",
          icon: _icons.reset,
          ...removeButtonProps
        })]
      });
    },
    renderContent: () => /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalDropdownContentWrapper, {
      paddingSize: "medium",
      className: "edit-site-global-styles__shadow-editor__dropdown-content",
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(ShadowPopover, {
        shadowObj: shadowObj,
        onChange: onShadowChange
      })
    })
  });
}
function ShadowPopover({
  shadowObj,
  onChange
}) {
  const __experimentalIsRenderedInSidebar = true;
  const enableAlpha = true;
  const onShadowChange = (key, value) => {
    const newShadow = {
      ...shadowObj,
      [key]: value
    };
    onChange(newShadow);
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalVStack, {
    spacing: 4,
    className: "edit-site-global-styles__shadow-editor-panel",
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.ColorPalette, {
      clearable: false,
      enableAlpha: enableAlpha,
      __experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
      value: shadowObj.color,
      onChange: value => onShadowChange('color', value)
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalToggleGroupControl, {
      __nextHasNoMarginBottom: true,
      value: shadowObj.inset ? 'inset' : 'outset',
      isBlock: true,
      onChange: value => onShadowChange('inset', value === 'inset'),
      hideLabelFromVision: true,
      __next40pxDefaultSize: true,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalToggleGroupControlOption, {
        value: "outset",
        label: (0, _i18n.__)('Outset')
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalToggleGroupControlOption, {
        value: "inset",
        label: (0, _i18n.__)('Inset')
      })]
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalGrid, {
      columns: 2,
      gap: 4,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(ShadowInputControl, {
        label: (0, _i18n.__)('X Position'),
        value: shadowObj.x,
        onChange: value => onShadowChange('x', value)
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(ShadowInputControl, {
        label: (0, _i18n.__)('Y Position'),
        value: shadowObj.y,
        onChange: value => onShadowChange('y', value)
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(ShadowInputControl, {
        label: (0, _i18n.__)('Blur'),
        value: shadowObj.blur,
        onChange: value => onShadowChange('blur', value)
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(ShadowInputControl, {
        label: (0, _i18n.__)('Spread'),
        value: shadowObj.spread,
        onChange: value => onShadowChange('spread', value)
      })]
    })]
  });
}
function ShadowInputControl({
  label,
  value,
  onChange
}) {
  const onValueChange = next => {
    const isNumeric = next !== undefined && !isNaN(parseFloat(next));
    const nextValue = isNumeric ? next : '0px';
    onChange(nextValue);
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalUnitControl, {
    label: label,
    __next40pxDefaultSize: true,
    value: value,
    onChange: onValueChange
  });
}
//# sourceMappingURL=shadows-edit-panel.js.map