UNPKG

@atlaskit/editor-common

Version:

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

79 lines (78 loc) 2.98 kB
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray"; import memoizeOne from 'memoize-one'; import { MEDIA_DYNAMIC_GUIDELINE_PREFIX } from './constants'; import { isVerticalPosition } from './utils'; /** * Returns keys of guidelines that are closest to the image and withthin the snapGap. * If both default and dynamic guidelines present, only returns default guidelines */ export var findClosestSnap = function findClosestSnap(mediaSingleWidth, snapArray, guidelineSnaps) { var snapGap = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; var closestGapIndex = snapArray.reduce(function (prev, curr, index) { return Math.abs(curr - mediaSingleWidth) < Math.abs(snapArray[prev] - mediaSingleWidth) ? index : prev; }, 0); var gap = Math.abs(snapArray[closestGapIndex] - mediaSingleWidth); if (gap < snapGap) { var snappingWidth = snapArray[closestGapIndex]; var guidelineKeys = []; // find wich guideline have the matching snap width guidelineSnaps.forEach(function (gs) { if (gs.width === snappingWidth) { guidelineKeys.push(gs.guidelineKey); } }); var defaultGuidelineKeys = guidelineKeys.filter(function (guidelineKey) { return !guidelineKey.startsWith(MEDIA_DYNAMIC_GUIDELINE_PREFIX); }); return { gap: gap, // only highlight default guidelines // when there are both default and dynamic guidelines to be highlighted keys: defaultGuidelineKeys.length && defaultGuidelineKeys.length < guidelineKeys.length ? defaultGuidelineKeys : guidelineKeys }; } return { gap: gap, keys: [] }; }; export var getGuidelineSnaps = memoizeOne(function (guidelines, editorWidth) { var layout = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'center'; var offset = editorWidth / 2; var getPositionX = function getPositionX(position) { return isVerticalPosition(position) ? position.x : 0; }; var calcXSnaps = function calcXSnaps(guidelineReference) { var snapsWidth = guidelineReference.filter(function (g) { return g.width > 0; }).map(function (g) { return g.width; }); var uniqueSnapWidth = _toConsumableArray(new Set(snapsWidth)); return snapsWidth.length ? uniqueSnapWidth : undefined; }; var guidelinesSnapsReference = guidelines.map(function (guideline) { var positionX = getPositionX(guideline.position); if (['align-end', 'wrap-right'].includes(layout)) { return { guidelineKey: guideline.key, width: offset - positionX }; } else if (['align-start', 'wrap-left'].includes(layout)) { return { guidelineKey: guideline.key, width: positionX + offset }; } return { guidelineKey: guideline.key, width: Math.abs(positionX) * 2 }; }); return { guidelineReference: guidelinesSnapsReference, snaps: { x: calcXSnaps(guidelinesSnapsReference) } }; });