"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _clsx = _interopRequireDefault(require("clsx"));
var _blob = require("@wordpress/blob");
var _components = require("@wordpress/components");
var _blockEditor = require("@wordpress/block-editor");
var _element = require("@wordpress/element");
var _i18n = require("@wordpress/i18n");
var _compose = require("@wordpress/compose");
var _data = require("@wordpress/data");
var _icons = require("@wordpress/icons");
var _notices = require("@wordpress/notices");
var _util = require("../embed/util");
var _hooks = require("../utils/hooks");
var _editCommonSettings = _interopRequireDefault(require("./edit-common-settings"));
var _tracksEditor = _interopRequireDefault(require("./tracks-editor"));
var _tracks = _interopRequireDefault(require("./tracks"));
var _caption = require("../utils/caption");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * External dependencies
 */

/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const ALLOWED_MEDIA_TYPES = ['video'];
const VIDEO_POSTER_ALLOWED_MEDIA_TYPES = ['image'];
function VideoEdit({
  isSelected: isSingleSelected,
  attributes,
  className,
  setAttributes,
  insertBlocksAfter,
  onReplace
}) {
  const instanceId = (0, _compose.useInstanceId)(VideoEdit);
  const videoPlayer = (0, _element.useRef)();
  const posterImageButton = (0, _element.useRef)();
  const {
    id,
    controls,
    poster,
    src,
    tracks
  } = attributes;
  const [temporaryURL, setTemporaryURL] = (0, _element.useState)(attributes.blob);
  (0, _hooks.useUploadMediaFromBlobURL)({
    url: temporaryURL,
    allowedTypes: ALLOWED_MEDIA_TYPES,
    onChange: onSelectVideo,
    onError: onUploadError
  });
  (0, _element.useEffect)(() => {
    // Placeholder may be rendered.
    if (videoPlayer.current) {
      videoPlayer.current.load();
    }
  }, [poster]);
  function onSelectVideo(media) {
    if (!media || !media.url) {
      // In this case there was an error
      // previous attributes should be removed
      // because they may be temporary blob urls.
      setAttributes({
        src: undefined,
        id: undefined,
        poster: undefined,
        caption: undefined,
        blob: undefined
      });
      setTemporaryURL();
      return;
    }
    if ((0, _blob.isBlobURL)(media.url)) {
      setTemporaryURL(media.url);
      return;
    }

    // Sets the block's attribute and updates the edit component from the
    // selected media.
    setAttributes({
      blob: undefined,
      src: media.url,
      id: media.id,
      poster: media.image?.src !== media.icon ? media.image?.src : undefined,
      caption: media.caption
    });
    setTemporaryURL();
  }
  function onSelectURL(newSrc) {
    if (newSrc !== src) {
      // Check if there's an embed block that handles this URL.
      const embedBlock = (0, _util.createUpgradedEmbedBlock)({
        attributes: {
          url: newSrc
        }
      });
      if (undefined !== embedBlock && onReplace) {
        onReplace(embedBlock);
        return;
      }
      setAttributes({
        blob: undefined,
        src: newSrc,
        id: undefined,
        poster: undefined
      });
      setTemporaryURL();
    }
  }
  const {
    createErrorNotice
  } = (0, _data.useDispatch)(_notices.store);
  function onUploadError(message) {
    createErrorNotice(message, {
      type: 'snackbar'
    });
  }

  // Much of this description is duplicated from MediaPlaceholder.
  const placeholder = content => {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Placeholder, {
      className: "block-editor-media-placeholder",
      withIllustration: !isSingleSelected,
      icon: _icons.video,
      label: (0, _i18n.__)('Video'),
      instructions: (0, _i18n.__)('Upload a video file, pick one from your media library, or add one with a URL.'),
      children: content
    });
  };
  const classes = (0, _clsx.default)(className, {
    'is-transient': !!temporaryURL
  });
  const blockProps = (0, _blockEditor.useBlockProps)({
    className: classes
  });
  if (!src && !temporaryURL) {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      ...blockProps,
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockEditor.MediaPlaceholder, {
        icon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockEditor.BlockIcon, {
          icon: _icons.video
        }),
        onSelect: onSelectVideo,
        onSelectURL: onSelectURL,
        accept: "video/*",
        allowedTypes: ALLOWED_MEDIA_TYPES,
        value: attributes,
        onError: onUploadError,
        placeholder: placeholder
      })
    });
  }
  function onSelectPoster(image) {
    setAttributes({
      poster: image.url
    });
  }
  function onRemovePoster() {
    setAttributes({
      poster: undefined
    });

    // Move focus back to the Media Upload button.
    posterImageButton.current.focus();
  }
  const videoPosterDescription = `video-block__poster-image-description-${instanceId}`;
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [isSingleSelected && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_blockEditor.BlockControls, {
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_tracksEditor.default, {
          tracks: tracks,
          onChange: newTracks => {
            setAttributes({
              tracks: newTracks
            });
          }
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockEditor.BlockControls, {
        group: "other",
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockEditor.MediaReplaceFlow, {
          mediaId: id,
          mediaURL: src,
          allowedTypes: ALLOWED_MEDIA_TYPES,
          accept: "video/*",
          onSelect: onSelectVideo,
          onSelectURL: onSelectURL,
          onError: onUploadError,
          onReset: () => onSelectVideo(undefined)
        })
      })]
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockEditor.InspectorControls, {
      children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.PanelBody, {
        title: (0, _i18n.__)('Settings'),
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_editCommonSettings.default, {
          setAttributes: setAttributes,
          attributes: attributes
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockEditor.MediaUploadCheck, {
          children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
            className: "editor-video-poster-control",
            children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.BaseControl.VisualLabel, {
              children: (0, _i18n.__)('Poster image')
            }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockEditor.MediaUpload, {
              title: (0, _i18n.__)('Select poster image'),
              onSelect: onSelectPoster,
              allowedTypes: VIDEO_POSTER_ALLOWED_MEDIA_TYPES,
              render: ({
                open
              }) => /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
                __next40pxDefaultSize: true,
                variant: "primary",
                onClick: open,
                ref: posterImageButton,
                "aria-describedby": videoPosterDescription,
                children: !poster ? (0, _i18n.__)('Select') : (0, _i18n.__)('Replace')
              })
            }), /*#__PURE__*/(0, _jsxRuntime.jsx)("p", {
              id: videoPosterDescription,
              hidden: true,
              children: poster ? (0, _i18n.sprintf)( /* translators: %s: poster image URL. */
              (0, _i18n.__)('The current poster image url is %s'), poster) : (0, _i18n.__)('There is no poster image currently selected')
            }), !!poster && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
              __next40pxDefaultSize: true,
              onClick: onRemovePoster,
              variant: "tertiary",
              children: (0, _i18n.__)('Remove')
            })]
          })
        })]
      })
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("figure", {
      ...blockProps,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Disabled, {
        isDisabled: !isSingleSelected,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)("video", {
          controls: controls,
          poster: poster,
          src: src || temporaryURL,
          ref: videoPlayer,
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_tracks.default, {
            tracks: tracks
          })
        })
      }), !!temporaryURL && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Spinner, {}), /*#__PURE__*/(0, _jsxRuntime.jsx)(_caption.Caption, {
        attributes: attributes,
        setAttributes: setAttributes,
        isSelected: isSingleSelected,
        insertBlocksAfter: insertBlocksAfter,
        label: (0, _i18n.__)('Video caption text'),
        showToolbarButton: isSingleSelected
      })]
    })]
  });
}
var _default = exports.default = VideoEdit;
//# sourceMappingURL=edit.js.map