index.js 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126
  1. import { createPlugin } from '@fullcalendar/core/index.js';
  2. import { config, Emitter, elementClosest, applyStyle, whenTransitionDone, removeElement, ScrollController, ElementScrollController, computeInnerRect, WindowScrollController, ElementDragging, preventSelection, preventContextMenu, allowSelection, allowContextMenu, computeRect, getClippingParents, pointInsideRect, constrainPoint, intersectRects, getRectCenter, diffPoints, mapHash, rangeContainsRange, isDateSpansEqual, Interaction, interactionSettingsToStore, isDateSelectionValid, enableCursor, disableCursor, triggerDateSelect, compareNumbers, getElSeg, getRelevantEvents, EventImpl, createEmptyEventStore, applyMutationToEventStore, isInteractionValid, buildEventApis, interactionSettingsStore, startOfDay, diffDates, createDuration, getEventTargetViaRoot, identity, eventTupleToStore, parseDragMeta, elementMatches, refineEventDef, parseEventDef, getDefaultEventEnd, createEventInstance, BASE_OPTION_DEFAULTS } from '@fullcalendar/core/internal.js';
  3. config.touchMouseIgnoreWait = 500;
  4. let ignoreMouseDepth = 0;
  5. let listenerCnt = 0;
  6. let isWindowTouchMoveCancelled = false;
  7. /*
  8. Uses a "pointer" abstraction, which monitors UI events for both mouse and touch.
  9. Tracks when the pointer "drags" on a certain element, meaning down+move+up.
  10. Also, tracks if there was touch-scrolling.
  11. Also, can prevent touch-scrolling from happening.
  12. Also, can fire pointermove events when scrolling happens underneath, even when no real pointer movement.
  13. emits:
  14. - pointerdown
  15. - pointermove
  16. - pointerup
  17. */
  18. class PointerDragging {
  19. constructor(containerEl) {
  20. this.subjectEl = null;
  21. // options that can be directly assigned by caller
  22. this.selector = ''; // will cause subjectEl in all emitted events to be this element
  23. this.handleSelector = '';
  24. this.shouldIgnoreMove = false;
  25. this.shouldWatchScroll = true; // for simulating pointermove on scroll
  26. // internal states
  27. this.isDragging = false;
  28. this.isTouchDragging = false;
  29. this.wasTouchScroll = false;
  30. // Mouse
  31. // ----------------------------------------------------------------------------------------------------
  32. this.handleMouseDown = (ev) => {
  33. if (!this.shouldIgnoreMouse() &&
  34. isPrimaryMouseButton(ev) &&
  35. this.tryStart(ev)) {
  36. let pev = this.createEventFromMouse(ev, true);
  37. this.emitter.trigger('pointerdown', pev);
  38. this.initScrollWatch(pev);
  39. if (!this.shouldIgnoreMove) {
  40. document.addEventListener('mousemove', this.handleMouseMove);
  41. }
  42. document.addEventListener('mouseup', this.handleMouseUp);
  43. }
  44. };
  45. this.handleMouseMove = (ev) => {
  46. let pev = this.createEventFromMouse(ev);
  47. this.recordCoords(pev);
  48. this.emitter.trigger('pointermove', pev);
  49. };
  50. this.handleMouseUp = (ev) => {
  51. document.removeEventListener('mousemove', this.handleMouseMove);
  52. document.removeEventListener('mouseup', this.handleMouseUp);
  53. this.emitter.trigger('pointerup', this.createEventFromMouse(ev));
  54. this.cleanup(); // call last so that pointerup has access to props
  55. };
  56. // Touch
  57. // ----------------------------------------------------------------------------------------------------
  58. this.handleTouchStart = (ev) => {
  59. if (this.tryStart(ev)) {
  60. this.isTouchDragging = true;
  61. let pev = this.createEventFromTouch(ev, true);
  62. this.emitter.trigger('pointerdown', pev);
  63. this.initScrollWatch(pev);
  64. // unlike mouse, need to attach to target, not document
  65. // https://stackoverflow.com/a/45760014
  66. let targetEl = ev.target;
  67. if (!this.shouldIgnoreMove) {
  68. targetEl.addEventListener('touchmove', this.handleTouchMove);
  69. }
  70. targetEl.addEventListener('touchend', this.handleTouchEnd);
  71. targetEl.addEventListener('touchcancel', this.handleTouchEnd); // treat it as a touch end
  72. // attach a handler to get called when ANY scroll action happens on the page.
  73. // this was impossible to do with normal on/off because 'scroll' doesn't bubble.
  74. // http://stackoverflow.com/a/32954565/96342
  75. window.addEventListener('scroll', this.handleTouchScroll, true);
  76. }
  77. };
  78. this.handleTouchMove = (ev) => {
  79. let pev = this.createEventFromTouch(ev);
  80. this.recordCoords(pev);
  81. this.emitter.trigger('pointermove', pev);
  82. };
  83. this.handleTouchEnd = (ev) => {
  84. if (this.isDragging) { // done to guard against touchend followed by touchcancel
  85. let targetEl = ev.target;
  86. targetEl.removeEventListener('touchmove', this.handleTouchMove);
  87. targetEl.removeEventListener('touchend', this.handleTouchEnd);
  88. targetEl.removeEventListener('touchcancel', this.handleTouchEnd);
  89. window.removeEventListener('scroll', this.handleTouchScroll, true); // useCaptured=true
  90. this.emitter.trigger('pointerup', this.createEventFromTouch(ev));
  91. this.cleanup(); // call last so that pointerup has access to props
  92. this.isTouchDragging = false;
  93. startIgnoringMouse();
  94. }
  95. };
  96. this.handleTouchScroll = () => {
  97. this.wasTouchScroll = true;
  98. };
  99. this.handleScroll = (ev) => {
  100. if (!this.shouldIgnoreMove) {
  101. let pageX = (window.scrollX - this.prevScrollX) + this.prevPageX;
  102. let pageY = (window.scrollY - this.prevScrollY) + this.prevPageY;
  103. this.emitter.trigger('pointermove', {
  104. origEvent: ev,
  105. isTouch: this.isTouchDragging,
  106. subjectEl: this.subjectEl,
  107. pageX,
  108. pageY,
  109. deltaX: pageX - this.origPageX,
  110. deltaY: pageY - this.origPageY,
  111. });
  112. }
  113. };
  114. this.containerEl = containerEl;
  115. this.emitter = new Emitter();
  116. containerEl.addEventListener('mousedown', this.handleMouseDown);
  117. containerEl.addEventListener('touchstart', this.handleTouchStart, { passive: true });
  118. listenerCreated();
  119. }
  120. destroy() {
  121. this.containerEl.removeEventListener('mousedown', this.handleMouseDown);
  122. this.containerEl.removeEventListener('touchstart', this.handleTouchStart, { passive: true });
  123. listenerDestroyed();
  124. }
  125. tryStart(ev) {
  126. let subjectEl = this.querySubjectEl(ev);
  127. let downEl = ev.target;
  128. if (subjectEl &&
  129. (!this.handleSelector || elementClosest(downEl, this.handleSelector))) {
  130. this.subjectEl = subjectEl;
  131. this.isDragging = true; // do this first so cancelTouchScroll will work
  132. this.wasTouchScroll = false;
  133. return true;
  134. }
  135. return false;
  136. }
  137. cleanup() {
  138. isWindowTouchMoveCancelled = false;
  139. this.isDragging = false;
  140. this.subjectEl = null;
  141. // keep wasTouchScroll around for later access
  142. this.destroyScrollWatch();
  143. }
  144. querySubjectEl(ev) {
  145. if (this.selector) {
  146. return elementClosest(ev.target, this.selector);
  147. }
  148. return this.containerEl;
  149. }
  150. shouldIgnoreMouse() {
  151. return ignoreMouseDepth || this.isTouchDragging;
  152. }
  153. // can be called by user of this class, to cancel touch-based scrolling for the current drag
  154. cancelTouchScroll() {
  155. if (this.isDragging) {
  156. isWindowTouchMoveCancelled = true;
  157. }
  158. }
  159. // Scrolling that simulates pointermoves
  160. // ----------------------------------------------------------------------------------------------------
  161. initScrollWatch(ev) {
  162. if (this.shouldWatchScroll) {
  163. this.recordCoords(ev);
  164. window.addEventListener('scroll', this.handleScroll, true); // useCapture=true
  165. }
  166. }
  167. recordCoords(ev) {
  168. if (this.shouldWatchScroll) {
  169. this.prevPageX = ev.pageX;
  170. this.prevPageY = ev.pageY;
  171. this.prevScrollX = window.scrollX;
  172. this.prevScrollY = window.scrollY;
  173. }
  174. }
  175. destroyScrollWatch() {
  176. if (this.shouldWatchScroll) {
  177. window.removeEventListener('scroll', this.handleScroll, true); // useCaptured=true
  178. }
  179. }
  180. // Event Normalization
  181. // ----------------------------------------------------------------------------------------------------
  182. createEventFromMouse(ev, isFirst) {
  183. let deltaX = 0;
  184. let deltaY = 0;
  185. // TODO: repeat code
  186. if (isFirst) {
  187. this.origPageX = ev.pageX;
  188. this.origPageY = ev.pageY;
  189. }
  190. else {
  191. deltaX = ev.pageX - this.origPageX;
  192. deltaY = ev.pageY - this.origPageY;
  193. }
  194. return {
  195. origEvent: ev,
  196. isTouch: false,
  197. subjectEl: this.subjectEl,
  198. pageX: ev.pageX,
  199. pageY: ev.pageY,
  200. deltaX,
  201. deltaY,
  202. };
  203. }
  204. createEventFromTouch(ev, isFirst) {
  205. let touches = ev.touches;
  206. let pageX;
  207. let pageY;
  208. let deltaX = 0;
  209. let deltaY = 0;
  210. // if touch coords available, prefer,
  211. // because FF would give bad ev.pageX ev.pageY
  212. if (touches && touches.length) {
  213. pageX = touches[0].pageX;
  214. pageY = touches[0].pageY;
  215. }
  216. else {
  217. pageX = ev.pageX;
  218. pageY = ev.pageY;
  219. }
  220. // TODO: repeat code
  221. if (isFirst) {
  222. this.origPageX = pageX;
  223. this.origPageY = pageY;
  224. }
  225. else {
  226. deltaX = pageX - this.origPageX;
  227. deltaY = pageY - this.origPageY;
  228. }
  229. return {
  230. origEvent: ev,
  231. isTouch: true,
  232. subjectEl: this.subjectEl,
  233. pageX,
  234. pageY,
  235. deltaX,
  236. deltaY,
  237. };
  238. }
  239. }
  240. // Returns a boolean whether this was a left mouse click and no ctrl key (which means right click on Mac)
  241. function isPrimaryMouseButton(ev) {
  242. return ev.button === 0 && !ev.ctrlKey;
  243. }
  244. // Ignoring fake mouse events generated by touch
  245. // ----------------------------------------------------------------------------------------------------
  246. function startIgnoringMouse() {
  247. ignoreMouseDepth += 1;
  248. setTimeout(() => {
  249. ignoreMouseDepth -= 1;
  250. }, config.touchMouseIgnoreWait);
  251. }
  252. // We want to attach touchmove as early as possible for Safari
  253. // ----------------------------------------------------------------------------------------------------
  254. function listenerCreated() {
  255. listenerCnt += 1;
  256. if (listenerCnt === 1) {
  257. window.addEventListener('touchmove', onWindowTouchMove, { passive: false });
  258. }
  259. }
  260. function listenerDestroyed() {
  261. listenerCnt -= 1;
  262. if (!listenerCnt) {
  263. window.removeEventListener('touchmove', onWindowTouchMove, { passive: false });
  264. }
  265. }
  266. function onWindowTouchMove(ev) {
  267. if (isWindowTouchMoveCancelled) {
  268. ev.preventDefault();
  269. }
  270. }
  271. /*
  272. An effect in which an element follows the movement of a pointer across the screen.
  273. The moving element is a clone of some other element.
  274. Must call start + handleMove + stop.
  275. */
  276. class ElementMirror {
  277. constructor() {
  278. this.isVisible = false; // must be explicitly enabled
  279. this.sourceEl = null;
  280. this.mirrorEl = null;
  281. this.sourceElRect = null; // screen coords relative to viewport
  282. // options that can be set directly by caller
  283. this.parentNode = document.body; // HIGHLY SUGGESTED to set this to sidestep ShadowDOM issues
  284. this.zIndex = 9999;
  285. this.revertDuration = 0;
  286. }
  287. start(sourceEl, pageX, pageY) {
  288. this.sourceEl = sourceEl;
  289. this.sourceElRect = this.sourceEl.getBoundingClientRect();
  290. this.origScreenX = pageX - window.scrollX;
  291. this.origScreenY = pageY - window.scrollY;
  292. this.deltaX = 0;
  293. this.deltaY = 0;
  294. this.updateElPosition();
  295. }
  296. handleMove(pageX, pageY) {
  297. this.deltaX = (pageX - window.scrollX) - this.origScreenX;
  298. this.deltaY = (pageY - window.scrollY) - this.origScreenY;
  299. this.updateElPosition();
  300. }
  301. // can be called before start
  302. setIsVisible(bool) {
  303. if (bool) {
  304. if (!this.isVisible) {
  305. if (this.mirrorEl) {
  306. this.mirrorEl.style.display = '';
  307. }
  308. this.isVisible = bool; // needs to happen before updateElPosition
  309. this.updateElPosition(); // because was not updating the position while invisible
  310. }
  311. }
  312. else if (this.isVisible) {
  313. if (this.mirrorEl) {
  314. this.mirrorEl.style.display = 'none';
  315. }
  316. this.isVisible = bool;
  317. }
  318. }
  319. // always async
  320. stop(needsRevertAnimation, callback) {
  321. let done = () => {
  322. this.cleanup();
  323. callback();
  324. };
  325. if (needsRevertAnimation &&
  326. this.mirrorEl &&
  327. this.isVisible &&
  328. this.revertDuration && // if 0, transition won't work
  329. (this.deltaX || this.deltaY) // if same coords, transition won't work
  330. ) {
  331. this.doRevertAnimation(done, this.revertDuration);
  332. }
  333. else {
  334. setTimeout(done, 0);
  335. }
  336. }
  337. doRevertAnimation(callback, revertDuration) {
  338. let mirrorEl = this.mirrorEl;
  339. let finalSourceElRect = this.sourceEl.getBoundingClientRect(); // because autoscrolling might have happened
  340. mirrorEl.style.transition =
  341. 'top ' + revertDuration + 'ms,' +
  342. 'left ' + revertDuration + 'ms';
  343. applyStyle(mirrorEl, {
  344. left: finalSourceElRect.left,
  345. top: finalSourceElRect.top,
  346. });
  347. whenTransitionDone(mirrorEl, () => {
  348. mirrorEl.style.transition = '';
  349. callback();
  350. });
  351. }
  352. cleanup() {
  353. if (this.mirrorEl) {
  354. removeElement(this.mirrorEl);
  355. this.mirrorEl = null;
  356. }
  357. this.sourceEl = null;
  358. }
  359. updateElPosition() {
  360. if (this.sourceEl && this.isVisible) {
  361. applyStyle(this.getMirrorEl(), {
  362. left: this.sourceElRect.left + this.deltaX,
  363. top: this.sourceElRect.top + this.deltaY,
  364. });
  365. }
  366. }
  367. getMirrorEl() {
  368. let sourceElRect = this.sourceElRect;
  369. let mirrorEl = this.mirrorEl;
  370. if (!mirrorEl) {
  371. mirrorEl = this.mirrorEl = this.sourceEl.cloneNode(true); // cloneChildren=true
  372. // we don't want long taps or any mouse interaction causing selection/menus.
  373. // would use preventSelection(), but that prevents selectstart, causing problems.
  374. mirrorEl.style.userSelect = 'none';
  375. mirrorEl.style.webkitUserSelect = 'none';
  376. mirrorEl.style.pointerEvents = 'none';
  377. mirrorEl.classList.add('fc-event-dragging');
  378. applyStyle(mirrorEl, {
  379. position: 'fixed',
  380. zIndex: this.zIndex,
  381. visibility: '',
  382. boxSizing: 'border-box',
  383. width: sourceElRect.right - sourceElRect.left,
  384. height: sourceElRect.bottom - sourceElRect.top,
  385. right: 'auto',
  386. bottom: 'auto',
  387. margin: 0,
  388. });
  389. this.parentNode.appendChild(mirrorEl);
  390. }
  391. return mirrorEl;
  392. }
  393. }
  394. /*
  395. Is a cache for a given element's scroll information (all the info that ScrollController stores)
  396. in addition the "client rectangle" of the element.. the area within the scrollbars.
  397. The cache can be in one of two modes:
  398. - doesListening:false - ignores when the container is scrolled by someone else
  399. - doesListening:true - watch for scrolling and update the cache
  400. */
  401. class ScrollGeomCache extends ScrollController {
  402. constructor(scrollController, doesListening) {
  403. super();
  404. this.handleScroll = () => {
  405. this.scrollTop = this.scrollController.getScrollTop();
  406. this.scrollLeft = this.scrollController.getScrollLeft();
  407. this.handleScrollChange();
  408. };
  409. this.scrollController = scrollController;
  410. this.doesListening = doesListening;
  411. this.scrollTop = this.origScrollTop = scrollController.getScrollTop();
  412. this.scrollLeft = this.origScrollLeft = scrollController.getScrollLeft();
  413. this.scrollWidth = scrollController.getScrollWidth();
  414. this.scrollHeight = scrollController.getScrollHeight();
  415. this.clientWidth = scrollController.getClientWidth();
  416. this.clientHeight = scrollController.getClientHeight();
  417. this.clientRect = this.computeClientRect(); // do last in case it needs cached values
  418. if (this.doesListening) {
  419. this.getEventTarget().addEventListener('scroll', this.handleScroll);
  420. }
  421. }
  422. destroy() {
  423. if (this.doesListening) {
  424. this.getEventTarget().removeEventListener('scroll', this.handleScroll);
  425. }
  426. }
  427. getScrollTop() {
  428. return this.scrollTop;
  429. }
  430. getScrollLeft() {
  431. return this.scrollLeft;
  432. }
  433. setScrollTop(top) {
  434. this.scrollController.setScrollTop(top);
  435. if (!this.doesListening) {
  436. // we are not relying on the element to normalize out-of-bounds scroll values
  437. // so we need to sanitize ourselves
  438. this.scrollTop = Math.max(Math.min(top, this.getMaxScrollTop()), 0);
  439. this.handleScrollChange();
  440. }
  441. }
  442. setScrollLeft(top) {
  443. this.scrollController.setScrollLeft(top);
  444. if (!this.doesListening) {
  445. // we are not relying on the element to normalize out-of-bounds scroll values
  446. // so we need to sanitize ourselves
  447. this.scrollLeft = Math.max(Math.min(top, this.getMaxScrollLeft()), 0);
  448. this.handleScrollChange();
  449. }
  450. }
  451. getClientWidth() {
  452. return this.clientWidth;
  453. }
  454. getClientHeight() {
  455. return this.clientHeight;
  456. }
  457. getScrollWidth() {
  458. return this.scrollWidth;
  459. }
  460. getScrollHeight() {
  461. return this.scrollHeight;
  462. }
  463. handleScrollChange() {
  464. }
  465. }
  466. class ElementScrollGeomCache extends ScrollGeomCache {
  467. constructor(el, doesListening) {
  468. super(new ElementScrollController(el), doesListening);
  469. }
  470. getEventTarget() {
  471. return this.scrollController.el;
  472. }
  473. computeClientRect() {
  474. return computeInnerRect(this.scrollController.el);
  475. }
  476. }
  477. class WindowScrollGeomCache extends ScrollGeomCache {
  478. constructor(doesListening) {
  479. super(new WindowScrollController(), doesListening);
  480. }
  481. getEventTarget() {
  482. return window;
  483. }
  484. computeClientRect() {
  485. return {
  486. left: this.scrollLeft,
  487. right: this.scrollLeft + this.clientWidth,
  488. top: this.scrollTop,
  489. bottom: this.scrollTop + this.clientHeight,
  490. };
  491. }
  492. // the window is the only scroll object that changes it's rectangle relative
  493. // to the document's topleft as it scrolls
  494. handleScrollChange() {
  495. this.clientRect = this.computeClientRect();
  496. }
  497. }
  498. // If available we are using native "performance" API instead of "Date"
  499. // Read more about it on MDN:
  500. // https://developer.mozilla.org/en-US/docs/Web/API/Performance
  501. const getTime = typeof performance === 'function' ? performance.now : Date.now;
  502. /*
  503. For a pointer interaction, automatically scrolls certain scroll containers when the pointer
  504. approaches the edge.
  505. The caller must call start + handleMove + stop.
  506. */
  507. class AutoScroller {
  508. constructor() {
  509. // options that can be set by caller
  510. this.isEnabled = true;
  511. this.scrollQuery = [window, '.fc-scroller'];
  512. this.edgeThreshold = 50; // pixels
  513. this.maxVelocity = 300; // pixels per second
  514. // internal state
  515. this.pointerScreenX = null;
  516. this.pointerScreenY = null;
  517. this.isAnimating = false;
  518. this.scrollCaches = null;
  519. // protect against the initial pointerdown being too close to an edge and starting the scroll
  520. this.everMovedUp = false;
  521. this.everMovedDown = false;
  522. this.everMovedLeft = false;
  523. this.everMovedRight = false;
  524. this.animate = () => {
  525. if (this.isAnimating) { // wasn't cancelled between animation calls
  526. let edge = this.computeBestEdge(this.pointerScreenX + window.scrollX, this.pointerScreenY + window.scrollY);
  527. if (edge) {
  528. let now = getTime();
  529. this.handleSide(edge, (now - this.msSinceRequest) / 1000);
  530. this.requestAnimation(now);
  531. }
  532. else {
  533. this.isAnimating = false; // will stop animation
  534. }
  535. }
  536. };
  537. }
  538. start(pageX, pageY, scrollStartEl) {
  539. if (this.isEnabled) {
  540. this.scrollCaches = this.buildCaches(scrollStartEl);
  541. this.pointerScreenX = null;
  542. this.pointerScreenY = null;
  543. this.everMovedUp = false;
  544. this.everMovedDown = false;
  545. this.everMovedLeft = false;
  546. this.everMovedRight = false;
  547. this.handleMove(pageX, pageY);
  548. }
  549. }
  550. handleMove(pageX, pageY) {
  551. if (this.isEnabled) {
  552. let pointerScreenX = pageX - window.scrollX;
  553. let pointerScreenY = pageY - window.scrollY;
  554. let yDelta = this.pointerScreenY === null ? 0 : pointerScreenY - this.pointerScreenY;
  555. let xDelta = this.pointerScreenX === null ? 0 : pointerScreenX - this.pointerScreenX;
  556. if (yDelta < 0) {
  557. this.everMovedUp = true;
  558. }
  559. else if (yDelta > 0) {
  560. this.everMovedDown = true;
  561. }
  562. if (xDelta < 0) {
  563. this.everMovedLeft = true;
  564. }
  565. else if (xDelta > 0) {
  566. this.everMovedRight = true;
  567. }
  568. this.pointerScreenX = pointerScreenX;
  569. this.pointerScreenY = pointerScreenY;
  570. if (!this.isAnimating) {
  571. this.isAnimating = true;
  572. this.requestAnimation(getTime());
  573. }
  574. }
  575. }
  576. stop() {
  577. if (this.isEnabled) {
  578. this.isAnimating = false; // will stop animation
  579. for (let scrollCache of this.scrollCaches) {
  580. scrollCache.destroy();
  581. }
  582. this.scrollCaches = null;
  583. }
  584. }
  585. requestAnimation(now) {
  586. this.msSinceRequest = now;
  587. requestAnimationFrame(this.animate);
  588. }
  589. handleSide(edge, seconds) {
  590. let { scrollCache } = edge;
  591. let { edgeThreshold } = this;
  592. let invDistance = edgeThreshold - edge.distance;
  593. let velocity = // the closer to the edge, the faster we scroll
  594. ((invDistance * invDistance) / (edgeThreshold * edgeThreshold)) * // quadratic
  595. this.maxVelocity * seconds;
  596. let sign = 1;
  597. switch (edge.name) {
  598. case 'left':
  599. sign = -1;
  600. // falls through
  601. case 'right':
  602. scrollCache.setScrollLeft(scrollCache.getScrollLeft() + velocity * sign);
  603. break;
  604. case 'top':
  605. sign = -1;
  606. // falls through
  607. case 'bottom':
  608. scrollCache.setScrollTop(scrollCache.getScrollTop() + velocity * sign);
  609. break;
  610. }
  611. }
  612. // left/top are relative to document topleft
  613. computeBestEdge(left, top) {
  614. let { edgeThreshold } = this;
  615. let bestSide = null;
  616. let scrollCaches = this.scrollCaches || [];
  617. for (let scrollCache of scrollCaches) {
  618. let rect = scrollCache.clientRect;
  619. let leftDist = left - rect.left;
  620. let rightDist = rect.right - left;
  621. let topDist = top - rect.top;
  622. let bottomDist = rect.bottom - top;
  623. // completely within the rect?
  624. if (leftDist >= 0 && rightDist >= 0 && topDist >= 0 && bottomDist >= 0) {
  625. if (topDist <= edgeThreshold && this.everMovedUp && scrollCache.canScrollUp() &&
  626. (!bestSide || bestSide.distance > topDist)) {
  627. bestSide = { scrollCache, name: 'top', distance: topDist };
  628. }
  629. if (bottomDist <= edgeThreshold && this.everMovedDown && scrollCache.canScrollDown() &&
  630. (!bestSide || bestSide.distance > bottomDist)) {
  631. bestSide = { scrollCache, name: 'bottom', distance: bottomDist };
  632. }
  633. /*
  634. TODO: fix broken RTL scrolling. canScrollLeft always returning false
  635. https://github.com/fullcalendar/fullcalendar/issues/4837
  636. */
  637. if (leftDist <= edgeThreshold && this.everMovedLeft && scrollCache.canScrollLeft() &&
  638. (!bestSide || bestSide.distance > leftDist)) {
  639. bestSide = { scrollCache, name: 'left', distance: leftDist };
  640. }
  641. if (rightDist <= edgeThreshold && this.everMovedRight && scrollCache.canScrollRight() &&
  642. (!bestSide || bestSide.distance > rightDist)) {
  643. bestSide = { scrollCache, name: 'right', distance: rightDist };
  644. }
  645. }
  646. }
  647. return bestSide;
  648. }
  649. buildCaches(scrollStartEl) {
  650. return this.queryScrollEls(scrollStartEl).map((el) => {
  651. if (el === window) {
  652. return new WindowScrollGeomCache(false); // false = don't listen to user-generated scrolls
  653. }
  654. return new ElementScrollGeomCache(el, false); // false = don't listen to user-generated scrolls
  655. });
  656. }
  657. queryScrollEls(scrollStartEl) {
  658. let els = [];
  659. for (let query of this.scrollQuery) {
  660. if (typeof query === 'object') {
  661. els.push(query);
  662. }
  663. else {
  664. /*
  665. TODO: in the future, always have auto-scroll happen on element where current Hit came from
  666. Ticket: https://github.com/fullcalendar/fullcalendar/issues/4593
  667. */
  668. els.push(...Array.prototype.slice.call(scrollStartEl.getRootNode().querySelectorAll(query)));
  669. }
  670. }
  671. return els;
  672. }
  673. }
  674. /*
  675. Monitors dragging on an element. Has a number of high-level features:
  676. - minimum distance required before dragging
  677. - minimum wait time ("delay") before dragging
  678. - a mirror element that follows the pointer
  679. */
  680. class FeaturefulElementDragging extends ElementDragging {
  681. constructor(containerEl, selector) {
  682. super(containerEl);
  683. this.containerEl = containerEl;
  684. // options that can be directly set by caller
  685. // the caller can also set the PointerDragging's options as well
  686. this.delay = null;
  687. this.minDistance = 0;
  688. this.touchScrollAllowed = true; // prevents drag from starting and blocks scrolling during drag
  689. this.mirrorNeedsRevert = false;
  690. this.isInteracting = false; // is the user validly moving the pointer? lasts until pointerup
  691. this.isDragging = false; // is it INTENTFULLY dragging? lasts until after revert animation
  692. this.isDelayEnded = false;
  693. this.isDistanceSurpassed = false;
  694. this.delayTimeoutId = null;
  695. this.onPointerDown = (ev) => {
  696. if (!this.isDragging) { // so new drag doesn't happen while revert animation is going
  697. this.isInteracting = true;
  698. this.isDelayEnded = false;
  699. this.isDistanceSurpassed = false;
  700. preventSelection(document.body);
  701. preventContextMenu(document.body);
  702. // prevent links from being visited if there's an eventual drag.
  703. // also prevents selection in older browsers (maybe?).
  704. // not necessary for touch, besides, browser would complain about passiveness.
  705. if (!ev.isTouch) {
  706. ev.origEvent.preventDefault();
  707. }
  708. this.emitter.trigger('pointerdown', ev);
  709. if (this.isInteracting && // not destroyed via pointerdown handler
  710. !this.pointer.shouldIgnoreMove) {
  711. // actions related to initiating dragstart+dragmove+dragend...
  712. this.mirror.setIsVisible(false); // reset. caller must set-visible
  713. this.mirror.start(ev.subjectEl, ev.pageX, ev.pageY); // must happen on first pointer down
  714. this.startDelay(ev);
  715. if (!this.minDistance) {
  716. this.handleDistanceSurpassed(ev);
  717. }
  718. }
  719. }
  720. };
  721. this.onPointerMove = (ev) => {
  722. if (this.isInteracting) {
  723. this.emitter.trigger('pointermove', ev);
  724. if (!this.isDistanceSurpassed) {
  725. let minDistance = this.minDistance;
  726. let distanceSq; // current distance from the origin, squared
  727. let { deltaX, deltaY } = ev;
  728. distanceSq = deltaX * deltaX + deltaY * deltaY;
  729. if (distanceSq >= minDistance * minDistance) { // use pythagorean theorem
  730. this.handleDistanceSurpassed(ev);
  731. }
  732. }
  733. if (this.isDragging) {
  734. // a real pointer move? (not one simulated by scrolling)
  735. if (ev.origEvent.type !== 'scroll') {
  736. this.mirror.handleMove(ev.pageX, ev.pageY);
  737. this.autoScroller.handleMove(ev.pageX, ev.pageY);
  738. }
  739. this.emitter.trigger('dragmove', ev);
  740. }
  741. }
  742. };
  743. this.onPointerUp = (ev) => {
  744. if (this.isInteracting) {
  745. this.isInteracting = false;
  746. allowSelection(document.body);
  747. allowContextMenu(document.body);
  748. this.emitter.trigger('pointerup', ev); // can potentially set mirrorNeedsRevert
  749. if (this.isDragging) {
  750. this.autoScroller.stop();
  751. this.tryStopDrag(ev); // which will stop the mirror
  752. }
  753. if (this.delayTimeoutId) {
  754. clearTimeout(this.delayTimeoutId);
  755. this.delayTimeoutId = null;
  756. }
  757. }
  758. };
  759. let pointer = this.pointer = new PointerDragging(containerEl);
  760. pointer.emitter.on('pointerdown', this.onPointerDown);
  761. pointer.emitter.on('pointermove', this.onPointerMove);
  762. pointer.emitter.on('pointerup', this.onPointerUp);
  763. if (selector) {
  764. pointer.selector = selector;
  765. }
  766. this.mirror = new ElementMirror();
  767. this.autoScroller = new AutoScroller();
  768. }
  769. destroy() {
  770. this.pointer.destroy();
  771. // HACK: simulate a pointer-up to end the current drag
  772. // TODO: fire 'dragend' directly and stop interaction. discourage use of pointerup event (b/c might not fire)
  773. this.onPointerUp({});
  774. }
  775. startDelay(ev) {
  776. if (typeof this.delay === 'number') {
  777. this.delayTimeoutId = setTimeout(() => {
  778. this.delayTimeoutId = null;
  779. this.handleDelayEnd(ev);
  780. }, this.delay); // not assignable to number!
  781. }
  782. else {
  783. this.handleDelayEnd(ev);
  784. }
  785. }
  786. handleDelayEnd(ev) {
  787. this.isDelayEnded = true;
  788. this.tryStartDrag(ev);
  789. }
  790. handleDistanceSurpassed(ev) {
  791. this.isDistanceSurpassed = true;
  792. this.tryStartDrag(ev);
  793. }
  794. tryStartDrag(ev) {
  795. if (this.isDelayEnded && this.isDistanceSurpassed) {
  796. if (!this.pointer.wasTouchScroll || this.touchScrollAllowed) {
  797. this.isDragging = true;
  798. this.mirrorNeedsRevert = false;
  799. this.autoScroller.start(ev.pageX, ev.pageY, this.containerEl);
  800. this.emitter.trigger('dragstart', ev);
  801. if (this.touchScrollAllowed === false) {
  802. this.pointer.cancelTouchScroll();
  803. }
  804. }
  805. }
  806. }
  807. tryStopDrag(ev) {
  808. // .stop() is ALWAYS asynchronous, which we NEED because we want all pointerup events
  809. // that come from the document to fire beforehand. much more convenient this way.
  810. this.mirror.stop(this.mirrorNeedsRevert, this.stopDrag.bind(this, ev));
  811. }
  812. stopDrag(ev) {
  813. this.isDragging = false;
  814. this.emitter.trigger('dragend', ev);
  815. }
  816. // fill in the implementations...
  817. setIgnoreMove(bool) {
  818. this.pointer.shouldIgnoreMove = bool;
  819. }
  820. setMirrorIsVisible(bool) {
  821. this.mirror.setIsVisible(bool);
  822. }
  823. setMirrorNeedsRevert(bool) {
  824. this.mirrorNeedsRevert = bool;
  825. }
  826. setAutoScrollEnabled(bool) {
  827. this.autoScroller.isEnabled = bool;
  828. }
  829. }
  830. /*
  831. When this class is instantiated, it records the offset of an element (relative to the document topleft),
  832. and continues to monitor scrolling, updating the cached coordinates if it needs to.
  833. Does not access the DOM after instantiation, so highly performant.
  834. Also keeps track of all scrolling/overflow:hidden containers that are parents of the given element
  835. and an determine if a given point is inside the combined clipping rectangle.
  836. */
  837. class OffsetTracker {
  838. constructor(el) {
  839. this.el = el;
  840. this.origRect = computeRect(el);
  841. // will work fine for divs that have overflow:hidden
  842. this.scrollCaches = getClippingParents(el).map((scrollEl) => new ElementScrollGeomCache(scrollEl, true));
  843. }
  844. destroy() {
  845. for (let scrollCache of this.scrollCaches) {
  846. scrollCache.destroy();
  847. }
  848. }
  849. computeLeft() {
  850. let left = this.origRect.left;
  851. for (let scrollCache of this.scrollCaches) {
  852. left += scrollCache.origScrollLeft - scrollCache.getScrollLeft();
  853. }
  854. return left;
  855. }
  856. computeTop() {
  857. let top = this.origRect.top;
  858. for (let scrollCache of this.scrollCaches) {
  859. top += scrollCache.origScrollTop - scrollCache.getScrollTop();
  860. }
  861. return top;
  862. }
  863. isWithinClipping(pageX, pageY) {
  864. let point = { left: pageX, top: pageY };
  865. for (let scrollCache of this.scrollCaches) {
  866. if (!isIgnoredClipping(scrollCache.getEventTarget()) &&
  867. !pointInsideRect(point, scrollCache.clientRect)) {
  868. return false;
  869. }
  870. }
  871. return true;
  872. }
  873. }
  874. // certain clipping containers should never constrain interactions, like <html> and <body>
  875. // https://github.com/fullcalendar/fullcalendar/issues/3615
  876. function isIgnoredClipping(node) {
  877. let tagName = node.tagName;
  878. return tagName === 'HTML' || tagName === 'BODY';
  879. }
  880. /*
  881. Tracks movement over multiple droppable areas (aka "hits")
  882. that exist in one or more DateComponents.
  883. Relies on an existing draggable.
  884. emits:
  885. - pointerdown
  886. - dragstart
  887. - hitchange - fires initially, even if not over a hit
  888. - pointerup
  889. - (hitchange - again, to null, if ended over a hit)
  890. - dragend
  891. */
  892. class HitDragging {
  893. constructor(dragging, droppableStore) {
  894. // options that can be set by caller
  895. this.useSubjectCenter = false;
  896. this.requireInitial = true; // if doesn't start out on a hit, won't emit any events
  897. this.disablePointCheck = false;
  898. this.initialHit = null;
  899. this.movingHit = null;
  900. this.finalHit = null; // won't ever be populated if shouldIgnoreMove
  901. this.handlePointerDown = (ev) => {
  902. let { dragging } = this;
  903. this.initialHit = null;
  904. this.movingHit = null;
  905. this.finalHit = null;
  906. this.prepareHits();
  907. this.processFirstCoord(ev);
  908. if (this.initialHit || !this.requireInitial) {
  909. dragging.setIgnoreMove(false);
  910. // TODO: fire this before computing processFirstCoord, so listeners can cancel. this gets fired by almost every handler :(
  911. this.emitter.trigger('pointerdown', ev);
  912. }
  913. else {
  914. dragging.setIgnoreMove(true);
  915. }
  916. };
  917. this.handleDragStart = (ev) => {
  918. this.emitter.trigger('dragstart', ev);
  919. this.handleMove(ev, true); // force = fire even if initially null
  920. };
  921. this.handleDragMove = (ev) => {
  922. this.emitter.trigger('dragmove', ev);
  923. this.handleMove(ev);
  924. };
  925. this.handlePointerUp = (ev) => {
  926. this.releaseHits();
  927. this.emitter.trigger('pointerup', ev);
  928. };
  929. this.handleDragEnd = (ev) => {
  930. if (this.movingHit) {
  931. this.emitter.trigger('hitupdate', null, true, ev);
  932. }
  933. this.finalHit = this.movingHit;
  934. this.movingHit = null;
  935. this.emitter.trigger('dragend', ev);
  936. };
  937. this.droppableStore = droppableStore;
  938. dragging.emitter.on('pointerdown', this.handlePointerDown);
  939. dragging.emitter.on('dragstart', this.handleDragStart);
  940. dragging.emitter.on('dragmove', this.handleDragMove);
  941. dragging.emitter.on('pointerup', this.handlePointerUp);
  942. dragging.emitter.on('dragend', this.handleDragEnd);
  943. this.dragging = dragging;
  944. this.emitter = new Emitter();
  945. }
  946. // sets initialHit
  947. // sets coordAdjust
  948. processFirstCoord(ev) {
  949. let origPoint = { left: ev.pageX, top: ev.pageY };
  950. let adjustedPoint = origPoint;
  951. let subjectEl = ev.subjectEl;
  952. let subjectRect;
  953. if (subjectEl instanceof HTMLElement) { // i.e. not a Document/ShadowRoot
  954. subjectRect = computeRect(subjectEl);
  955. adjustedPoint = constrainPoint(adjustedPoint, subjectRect);
  956. }
  957. let initialHit = this.initialHit = this.queryHitForOffset(adjustedPoint.left, adjustedPoint.top);
  958. if (initialHit) {
  959. if (this.useSubjectCenter && subjectRect) {
  960. let slicedSubjectRect = intersectRects(subjectRect, initialHit.rect);
  961. if (slicedSubjectRect) {
  962. adjustedPoint = getRectCenter(slicedSubjectRect);
  963. }
  964. }
  965. this.coordAdjust = diffPoints(adjustedPoint, origPoint);
  966. }
  967. else {
  968. this.coordAdjust = { left: 0, top: 0 };
  969. }
  970. }
  971. handleMove(ev, forceHandle) {
  972. let hit = this.queryHitForOffset(ev.pageX + this.coordAdjust.left, ev.pageY + this.coordAdjust.top);
  973. if (forceHandle || !isHitsEqual(this.movingHit, hit)) {
  974. this.movingHit = hit;
  975. this.emitter.trigger('hitupdate', hit, false, ev);
  976. }
  977. }
  978. prepareHits() {
  979. this.offsetTrackers = mapHash(this.droppableStore, (interactionSettings) => {
  980. interactionSettings.component.prepareHits();
  981. return new OffsetTracker(interactionSettings.el);
  982. });
  983. }
  984. releaseHits() {
  985. let { offsetTrackers } = this;
  986. for (let id in offsetTrackers) {
  987. offsetTrackers[id].destroy();
  988. }
  989. this.offsetTrackers = {};
  990. }
  991. queryHitForOffset(offsetLeft, offsetTop) {
  992. let { droppableStore, offsetTrackers } = this;
  993. let bestHit = null;
  994. for (let id in droppableStore) {
  995. let component = droppableStore[id].component;
  996. let offsetTracker = offsetTrackers[id];
  997. if (offsetTracker && // wasn't destroyed mid-drag
  998. offsetTracker.isWithinClipping(offsetLeft, offsetTop)) {
  999. let originLeft = offsetTracker.computeLeft();
  1000. let originTop = offsetTracker.computeTop();
  1001. let positionLeft = offsetLeft - originLeft;
  1002. let positionTop = offsetTop - originTop;
  1003. let { origRect } = offsetTracker;
  1004. let width = origRect.right - origRect.left;
  1005. let height = origRect.bottom - origRect.top;
  1006. if (
  1007. // must be within the element's bounds
  1008. positionLeft >= 0 && positionLeft < width &&
  1009. positionTop >= 0 && positionTop < height) {
  1010. let hit = component.queryHit(positionLeft, positionTop, width, height);
  1011. if (hit && (
  1012. // make sure the hit is within activeRange, meaning it's not a dead cell
  1013. rangeContainsRange(hit.dateProfile.activeRange, hit.dateSpan.range)) &&
  1014. // Ensure the component we are querying for the hit is accessibly my the pointer
  1015. // Prevents obscured calendars (ex: under a modal dialog) from accepting hit
  1016. // https://github.com/fullcalendar/fullcalendar/issues/5026
  1017. (this.disablePointCheck ||
  1018. offsetTracker.el.contains(document.elementFromPoint(
  1019. // add-back origins to get coordinate relative to top-left of window viewport
  1020. positionLeft + originLeft - window.scrollX, positionTop + originTop - window.scrollY))) &&
  1021. (!bestHit || hit.layer > bestHit.layer)) {
  1022. hit.componentId = id;
  1023. hit.context = component.context;
  1024. // TODO: better way to re-orient rectangle
  1025. hit.rect.left += originLeft;
  1026. hit.rect.right += originLeft;
  1027. hit.rect.top += originTop;
  1028. hit.rect.bottom += originTop;
  1029. bestHit = hit;
  1030. }
  1031. }
  1032. }
  1033. }
  1034. return bestHit;
  1035. }
  1036. }
  1037. function isHitsEqual(hit0, hit1) {
  1038. if (!hit0 && !hit1) {
  1039. return true;
  1040. }
  1041. if (Boolean(hit0) !== Boolean(hit1)) {
  1042. return false;
  1043. }
  1044. return isDateSpansEqual(hit0.dateSpan, hit1.dateSpan);
  1045. }
  1046. function buildDatePointApiWithContext(dateSpan, context) {
  1047. let props = {};
  1048. for (let transform of context.pluginHooks.datePointTransforms) {
  1049. Object.assign(props, transform(dateSpan, context));
  1050. }
  1051. Object.assign(props, buildDatePointApi(dateSpan, context.dateEnv));
  1052. return props;
  1053. }
  1054. function buildDatePointApi(span, dateEnv) {
  1055. return {
  1056. date: dateEnv.toDate(span.range.start),
  1057. dateStr: dateEnv.formatIso(span.range.start, { omitTime: span.allDay }),
  1058. allDay: span.allDay,
  1059. };
  1060. }
  1061. /*
  1062. Monitors when the user clicks on a specific date/time of a component.
  1063. A pointerdown+pointerup on the same "hit" constitutes a click.
  1064. */
  1065. class DateClicking extends Interaction {
  1066. constructor(settings) {
  1067. super(settings);
  1068. this.handlePointerDown = (pev) => {
  1069. let { dragging } = this;
  1070. let downEl = pev.origEvent.target;
  1071. // do this in pointerdown (not dragend) because DOM might be mutated by the time dragend is fired
  1072. dragging.setIgnoreMove(!this.component.isValidDateDownEl(downEl));
  1073. };
  1074. // won't even fire if moving was ignored
  1075. this.handleDragEnd = (ev) => {
  1076. let { component } = this;
  1077. let { pointer } = this.dragging;
  1078. if (!pointer.wasTouchScroll) {
  1079. let { initialHit, finalHit } = this.hitDragging;
  1080. if (initialHit && finalHit && isHitsEqual(initialHit, finalHit)) {
  1081. let { context } = component;
  1082. let arg = Object.assign(Object.assign({}, buildDatePointApiWithContext(initialHit.dateSpan, context)), { dayEl: initialHit.dayEl, jsEvent: ev.origEvent, view: context.viewApi || context.calendarApi.view });
  1083. context.emitter.trigger('dateClick', arg);
  1084. }
  1085. }
  1086. };
  1087. // we DO want to watch pointer moves because otherwise finalHit won't get populated
  1088. this.dragging = new FeaturefulElementDragging(settings.el);
  1089. this.dragging.autoScroller.isEnabled = false;
  1090. let hitDragging = this.hitDragging = new HitDragging(this.dragging, interactionSettingsToStore(settings));
  1091. hitDragging.emitter.on('pointerdown', this.handlePointerDown);
  1092. hitDragging.emitter.on('dragend', this.handleDragEnd);
  1093. }
  1094. destroy() {
  1095. this.dragging.destroy();
  1096. }
  1097. }
  1098. /*
  1099. Tracks when the user selects a portion of time of a component,
  1100. constituted by a drag over date cells, with a possible delay at the beginning of the drag.
  1101. */
  1102. class DateSelecting extends Interaction {
  1103. constructor(settings) {
  1104. super(settings);
  1105. this.dragSelection = null;
  1106. this.handlePointerDown = (ev) => {
  1107. let { component, dragging } = this;
  1108. let { options } = component.context;
  1109. let canSelect = options.selectable &&
  1110. component.isValidDateDownEl(ev.origEvent.target);
  1111. // don't bother to watch expensive moves if component won't do selection
  1112. dragging.setIgnoreMove(!canSelect);
  1113. // if touch, require user to hold down
  1114. dragging.delay = ev.isTouch ? getComponentTouchDelay$1(component) : null;
  1115. };
  1116. this.handleDragStart = (ev) => {
  1117. this.component.context.calendarApi.unselect(ev); // unselect previous selections
  1118. };
  1119. this.handleHitUpdate = (hit, isFinal) => {
  1120. let { context } = this.component;
  1121. let dragSelection = null;
  1122. let isInvalid = false;
  1123. if (hit) {
  1124. let initialHit = this.hitDragging.initialHit;
  1125. let disallowed = hit.componentId === initialHit.componentId
  1126. && this.isHitComboAllowed
  1127. && !this.isHitComboAllowed(initialHit, hit);
  1128. if (!disallowed) {
  1129. dragSelection = joinHitsIntoSelection(initialHit, hit, context.pluginHooks.dateSelectionTransformers);
  1130. }
  1131. if (!dragSelection || !isDateSelectionValid(dragSelection, hit.dateProfile, context)) {
  1132. isInvalid = true;
  1133. dragSelection = null;
  1134. }
  1135. }
  1136. if (dragSelection) {
  1137. context.dispatch({ type: 'SELECT_DATES', selection: dragSelection });
  1138. }
  1139. else if (!isFinal) { // only unselect if moved away while dragging
  1140. context.dispatch({ type: 'UNSELECT_DATES' });
  1141. }
  1142. if (!isInvalid) {
  1143. enableCursor();
  1144. }
  1145. else {
  1146. disableCursor();
  1147. }
  1148. if (!isFinal) {
  1149. this.dragSelection = dragSelection; // only clear if moved away from all hits while dragging
  1150. }
  1151. };
  1152. this.handlePointerUp = (pev) => {
  1153. if (this.dragSelection) {
  1154. // selection is already rendered, so just need to report selection
  1155. triggerDateSelect(this.dragSelection, pev, this.component.context);
  1156. this.dragSelection = null;
  1157. }
  1158. };
  1159. let { component } = settings;
  1160. let { options } = component.context;
  1161. let dragging = this.dragging = new FeaturefulElementDragging(settings.el);
  1162. dragging.touchScrollAllowed = false;
  1163. dragging.minDistance = options.selectMinDistance || 0;
  1164. dragging.autoScroller.isEnabled = options.dragScroll;
  1165. let hitDragging = this.hitDragging = new HitDragging(this.dragging, interactionSettingsToStore(settings));
  1166. hitDragging.emitter.on('pointerdown', this.handlePointerDown);
  1167. hitDragging.emitter.on('dragstart', this.handleDragStart);
  1168. hitDragging.emitter.on('hitupdate', this.handleHitUpdate);
  1169. hitDragging.emitter.on('pointerup', this.handlePointerUp);
  1170. }
  1171. destroy() {
  1172. this.dragging.destroy();
  1173. }
  1174. }
  1175. function getComponentTouchDelay$1(component) {
  1176. let { options } = component.context;
  1177. let delay = options.selectLongPressDelay;
  1178. if (delay == null) {
  1179. delay = options.longPressDelay;
  1180. }
  1181. return delay;
  1182. }
  1183. function joinHitsIntoSelection(hit0, hit1, dateSelectionTransformers) {
  1184. let dateSpan0 = hit0.dateSpan;
  1185. let dateSpan1 = hit1.dateSpan;
  1186. let ms = [
  1187. dateSpan0.range.start,
  1188. dateSpan0.range.end,
  1189. dateSpan1.range.start,
  1190. dateSpan1.range.end,
  1191. ];
  1192. ms.sort(compareNumbers);
  1193. let props = {};
  1194. for (let transformer of dateSelectionTransformers) {
  1195. let res = transformer(hit0, hit1);
  1196. if (res === false) {
  1197. return null;
  1198. }
  1199. if (res) {
  1200. Object.assign(props, res);
  1201. }
  1202. }
  1203. props.range = { start: ms[0], end: ms[3] };
  1204. props.allDay = dateSpan0.allDay;
  1205. return props;
  1206. }
  1207. class EventDragging extends Interaction {
  1208. constructor(settings) {
  1209. super(settings);
  1210. // internal state
  1211. this.subjectEl = null;
  1212. this.subjectSeg = null; // the seg being selected/dragged
  1213. this.isDragging = false;
  1214. this.eventRange = null;
  1215. this.relevantEvents = null; // the events being dragged
  1216. this.receivingContext = null;
  1217. this.validMutation = null;
  1218. this.mutatedRelevantEvents = null;
  1219. this.handlePointerDown = (ev) => {
  1220. let origTarget = ev.origEvent.target;
  1221. let { component, dragging } = this;
  1222. let { mirror } = dragging;
  1223. let { options } = component.context;
  1224. let initialContext = component.context;
  1225. this.subjectEl = ev.subjectEl;
  1226. let subjectSeg = this.subjectSeg = getElSeg(ev.subjectEl);
  1227. let eventRange = this.eventRange = subjectSeg.eventRange;
  1228. let eventInstanceId = eventRange.instance.instanceId;
  1229. this.relevantEvents = getRelevantEvents(initialContext.getCurrentData().eventStore, eventInstanceId);
  1230. dragging.minDistance = ev.isTouch ? 0 : options.eventDragMinDistance;
  1231. dragging.delay =
  1232. // only do a touch delay if touch and this event hasn't been selected yet
  1233. (ev.isTouch && eventInstanceId !== component.props.eventSelection) ?
  1234. getComponentTouchDelay(component) :
  1235. null;
  1236. if (options.fixedMirrorParent) {
  1237. mirror.parentNode = options.fixedMirrorParent;
  1238. }
  1239. else {
  1240. mirror.parentNode = elementClosest(origTarget, '.fc');
  1241. }
  1242. mirror.revertDuration = options.dragRevertDuration;
  1243. let isValid = component.isValidSegDownEl(origTarget) &&
  1244. !elementClosest(origTarget, '.fc-event-resizer'); // NOT on a resizer
  1245. dragging.setIgnoreMove(!isValid);
  1246. // disable dragging for elements that are resizable (ie, selectable)
  1247. // but are not draggable
  1248. this.isDragging = isValid &&
  1249. ev.subjectEl.classList.contains('fc-event-draggable');
  1250. };
  1251. this.handleDragStart = (ev) => {
  1252. let initialContext = this.component.context;
  1253. let eventRange = this.eventRange;
  1254. let eventInstanceId = eventRange.instance.instanceId;
  1255. if (ev.isTouch) {
  1256. // need to select a different event?
  1257. if (eventInstanceId !== this.component.props.eventSelection) {
  1258. initialContext.dispatch({ type: 'SELECT_EVENT', eventInstanceId });
  1259. }
  1260. }
  1261. else {
  1262. // if now using mouse, but was previous touch interaction, clear selected event
  1263. initialContext.dispatch({ type: 'UNSELECT_EVENT' });
  1264. }
  1265. if (this.isDragging) {
  1266. initialContext.calendarApi.unselect(ev); // unselect *date* selection
  1267. initialContext.emitter.trigger('eventDragStart', {
  1268. el: this.subjectEl,
  1269. event: new EventImpl(initialContext, eventRange.def, eventRange.instance),
  1270. jsEvent: ev.origEvent,
  1271. view: initialContext.viewApi,
  1272. });
  1273. }
  1274. };
  1275. this.handleHitUpdate = (hit, isFinal) => {
  1276. if (!this.isDragging) {
  1277. return;
  1278. }
  1279. let relevantEvents = this.relevantEvents;
  1280. let initialHit = this.hitDragging.initialHit;
  1281. let initialContext = this.component.context;
  1282. // states based on new hit
  1283. let receivingContext = null;
  1284. let mutation = null;
  1285. let mutatedRelevantEvents = null;
  1286. let isInvalid = false;
  1287. let interaction = {
  1288. affectedEvents: relevantEvents,
  1289. mutatedEvents: createEmptyEventStore(),
  1290. isEvent: true,
  1291. };
  1292. if (hit) {
  1293. receivingContext = hit.context;
  1294. let receivingOptions = receivingContext.options;
  1295. if (initialContext === receivingContext ||
  1296. (receivingOptions.editable && receivingOptions.droppable)) {
  1297. mutation = computeEventMutation(initialHit, hit, this.eventRange.instance.range.start, receivingContext.getCurrentData().pluginHooks.eventDragMutationMassagers);
  1298. if (mutation) {
  1299. mutatedRelevantEvents = applyMutationToEventStore(relevantEvents, receivingContext.getCurrentData().eventUiBases, mutation, receivingContext);
  1300. interaction.mutatedEvents = mutatedRelevantEvents;
  1301. if (!isInteractionValid(interaction, hit.dateProfile, receivingContext)) {
  1302. isInvalid = true;
  1303. mutation = null;
  1304. mutatedRelevantEvents = null;
  1305. interaction.mutatedEvents = createEmptyEventStore();
  1306. }
  1307. }
  1308. }
  1309. else {
  1310. receivingContext = null;
  1311. }
  1312. }
  1313. this.displayDrag(receivingContext, interaction);
  1314. if (!isInvalid) {
  1315. enableCursor();
  1316. }
  1317. else {
  1318. disableCursor();
  1319. }
  1320. if (!isFinal) {
  1321. if (initialContext === receivingContext && // TODO: write test for this
  1322. isHitsEqual(initialHit, hit)) {
  1323. mutation = null;
  1324. }
  1325. this.dragging.setMirrorNeedsRevert(!mutation);
  1326. // render the mirror if no already-rendered mirror
  1327. // TODO: wish we could somehow wait for dispatch to guarantee render
  1328. this.dragging.setMirrorIsVisible(!hit || !this.subjectEl.getRootNode().querySelector('.fc-event-mirror'));
  1329. // assign states based on new hit
  1330. this.receivingContext = receivingContext;
  1331. this.validMutation = mutation;
  1332. this.mutatedRelevantEvents = mutatedRelevantEvents;
  1333. }
  1334. };
  1335. this.handlePointerUp = () => {
  1336. if (!this.isDragging) {
  1337. this.cleanup(); // because handleDragEnd won't fire
  1338. }
  1339. };
  1340. this.handleDragEnd = (ev) => {
  1341. if (this.isDragging) {
  1342. let initialContext = this.component.context;
  1343. let initialView = initialContext.viewApi;
  1344. let { receivingContext, validMutation } = this;
  1345. let eventDef = this.eventRange.def;
  1346. let eventInstance = this.eventRange.instance;
  1347. let eventApi = new EventImpl(initialContext, eventDef, eventInstance);
  1348. let relevantEvents = this.relevantEvents;
  1349. let mutatedRelevantEvents = this.mutatedRelevantEvents;
  1350. let { finalHit } = this.hitDragging;
  1351. this.clearDrag(); // must happen after revert animation
  1352. initialContext.emitter.trigger('eventDragStop', {
  1353. el: this.subjectEl,
  1354. event: eventApi,
  1355. jsEvent: ev.origEvent,
  1356. view: initialView,
  1357. });
  1358. if (validMutation) {
  1359. // dropped within same calendar
  1360. if (receivingContext === initialContext) {
  1361. let updatedEventApi = new EventImpl(initialContext, mutatedRelevantEvents.defs[eventDef.defId], eventInstance ? mutatedRelevantEvents.instances[eventInstance.instanceId] : null);
  1362. initialContext.dispatch({
  1363. type: 'MERGE_EVENTS',
  1364. eventStore: mutatedRelevantEvents,
  1365. });
  1366. let eventChangeArg = {
  1367. oldEvent: eventApi,
  1368. event: updatedEventApi,
  1369. relatedEvents: buildEventApis(mutatedRelevantEvents, initialContext, eventInstance),
  1370. revert() {
  1371. initialContext.dispatch({
  1372. type: 'MERGE_EVENTS',
  1373. eventStore: relevantEvents, // the pre-change data
  1374. });
  1375. },
  1376. };
  1377. let transformed = {};
  1378. for (let transformer of initialContext.getCurrentData().pluginHooks.eventDropTransformers) {
  1379. Object.assign(transformed, transformer(validMutation, initialContext));
  1380. }
  1381. initialContext.emitter.trigger('eventDrop', Object.assign(Object.assign(Object.assign({}, eventChangeArg), transformed), { el: ev.subjectEl, delta: validMutation.datesDelta, jsEvent: ev.origEvent, view: initialView }));
  1382. initialContext.emitter.trigger('eventChange', eventChangeArg);
  1383. // dropped in different calendar
  1384. }
  1385. else if (receivingContext) {
  1386. let eventRemoveArg = {
  1387. event: eventApi,
  1388. relatedEvents: buildEventApis(relevantEvents, initialContext, eventInstance),
  1389. revert() {
  1390. initialContext.dispatch({
  1391. type: 'MERGE_EVENTS',
  1392. eventStore: relevantEvents,
  1393. });
  1394. },
  1395. };
  1396. initialContext.emitter.trigger('eventLeave', Object.assign(Object.assign({}, eventRemoveArg), { draggedEl: ev.subjectEl, view: initialView }));
  1397. initialContext.dispatch({
  1398. type: 'REMOVE_EVENTS',
  1399. eventStore: relevantEvents,
  1400. });
  1401. initialContext.emitter.trigger('eventRemove', eventRemoveArg);
  1402. let addedEventDef = mutatedRelevantEvents.defs[eventDef.defId];
  1403. let addedEventInstance = mutatedRelevantEvents.instances[eventInstance.instanceId];
  1404. let addedEventApi = new EventImpl(receivingContext, addedEventDef, addedEventInstance);
  1405. receivingContext.dispatch({
  1406. type: 'MERGE_EVENTS',
  1407. eventStore: mutatedRelevantEvents,
  1408. });
  1409. let eventAddArg = {
  1410. event: addedEventApi,
  1411. relatedEvents: buildEventApis(mutatedRelevantEvents, receivingContext, addedEventInstance),
  1412. revert() {
  1413. receivingContext.dispatch({
  1414. type: 'REMOVE_EVENTS',
  1415. eventStore: mutatedRelevantEvents,
  1416. });
  1417. },
  1418. };
  1419. receivingContext.emitter.trigger('eventAdd', eventAddArg);
  1420. if (ev.isTouch) {
  1421. receivingContext.dispatch({
  1422. type: 'SELECT_EVENT',
  1423. eventInstanceId: eventInstance.instanceId,
  1424. });
  1425. }
  1426. receivingContext.emitter.trigger('drop', Object.assign(Object.assign({}, buildDatePointApiWithContext(finalHit.dateSpan, receivingContext)), { draggedEl: ev.subjectEl, jsEvent: ev.origEvent, view: finalHit.context.viewApi }));
  1427. receivingContext.emitter.trigger('eventReceive', Object.assign(Object.assign({}, eventAddArg), { draggedEl: ev.subjectEl, view: finalHit.context.viewApi }));
  1428. }
  1429. }
  1430. else {
  1431. initialContext.emitter.trigger('_noEventDrop');
  1432. }
  1433. }
  1434. this.cleanup();
  1435. };
  1436. let { component } = this;
  1437. let { options } = component.context;
  1438. let dragging = this.dragging = new FeaturefulElementDragging(settings.el);
  1439. dragging.pointer.selector = EventDragging.SELECTOR;
  1440. dragging.touchScrollAllowed = false;
  1441. dragging.autoScroller.isEnabled = options.dragScroll;
  1442. let hitDragging = this.hitDragging = new HitDragging(this.dragging, interactionSettingsStore);
  1443. hitDragging.useSubjectCenter = settings.useEventCenter;
  1444. hitDragging.emitter.on('pointerdown', this.handlePointerDown);
  1445. hitDragging.emitter.on('dragstart', this.handleDragStart);
  1446. hitDragging.emitter.on('hitupdate', this.handleHitUpdate);
  1447. hitDragging.emitter.on('pointerup', this.handlePointerUp);
  1448. hitDragging.emitter.on('dragend', this.handleDragEnd);
  1449. }
  1450. destroy() {
  1451. this.dragging.destroy();
  1452. }
  1453. // render a drag state on the next receivingCalendar
  1454. displayDrag(nextContext, state) {
  1455. let initialContext = this.component.context;
  1456. let prevContext = this.receivingContext;
  1457. // does the previous calendar need to be cleared?
  1458. if (prevContext && prevContext !== nextContext) {
  1459. // does the initial calendar need to be cleared?
  1460. // if so, don't clear all the way. we still need to to hide the affectedEvents
  1461. if (prevContext === initialContext) {
  1462. prevContext.dispatch({
  1463. type: 'SET_EVENT_DRAG',
  1464. state: {
  1465. affectedEvents: state.affectedEvents,
  1466. mutatedEvents: createEmptyEventStore(),
  1467. isEvent: true,
  1468. },
  1469. });
  1470. // completely clear the old calendar if it wasn't the initial
  1471. }
  1472. else {
  1473. prevContext.dispatch({ type: 'UNSET_EVENT_DRAG' });
  1474. }
  1475. }
  1476. if (nextContext) {
  1477. nextContext.dispatch({ type: 'SET_EVENT_DRAG', state });
  1478. }
  1479. }
  1480. clearDrag() {
  1481. let initialCalendar = this.component.context;
  1482. let { receivingContext } = this;
  1483. if (receivingContext) {
  1484. receivingContext.dispatch({ type: 'UNSET_EVENT_DRAG' });
  1485. }
  1486. // the initial calendar might have an dummy drag state from displayDrag
  1487. if (initialCalendar !== receivingContext) {
  1488. initialCalendar.dispatch({ type: 'UNSET_EVENT_DRAG' });
  1489. }
  1490. }
  1491. cleanup() {
  1492. this.subjectSeg = null;
  1493. this.isDragging = false;
  1494. this.eventRange = null;
  1495. this.relevantEvents = null;
  1496. this.receivingContext = null;
  1497. this.validMutation = null;
  1498. this.mutatedRelevantEvents = null;
  1499. }
  1500. }
  1501. // TODO: test this in IE11
  1502. // QUESTION: why do we need it on the resizable???
  1503. EventDragging.SELECTOR = '.fc-event-draggable, .fc-event-resizable';
  1504. function computeEventMutation(hit0, hit1, eventInstanceStart, massagers) {
  1505. let dateSpan0 = hit0.dateSpan;
  1506. let dateSpan1 = hit1.dateSpan;
  1507. let date0 = dateSpan0.range.start;
  1508. let date1 = dateSpan1.range.start;
  1509. let standardProps = {};
  1510. if (dateSpan0.allDay !== dateSpan1.allDay) {
  1511. standardProps.allDay = dateSpan1.allDay;
  1512. standardProps.hasEnd = hit1.context.options.allDayMaintainDuration;
  1513. if (dateSpan1.allDay) {
  1514. // means date1 is already start-of-day,
  1515. // but date0 needs to be converted
  1516. date0 = startOfDay(eventInstanceStart);
  1517. }
  1518. else {
  1519. // Moving from allDate->timed
  1520. // Doesn't matter where on the event the drag began, mutate the event's start-date to date1
  1521. date0 = eventInstanceStart;
  1522. }
  1523. }
  1524. let delta = diffDates(date0, date1, hit0.context.dateEnv, hit0.componentId === hit1.componentId ?
  1525. hit0.largeUnit :
  1526. null);
  1527. if (delta.milliseconds) { // has hours/minutes/seconds
  1528. standardProps.allDay = false;
  1529. }
  1530. let mutation = {
  1531. datesDelta: delta,
  1532. standardProps,
  1533. };
  1534. for (let massager of massagers) {
  1535. massager(mutation, hit0, hit1);
  1536. }
  1537. return mutation;
  1538. }
  1539. function getComponentTouchDelay(component) {
  1540. let { options } = component.context;
  1541. let delay = options.eventLongPressDelay;
  1542. if (delay == null) {
  1543. delay = options.longPressDelay;
  1544. }
  1545. return delay;
  1546. }
  1547. class EventResizing extends Interaction {
  1548. constructor(settings) {
  1549. super(settings);
  1550. // internal state
  1551. this.draggingSegEl = null;
  1552. this.draggingSeg = null; // TODO: rename to resizingSeg? subjectSeg?
  1553. this.eventRange = null;
  1554. this.relevantEvents = null;
  1555. this.validMutation = null;
  1556. this.mutatedRelevantEvents = null;
  1557. this.handlePointerDown = (ev) => {
  1558. let { component } = this;
  1559. let segEl = this.querySegEl(ev);
  1560. let seg = getElSeg(segEl);
  1561. let eventRange = this.eventRange = seg.eventRange;
  1562. this.dragging.minDistance = component.context.options.eventDragMinDistance;
  1563. // if touch, need to be working with a selected event
  1564. this.dragging.setIgnoreMove(!this.component.isValidSegDownEl(ev.origEvent.target) ||
  1565. (ev.isTouch && this.component.props.eventSelection !== eventRange.instance.instanceId));
  1566. };
  1567. this.handleDragStart = (ev) => {
  1568. let { context } = this.component;
  1569. let eventRange = this.eventRange;
  1570. this.relevantEvents = getRelevantEvents(context.getCurrentData().eventStore, this.eventRange.instance.instanceId);
  1571. let segEl = this.querySegEl(ev);
  1572. this.draggingSegEl = segEl;
  1573. this.draggingSeg = getElSeg(segEl);
  1574. context.calendarApi.unselect();
  1575. context.emitter.trigger('eventResizeStart', {
  1576. el: segEl,
  1577. event: new EventImpl(context, eventRange.def, eventRange.instance),
  1578. jsEvent: ev.origEvent,
  1579. view: context.viewApi,
  1580. });
  1581. };
  1582. this.handleHitUpdate = (hit, isFinal, ev) => {
  1583. let { context } = this.component;
  1584. let relevantEvents = this.relevantEvents;
  1585. let initialHit = this.hitDragging.initialHit;
  1586. let eventInstance = this.eventRange.instance;
  1587. let mutation = null;
  1588. let mutatedRelevantEvents = null;
  1589. let isInvalid = false;
  1590. let interaction = {
  1591. affectedEvents: relevantEvents,
  1592. mutatedEvents: createEmptyEventStore(),
  1593. isEvent: true,
  1594. };
  1595. if (hit) {
  1596. let disallowed = hit.componentId === initialHit.componentId
  1597. && this.isHitComboAllowed
  1598. && !this.isHitComboAllowed(initialHit, hit);
  1599. if (!disallowed) {
  1600. mutation = computeMutation(initialHit, hit, ev.subjectEl.classList.contains('fc-event-resizer-start'), eventInstance.range);
  1601. }
  1602. }
  1603. if (mutation) {
  1604. mutatedRelevantEvents = applyMutationToEventStore(relevantEvents, context.getCurrentData().eventUiBases, mutation, context);
  1605. interaction.mutatedEvents = mutatedRelevantEvents;
  1606. if (!isInteractionValid(interaction, hit.dateProfile, context)) {
  1607. isInvalid = true;
  1608. mutation = null;
  1609. mutatedRelevantEvents = null;
  1610. interaction.mutatedEvents = null;
  1611. }
  1612. }
  1613. if (mutatedRelevantEvents) {
  1614. context.dispatch({
  1615. type: 'SET_EVENT_RESIZE',
  1616. state: interaction,
  1617. });
  1618. }
  1619. else {
  1620. context.dispatch({ type: 'UNSET_EVENT_RESIZE' });
  1621. }
  1622. if (!isInvalid) {
  1623. enableCursor();
  1624. }
  1625. else {
  1626. disableCursor();
  1627. }
  1628. if (!isFinal) {
  1629. if (mutation && isHitsEqual(initialHit, hit)) {
  1630. mutation = null;
  1631. }
  1632. this.validMutation = mutation;
  1633. this.mutatedRelevantEvents = mutatedRelevantEvents;
  1634. }
  1635. };
  1636. this.handleDragEnd = (ev) => {
  1637. let { context } = this.component;
  1638. let eventDef = this.eventRange.def;
  1639. let eventInstance = this.eventRange.instance;
  1640. let eventApi = new EventImpl(context, eventDef, eventInstance);
  1641. let relevantEvents = this.relevantEvents;
  1642. let mutatedRelevantEvents = this.mutatedRelevantEvents;
  1643. context.emitter.trigger('eventResizeStop', {
  1644. el: this.draggingSegEl,
  1645. event: eventApi,
  1646. jsEvent: ev.origEvent,
  1647. view: context.viewApi,
  1648. });
  1649. if (this.validMutation) {
  1650. let updatedEventApi = new EventImpl(context, mutatedRelevantEvents.defs[eventDef.defId], eventInstance ? mutatedRelevantEvents.instances[eventInstance.instanceId] : null);
  1651. context.dispatch({
  1652. type: 'MERGE_EVENTS',
  1653. eventStore: mutatedRelevantEvents,
  1654. });
  1655. let eventChangeArg = {
  1656. oldEvent: eventApi,
  1657. event: updatedEventApi,
  1658. relatedEvents: buildEventApis(mutatedRelevantEvents, context, eventInstance),
  1659. revert() {
  1660. context.dispatch({
  1661. type: 'MERGE_EVENTS',
  1662. eventStore: relevantEvents, // the pre-change events
  1663. });
  1664. },
  1665. };
  1666. context.emitter.trigger('eventResize', Object.assign(Object.assign({}, eventChangeArg), { el: this.draggingSegEl, startDelta: this.validMutation.startDelta || createDuration(0), endDelta: this.validMutation.endDelta || createDuration(0), jsEvent: ev.origEvent, view: context.viewApi }));
  1667. context.emitter.trigger('eventChange', eventChangeArg);
  1668. }
  1669. else {
  1670. context.emitter.trigger('_noEventResize');
  1671. }
  1672. // reset all internal state
  1673. this.draggingSeg = null;
  1674. this.relevantEvents = null;
  1675. this.validMutation = null;
  1676. // okay to keep eventInstance around. useful to set it in handlePointerDown
  1677. };
  1678. let { component } = settings;
  1679. let dragging = this.dragging = new FeaturefulElementDragging(settings.el);
  1680. dragging.pointer.selector = '.fc-event-resizer';
  1681. dragging.touchScrollAllowed = false;
  1682. dragging.autoScroller.isEnabled = component.context.options.dragScroll;
  1683. let hitDragging = this.hitDragging = new HitDragging(this.dragging, interactionSettingsToStore(settings));
  1684. hitDragging.emitter.on('pointerdown', this.handlePointerDown);
  1685. hitDragging.emitter.on('dragstart', this.handleDragStart);
  1686. hitDragging.emitter.on('hitupdate', this.handleHitUpdate);
  1687. hitDragging.emitter.on('dragend', this.handleDragEnd);
  1688. }
  1689. destroy() {
  1690. this.dragging.destroy();
  1691. }
  1692. querySegEl(ev) {
  1693. return elementClosest(ev.subjectEl, '.fc-event');
  1694. }
  1695. }
  1696. function computeMutation(hit0, hit1, isFromStart, instanceRange) {
  1697. let dateEnv = hit0.context.dateEnv;
  1698. let date0 = hit0.dateSpan.range.start;
  1699. let date1 = hit1.dateSpan.range.start;
  1700. let delta = diffDates(date0, date1, dateEnv, hit0.largeUnit);
  1701. if (isFromStart) {
  1702. if (dateEnv.add(instanceRange.start, delta) < instanceRange.end) {
  1703. return { startDelta: delta };
  1704. }
  1705. }
  1706. else if (dateEnv.add(instanceRange.end, delta) > instanceRange.start) {
  1707. return { endDelta: delta };
  1708. }
  1709. return null;
  1710. }
  1711. class UnselectAuto {
  1712. constructor(context) {
  1713. this.context = context;
  1714. this.isRecentPointerDateSelect = false; // wish we could use a selector to detect date selection, but uses hit system
  1715. this.matchesCancel = false;
  1716. this.matchesEvent = false;
  1717. this.onSelect = (selectInfo) => {
  1718. if (selectInfo.jsEvent) {
  1719. this.isRecentPointerDateSelect = true;
  1720. }
  1721. };
  1722. this.onDocumentPointerDown = (pev) => {
  1723. let unselectCancel = this.context.options.unselectCancel;
  1724. let downEl = getEventTargetViaRoot(pev.origEvent);
  1725. this.matchesCancel = !!elementClosest(downEl, unselectCancel);
  1726. this.matchesEvent = !!elementClosest(downEl, EventDragging.SELECTOR); // interaction started on an event?
  1727. };
  1728. this.onDocumentPointerUp = (pev) => {
  1729. let { context } = this;
  1730. let { documentPointer } = this;
  1731. let calendarState = context.getCurrentData();
  1732. // touch-scrolling should never unfocus any type of selection
  1733. if (!documentPointer.wasTouchScroll) {
  1734. if (calendarState.dateSelection && // an existing date selection?
  1735. !this.isRecentPointerDateSelect // a new pointer-initiated date selection since last onDocumentPointerUp?
  1736. ) {
  1737. let unselectAuto = context.options.unselectAuto;
  1738. if (unselectAuto && (!unselectAuto || !this.matchesCancel)) {
  1739. context.calendarApi.unselect(pev);
  1740. }
  1741. }
  1742. if (calendarState.eventSelection && // an existing event selected?
  1743. !this.matchesEvent // interaction DIDN'T start on an event
  1744. ) {
  1745. context.dispatch({ type: 'UNSELECT_EVENT' });
  1746. }
  1747. }
  1748. this.isRecentPointerDateSelect = false;
  1749. };
  1750. let documentPointer = this.documentPointer = new PointerDragging(document);
  1751. documentPointer.shouldIgnoreMove = true;
  1752. documentPointer.shouldWatchScroll = false;
  1753. documentPointer.emitter.on('pointerdown', this.onDocumentPointerDown);
  1754. documentPointer.emitter.on('pointerup', this.onDocumentPointerUp);
  1755. /*
  1756. TODO: better way to know about whether there was a selection with the pointer
  1757. */
  1758. context.emitter.on('select', this.onSelect);
  1759. }
  1760. destroy() {
  1761. this.context.emitter.off('select', this.onSelect);
  1762. this.documentPointer.destroy();
  1763. }
  1764. }
  1765. const OPTION_REFINERS = {
  1766. fixedMirrorParent: identity,
  1767. };
  1768. const LISTENER_REFINERS = {
  1769. dateClick: identity,
  1770. eventDragStart: identity,
  1771. eventDragStop: identity,
  1772. eventDrop: identity,
  1773. eventResizeStart: identity,
  1774. eventResizeStop: identity,
  1775. eventResize: identity,
  1776. drop: identity,
  1777. eventReceive: identity,
  1778. eventLeave: identity,
  1779. };
  1780. /*
  1781. Given an already instantiated draggable object for one-or-more elements,
  1782. Interprets any dragging as an attempt to drag an events that lives outside
  1783. of a calendar onto a calendar.
  1784. */
  1785. class ExternalElementDragging {
  1786. constructor(dragging, suppliedDragMeta) {
  1787. this.receivingContext = null;
  1788. this.droppableEvent = null; // will exist for all drags, even if create:false
  1789. this.suppliedDragMeta = null;
  1790. this.dragMeta = null;
  1791. this.handleDragStart = (ev) => {
  1792. this.dragMeta = this.buildDragMeta(ev.subjectEl);
  1793. };
  1794. this.handleHitUpdate = (hit, isFinal, ev) => {
  1795. let { dragging } = this.hitDragging;
  1796. let receivingContext = null;
  1797. let droppableEvent = null;
  1798. let isInvalid = false;
  1799. let interaction = {
  1800. affectedEvents: createEmptyEventStore(),
  1801. mutatedEvents: createEmptyEventStore(),
  1802. isEvent: this.dragMeta.create,
  1803. };
  1804. if (hit) {
  1805. receivingContext = hit.context;
  1806. if (this.canDropElOnCalendar(ev.subjectEl, receivingContext)) {
  1807. droppableEvent = computeEventForDateSpan(hit.dateSpan, this.dragMeta, receivingContext);
  1808. interaction.mutatedEvents = eventTupleToStore(droppableEvent);
  1809. isInvalid = !isInteractionValid(interaction, hit.dateProfile, receivingContext);
  1810. if (isInvalid) {
  1811. interaction.mutatedEvents = createEmptyEventStore();
  1812. droppableEvent = null;
  1813. }
  1814. }
  1815. }
  1816. this.displayDrag(receivingContext, interaction);
  1817. // show mirror if no already-rendered mirror element OR if we are shutting down the mirror (?)
  1818. // TODO: wish we could somehow wait for dispatch to guarantee render
  1819. dragging.setMirrorIsVisible(isFinal || !droppableEvent || !document.querySelector('.fc-event-mirror'));
  1820. if (!isInvalid) {
  1821. enableCursor();
  1822. }
  1823. else {
  1824. disableCursor();
  1825. }
  1826. if (!isFinal) {
  1827. dragging.setMirrorNeedsRevert(!droppableEvent);
  1828. this.receivingContext = receivingContext;
  1829. this.droppableEvent = droppableEvent;
  1830. }
  1831. };
  1832. this.handleDragEnd = (pev) => {
  1833. let { receivingContext, droppableEvent } = this;
  1834. this.clearDrag();
  1835. if (receivingContext && droppableEvent) {
  1836. let finalHit = this.hitDragging.finalHit;
  1837. let finalView = finalHit.context.viewApi;
  1838. let dragMeta = this.dragMeta;
  1839. receivingContext.emitter.trigger('drop', Object.assign(Object.assign({}, buildDatePointApiWithContext(finalHit.dateSpan, receivingContext)), { draggedEl: pev.subjectEl, jsEvent: pev.origEvent, view: finalView }));
  1840. if (dragMeta.create) {
  1841. let addingEvents = eventTupleToStore(droppableEvent);
  1842. receivingContext.dispatch({
  1843. type: 'MERGE_EVENTS',
  1844. eventStore: addingEvents,
  1845. });
  1846. if (pev.isTouch) {
  1847. receivingContext.dispatch({
  1848. type: 'SELECT_EVENT',
  1849. eventInstanceId: droppableEvent.instance.instanceId,
  1850. });
  1851. }
  1852. // signal that an external event landed
  1853. receivingContext.emitter.trigger('eventReceive', {
  1854. event: new EventImpl(receivingContext, droppableEvent.def, droppableEvent.instance),
  1855. relatedEvents: [],
  1856. revert() {
  1857. receivingContext.dispatch({
  1858. type: 'REMOVE_EVENTS',
  1859. eventStore: addingEvents,
  1860. });
  1861. },
  1862. draggedEl: pev.subjectEl,
  1863. view: finalView,
  1864. });
  1865. }
  1866. }
  1867. this.receivingContext = null;
  1868. this.droppableEvent = null;
  1869. };
  1870. let hitDragging = this.hitDragging = new HitDragging(dragging, interactionSettingsStore);
  1871. hitDragging.requireInitial = false; // will start outside of a component
  1872. hitDragging.emitter.on('dragstart', this.handleDragStart);
  1873. hitDragging.emitter.on('hitupdate', this.handleHitUpdate);
  1874. hitDragging.emitter.on('dragend', this.handleDragEnd);
  1875. this.suppliedDragMeta = suppliedDragMeta;
  1876. }
  1877. buildDragMeta(subjectEl) {
  1878. if (typeof this.suppliedDragMeta === 'object') {
  1879. return parseDragMeta(this.suppliedDragMeta);
  1880. }
  1881. if (typeof this.suppliedDragMeta === 'function') {
  1882. return parseDragMeta(this.suppliedDragMeta(subjectEl));
  1883. }
  1884. return getDragMetaFromEl(subjectEl);
  1885. }
  1886. displayDrag(nextContext, state) {
  1887. let prevContext = this.receivingContext;
  1888. if (prevContext && prevContext !== nextContext) {
  1889. prevContext.dispatch({ type: 'UNSET_EVENT_DRAG' });
  1890. }
  1891. if (nextContext) {
  1892. nextContext.dispatch({ type: 'SET_EVENT_DRAG', state });
  1893. }
  1894. }
  1895. clearDrag() {
  1896. if (this.receivingContext) {
  1897. this.receivingContext.dispatch({ type: 'UNSET_EVENT_DRAG' });
  1898. }
  1899. }
  1900. canDropElOnCalendar(el, receivingContext) {
  1901. let dropAccept = receivingContext.options.dropAccept;
  1902. if (typeof dropAccept === 'function') {
  1903. return dropAccept.call(receivingContext.calendarApi, el);
  1904. }
  1905. if (typeof dropAccept === 'string' && dropAccept) {
  1906. return Boolean(elementMatches(el, dropAccept));
  1907. }
  1908. return true;
  1909. }
  1910. }
  1911. // Utils for computing event store from the DragMeta
  1912. // ----------------------------------------------------------------------------------------------------
  1913. function computeEventForDateSpan(dateSpan, dragMeta, context) {
  1914. let defProps = Object.assign({}, dragMeta.leftoverProps);
  1915. for (let transform of context.pluginHooks.externalDefTransforms) {
  1916. Object.assign(defProps, transform(dateSpan, dragMeta));
  1917. }
  1918. let { refined, extra } = refineEventDef(defProps, context);
  1919. let def = parseEventDef(refined, extra, dragMeta.sourceId, dateSpan.allDay, context.options.forceEventDuration || Boolean(dragMeta.duration), // hasEnd
  1920. context);
  1921. let start = dateSpan.range.start;
  1922. // only rely on time info if drop zone is all-day,
  1923. // otherwise, we already know the time
  1924. if (dateSpan.allDay && dragMeta.startTime) {
  1925. start = context.dateEnv.add(start, dragMeta.startTime);
  1926. }
  1927. let end = dragMeta.duration ?
  1928. context.dateEnv.add(start, dragMeta.duration) :
  1929. getDefaultEventEnd(dateSpan.allDay, start, context);
  1930. let instance = createEventInstance(def.defId, { start, end });
  1931. return { def, instance };
  1932. }
  1933. // Utils for extracting data from element
  1934. // ----------------------------------------------------------------------------------------------------
  1935. function getDragMetaFromEl(el) {
  1936. let str = getEmbeddedElData(el, 'event');
  1937. let obj = str ?
  1938. JSON.parse(str) :
  1939. { create: false }; // if no embedded data, assume no event creation
  1940. return parseDragMeta(obj);
  1941. }
  1942. config.dataAttrPrefix = '';
  1943. function getEmbeddedElData(el, name) {
  1944. let prefix = config.dataAttrPrefix;
  1945. let prefixedName = (prefix ? prefix + '-' : '') + name;
  1946. return el.getAttribute('data-' + prefixedName) || '';
  1947. }
  1948. /*
  1949. Makes an element (that is *external* to any calendar) draggable.
  1950. Can pass in data that determines how an event will be created when dropped onto a calendar.
  1951. Leverages FullCalendar's internal drag-n-drop functionality WITHOUT a third-party drag system.
  1952. */
  1953. class ExternalDraggable {
  1954. constructor(el, settings = {}) {
  1955. this.handlePointerDown = (ev) => {
  1956. let { dragging } = this;
  1957. let { minDistance, longPressDelay } = this.settings;
  1958. dragging.minDistance =
  1959. minDistance != null ?
  1960. minDistance :
  1961. (ev.isTouch ? 0 : BASE_OPTION_DEFAULTS.eventDragMinDistance);
  1962. dragging.delay =
  1963. ev.isTouch ? // TODO: eventually read eventLongPressDelay instead vvv
  1964. (longPressDelay != null ? longPressDelay : BASE_OPTION_DEFAULTS.longPressDelay) :
  1965. 0;
  1966. };
  1967. this.handleDragStart = (ev) => {
  1968. if (ev.isTouch &&
  1969. this.dragging.delay &&
  1970. ev.subjectEl.classList.contains('fc-event')) {
  1971. this.dragging.mirror.getMirrorEl().classList.add('fc-event-selected');
  1972. }
  1973. };
  1974. this.settings = settings;
  1975. let dragging = this.dragging = new FeaturefulElementDragging(el);
  1976. dragging.touchScrollAllowed = false;
  1977. if (settings.itemSelector != null) {
  1978. dragging.pointer.selector = settings.itemSelector;
  1979. }
  1980. if (settings.appendTo != null) {
  1981. dragging.mirror.parentNode = settings.appendTo; // TODO: write tests
  1982. }
  1983. dragging.emitter.on('pointerdown', this.handlePointerDown);
  1984. dragging.emitter.on('dragstart', this.handleDragStart);
  1985. new ExternalElementDragging(dragging, settings.eventData); // eslint-disable-line no-new
  1986. }
  1987. destroy() {
  1988. this.dragging.destroy();
  1989. }
  1990. }
  1991. /*
  1992. Detects when a *THIRD-PARTY* drag-n-drop system interacts with elements.
  1993. The third-party system is responsible for drawing the visuals effects of the drag.
  1994. This class simply monitors for pointer movements and fires events.
  1995. It also has the ability to hide the moving element (the "mirror") during the drag.
  1996. */
  1997. class InferredElementDragging extends ElementDragging {
  1998. constructor(containerEl) {
  1999. super(containerEl);
  2000. this.shouldIgnoreMove = false;
  2001. this.mirrorSelector = '';
  2002. this.currentMirrorEl = null;
  2003. this.handlePointerDown = (ev) => {
  2004. this.emitter.trigger('pointerdown', ev);
  2005. if (!this.shouldIgnoreMove) {
  2006. // fire dragstart right away. does not support delay or min-distance
  2007. this.emitter.trigger('dragstart', ev);
  2008. }
  2009. };
  2010. this.handlePointerMove = (ev) => {
  2011. if (!this.shouldIgnoreMove) {
  2012. this.emitter.trigger('dragmove', ev);
  2013. }
  2014. };
  2015. this.handlePointerUp = (ev) => {
  2016. this.emitter.trigger('pointerup', ev);
  2017. if (!this.shouldIgnoreMove) {
  2018. // fire dragend right away. does not support a revert animation
  2019. this.emitter.trigger('dragend', ev);
  2020. }
  2021. };
  2022. let pointer = this.pointer = new PointerDragging(containerEl);
  2023. pointer.emitter.on('pointerdown', this.handlePointerDown);
  2024. pointer.emitter.on('pointermove', this.handlePointerMove);
  2025. pointer.emitter.on('pointerup', this.handlePointerUp);
  2026. }
  2027. destroy() {
  2028. this.pointer.destroy();
  2029. }
  2030. setIgnoreMove(bool) {
  2031. this.shouldIgnoreMove = bool;
  2032. }
  2033. setMirrorIsVisible(bool) {
  2034. if (bool) {
  2035. // restore a previously hidden element.
  2036. // use the reference in case the selector class has already been removed.
  2037. if (this.currentMirrorEl) {
  2038. this.currentMirrorEl.style.visibility = '';
  2039. this.currentMirrorEl = null;
  2040. }
  2041. }
  2042. else {
  2043. let mirrorEl = this.mirrorSelector
  2044. // TODO: somehow query FullCalendars WITHIN shadow-roots
  2045. ? document.querySelector(this.mirrorSelector)
  2046. : null;
  2047. if (mirrorEl) {
  2048. this.currentMirrorEl = mirrorEl;
  2049. mirrorEl.style.visibility = 'hidden';
  2050. }
  2051. }
  2052. }
  2053. }
  2054. /*
  2055. Bridges third-party drag-n-drop systems with FullCalendar.
  2056. Must be instantiated and destroyed by caller.
  2057. */
  2058. class ThirdPartyDraggable {
  2059. constructor(containerOrSettings, settings) {
  2060. let containerEl = document;
  2061. if (
  2062. // wish we could just test instanceof EventTarget, but doesn't work in IE11
  2063. containerOrSettings === document ||
  2064. containerOrSettings instanceof Element) {
  2065. containerEl = containerOrSettings;
  2066. settings = settings || {};
  2067. }
  2068. else {
  2069. settings = (containerOrSettings || {});
  2070. }
  2071. let dragging = this.dragging = new InferredElementDragging(containerEl);
  2072. if (typeof settings.itemSelector === 'string') {
  2073. dragging.pointer.selector = settings.itemSelector;
  2074. }
  2075. else if (containerEl === document) {
  2076. dragging.pointer.selector = '[data-event]';
  2077. }
  2078. if (typeof settings.mirrorSelector === 'string') {
  2079. dragging.mirrorSelector = settings.mirrorSelector;
  2080. }
  2081. let externalDragging = new ExternalElementDragging(dragging, settings.eventData);
  2082. // The hit-detection system requires that the dnd-mirror-element be pointer-events:none,
  2083. // but this can't be guaranteed for third-party draggables, so disable
  2084. externalDragging.hitDragging.disablePointCheck = true;
  2085. }
  2086. destroy() {
  2087. this.dragging.destroy();
  2088. }
  2089. }
  2090. var index = createPlugin({
  2091. name: '@fullcalendar/interaction',
  2092. componentInteractions: [DateClicking, DateSelecting, EventDragging, EventResizing],
  2093. calendarInteractions: [UnselectAuto],
  2094. elementDraggingImpl: FeaturefulElementDragging,
  2095. optionRefiners: OPTION_REFINERS,
  2096. listenerRefiners: LISTENER_REFINERS,
  2097. });
  2098. export { ExternalDraggable as Draggable, ThirdPartyDraggable, index as default };