UNPKG

@atlaskit/editor-plugin-media

Version:

Media plugin for @atlaskit/editor-core

534 lines (526 loc) 23.8 kB
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray"; import _classCallCheck from "@babel/runtime/helpers/classCallCheck"; import _createClass from "@babel/runtime/helpers/createClass"; import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized"; import _inherits from "@babel/runtime/helpers/inherits"; import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn"; import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf"; import _defineProperty from "@babel/runtime/helpers/defineProperty"; import _regeneratorRuntime from "@babel/runtime/regenerator"; function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } 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; } } /** @jsx jsx */ import React from 'react'; import { jsx } from '@emotion/react'; import classnames from 'classnames'; import throttle from 'lodash/throttle'; import memoizeOne from 'memoize-one'; import { findClosestSnap, generateDefaultGuidelines, generateDynamicGuidelines, getGuidelineSnaps, getGuidelinesWithHighlights, getGuidelineTypeFromKey, getRelativeGuidelines, getRelativeGuideSnaps } from '@atlaskit/editor-common/guideline'; import { calcMediaSingleMaxWidth, DEFAULT_IMAGE_WIDTH, MEDIA_SINGLE_DEFAULT_MIN_PIXEL_WIDTH, MEDIA_SINGLE_RESIZE_THROTTLE_TIME, MEDIA_SINGLE_SNAP_GAP, MEDIA_SINGLE_VIDEO_MIN_PIXEL_WIDTH } from '@atlaskit/editor-common/media-single'; import { ResizerNext } from '@atlaskit/editor-common/resizer'; import { resizerStyles, richMediaClassName } from '@atlaskit/editor-common/styles'; import { calcPctFromPx, handleSides, imageAlignmentMap, wrappedLayouts } from '@atlaskit/editor-common/ui'; import { nonWrappedLayouts, setNodeSelection } from '@atlaskit/editor-common/utils'; import { findParentNodeOfTypeClosestToPos } from '@atlaskit/editor-prosemirror/utils'; import { akEditorDefaultLayoutWidth, akEditorFullWidthLayoutWidth, akEditorGutterPadding } from '@atlaskit/editor-shared-styles'; import { MEDIA_PLUGIN_IS_RESIZING_KEY, MEDIA_PLUGIN_RESIZING_WIDTH_KEY } from '../../pm-plugins/main'; import { getMediaResizeAnalyticsEvent } from '../../utils/analytics'; import { checkMediaType } from '../../utils/check-media-type'; import { ResizableMediaMigrationNotification } from './ResizableMediaMigrationNotification'; import { wrapperStyle } from './styled'; export var resizerNextTestId = 'mediaSingle.resizerNext.testid'; // eslint-disable-next-line @repo/internal/react/no-class-components var ResizableMediaSingleNext = /*#__PURE__*/function (_React$Component) { _inherits(ResizableMediaSingleNext, _React$Component); var _super = _createSuper(ResizableMediaSingleNext); function ResizableMediaSingleNext(props) { var _this; _classCallCheck(this, ResizableMediaSingleNext); _this = _super.call(this, props); _defineProperty(_assertThisInitialized(_this), "lastSnappedGuidelineKeys", []); _defineProperty(_assertThisInitialized(_this), "updateGuidelines", function () { var _this$props = _this.props, view = _this$props.view, lineLength = _this$props.lineLength; var defaultGuidelines = _this.getDefaultGuidelines(); var _generateDynamicGuide = generateDynamicGuidelines(view.state, lineLength, { styles: { lineStyle: 'dashed' }, show: false }), relativeGuides = _generateDynamicGuide.relativeGuides, dynamicGuides = _generateDynamicGuide.dynamicGuides; // disable guidelines for nested media single node var dynamicGuidelines = _this.isNestedNode() ? [] : dynamicGuides; _this.setState({ relativeGuides: relativeGuides, guidelines: [].concat(_toConsumableArray(defaultGuidelines), _toConsumableArray(dynamicGuidelines)) }); }); _defineProperty(_assertThisInitialized(_this), "calcNewLayout", function (newWidth, stop) { var _this$props2 = _this.props, layout = _this$props2.layout, containerWidth = _this$props2.containerWidth, lineLength = _this$props2.lineLength, fullWidthMode = _this$props2.fullWidthMode; var newPct = calcPctFromPx(newWidth, lineLength) * 100; if (newPct <= 100 && _this.wrappedLayout) { if (!stop || newPct !== 100) { return layout; } } return _this.calcUnwrappedLayout(newWidth, containerWidth, lineLength, fullWidthMode, _this.isNestedNode()); }); _defineProperty(_assertThisInitialized(_this), "calcUnwrappedLayout", function (width, containerWidth, contentWidth, fullWidthMode, isNestedNode) { if (isNestedNode) { return 'center'; } if (fullWidthMode) { if (width < contentWidth) { return 'center'; } return 'full-width'; } // handle top-level node in fixed-width editor if (width <= contentWidth) { return 'center'; } if (width < Math.min(containerWidth - akEditorGutterPadding * 2, akEditorFullWidthLayoutWidth)) { return 'wide'; } // set full width to be containerWidth - akEditorGutterPadding * 2 // instead of containerWidth - akEditorBreakoutPadding, // so that we have image aligned with text return 'full-width'; }); _defineProperty(_assertThisInitialized(_this), "calcPxHeight", function (newWidth) { var _this$props3 = _this.props, _this$props3$width = _this$props3.width, width = _this$props3$width === void 0 ? newWidth : _this$props3$width, height = _this$props3.height; return Math.round(height / width * newWidth); }); _defineProperty(_assertThisInitialized(_this), "displayGuideline", function (guidelines) { var _this$props$pluginInj; return (_this$props$pluginInj = _this.props.pluginInjectionApi) === null || _this$props$pluginInj === void 0 || (_this$props$pluginInj = _this$props$pluginInj.guideline) === null || _this$props$pluginInj === void 0 || (_this$props$pluginInj = _this$props$pluginInj.actions) === null || _this$props$pluginInj === void 0 ? void 0 : _this$props$pluginInj.displayGuideline(_this.props.view)({ guidelines: guidelines }); }); _defineProperty(_assertThisInitialized(_this), "setIsResizing", function (isResizing) { var _this$props$view = _this.props.view, state = _this$props$view.state, dispatch = _this$props$view.dispatch; var tr = state.tr; tr.setMeta(MEDIA_PLUGIN_IS_RESIZING_KEY, isResizing); return dispatch(tr); }); _defineProperty(_assertThisInitialized(_this), "updateSizeInPluginState", throttle(function (width) { var _this$props$view2 = _this.props.view, state = _this$props$view2.state, dispatch = _this$props$view2.dispatch; var tr = state.tr; tr.setMeta(MEDIA_PLUGIN_RESIZING_WIDTH_KEY, width); return dispatch(tr); }, MEDIA_SINGLE_RESIZE_THROTTLE_TIME)); _defineProperty(_assertThisInitialized(_this), "calcMaxWidth", memoizeOne(function (contentWidth, containerWidth, fullWidthMode) { if (_this.isNestedNode() || fullWidthMode) { return contentWidth; } return calcMediaSingleMaxWidth(containerWidth); })); _defineProperty(_assertThisInitialized(_this), "calcMinWidth", memoizeOne(function (isVideoFile, contentWidth) { return Math.min(contentWidth || akEditorDefaultLayoutWidth, isVideoFile ? MEDIA_SINGLE_VIDEO_MIN_PIXEL_WIDTH : MEDIA_SINGLE_DEFAULT_MIN_PIXEL_WIDTH); })); _defineProperty(_assertThisInitialized(_this), "getRelativeGuides", function () { var _this$props$pluginInj2; var guidelinePluginState = (_this$props$pluginInj2 = _this.props.pluginInjectionApi) === null || _this$props$pluginInj2 === void 0 || (_this$props$pluginInj2 = _this$props$pluginInj2.guideline) === null || _this$props$pluginInj2 === void 0 || (_this$props$pluginInj2 = _this$props$pluginInj2.sharedState) === null || _this$props$pluginInj2 === void 0 ? void 0 : _this$props$pluginInj2.currentState(); var _ref = (guidelinePluginState === null || guidelinePluginState === void 0 ? void 0 : guidelinePluginState.rect) || { top: 0, left: 0 }, topOffset = _ref.top; var $pos = _this.$pos; var relativeGuides = $pos && $pos.nodeAfter && _this.state.size.width ? getRelativeGuidelines(_this.state.relativeGuides, { node: $pos.nodeAfter, pos: $pos.pos }, _this.props.view, _this.props.lineLength, topOffset, _this.state.size) : []; return relativeGuides; }); _defineProperty(_assertThisInitialized(_this), "updateActiveGuidelines", function () { var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var guidelines = arguments.length > 1 ? arguments[1] : undefined; var guidelineSnapsReference = arguments.length > 2 ? arguments[2] : undefined; if (guidelineSnapsReference.snaps.x) { var _findClosestSnap = findClosestSnap(width, guidelineSnapsReference.snaps.x, guidelineSnapsReference.guidelineReference, MEDIA_SINGLE_SNAP_GAP), gap = _findClosestSnap.gap, activeGuidelineKeys = _findClosestSnap.keys; var relativeGuidelines = activeGuidelineKeys.length ? [] : _this.getRelativeGuides(); _this.lastSnappedGuidelineKeys = activeGuidelineKeys.length ? activeGuidelineKeys : relativeGuidelines.map(function (rg) { return rg.key; }); _this.displayGuideline([].concat(_toConsumableArray(getGuidelinesWithHighlights(gap, MEDIA_SINGLE_SNAP_GAP, activeGuidelineKeys, guidelines)), _toConsumableArray(relativeGuidelines))); } }); _defineProperty(_assertThisInitialized(_this), "calculateSizeState", function (size, delta) { var onResizeStop = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var calculatedWidth = Math.round(size.width + delta.width); var calculatedWidthWithLayout = _this.calcNewLayout(calculatedWidth, onResizeStop); return { width: calculatedWidth, height: calculatedWidth / _this.aspectRatio, layout: calculatedWidthWithLayout }; }); _defineProperty(_assertThisInitialized(_this), "selectCurrentMediaNode", function () { // TODO: if adding !this.props.selected, it doesn't work if media single node is at top postion if (_this.pos === null) { return; } setNodeSelection(_this.props.view, _this.pos); }); _defineProperty(_assertThisInitialized(_this), "handleResizeStart", function () { _this.setState({ isResizing: true }); _this.selectCurrentMediaNode(); _this.setIsResizing(true); _this.updateSizeInPluginState(_this.state.size.width); // re-calculate guidelines if (_this.isGuidelineEnabled) { _this.updateGuidelines(); } }); _defineProperty(_assertThisInitialized(_this), "handleResize", function (size, delta) { var _this$props4 = _this.props, layout = _this$props4.layout, updateSize = _this$props4.updateSize, lineLength = _this$props4.lineLength; var _this$calculateSizeSt = _this.calculateSizeState(size, delta), width = _this$calculateSizeSt.width, height = _this$calculateSizeSt.height, newLayout = _this$calculateSizeSt.layout; if (_this.isGuidelineEnabled) { var guidelineSnaps = getGuidelineSnaps(_this.state.guidelines, lineLength, layout); _this.updateActiveGuidelines(width, _this.state.guidelines, guidelineSnaps); var relativeSnaps = getRelativeGuideSnaps(_this.state.relativeGuides, _this.aspectRatio); _this.setState({ size: { width: width, height: height }, snaps: { x: [].concat(_toConsumableArray(guidelineSnaps.snaps.x || []), _toConsumableArray(relativeSnaps)) } }); } else { _this.setState({ size: { width: width, height: height } }); } _this.updateSizeInPluginState(width); if (newLayout !== layout) { updateSize(width, newLayout); } }); _defineProperty(_assertThisInitialized(_this), "handleResizeStop", function (size, delta) { var _this$props5 = _this.props, updateSize = _this$props5.updateSize, dispatchAnalyticsEvent = _this$props5.dispatchAnalyticsEvent, nodeType = _this$props5.nodeType; var _this$calculateSizeSt2 = _this.calculateSizeState(size, delta, true), width = _this$calculateSizeSt2.width, height = _this$calculateSizeSt2.height, newLayout = _this$calculateSizeSt2.layout; if (dispatchAnalyticsEvent) { var $pos = _this.$pos; var event = getMediaResizeAnalyticsEvent(nodeType || 'mediaSingle', { width: width, layout: newLayout, widthType: 'pixel', snapType: getGuidelineTypeFromKey(_this.lastSnappedGuidelineKeys, _this.state.guidelines), parentNode: $pos ? $pos.parent.type.name : undefined }); if (event) { dispatchAnalyticsEvent(event); } } _this.setIsResizing(false); _this.displayGuideline([]); var newWidth = width; if (newLayout === 'full-width') { // When a node reaches full width in current viewport, // update its width with 1800 to align with pixel entry newWidth = akEditorFullWidthLayoutWidth; } _this.setState({ isResizing: false, size: { width: newWidth, height: height } }, function () { updateSize(newWidth, newLayout); }); }); var initialWidth = props.mediaSingleWidth || DEFAULT_IMAGE_WIDTH; _this.state = { isVideoFile: true, isResizing: false, size: { width: initialWidth, height: _this.calcPxHeight(initialWidth) }, snaps: {}, relativeGuides: {}, guidelines: [] }; return _this; } _createClass(ResizableMediaSingleNext, [{ key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (prevProps.mediaSingleWidth !== this.props.mediaSingleWidth && this.props.mediaSingleWidth) { // update size when lineLength becomes defined later // ensures extended experience renders legacy image with the same size as the legacy experience var initialWidth = this.props.mediaSingleWidth; this.setState({ size: { width: initialWidth, height: this.calcPxHeight(initialWidth) } }); } return true; } }, { key: "componentDidMount", value: function () { var _componentDidMount = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { var viewMediaClientConfig; return _regeneratorRuntime.wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: viewMediaClientConfig = this.props.viewMediaClientConfig; if (!viewMediaClientConfig) { _context.next = 4; break; } _context.next = 4; return this.checkVideoFile(viewMediaClientConfig); case 4: case "end": return _context.stop(); } }, _callee, this); })); function componentDidMount() { return _componentDidMount.apply(this, arguments); } return componentDidMount; }() }, { key: "UNSAFE_componentWillReceiveProps", value: function UNSAFE_componentWillReceiveProps(nextProps) { if (this.props.viewMediaClientConfig !== nextProps.viewMediaClientConfig) { this.checkVideoFile(nextProps.viewMediaClientConfig); } } }, { key: "wrappedLayout", get: function get() { return wrappedLayouts.indexOf(this.props.layout) > -1; } }, { key: "pos", get: function get() { if (typeof this.props.getPos !== 'function') { return null; } var pos = this.props.getPos(); if (Number.isNaN(pos) || typeof pos !== 'number') { return null; } return pos; } }, { key: "$pos", get: function get() { var pos = this.pos; // need to pass view because we may not get updated props in time return pos === null ? pos : this.props.view.state.doc.resolve(pos); } }, { key: "aspectRatio", get: function get() { var _this$props6 = this.props, width = _this$props6.width, height = _this$props6.height; if (width) { return width / height; } // TODO handle this case return 1; } }, { key: "insideInlineLike", get: function get() { var $pos = this.$pos; if (!$pos) { return false; } var listItem = this.props.view.state.schema.nodes.listItem; return !!findParentNodeOfTypeClosestToPos($pos, [listItem]); } }, { key: "insideLayout", get: function get() { var $pos = this.$pos; if (!$pos) { return false; } var layoutColumn = this.props.view.state.schema.nodes.layoutColumn; return !!findParentNodeOfTypeClosestToPos($pos, [layoutColumn]); } }, { key: "isGuidelineEnabled", get: function get() { var _this$props$pluginInj3; return !!((_this$props$pluginInj3 = this.props.pluginInjectionApi) !== null && _this$props$pluginInj3 !== void 0 && _this$props$pluginInj3.guideline); } // check if is inside of layout, table, expand, nestedExpand and list item }, { key: "isNestedNode", value: function isNestedNode() { var $pos = this.$pos; return !!($pos && $pos.depth !== 0); } }, { key: "getDefaultGuidelines", value: function getDefaultGuidelines() { var _this$props7 = this.props, lineLength = _this$props7.lineLength, containerWidth = _this$props7.containerWidth, fullWidthMode = _this$props7.fullWidthMode; // disable guidelines for nested media single node return this.isNestedNode() ? [] : generateDefaultGuidelines(lineLength, containerWidth, fullWidthMode); } }, { key: "checkVideoFile", value: function () { var _checkVideoFile = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(viewMediaClientConfig) { var mediaNode, mediaType, isVideoFile; return _regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: if (!(this.pos === null || !viewMediaClientConfig)) { _context2.next = 2; break; } return _context2.abrupt("return"); case 2: mediaNode = this.props.view.state.doc.nodeAt(this.pos + 1); if (!mediaNode) { _context2.next = 9; break; } _context2.next = 6; return checkMediaType(mediaNode, viewMediaClientConfig); case 6: _context2.t0 = _context2.sent; _context2.next = 10; break; case 9: _context2.t0 = undefined; case 10: mediaType = _context2.t0; isVideoFile = mediaType !== 'external' && mediaType !== 'image'; if (this.state.isVideoFile !== isVideoFile) { this.setState({ isVideoFile: isVideoFile }); } case 13: case "end": return _context2.stop(); } }, _callee2, this); })); function checkVideoFile(_x) { return _checkVideoFile.apply(this, arguments); } return checkVideoFile; }() }, { key: "render", value: function render() { var _this2 = this; var _this$props8 = this.props, origWidth = _this$props8.width, layout = _this$props8.layout, containerWidth = _this$props8.containerWidth, fullWidthMode = _this$props8.fullWidthMode, selected = _this$props8.selected, children = _this$props8.children, lineLength = _this$props8.lineLength, showLegacyNotification = _this$props8.showLegacyNotification; var _this$state = this.state, isResizing = _this$state.isResizing, size = _this$state.size, isVideoFile = _this$state.isVideoFile; var enable = {}; handleSides.forEach(function (side) { var oppositeSide = side === 'left' ? 'right' : 'left'; enable[side] = nonWrappedLayouts.concat("wrap-".concat(oppositeSide)).concat("align-".concat(imageAlignmentMap[oppositeSide])).indexOf(layout) > -1; if (side === 'left' && _this2.insideInlineLike) { enable[side] = false; } }); // TODO: Clean up where this lives and how it gets generated var className = classnames(richMediaClassName, "image-".concat(layout), isResizing ? 'is-resizing' : 'not-resizing', this.props.className, { 'richMedia-selected': selected, 'rich-media-wrapped': layout === 'wrap-left' || layout === 'wrap-right' }); var resizerNextClassName = classnames(className, resizerStyles); var isNestedNode = this.isNestedNode(); var maxWidth = !isResizing && isNestedNode ? // set undefined to fall back to 100% undefined : this.calcMaxWidth(lineLength, containerWidth, fullWidthMode); var minWidth = this.calcMinWidth(isVideoFile, lineLength); // while is not resizing, we take 100% as min-width if the container width is less than the min-width var minViewWidth = isResizing ? minWidth : "min(".concat(minWidth, "px, 100%)"); return jsx("div", { css: wrapperStyle({ layout: layout, containerWidth: containerWidth || origWidth, fullWidthMode: fullWidthMode, mediaSingleWidth: this.state.size.width, isNestedNode: isNestedNode, isExtendedResizeExperienceOn: true }) }, jsx(ResizerNext, { minWidth: minViewWidth, maxWidth: maxWidth, className: resizerNextClassName, snapGap: MEDIA_SINGLE_SNAP_GAP, enable: enable, width: size.width, handleResizeStart: this.handleResizeStart, handleResize: this.handleResize, handleResizeStop: this.handleResizeStop, snap: this.state.snaps, resizeRatio: nonWrappedLayouts.includes(layout) ? 2 : 1, "data-testid": resizerNextTestId, isHandleVisible: selected, handlePositioning: isNestedNode ? 'adjacent' : undefined, handleHighlight: "full-height" }, children, showLegacyNotification && jsx(ResizableMediaMigrationNotification, null))); } }]); return ResizableMediaSingleNext; }(React.Component); export default ResizableMediaSingleNext;