UNPKG

@atlaskit/editor-common

Version:

A package that contains common classes and components for editor and renderer

97 lines (96 loc) 3.08 kB
import { NodeSelection } from '@atlaskit/editor-prosemirror/state'; import { findChildren } from '@atlaskit/editor-prosemirror/utils'; import { roundToNearest } from '../media-single'; import { MEDIA_DYNAMIC_GUIDELINE_PREFIX } from './constants'; import { getMediaSingleDimensions } from './utils'; export const generateDynamicGuidelines = (state, editorWidth, styles = {}) => { const selectedNode = state.selection instanceof NodeSelection && state.selection.node; const offset = editorWidth / 2; return findChildren(state.tr.doc, node => node.type === state.schema.nodes.mediaSingle).reduce((acc, nodeWithPos, index) => { var _acc$relativeGuides, _acc$relativeGuides2; const { node, pos } = nodeWithPos; // if the current node the selected node // or the node is not using pixel width, // We will skip the node. if (selectedNode === node || node.attrs.widthType !== 'pixel') { return acc; } const $pos = state.tr.doc.resolve(pos); if ($pos.parent.type !== state.schema.nodes.doc) { return acc; } const dimensions = getMediaSingleDimensions(node, editorWidth); if (!dimensions) { return acc; } const { width, height } = dimensions; const dynamicGuides = [...acc.dynamicGuides, ...getDynamicGuides(node.attrs.layout, width, offset, `${MEDIA_DYNAMIC_GUIDELINE_PREFIX}${index}`, styles)]; const accRelativeGuidesWidth = ((_acc$relativeGuides = acc.relativeGuides) === null || _acc$relativeGuides === void 0 ? void 0 : _acc$relativeGuides.width) || {}; const accRelativeGuidesHeight = ((_acc$relativeGuides2 = acc.relativeGuides) === null || _acc$relativeGuides2 === void 0 ? void 0 : _acc$relativeGuides2.height) || {}; const relativeGuidesWidth = { ...accRelativeGuidesWidth, [width]: [...(accRelativeGuidesWidth[width] || []), nodeWithPos] }; const relativeGuidesWidthHeight = { ...accRelativeGuidesHeight, [Math.round(height)]: [...(accRelativeGuidesHeight[height] || []), nodeWithPos] }; return { dynamicGuides, relativeGuides: { width: relativeGuidesWidth, height: relativeGuidesWidthHeight } }; }, { relativeGuides: { width: {}, height: {} }, dynamicGuides: [] }); }; const getDynamicGuides = (layout, width, offset, key, styles) => { switch (layout) { case 'align-start': case 'wrap-left': return [{ position: { x: roundToNearest(width - offset) }, key, ...styles }]; case 'align-end': case 'wrap-right': return [{ position: { x: roundToNearest(offset - width) }, key, ...styles }]; case 'center': return [{ position: { x: roundToNearest(width / 2) }, key: `${key}_right`, ...styles }, { position: { x: -roundToNearest(width / 2) }, key: `${key}_left`, ...styles }]; default: return []; } };