UNPKG

@fullcalendar/web-component

Version:
1,268 lines (1,248 loc) 90.8 kB
import { e as excludeInstances, I as Interaction, b as interactionSettingsToStore, i as interactionSettingsStore } from './2b5ac8cd.js'; import { k as Emitter, a1 as compileEventUis, p as mapHash, v as EventImpl, a2 as buildDateSpanApiWithContext, $ as expandRecurring, Z as filterEventStoreDefs, a3 as preventSelection, a4 as preventContextMenu, a5 as allowSelection, a6 as allowContextMenu, a7 as enableCursor, a8 as disableCursor, t as triggerDateSelect, J as getElEventRange, a9 as getRelevantEvents, aa as getAppendableRoot, F as classNames, ab as applyMutationToEventStore, l as createEmptyEventStore, a as buildEventApis, ac as diffDates, ad as applyStyle, ae as whenTransitionDone, af as isDateSpansEqual, ag as compareNumbers, ah as getEventTargetViaRoot, R as computeElIsRtl } from './69b11357.js'; import { rangeContainsRange, rangesIntersect, startOfDay, createDuration } from '@full-ui/headless-calendar'; import { c as computeRect, a as constrainPoint, i as intersectRects, g as getRectCenter, d as diffPoints, b as computeInnerRect, e as getClippingParents, p as pointInsideRect } from './cf1edde2.js'; /* An abstraction for a dragging interaction originating on an event. Does higher-level things than PointerDragger, such as possibly: - a "mirror" that moves with the pointer - a minimum number of pixels or other criteria for a true drag to begin subclasses must emit: - pointerdown - dragstart - dragmove - pointerup - dragend */ class ElementDragging { constructor(el, selector) { this.emitter = new Emitter(); } destroy() { } setMirrorIsVisible(bool) { // optional if subclass doesn't want to support a mirror } setMirrorNeedsRevert(bool) { // optional if subclass doesn't want to support a mirror } setAutoScrollEnabled(bool) { // optional } } // TODO: get rid of this in favor of options system, // tho it's really easy to access this globally rather than pass thru options. const config = {}; // high-level segmenting-aware tester functions // ------------------------------------------------------------------------------------------------------------------------ function isInteractionValid(interaction, dateProfile, context) { let { instances } = interaction.mutatedEvents; for (let instanceId in instances) { if (!rangeContainsRange(dateProfile.validRange, instances[instanceId].range)) { return false; } } return isNewPropsValid({ eventDrag: interaction }, context); // HACK: the eventDrag props is used for ALL interactions } function isDateSelectionValid(dateSelection, dateProfile, context) { if (!rangeContainsRange(dateProfile.validRange, dateSelection.range)) { return false; } return isNewPropsValid({ dateSelection }, context); } function isNewPropsValid(newProps, context) { let calendarState = context.getCurrentData(); let props = { businessHours: calendarState.businessHours, dateSelection: '', eventStore: calendarState.eventStore, eventUiBases: calendarState.eventUiBases, eventSelection: '', eventDrag: null, eventResize: null, ...newProps, }; return (context.pluginHooks.isPropsValid || isPropsValid)(props, context); } function isPropsValid(state, context, dateSpanMeta = {}, filterConfig) { if (state.eventDrag && !isInteractionPropsValid(state, context, dateSpanMeta, filterConfig)) { return false; } if (state.dateSelection && !isDateSelectionPropsValid(state, context, dateSpanMeta, filterConfig)) { return false; } return true; } // Moving Event Validation // ------------------------------------------------------------------------------------------------------------------------ function isInteractionPropsValid(state, context, dateSpanMeta, filterConfig) { let currentState = context.getCurrentData(); let interaction = state.eventDrag; // HACK: the eventDrag props is used for ALL interactions let subjectEventStore = interaction.mutatedEvents; let subjectDefs = subjectEventStore.defs; let subjectInstances = subjectEventStore.instances; let subjectConfigs = compileEventUis(subjectDefs, interaction.isEvent ? state.eventUiBases : { '': currentState.selectionConfig }); if (filterConfig) { subjectConfigs = mapHash(subjectConfigs, filterConfig); } // exclude the subject events. TODO: exclude defs too? let otherEventStore = excludeInstances(state.eventStore, interaction.affectedEvents.instances); let otherDefs = otherEventStore.defs; let otherInstances = otherEventStore.instances; let otherConfigs = compileEventUis(otherDefs, state.eventUiBases); for (let subjectInstanceId in subjectInstances) { let subjectInstance = subjectInstances[subjectInstanceId]; let subjectRange = subjectInstance.range; let subjectConfig = subjectConfigs[subjectInstance.defId]; let subjectDef = subjectDefs[subjectInstance.defId]; // constraint if (!allConstraintsPass(subjectConfig.constraints, subjectRange, otherEventStore, state.businessHours, context)) { return false; } // overlap let { eventOverlap } = context.options; let eventOverlapFunc = typeof eventOverlap === 'function' ? eventOverlap : null; for (let otherInstanceId in otherInstances) { let otherInstance = otherInstances[otherInstanceId]; // intersect! evaluate if (rangesIntersect(subjectRange, otherInstance.range)) { let otherOverlap = otherConfigs[otherInstance.defId].overlap; // consider the other event's overlap. only do this if the subject event is a "real" event if (otherOverlap === false && interaction.isEvent) { return false; } if (subjectConfig.overlap === false) { return false; } if (eventOverlapFunc && !eventOverlapFunc(new EventImpl(context, otherDefs[otherInstance.defId], otherInstance), // still event new EventImpl(context, subjectDef, subjectInstance))) { return false; } } } // allow (a function) let calendarEventStore = currentState.eventStore; // need global-to-calendar, not local to component (splittable)state for (let subjectAllow of subjectConfig.allows) { let subjectDateSpan = { ...dateSpanMeta, range: subjectInstance.range, allDay: subjectDef.allDay, }; let origDef = calendarEventStore.defs[subjectDef.defId]; let origInstance = calendarEventStore.instances[subjectInstanceId]; let eventApi; if (origDef) { // was previously in the calendar eventApi = new EventImpl(context, origDef, origInstance); } else { // was an external event eventApi = new EventImpl(context, subjectDef); // no instance, because had no dates } if (!subjectAllow(buildDateSpanApiWithContext(subjectDateSpan, context), eventApi)) { return false; } } } return true; } // Date Selection Validation // ------------------------------------------------------------------------------------------------------------------------ function isDateSelectionPropsValid(state, context, dateSpanMeta, filterConfig) { let relevantEventStore = state.eventStore; let relevantDefs = relevantEventStore.defs; let relevantInstances = relevantEventStore.instances; let selection = state.dateSelection; let selectionRange = selection.range; let { selectionConfig } = context.getCurrentData(); if (filterConfig) { selectionConfig = filterConfig(selectionConfig); } // constraint if (!allConstraintsPass(selectionConfig.constraints, selectionRange, relevantEventStore, state.businessHours, context)) { return false; } // overlap let { selectOverlap } = context.options; let selectOverlapFunc = typeof selectOverlap === 'function' ? selectOverlap : null; for (let relevantInstanceId in relevantInstances) { let relevantInstance = relevantInstances[relevantInstanceId]; // intersect! evaluate if (rangesIntersect(selectionRange, relevantInstance.range)) { if (selectionConfig.overlap === false) { return false; } if (selectOverlapFunc && !selectOverlapFunc(new EventImpl(context, relevantDefs[relevantInstance.defId], relevantInstance), null)) { return false; } } } // allow (a function) for (let selectionAllow of selectionConfig.allows) { let fullDateSpan = { ...dateSpanMeta, ...selection }; if (!selectionAllow(buildDateSpanApiWithContext(fullDateSpan, context), null)) { return false; } } return true; } // Constraint Utils // ------------------------------------------------------------------------------------------------------------------------ function allConstraintsPass(constraints, subjectRange, otherEventStore, businessHoursUnexpanded, context) { for (let constraint of constraints) { if (!anyRangesContainRange(constraintToRanges(constraint, subjectRange, otherEventStore, businessHoursUnexpanded, context), subjectRange)) { return false; } } return true; } function constraintToRanges(constraint, subjectRange, // for expanding a recurring constraint, or expanding business hours otherEventStore, // for if constraint is an even group ID businessHoursUnexpanded, // for if constraint is 'businessHours' context) { if (constraint === 'businessHours') { return eventStoreToRanges(expandRecurring(businessHoursUnexpanded, subjectRange, context)); } if (typeof constraint === 'string') { // an group ID return eventStoreToRanges(filterEventStoreDefs(otherEventStore, (eventDef) => eventDef.groupId === constraint)); } if (typeof constraint === 'object' && constraint) { // non-null object return eventStoreToRanges(expandRecurring(constraint, subjectRange, context)); } return []; // if it's false } // TODO: move to event-store file? function eventStoreToRanges(eventStore) { let { instances } = eventStore; let ranges = []; for (let instanceId in instances) { ranges.push(instances[instanceId].range); } return ranges; } // TODO: move to geom file? function anyRangesContainRange(outerRanges, innerRange) { for (let outerRange of outerRanges) { if (rangeContainsRange(outerRange, innerRange)) { return true; } } return false; } config.touchMouseIgnoreWait = 500; let ignoreMouseDepth = 0; let listenerCnt = 0; let isWindowTouchMoveCancelled = false; /* Uses a "pointer" abstraction, which monitors UI events for both mouse and touch. Tracks when the pointer "drags" on a certain element, meaning down+move+up. Also, tracks if there was touch-scrolling. Also, can prevent touch-scrolling from happening. Also, can fire pointermove events when scrolling happens underneath, even when no real pointer movement. emits: - pointerdown - pointermove - pointerup */ class PointerDragging { constructor(containerEl) { this.subjectEl = null; // options that can be directly assigned by caller this.selector = ''; // will cause subjectEl in all emitted events to be this element this.handleSelector = ''; this.shouldIgnoreMove = false; this.shouldWatchScroll = true; // for simulating pointermove on scroll // internal states this.isDragging = false; this.isTouchDragging = false; this.wasTouchScroll = false; // HACK public // Mouse // ---------------------------------------------------------------------------------------------------- this.handleMouseDown = (ev) => { if (!this.shouldIgnoreMouse() && isPrimaryMouseButton(ev) && this.tryStart(ev)) { let pev = this.createEventFromMouse(ev, true); this.emitter.trigger('pointerdown', pev); this.initScrollWatch(pev); if (!this.shouldIgnoreMove) { document.addEventListener('mousemove', this.handleMouseMove); } document.addEventListener('mouseup', this.handleMouseUp); } }; this.handleMouseMove = (ev) => { let pev = this.createEventFromMouse(ev); this.recordCoords(pev); this.emitter.trigger('pointermove', pev); }; this.handleMouseUp = (ev) => { document.removeEventListener('mousemove', this.handleMouseMove); document.removeEventListener('mouseup', this.handleMouseUp); this.emitter.trigger('pointerup', this.createEventFromMouse(ev)); this.cleanup(); // call last so that pointerup has access to props }; // Touch // ---------------------------------------------------------------------------------------------------- this.handleTouchStart = (ev) => { if (this.tryStart(ev)) { this.isTouchDragging = true; let pev = this.createEventFromTouch(ev, true); this.emitter.trigger('pointerdown', pev); this.initScrollWatch(pev); // unlike mouse, need to attach to target, not document // https://stackoverflow.com/a/45760014 let targetEl = ev.target; if (!this.shouldIgnoreMove) { targetEl.addEventListener('touchmove', this.handleTouchMove); } targetEl.addEventListener('touchend', this.handleTouchEnd); targetEl.addEventListener('touchcancel', this.handleTouchEnd); // treat it as a touch end // attach a handler to get called when ANY scroll action happens on the page. // this was impossible to do with normal on/off because 'scroll' doesn't bubble. // http://stackoverflow.com/a/32954565/96342 window.addEventListener('scroll', this.handleTouchScroll, true); } }; this.handleTouchMove = (ev) => { if (this.isDragging) { let pev = this.createEventFromTouch(ev); this.recordCoords(pev); this.emitter.trigger('pointermove', pev); } }; this.handleTouchEnd = (ev) => { if (this.isDragging) { // done to guard against touchend followed by touchcancel let targetEl = ev.target; targetEl.removeEventListener('touchmove', this.handleTouchMove); targetEl.removeEventListener('touchend', this.handleTouchEnd); targetEl.removeEventListener('touchcancel', this.handleTouchEnd); window.removeEventListener('scroll', this.handleTouchScroll, true); // useCaptured=true this.emitter.trigger('pointerup', this.createEventFromTouch(ev)); this.cleanup(); // call last so that pointerup has access to props this.isTouchDragging = false; startIgnoringMouse(); } }; this.handleTouchScroll = () => { this.wasTouchScroll = true; }; this.handleScroll = (ev) => { if (!this.shouldIgnoreMove) { let pageX = (window.scrollX - this.prevScrollX) + this.prevPageX; let pageY = (window.scrollY - this.prevScrollY) + this.prevPageY; this.emitter.trigger('pointermove', { origEvent: ev, isTouch: this.isTouchDragging, subjectEl: this.subjectEl, pageX, pageY, deltaX: pageX - this.origPageX, deltaY: pageY - this.origPageY, }); } }; this.containerEl = containerEl; this.emitter = new Emitter(); containerEl.addEventListener('mousedown', this.handleMouseDown); containerEl.addEventListener('touchstart', this.handleTouchStart, { passive: true }); listenerCreated(); } destroy() { this.containerEl.removeEventListener('mousedown', this.handleMouseDown); this.containerEl.removeEventListener('touchstart', this.handleTouchStart, { passive: true }); listenerDestroyed(); } cancel() { if (this.isDragging) { this.cleanup(); } } tryStart(ev) { let subjectEl = this.querySubjectEl(ev); let downEl = ev.target; if (subjectEl && (!this.handleSelector || downEl.closest(this.handleSelector))) { this.subjectEl = subjectEl; this.isDragging = true; // do this first so cancelTouchScroll will work this.wasTouchScroll = false; return true; } return false; } cleanup() { isWindowTouchMoveCancelled = false; this.isDragging = false; this.subjectEl = null; // keep wasTouchScroll around for later access this.destroyScrollWatch(); } querySubjectEl(ev) { if (this.selector) { return ev.target.closest(this.selector); } return this.containerEl; } shouldIgnoreMouse() { return ignoreMouseDepth || this.isTouchDragging; } // can be called by user of this class, to cancel touch-based scrolling for the current drag cancelTouchScroll() { if (this.isDragging) { isWindowTouchMoveCancelled = true; } } // Scrolling that simulates pointermoves // ---------------------------------------------------------------------------------------------------- initScrollWatch(ev) { if (this.shouldWatchScroll) { this.recordCoords(ev); window.addEventListener('scroll', this.handleScroll, true); // useCapture=true } } recordCoords(ev) { if (this.shouldWatchScroll) { this.prevPageX = ev.pageX; this.prevPageY = ev.pageY; this.prevScrollX = window.scrollX; this.prevScrollY = window.scrollY; } } destroyScrollWatch() { if (this.shouldWatchScroll) { window.removeEventListener('scroll', this.handleScroll, true); // useCaptured=true } } // Event Normalization // ---------------------------------------------------------------------------------------------------- createEventFromMouse(ev, isFirst) { let deltaX = 0; let deltaY = 0; // TODO: repeat code if (isFirst) { this.origPageX = ev.pageX; this.origPageY = ev.pageY; } else { deltaX = ev.pageX - this.origPageX; deltaY = ev.pageY - this.origPageY; } return { origEvent: ev, isTouch: false, subjectEl: this.subjectEl, pageX: ev.pageX, pageY: ev.pageY, deltaX, deltaY, }; } createEventFromTouch(ev, isFirst) { let touches = ev.touches; let pageX; let pageY; let deltaX = 0; let deltaY = 0; // if touch coords available, prefer, // because FF would give bad ev.pageX ev.pageY if (touches && touches.length) { pageX = touches[0].pageX; pageY = touches[0].pageY; } else { pageX = ev.pageX; pageY = ev.pageY; } // TODO: repeat code if (isFirst) { this.origPageX = pageX; this.origPageY = pageY; } else { deltaX = pageX - this.origPageX; deltaY = pageY - this.origPageY; } return { origEvent: ev, isTouch: true, subjectEl: this.subjectEl, pageX, pageY, deltaX, deltaY, }; } } // Returns a boolean whether this was a left mouse click and no ctrl key (which means right click on Mac) function isPrimaryMouseButton(ev) { return ev.button === 0 && !ev.ctrlKey; } // Ignoring fake mouse events generated by touch // ---------------------------------------------------------------------------------------------------- function startIgnoringMouse() { ignoreMouseDepth += 1; setTimeout(() => { ignoreMouseDepth -= 1; }, config.touchMouseIgnoreWait); } // We want to attach touchmove as early as possible for Safari // ---------------------------------------------------------------------------------------------------- function listenerCreated() { listenerCnt += 1; if (listenerCnt === 1) { window.addEventListener('touchmove', onWindowTouchMove, { passive: false }); } } function listenerDestroyed() { listenerCnt -= 1; if (!listenerCnt) { window.removeEventListener('touchmove', onWindowTouchMove, { passive: false }); } } function onWindowTouchMove(ev) { if (isWindowTouchMoveCancelled) { ev.preventDefault(); } } /* An effect in which an element follows the movement of a pointer across the screen. The moving element is a clone of some other element. Must call start + handleMove + stop. */ class ElementMirror { constructor() { this.isVisible = false; // must be explicitly enabled this.sourceEl = null; this.mirrorEl = null; this.sourceElRect = null; // screen coords relative to viewport // options that can be set directly by caller this.parentNode = document.body; // HIGHLY SUGGESTED to set this to sidestep ShadowDOM issues this.zIndex = 9999; this.revertDuration = 0; this.colorScheme = ''; } start(sourceEl, pageX, pageY) { this.sourceEl = sourceEl; this.sourceElRect = this.sourceEl.getBoundingClientRect(); this.origScreenX = pageX - window.scrollX; this.origScreenY = pageY - window.scrollY; this.deltaX = 0; this.deltaY = 0; this.updateElPosition(); } handleMove(pageX, pageY) { this.deltaX = (pageX - window.scrollX) - this.origScreenX; this.deltaY = (pageY - window.scrollY) - this.origScreenY; this.updateElPosition(); } // can be called before start setIsVisible(bool) { if (bool) { if (!this.isVisible) { if (this.mirrorEl) { // important because competes with util.module.css classNames, which are all important // TODO: attach a util className here instead? this.mirrorEl.style.setProperty('display', '', 'important'); } this.isVisible = bool; // needs to happen before updateElPosition this.updateElPosition(); // because was not updating the position while invisible } } else if (this.isVisible) { if (this.mirrorEl) { // important because competes with util.module.css classNames, which are all important // TODO: attach a util className here instead? this.mirrorEl.style.setProperty('display', 'none', 'important'); } this.isVisible = bool; } } // always async stop(needsRevertAnimation, callback) { let done = () => { this.cleanup(); callback(); }; if (needsRevertAnimation && this.mirrorEl && this.isVisible && this.revertDuration && // if 0, transition won't work (this.deltaX || this.deltaY) // if same coords, transition won't work ) { this.doRevertAnimation(done, this.revertDuration); } else { setTimeout(done, 0); } } doRevertAnimation(callback, revertDuration) { let mirrorEl = this.mirrorEl; let finalSourceElRect = this.sourceEl.getBoundingClientRect(); // because autoscrolling might have happened mirrorEl.style.transition = 'top ' + revertDuration + 'ms,' + 'left ' + revertDuration + 'ms'; applyStyle(mirrorEl, { left: finalSourceElRect.left, top: finalSourceElRect.top, }); whenTransitionDone(mirrorEl, () => { mirrorEl.style.transition = ''; callback(); }); } cleanup() { if (this.mirrorEl) { this.mirrorEl.remove(); this.mirrorEl = null; } this.sourceEl = null; } updateElPosition() { if (this.sourceEl && this.isVisible) { applyStyle(this.getMirrorEl(), { left: this.sourceElRect.left + this.deltaX, top: this.sourceElRect.top + this.deltaY, }); } } getMirrorEl() { let sourceElRect = this.sourceElRect; let mirrorEl = this.mirrorEl; if (!mirrorEl) { mirrorEl = this.mirrorEl = this.sourceEl.cloneNode(true); // cloneChildren=true // we don't want long taps or any mouse interaction causing selection/menus. // would use preventSelection(), but that prevents selectstart, causing problems. // TODO: make className for this? mirrorEl.style.userSelect = 'none'; mirrorEl.style.webkitUserSelect = 'none'; mirrorEl.style.pointerEvents = 'none'; if (this.colorScheme) { mirrorEl.setAttribute('data-color-scheme', this.colorScheme); } mirrorEl.classList.add(classNames.borderBoxRoot); applyStyle(mirrorEl, { position: 'fixed', zIndex: this.zIndex, visibility: '', // in case original element was hidden by the drag effect width: sourceElRect.right - sourceElRect.left, // explicit height in case there was a 'right' value height: sourceElRect.bottom - sourceElRect.top, // explicit width in case there was a 'bottom' value right: 'auto', // erase and set width instead bottom: 'auto', // erase and set height instead margin: 0, }); this.parentNode.appendChild(mirrorEl); } return mirrorEl; } } /* eslint max-classes-per-file: "off" */ /* An object for getting/setting scroll-related information for an element. Internally, this is done very differently for window versus DOM element, so this object serves as a common interface. */ class ScrollController { getMaxScrollTop() { return this.getScrollHeight() - this.getClientHeight(); } getMaxScrollLeft() { return this.getScrollWidth() - this.getClientWidth(); } canScrollVertically() { return this.getMaxScrollTop() > 0; } canScrollHorizontally() { return this.getMaxScrollLeft() > 0; } canScrollUp() { return this.getScrollTop() > 0; } canScrollDown() { return this.getScrollTop() < this.getMaxScrollTop(); } canScrollLeft() { return this.getScrollLeft() > 0; } canScrollRight() { return this.getScrollLeft() < this.getMaxScrollLeft(); } } class ElementScrollController extends ScrollController { constructor(el) { super(); this.el = el; } getScrollTop() { return this.el.scrollTop; } getScrollLeft() { return this.el.scrollLeft; } setScrollTop(top) { this.el.scrollTop = top; } setScrollLeft(left) { this.el.scrollLeft = left; } getScrollWidth() { return this.el.scrollWidth; } getScrollHeight() { return this.el.scrollHeight; } getClientHeight() { return this.el.clientHeight; } getClientWidth() { return this.el.clientWidth; } } class WindowScrollController extends ScrollController { getScrollTop() { return window.scrollY; } getScrollLeft() { return window.scrollX; } setScrollTop(n) { window.scroll(window.scrollX, n); } setScrollLeft(n) { window.scroll(n, window.scrollY); } getScrollWidth() { return document.documentElement.scrollWidth; } getScrollHeight() { return document.documentElement.scrollHeight; } getClientHeight() { return document.documentElement.clientHeight; } getClientWidth() { return document.documentElement.clientWidth; } } /* Is a cache for a given element's scroll information (all the info that ScrollController stores) in addition the "client rectangle" of the element.. the area within the scrollbars. The cache can be in one of two modes: - doesListening:false - ignores when the container is scrolled by someone else - doesListening:true - watch for scrolling and update the cache */ class ScrollGeomCache extends ScrollController { constructor(scrollController, doesListening) { super(); this.handleScroll = () => { this.scrollTop = this.scrollController.getScrollTop(); this.scrollLeft = this.scrollController.getScrollLeft(); this.handleScrollChange(); }; this.scrollController = scrollController; this.doesListening = doesListening; this.scrollTop = this.origScrollTop = scrollController.getScrollTop(); this.scrollLeft = this.origScrollLeft = scrollController.getScrollLeft(); this.scrollWidth = scrollController.getScrollWidth(); this.scrollHeight = scrollController.getScrollHeight(); this.clientWidth = scrollController.getClientWidth(); this.clientHeight = scrollController.getClientHeight(); this.clientRect = this.computeClientRect(); // do last in case it needs cached values if (this.doesListening) { this.getEventTarget().addEventListener('scroll', this.handleScroll); } } destroy() { if (this.doesListening) { this.getEventTarget().removeEventListener('scroll', this.handleScroll); } } getScrollTop() { return this.scrollTop; } getScrollLeft() { return this.scrollLeft; } setScrollTop(top) { this.scrollController.setScrollTop(top); if (!this.doesListening) { // we are not relying on the element to normalize out-of-bounds scroll values // so we need to sanitize ourselves this.scrollTop = Math.max(Math.min(top, this.getMaxScrollTop()), 0); this.handleScrollChange(); } } setScrollLeft(top) { this.scrollController.setScrollLeft(top); if (!this.doesListening) { // we are not relying on the element to normalize out-of-bounds scroll values // so we need to sanitize ourselves this.scrollLeft = Math.max(Math.min(top, this.getMaxScrollLeft()), 0); this.handleScrollChange(); } } getClientWidth() { return this.clientWidth; } getClientHeight() { return this.clientHeight; } getScrollWidth() { return this.scrollWidth; } getScrollHeight() { return this.scrollHeight; } handleScrollChange() { } } class ElementScrollGeomCache extends ScrollGeomCache { constructor(el, doesListening) { super(new ElementScrollController(el), doesListening); } getEventTarget() { return this.scrollController.el; } computeClientRect() { return computeInnerRect(this.scrollController.el); } } class WindowScrollGeomCache extends ScrollGeomCache { constructor(doesListening) { super(new WindowScrollController(), doesListening); } getEventTarget() { return window; } computeClientRect() { return { left: this.scrollLeft, right: this.scrollLeft + this.clientWidth, top: this.scrollTop, bottom: this.scrollTop + this.clientHeight, }; } // the window is the only scroll object that changes it's rectangle relative // to the document's topleft as it scrolls handleScrollChange() { this.clientRect = this.computeClientRect(); } } // If available we are using native "performance" API instead of "Date" // Read more about it on MDN: // https://developer.mozilla.org/en-US/docs/Web/API/Performance const getTime = typeof performance === 'function' ? performance.now : Date.now; /* For a pointer interaction, automatically scrolls certain scroll containers when the pointer approaches the edge. The caller must call start + handleMove + stop. */ class AutoScroller { constructor() { // options that can be set by caller this.isEnabled = true; this.scrollQuery = [window, `.${classNames.internalScroller}`]; this.edgeThreshold = 50; // pixels this.maxVelocity = 300; // pixels per second // internal state this.pointerScreenX = null; this.pointerScreenY = null; this.isAnimating = false; this.scrollCaches = null; // protect against the initial pointerdown being too close to an edge and starting the scroll this.everMovedUp = false; this.everMovedDown = false; this.everMovedLeft = false; this.everMovedRight = false; this.animate = () => { if (this.isAnimating) { // wasn't cancelled between animation calls let edge = this.computeBestEdge(this.pointerScreenX + window.scrollX, this.pointerScreenY + window.scrollY); if (edge) { let now = getTime(); this.handleSide(edge, (now - this.msSinceRequest) / 1000); this.requestAnimation(now); } else { this.isAnimating = false; // will stop animation } } }; } start(pageX, pageY, scrollStartEl) { if (this.isEnabled) { this.scrollCaches = this.buildCaches(scrollStartEl); this.pointerScreenX = null; this.pointerScreenY = null; this.everMovedUp = false; this.everMovedDown = false; this.everMovedLeft = false; this.everMovedRight = false; this.handleMove(pageX, pageY); } } handleMove(pageX, pageY) { if (this.isEnabled) { let pointerScreenX = pageX - window.scrollX; let pointerScreenY = pageY - window.scrollY; let yDelta = this.pointerScreenY === null ? 0 : pointerScreenY - this.pointerScreenY; let xDelta = this.pointerScreenX === null ? 0 : pointerScreenX - this.pointerScreenX; if (yDelta < 0) { this.everMovedUp = true; } else if (yDelta > 0) { this.everMovedDown = true; } if (xDelta < 0) { this.everMovedLeft = true; } else if (xDelta > 0) { this.everMovedRight = true; } this.pointerScreenX = pointerScreenX; this.pointerScreenY = pointerScreenY; if (!this.isAnimating) { this.isAnimating = true; this.requestAnimation(getTime()); } } } stop() { if (this.isEnabled) { this.isAnimating = false; // will stop animation for (let scrollCache of this.scrollCaches) { scrollCache.destroy(); } this.scrollCaches = null; } } requestAnimation(now) { this.msSinceRequest = now; requestAnimationFrame(this.animate); } handleSide(edge, seconds) { let { scrollCache } = edge; let { edgeThreshold } = this; let invDistance = edgeThreshold - edge.distance; let velocity = // the closer to the edge, the faster we scroll ((invDistance * invDistance) / (edgeThreshold * edgeThreshold)) * // quadratic this.maxVelocity * seconds; let sign = 1; switch (edge.name) { case 'left': sign = -1; // falls through case 'right': scrollCache.setScrollLeft(scrollCache.getScrollLeft() + velocity * sign); break; case 'top': sign = -1; // falls through case 'bottom': scrollCache.setScrollTop(scrollCache.getScrollTop() + velocity * sign); break; } } // left/top are relative to document topleft computeBestEdge(left, top) { let { edgeThreshold } = this; let bestSide = null; let scrollCaches = this.scrollCaches || []; for (let scrollCache of scrollCaches) { let rect = scrollCache.clientRect; let leftDist = left - rect.left; let rightDist = rect.right - left; let topDist = top - rect.top; let bottomDist = rect.bottom - top; // completely within the rect? if (leftDist >= 0 && rightDist >= 0 && topDist >= 0 && bottomDist >= 0) { if (topDist <= edgeThreshold && this.everMovedUp && scrollCache.canScrollUp() && (!bestSide || bestSide.distance > topDist)) { bestSide = { scrollCache, name: 'top', distance: topDist }; } if (bottomDist <= edgeThreshold && this.everMovedDown && scrollCache.canScrollDown() && (!bestSide || bestSide.distance > bottomDist)) { bestSide = { scrollCache, name: 'bottom', distance: bottomDist }; } /* TODO: fix broken RTL scrolling. canScrollLeft always returning false https://github.com/fullcalendar/fullcalendar/issues/4837 */ if (leftDist <= edgeThreshold && this.everMovedLeft && scrollCache.canScrollLeft() && (!bestSide || bestSide.distance > leftDist)) { bestSide = { scrollCache, name: 'left', distance: leftDist }; } if (rightDist <= edgeThreshold && this.everMovedRight && scrollCache.canScrollRight() && (!bestSide || bestSide.distance > rightDist)) { bestSide = { scrollCache, name: 'right', distance: rightDist }; } } } return bestSide; } buildCaches(scrollStartEl) { return this.queryScrollEls(scrollStartEl).map((el) => { if (el === window) { return new WindowScrollGeomCache(false); // false = don't listen to user-generated scrolls } return new ElementScrollGeomCache(el, false); // false = don't listen to user-generated scrolls }); } queryScrollEls(scrollStartEl) { let els = []; for (let query of this.scrollQuery) { if (typeof query === 'object') { els.push(query); } else { /* TODO: in the future, always have auto-scroll happen on element where current Hit came from Ticket: https://github.com/fullcalendar/fullcalendar/issues/4593 */ els.push(...Array.prototype.slice.call(scrollStartEl.getRootNode().querySelectorAll(query))); } } return els; } } /* Monitors dragging on an element. Has a number of high-level features: - minimum distance required before dragging - minimum wait time ("delay") before dragging - a mirror element that follows the pointer */ class FeaturefulElementDragging extends ElementDragging { constructor(containerEl, selector) { super(containerEl); this.containerEl = containerEl; // options that can be directly set by caller // the caller can also set the PointerDragging's options as well this.delay = null; this.minDistance = 0; this.touchScrollAllowed = true; // prevents drag from starting and blocks scrolling during drag this.mirrorNeedsRevert = false; this.isInteracting = false; // is the user validly moving the pointer? lasts until pointerup this.isDragging = false; // is it INTENTFULLY dragging? lasts until after revert animation this.isDelayEnded = false; this.isDistanceSurpassed = false; this.delayTimeoutId = null; this.onPointerDown = (ev) => { if (!this.isDragging) { // so new drag doesn't happen while revert animation is going this.isInteracting = true; this.isDelayEnded = false; this.isDistanceSurpassed = false; this.emitter.trigger('pointerdown', ev); if (this.isInteracting) { // not cancelled? preventSelection(document.body); preventContextMenu(document.body); // prevent links from being visited if there's an eventual drag. // also prevents selection in older browsers (maybe?). // not necessary for touch, besides, browser would complain about passiveness. if (!ev.isTouch) { ev.origEvent.preventDefault(); } // actions related to initiating dragstart+dragmove+dragend... this.mirror.setIsVisible(false); // reset. caller must set-visible this.mirror.start(ev.subjectEl, ev.pageX, ev.pageY); // must happen on first pointer down this.startDelay(ev); if (!this.minDistance) { this.handleDistanceSurpassed(ev); } } } }; this.onPointerMove = (ev) => { if (this.isInteracting) { this.emitter.trigger('pointermove', ev); if (!this.isDistanceSurpassed) { let minDistance = this.minDistance; let distanceSq; // current distance from the origin, squared let { deltaX, deltaY } = ev; distanceSq = deltaX * deltaX + deltaY * deltaY; if (distanceSq >= minDistance * minDistance) { // use pythagorean theorem this.handleDistanceSurpassed(ev); } } if (this.isDragging) { // a real pointer move? (not one simulated by scrolling) if (ev.origEvent.type !== 'scroll') { this.mirror.handleMove(ev.pageX, ev.pageY); this.autoScroller.handleMove(ev.pageX, ev.pageY); } this.emitter.trigger('dragmove', ev); } } }; this.onPointerUp = (ev) => { if (this.isInteracting) { this.isInteracting = false; allowSelection(document.body); allowContextMenu(document.body); this.emitter.trigger('pointerup', ev); // can potentially set mirrorNeedsRevert if (this.isDragging) { this.autoScroller.stop(); this.tryStopDrag(ev); // which will stop the mirror } if (this.delayTimeoutId) { clearTimeout(this.delayTimeoutId); this.delayTimeoutId = null; } } }; let pointer = this.pointer = new PointerDragging(containerEl); pointer.emitter.on('pointerdown', this.onPointerDown); pointer.emitter.on('pointermove', this.onPointerMove); pointer.emitter.on('pointerup', this.onPointerUp); if (selector) { pointer.selector = selector; } this.mirror = new ElementMirror(); this.autoScroller = new AutoScroller(); } destroy() { this.pointer.destroy(); // HACK: simulate a pointer-up to end the current drag // TODO: fire 'dragend' directly and stop interaction. discourage use of pointerup event (b/c might not fire) this.onPointerUp({}); } startDelay(ev) { if (typeof this.delay === 'number') { this.delayTimeoutId = setTimeout(() => { this.delayTimeoutId = null; this.handleDelayEnd(ev); }, this.delay); // not assignable to number! } else { this.handleDelayEnd(ev); } } handleDelayEnd(ev) { this.isDelayEnded = true; this.tryStartDrag(ev); } handleDistanceSurpassed(ev) { this.isDistanceSurpassed = true; this.tryStartDrag(ev); } tryStartDrag(ev) { if (this.isDelayEnded && this.isDistanceSurpassed) { if (!this.pointer.wasTouchScroll || this.touchScrollAllowed) { this.isDragging = true; this.mirrorNeedsRevert = false; this.autoScroller.start(ev.pageX, ev.pageY, this.containerEl); this.emitter.trigger('dragstart', ev); if (this.touchScrollAllowed === false) { this.pointer.cancelTouchScroll(); } } } } tryStopDrag(ev) { // .stop() is ALWAYS asynchronous, which we NEED because we want all pointerup events // that come from the document to fire beforehand. much more convenient this way. this.mirror.stop(this.mirrorNeedsRevert, this.stopDrag.bind(this, ev)); } stopDrag(ev) { this.isDragging = false; this.emitter.trigger('dragend', ev); } // fill in the implementations... /* Can only be called by pointerdown to prevent drag */ cancel() { if (this.isInteracting) { this.isInteracting = false; this.pointer.cancel(); } } setMirrorIsVisible(bool) { this.mirror.setIsVisible(bool); } setMirrorNeedsRevert(bool) { this.mirrorNeedsRevert = bool; } setAutoScrollEnabled(bool) { this.autoScroller.isEnabled = bool; } } /* When this class is instantiated, it records the offset of an element (relative to the document topleft), and continues to monitor scrolling, updating the cached coordinates if it needs to. Does not access the DOM after instantiation, so highly performant. Also keeps track of all scrolling/overflow:hidden containers that are parents of the given element and an determine if a given point is inside the combined clipping rectangle. */ class OffsetTracker { constructor(el) { this.el = el; this.origRect = computeRect(el); this.isRtl = computeElIsRtl(el); // will work fine for divs that have overflow:hidden this.scrollCaches = getClippingParents(el).map((scrollEl) => new ElementScrollGeomCache(scrollEl, true)); } destroy() { for (let scrollCache of this.scrollCaches) { scrollCache.destroy(); } } computeLeft() { let left = this.origRect.left; for (let scrollCache of this.scrollCaches) { left += scrollCache.origScrollLeft - scrollCache.getScrollLeft(); } return left; } computeTop() { let top = this.origRect.top; for (let scrollCache of this.scrollCaches) { top += scrollCache.origScrollTop - scrollCache.getScrollTop(); } return top; } isWithinClipping(pageX, pageY) { let point = { left: pageX, top: pageY }; for (let scrollCache of this.scrollCaches) { if (!isIgnoredClipping(scrollCache.getEventTarget()) && !pointInsideRect(point, scrollCache.clientRect)) { return false; } } return true; } } // certain clipping containers should never constrain interactions, like <html> and <body> // https://github.com/fullcalendar/fullcalendar/issues/3615 function isIgnoredClipping(node) { let tagName = node.tagName; return tagName === 'HTML' || tagName === 'BODY'; } /* Tracks movement over multiple droppable areas (aka "hits") that exist in one or more DateComponents. Relies on an existing draggable. emits: - pointerdown - dragstart - hitchange - fires initially, even if not over a hit - pointerup - (hitchange - again, to null, if ended over a hit) - dragend */ class HitDragging { constructor(dragging, droppableStore) { // options that can be set by caller this.useSubjectCenter = false; this.requireInitial = true; // if doesn't start out on a hit, won't emit any events this.disablePointCheck = false; this.initialHit = null; this.movingHit = null; this.finalHit = null; // won't ever be populated if shouldIgnoreMove this.handlePointerDown = (ev) => { let { dragging } = this; this.initialHit = null; this.movingHit = null; this.finalHit = null; this.prepareHits(); this.processFirstCoord(ev); if (this.initialHit || !this.requireInitial) { // TODO: fire this before computing processFirstCoord, so listeners can cancel. this gets fired by almost every handler :( this.