drag-drop.js 150 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030
  1. /**
  2. * @license
  3. * Copyright Google LLC All Rights Reserved.
  4. *
  5. * Use of this source code is governed by an MIT-style license that can be
  6. * found in the LICENSE file at https://angular.io/license
  7. */
  8. import { normalizePassiveListenerOptions, _supportsShadowDom } from '@angular/cdk/platform';
  9. import { coerceBooleanProperty, coerceElement, coerceNumberProperty, coerceArray } from '@angular/cdk/coercion';
  10. import { Subscription, Subject, interval, animationFrameScheduler, Observable, merge } from 'rxjs';
  11. import { startWith, takeUntil, take, map, switchMap, tap } from 'rxjs/operators';
  12. import { Injectable, NgZone, Inject, InjectionToken, NgModule, ContentChildren, ElementRef, EventEmitter, forwardRef, Input, Output, Optional, Directive, ChangeDetectorRef, SkipSelf, ContentChild, ViewContainerRef, isDevMode, TemplateRef, ɵɵdefineInjectable, ɵɵinject } from '@angular/core';
  13. import { DOCUMENT } from '@angular/common';
  14. import { ViewportRuler } from '@angular/cdk/scrolling';
  15. import { Directionality } from '@angular/cdk/bidi';
  16. /**
  17. * @fileoverview added by tsickle
  18. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  19. */
  20. /**
  21. * Shallow-extends a stylesheet object with another stylesheet object.
  22. * \@docs-private
  23. * @param {?} dest
  24. * @param {?} source
  25. * @return {?}
  26. */
  27. function extendStyles(dest, source) {
  28. for (let key in source) {
  29. if (source.hasOwnProperty(key)) {
  30. dest[key] = (/** @type {?} */ (source[key]));
  31. }
  32. }
  33. return dest;
  34. }
  35. /**
  36. * Toggles whether the native drag interactions should be enabled for an element.
  37. * \@docs-private
  38. * @param {?} element Element on which to toggle the drag interactions.
  39. * @param {?} enable Whether the drag interactions should be enabled.
  40. * @return {?}
  41. */
  42. function toggleNativeDragInteractions(element, enable) {
  43. /** @type {?} */
  44. const userSelect = enable ? '' : 'none';
  45. extendStyles(element.style, {
  46. touchAction: enable ? '' : 'none',
  47. webkitUserDrag: enable ? '' : 'none',
  48. webkitTapHighlightColor: enable ? '' : 'transparent',
  49. userSelect: userSelect,
  50. msUserSelect: userSelect,
  51. webkitUserSelect: userSelect,
  52. MozUserSelect: userSelect
  53. });
  54. }
  55. /**
  56. * @fileoverview added by tsickle
  57. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  58. */
  59. /**
  60. * Parses a CSS time value to milliseconds.
  61. * @param {?} value
  62. * @return {?}
  63. */
  64. function parseCssTimeUnitsToMs(value) {
  65. // Some browsers will return it in seconds, whereas others will return milliseconds.
  66. /** @type {?} */
  67. const multiplier = value.toLowerCase().indexOf('ms') > -1 ? 1 : 1000;
  68. return parseFloat(value) * multiplier;
  69. }
  70. /**
  71. * Gets the transform transition duration, including the delay, of an element in milliseconds.
  72. * @param {?} element
  73. * @return {?}
  74. */
  75. function getTransformTransitionDurationInMs(element) {
  76. /** @type {?} */
  77. const computedStyle = getComputedStyle(element);
  78. /** @type {?} */
  79. const transitionedProperties = parseCssPropertyValue(computedStyle, 'transition-property');
  80. /** @type {?} */
  81. const property = transitionedProperties.find((/**
  82. * @param {?} prop
  83. * @return {?}
  84. */
  85. prop => prop === 'transform' || prop === 'all'));
  86. // If there's no transition for `all` or `transform`, we shouldn't do anything.
  87. if (!property) {
  88. return 0;
  89. }
  90. // Get the index of the property that we're interested in and match
  91. // it up to the same index in `transition-delay` and `transition-duration`.
  92. /** @type {?} */
  93. const propertyIndex = transitionedProperties.indexOf(property);
  94. /** @type {?} */
  95. const rawDurations = parseCssPropertyValue(computedStyle, 'transition-duration');
  96. /** @type {?} */
  97. const rawDelays = parseCssPropertyValue(computedStyle, 'transition-delay');
  98. return parseCssTimeUnitsToMs(rawDurations[propertyIndex]) +
  99. parseCssTimeUnitsToMs(rawDelays[propertyIndex]);
  100. }
  101. /**
  102. * Parses out multiple values from a computed style into an array.
  103. * @param {?} computedStyle
  104. * @param {?} name
  105. * @return {?}
  106. */
  107. function parseCssPropertyValue(computedStyle, name) {
  108. /** @type {?} */
  109. const value = computedStyle.getPropertyValue(name);
  110. return value.split(',').map((/**
  111. * @param {?} part
  112. * @return {?}
  113. */
  114. part => part.trim()));
  115. }
  116. /**
  117. * @fileoverview added by tsickle
  118. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  119. */
  120. /**
  121. * Options that can be used to bind a passive event listener.
  122. * @type {?}
  123. */
  124. const passiveEventListenerOptions = normalizePassiveListenerOptions({ passive: true });
  125. /**
  126. * Options that can be used to bind an active event listener.
  127. * @type {?}
  128. */
  129. const activeEventListenerOptions = normalizePassiveListenerOptions({ passive: false });
  130. /**
  131. * Time in milliseconds for which to ignore mouse events, after
  132. * receiving a touch event. Used to avoid doing double work for
  133. * touch devices where the browser fires fake mouse events, in
  134. * addition to touch events.
  135. * @type {?}
  136. */
  137. const MOUSE_EVENT_IGNORE_TIME = 800;
  138. /**
  139. * Reference to a draggable item. Used to manipulate or dispose of the item.
  140. * \@docs-private
  141. * @template T
  142. */
  143. class DragRef {
  144. /**
  145. * @param {?} element
  146. * @param {?} _config
  147. * @param {?} _document
  148. * @param {?} _ngZone
  149. * @param {?} _viewportRuler
  150. * @param {?} _dragDropRegistry
  151. */
  152. constructor(element, _config, _document, _ngZone, _viewportRuler, _dragDropRegistry) {
  153. this._config = _config;
  154. this._document = _document;
  155. this._ngZone = _ngZone;
  156. this._viewportRuler = _viewportRuler;
  157. this._dragDropRegistry = _dragDropRegistry;
  158. /**
  159. * CSS `transform` applied to the element when it isn't being dragged. We need a
  160. * passive transform in order for the dragged element to retain its new position
  161. * after the user has stopped dragging and because we need to know the relative
  162. * position in case they start dragging again. This corresponds to `element.style.transform`.
  163. */
  164. this._passiveTransform = { x: 0, y: 0 };
  165. /**
  166. * CSS `transform` that is applied to the element while it's being dragged.
  167. */
  168. this._activeTransform = { x: 0, y: 0 };
  169. /**
  170. * Emits when the item is being moved.
  171. */
  172. this._moveEvents = new Subject();
  173. /**
  174. * Subscription to pointer movement events.
  175. */
  176. this._pointerMoveSubscription = Subscription.EMPTY;
  177. /**
  178. * Subscription to the event that is dispatched when the user lifts their pointer.
  179. */
  180. this._pointerUpSubscription = Subscription.EMPTY;
  181. /**
  182. * Subscription to the viewport being scrolled.
  183. */
  184. this._scrollSubscription = Subscription.EMPTY;
  185. /**
  186. * Subscription to the viewport being resized.
  187. */
  188. this._resizeSubscription = Subscription.EMPTY;
  189. /**
  190. * Cached reference to the boundary element.
  191. */
  192. this._boundaryElement = null;
  193. /**
  194. * Whether the native dragging interactions have been enabled on the root element.
  195. */
  196. this._nativeInteractionsEnabled = true;
  197. /**
  198. * Elements that can be used to drag the draggable item.
  199. */
  200. this._handles = [];
  201. /**
  202. * Registered handles that are currently disabled.
  203. */
  204. this._disabledHandles = new Set();
  205. /**
  206. * Layout direction of the item.
  207. */
  208. this._direction = 'ltr';
  209. /**
  210. * Amount of milliseconds to wait after the user has put their
  211. * pointer down before starting to drag the element.
  212. */
  213. this.dragStartDelay = 0;
  214. this._disabled = false;
  215. /**
  216. * Emits as the drag sequence is being prepared.
  217. */
  218. this.beforeStarted = new Subject();
  219. /**
  220. * Emits when the user starts dragging the item.
  221. */
  222. this.started = new Subject();
  223. /**
  224. * Emits when the user has released a drag item, before any animations have started.
  225. */
  226. this.released = new Subject();
  227. /**
  228. * Emits when the user stops dragging an item in the container.
  229. */
  230. this.ended = new Subject();
  231. /**
  232. * Emits when the user has moved the item into a new container.
  233. */
  234. this.entered = new Subject();
  235. /**
  236. * Emits when the user removes the item its container by dragging it into another container.
  237. */
  238. this.exited = new Subject();
  239. /**
  240. * Emits when the user drops the item inside a container.
  241. */
  242. this.dropped = new Subject();
  243. /**
  244. * Emits as the user is dragging the item. Use with caution,
  245. * because this event will fire for every pixel that the user has dragged.
  246. */
  247. this.moved = this._moveEvents.asObservable();
  248. /**
  249. * Handler for the `mousedown`/`touchstart` events.
  250. */
  251. this._pointerDown = (/**
  252. * @param {?} event
  253. * @return {?}
  254. */
  255. (event) => {
  256. this.beforeStarted.next();
  257. // Delegate the event based on whether it started from a handle or the element itself.
  258. if (this._handles.length) {
  259. /** @type {?} */
  260. const targetHandle = this._handles.find((/**
  261. * @param {?} handle
  262. * @return {?}
  263. */
  264. handle => {
  265. /** @type {?} */
  266. const target = event.target;
  267. return !!target && (target === handle || handle.contains((/** @type {?} */ (target))));
  268. }));
  269. if (targetHandle && !this._disabledHandles.has(targetHandle) && !this.disabled) {
  270. this._initializeDragSequence(targetHandle, event);
  271. }
  272. }
  273. else if (!this.disabled) {
  274. this._initializeDragSequence(this._rootElement, event);
  275. }
  276. });
  277. /**
  278. * Handler that is invoked when the user moves their pointer after they've initiated a drag.
  279. */
  280. this._pointerMove = (/**
  281. * @param {?} event
  282. * @return {?}
  283. */
  284. (event) => {
  285. if (!this._hasStartedDragging) {
  286. /** @type {?} */
  287. const pointerPosition = this._getPointerPositionOnPage(event);
  288. /** @type {?} */
  289. const distanceX = Math.abs(pointerPosition.x - this._pickupPositionOnPage.x);
  290. /** @type {?} */
  291. const distanceY = Math.abs(pointerPosition.y - this._pickupPositionOnPage.y);
  292. /** @type {?} */
  293. const isOverThreshold = distanceX + distanceY >= this._config.dragStartThreshold;
  294. // Only start dragging after the user has moved more than the minimum distance in either
  295. // direction. Note that this is preferrable over doing something like `skip(minimumDistance)`
  296. // in the `pointerMove` subscription, because we're not guaranteed to have one move event
  297. // per pixel of movement (e.g. if the user moves their pointer quickly).
  298. if (isOverThreshold) {
  299. /** @type {?} */
  300. const isDelayElapsed = Date.now() >= this._dragStartTime + (this.dragStartDelay || 0);
  301. if (!isDelayElapsed) {
  302. this._endDragSequence(event);
  303. return;
  304. }
  305. // Prevent other drag sequences from starting while something in the container is still
  306. // being dragged. This can happen while we're waiting for the drop animation to finish
  307. // and can cause errors, because some elements might still be moving around.
  308. if (!this._dropContainer || !this._dropContainer.isDragging()) {
  309. this._hasStartedDragging = true;
  310. this._ngZone.run((/**
  311. * @return {?}
  312. */
  313. () => this._startDragSequence(event)));
  314. }
  315. }
  316. return;
  317. }
  318. // We only need the preview dimensions if we have a boundary element.
  319. if (this._boundaryElement) {
  320. // Cache the preview element rect if we haven't cached it already or if
  321. // we cached it too early before the element dimensions were computed.
  322. if (!this._previewRect || (!this._previewRect.width && !this._previewRect.height)) {
  323. this._previewRect = (this._preview || this._rootElement).getBoundingClientRect();
  324. }
  325. }
  326. /** @type {?} */
  327. const constrainedPointerPosition = this._getConstrainedPointerPosition(event);
  328. this._hasMoved = true;
  329. event.preventDefault();
  330. this._updatePointerDirectionDelta(constrainedPointerPosition);
  331. if (this._dropContainer) {
  332. this._updateActiveDropContainer(constrainedPointerPosition);
  333. }
  334. else {
  335. /** @type {?} */
  336. const activeTransform = this._activeTransform;
  337. activeTransform.x =
  338. constrainedPointerPosition.x - this._pickupPositionOnPage.x + this._passiveTransform.x;
  339. activeTransform.y =
  340. constrainedPointerPosition.y - this._pickupPositionOnPage.y + this._passiveTransform.y;
  341. this._applyRootElementTransform(activeTransform.x, activeTransform.y);
  342. // Apply transform as attribute if dragging and svg element to work for IE
  343. if (typeof SVGElement !== 'undefined' && this._rootElement instanceof SVGElement) {
  344. /** @type {?} */
  345. const appliedTransform = `translate(${activeTransform.x} ${activeTransform.y})`;
  346. this._rootElement.setAttribute('transform', appliedTransform);
  347. }
  348. }
  349. // Since this event gets fired for every pixel while dragging, we only
  350. // want to fire it if the consumer opted into it. Also we have to
  351. // re-enter the zone because we run all of the events on the outside.
  352. if (this._moveEvents.observers.length) {
  353. this._ngZone.run((/**
  354. * @return {?}
  355. */
  356. () => {
  357. this._moveEvents.next({
  358. source: this,
  359. pointerPosition: constrainedPointerPosition,
  360. event,
  361. distance: this._getDragDistance(constrainedPointerPosition),
  362. delta: this._pointerDirectionDelta
  363. });
  364. }));
  365. }
  366. });
  367. /**
  368. * Handler that is invoked when the user lifts their pointer up, after initiating a drag.
  369. */
  370. this._pointerUp = (/**
  371. * @param {?} event
  372. * @return {?}
  373. */
  374. (event) => {
  375. this._endDragSequence(event);
  376. });
  377. this.withRootElement(element);
  378. _dragDropRegistry.registerDragItem(this);
  379. }
  380. /**
  381. * Whether starting to drag this element is disabled.
  382. * @return {?}
  383. */
  384. get disabled() {
  385. return this._disabled || !!(this._dropContainer && this._dropContainer.disabled);
  386. }
  387. /**
  388. * @param {?} value
  389. * @return {?}
  390. */
  391. set disabled(value) {
  392. /** @type {?} */
  393. const newValue = coerceBooleanProperty(value);
  394. if (newValue !== this._disabled) {
  395. this._disabled = newValue;
  396. this._toggleNativeDragInteractions();
  397. }
  398. }
  399. /**
  400. * Returns the element that is being used as a placeholder
  401. * while the current element is being dragged.
  402. * @return {?}
  403. */
  404. getPlaceholderElement() {
  405. return this._placeholder;
  406. }
  407. /**
  408. * Returns the root draggable element.
  409. * @return {?}
  410. */
  411. getRootElement() {
  412. return this._rootElement;
  413. }
  414. /**
  415. * Registers the handles that can be used to drag the element.
  416. * @template THIS
  417. * @this {THIS}
  418. * @param {?} handles
  419. * @return {THIS}
  420. */
  421. withHandles(handles) {
  422. (/** @type {?} */ (this))._handles = handles.map((/**
  423. * @param {?} handle
  424. * @return {?}
  425. */
  426. handle => coerceElement(handle)));
  427. (/** @type {?} */ (this))._handles.forEach((/**
  428. * @param {?} handle
  429. * @return {?}
  430. */
  431. handle => toggleNativeDragInteractions(handle, false)));
  432. (/** @type {?} */ (this))._toggleNativeDragInteractions();
  433. return (/** @type {?} */ (this));
  434. }
  435. /**
  436. * Registers the template that should be used for the drag preview.
  437. * @template THIS
  438. * @this {THIS}
  439. * @param {?} template Template that from which to stamp out the preview.
  440. * @return {THIS}
  441. */
  442. withPreviewTemplate(template) {
  443. (/** @type {?} */ (this))._previewTemplate = template;
  444. return (/** @type {?} */ (this));
  445. }
  446. /**
  447. * Registers the template that should be used for the drag placeholder.
  448. * @template THIS
  449. * @this {THIS}
  450. * @param {?} template Template that from which to stamp out the placeholder.
  451. * @return {THIS}
  452. */
  453. withPlaceholderTemplate(template) {
  454. (/** @type {?} */ (this))._placeholderTemplate = template;
  455. return (/** @type {?} */ (this));
  456. }
  457. /**
  458. * Sets an alternate drag root element. The root element is the element that will be moved as
  459. * the user is dragging. Passing an alternate root element is useful when trying to enable
  460. * dragging on an element that you might not have access to.
  461. * @template THIS
  462. * @this {THIS}
  463. * @param {?} rootElement
  464. * @return {THIS}
  465. */
  466. withRootElement(rootElement) {
  467. /** @type {?} */
  468. const element = coerceElement(rootElement);
  469. if (element !== (/** @type {?} */ (this))._rootElement) {
  470. if ((/** @type {?} */ (this))._rootElement) {
  471. (/** @type {?} */ (this))._removeRootElementListeners((/** @type {?} */ (this))._rootElement);
  472. }
  473. element.addEventListener('mousedown', (/** @type {?} */ (this))._pointerDown, activeEventListenerOptions);
  474. element.addEventListener('touchstart', (/** @type {?} */ (this))._pointerDown, passiveEventListenerOptions);
  475. (/** @type {?} */ (this))._initialTransform = undefined;
  476. (/** @type {?} */ (this))._rootElement = element;
  477. }
  478. return (/** @type {?} */ (this));
  479. }
  480. /**
  481. * Element to which the draggable's position will be constrained.
  482. * @template THIS
  483. * @this {THIS}
  484. * @param {?} boundaryElement
  485. * @return {THIS}
  486. */
  487. withBoundaryElement(boundaryElement) {
  488. (/** @type {?} */ (this))._boundaryElement = boundaryElement ? coerceElement(boundaryElement) : null;
  489. (/** @type {?} */ (this))._resizeSubscription.unsubscribe();
  490. if (boundaryElement) {
  491. (/** @type {?} */ (this))._resizeSubscription = (/** @type {?} */ (this))._viewportRuler
  492. .change(10)
  493. .subscribe((/**
  494. * @return {?}
  495. */
  496. () => (/** @type {?} */ (this))._containInsideBoundaryOnResize()));
  497. }
  498. return (/** @type {?} */ (this));
  499. }
  500. /**
  501. * Removes the dragging functionality from the DOM element.
  502. * @return {?}
  503. */
  504. dispose() {
  505. this._removeRootElementListeners(this._rootElement);
  506. // Do this check before removing from the registry since it'll
  507. // stop being considered as dragged once it is removed.
  508. if (this.isDragging()) {
  509. // Since we move out the element to the end of the body while it's being
  510. // dragged, we have to make sure that it's removed if it gets destroyed.
  511. removeElement(this._rootElement);
  512. }
  513. this._destroyPreview();
  514. this._destroyPlaceholder();
  515. this._dragDropRegistry.removeDragItem(this);
  516. this._removeSubscriptions();
  517. this.beforeStarted.complete();
  518. this.started.complete();
  519. this.released.complete();
  520. this.ended.complete();
  521. this.entered.complete();
  522. this.exited.complete();
  523. this.dropped.complete();
  524. this._moveEvents.complete();
  525. this._handles = [];
  526. this._disabledHandles.clear();
  527. this._dropContainer = undefined;
  528. this._boundaryElement = this._rootElement = this._placeholderTemplate =
  529. this._previewTemplate = this._nextSibling = (/** @type {?} */ (null));
  530. }
  531. /**
  532. * Checks whether the element is currently being dragged.
  533. * @return {?}
  534. */
  535. isDragging() {
  536. return this._hasStartedDragging && this._dragDropRegistry.isDragging(this);
  537. }
  538. /**
  539. * Resets a standalone drag item to its initial position.
  540. * @return {?}
  541. */
  542. reset() {
  543. this._rootElement.style.transform = this._initialTransform || '';
  544. this._activeTransform = { x: 0, y: 0 };
  545. this._passiveTransform = { x: 0, y: 0 };
  546. }
  547. /**
  548. * Sets a handle as disabled. While a handle is disabled, it'll capture and interrupt dragging.
  549. * @param {?} handle Handle element that should be disabled.
  550. * @return {?}
  551. */
  552. disableHandle(handle) {
  553. if (this._handles.indexOf(handle) > -1) {
  554. this._disabledHandles.add(handle);
  555. }
  556. }
  557. /**
  558. * Enables a handle, if it has been disabled.
  559. * @param {?} handle Handle element to be enabled.
  560. * @return {?}
  561. */
  562. enableHandle(handle) {
  563. this._disabledHandles.delete(handle);
  564. }
  565. /**
  566. * Sets the layout direction of the draggable item.
  567. * @template THIS
  568. * @this {THIS}
  569. * @param {?} direction
  570. * @return {THIS}
  571. */
  572. withDirection(direction) {
  573. (/** @type {?} */ (this))._direction = direction;
  574. return (/** @type {?} */ (this));
  575. }
  576. /**
  577. * Sets the container that the item is part of.
  578. * @param {?} container
  579. * @return {?}
  580. */
  581. _withDropContainer(container) {
  582. this._dropContainer = container;
  583. }
  584. /**
  585. * Gets the current position in pixels the draggable outside of a drop container.
  586. * @return {?}
  587. */
  588. getFreeDragPosition() {
  589. /** @type {?} */
  590. const position = this.isDragging() ? this._activeTransform : this._passiveTransform;
  591. return { x: position.x, y: position.y };
  592. }
  593. /**
  594. * Sets the current position in pixels the draggable outside of a drop container.
  595. * @template THIS
  596. * @this {THIS}
  597. * @param {?} value New position to be set.
  598. * @return {THIS}
  599. */
  600. setFreeDragPosition(value) {
  601. (/** @type {?} */ (this))._activeTransform = { x: 0, y: 0 };
  602. (/** @type {?} */ (this))._passiveTransform.x = value.x;
  603. (/** @type {?} */ (this))._passiveTransform.y = value.y;
  604. if (!(/** @type {?} */ (this))._dropContainer) {
  605. (/** @type {?} */ (this))._applyRootElementTransform(value.x, value.y);
  606. }
  607. return (/** @type {?} */ (this));
  608. }
  609. /**
  610. * Updates the item's sort order based on the last-known pointer position.
  611. * @return {?}
  612. */
  613. _sortFromLastPointerPosition() {
  614. /** @type {?} */
  615. const position = this._pointerPositionAtLastDirectionChange;
  616. if (position && this._dropContainer) {
  617. this._updateActiveDropContainer(position);
  618. }
  619. }
  620. /**
  621. * Unsubscribes from the global subscriptions.
  622. * @private
  623. * @return {?}
  624. */
  625. _removeSubscriptions() {
  626. this._pointerMoveSubscription.unsubscribe();
  627. this._pointerUpSubscription.unsubscribe();
  628. this._scrollSubscription.unsubscribe();
  629. }
  630. /**
  631. * Destroys the preview element and its ViewRef.
  632. * @private
  633. * @return {?}
  634. */
  635. _destroyPreview() {
  636. if (this._preview) {
  637. removeElement(this._preview);
  638. }
  639. if (this._previewRef) {
  640. this._previewRef.destroy();
  641. }
  642. this._preview = this._previewRef = (/** @type {?} */ (null));
  643. }
  644. /**
  645. * Destroys the placeholder element and its ViewRef.
  646. * @private
  647. * @return {?}
  648. */
  649. _destroyPlaceholder() {
  650. if (this._placeholder) {
  651. removeElement(this._placeholder);
  652. }
  653. if (this._placeholderRef) {
  654. this._placeholderRef.destroy();
  655. }
  656. this._placeholder = this._placeholderRef = (/** @type {?} */ (null));
  657. }
  658. /**
  659. * Clears subscriptions and stops the dragging sequence.
  660. * @private
  661. * @param {?} event Browser event object that ended the sequence.
  662. * @return {?}
  663. */
  664. _endDragSequence(event) {
  665. // Note that here we use `isDragging` from the service, rather than from `this`.
  666. // The difference is that the one from the service reflects whether a dragging sequence
  667. // has been initiated, whereas the one on `this` includes whether the user has passed
  668. // the minimum dragging threshold.
  669. if (!this._dragDropRegistry.isDragging(this)) {
  670. return;
  671. }
  672. this._removeSubscriptions();
  673. this._dragDropRegistry.stopDragging(this);
  674. this._toggleNativeDragInteractions();
  675. if (this._handles) {
  676. this._rootElement.style.webkitTapHighlightColor = this._rootElementTapHighlight;
  677. }
  678. if (!this._hasStartedDragging) {
  679. return;
  680. }
  681. this.released.next({ source: this });
  682. if (this._dropContainer) {
  683. // Stop scrolling immediately, instead of waiting for the animation to finish.
  684. this._dropContainer._stopScrolling();
  685. this._animatePreviewToPlaceholder().then((/**
  686. * @return {?}
  687. */
  688. () => {
  689. this._cleanupDragArtifacts(event);
  690. this._cleanupCachedDimensions();
  691. this._dragDropRegistry.stopDragging(this);
  692. }));
  693. }
  694. else {
  695. // Convert the active transform into a passive one. This means that next time
  696. // the user starts dragging the item, its position will be calculated relatively
  697. // to the new passive transform.
  698. this._passiveTransform.x = this._activeTransform.x;
  699. this._passiveTransform.y = this._activeTransform.y;
  700. this._ngZone.run((/**
  701. * @return {?}
  702. */
  703. () => {
  704. this.ended.next({
  705. source: this,
  706. distance: this._getDragDistance(this._getPointerPositionOnPage(event))
  707. });
  708. }));
  709. this._cleanupCachedDimensions();
  710. this._dragDropRegistry.stopDragging(this);
  711. }
  712. }
  713. /**
  714. * Starts the dragging sequence.
  715. * @private
  716. * @param {?} event
  717. * @return {?}
  718. */
  719. _startDragSequence(event) {
  720. // Emit the event on the item before the one on the container.
  721. this.started.next({ source: this });
  722. if (isTouchEvent(event)) {
  723. this._lastTouchEventTime = Date.now();
  724. }
  725. this._toggleNativeDragInteractions();
  726. if (this._dropContainer) {
  727. /** @type {?} */
  728. const element = this._rootElement;
  729. // Grab the `nextSibling` before the preview and placeholder
  730. // have been created so we don't get the preview by accident.
  731. this._nextSibling = element.nextSibling;
  732. /** @type {?} */
  733. const preview = this._preview = this._createPreviewElement();
  734. /** @type {?} */
  735. const placeholder = this._placeholder = this._createPlaceholderElement();
  736. // We move the element out at the end of the body and we make it hidden, because keeping it in
  737. // place will throw off the consumer's `:last-child` selectors. We can't remove the element
  738. // from the DOM completely, because iOS will stop firing all subsequent events in the chain.
  739. element.style.display = 'none';
  740. this._document.body.appendChild((/** @type {?} */ (element.parentNode)).replaceChild(placeholder, element));
  741. getPreviewInsertionPoint(this._document).appendChild(preview);
  742. this._dropContainer.start();
  743. }
  744. }
  745. /**
  746. * Sets up the different variables and subscriptions
  747. * that will be necessary for the dragging sequence.
  748. * @private
  749. * @param {?} referenceElement Element that started the drag sequence.
  750. * @param {?} event Browser event object that started the sequence.
  751. * @return {?}
  752. */
  753. _initializeDragSequence(referenceElement, event) {
  754. // Always stop propagation for the event that initializes
  755. // the dragging sequence, in order to prevent it from potentially
  756. // starting another sequence for a draggable parent somewhere up the DOM tree.
  757. event.stopPropagation();
  758. /** @type {?} */
  759. const isDragging = this.isDragging();
  760. /** @type {?} */
  761. const isTouchSequence = isTouchEvent(event);
  762. /** @type {?} */
  763. const isAuxiliaryMouseButton = !isTouchSequence && ((/** @type {?} */ (event))).button !== 0;
  764. /** @type {?} */
  765. const rootElement = this._rootElement;
  766. /** @type {?} */
  767. const isSyntheticEvent = !isTouchSequence && this._lastTouchEventTime &&
  768. this._lastTouchEventTime + MOUSE_EVENT_IGNORE_TIME > Date.now();
  769. // If the event started from an element with the native HTML drag&drop, it'll interfere
  770. // with our own dragging (e.g. `img` tags do it by default). Prevent the default action
  771. // to stop it from happening. Note that preventing on `dragstart` also seems to work, but
  772. // it's flaky and it fails if the user drags it away quickly. Also note that we only want
  773. // to do this for `mousedown` since doing the same for `touchstart` will stop any `click`
  774. // events from firing on touch devices.
  775. if (event.target && ((/** @type {?} */ (event.target))).draggable && event.type === 'mousedown') {
  776. event.preventDefault();
  777. }
  778. // Abort if the user is already dragging or is using a mouse button other than the primary one.
  779. if (isDragging || isAuxiliaryMouseButton || isSyntheticEvent) {
  780. return;
  781. }
  782. // If we've got handles, we need to disable the tap highlight on the entire root element,
  783. // otherwise iOS will still add it, even though all the drag interactions on the handle
  784. // are disabled.
  785. if (this._handles.length) {
  786. this._rootElementTapHighlight = rootElement.style.webkitTapHighlightColor;
  787. rootElement.style.webkitTapHighlightColor = 'transparent';
  788. }
  789. this._hasStartedDragging = this._hasMoved = false;
  790. this._initialContainer = (/** @type {?} */ (this._dropContainer));
  791. // Avoid multiple subscriptions and memory leaks when multi touch
  792. // (isDragging check above isn't enough because of possible temporal and/or dimensional delays)
  793. this._removeSubscriptions();
  794. this._pointerMoveSubscription = this._dragDropRegistry.pointerMove.subscribe(this._pointerMove);
  795. this._pointerUpSubscription = this._dragDropRegistry.pointerUp.subscribe(this._pointerUp);
  796. this._scrollSubscription = this._dragDropRegistry.scroll.pipe(startWith(null)).subscribe((/**
  797. * @return {?}
  798. */
  799. () => {
  800. this._scrollPosition = this._viewportRuler.getViewportScrollPosition();
  801. }));
  802. if (this._boundaryElement) {
  803. this._boundaryRect = this._boundaryElement.getBoundingClientRect();
  804. }
  805. // If we have a custom preview template, the element won't be visible anyway so we avoid the
  806. // extra `getBoundingClientRect` calls and just move the preview next to the cursor.
  807. this._pickupPositionInElement = this._previewTemplate && this._previewTemplate.template ?
  808. { x: 0, y: 0 } :
  809. this._getPointerPositionInElement(referenceElement, event);
  810. /** @type {?} */
  811. const pointerPosition = this._pickupPositionOnPage = this._getPointerPositionOnPage(event);
  812. this._pointerDirectionDelta = { x: 0, y: 0 };
  813. this._pointerPositionAtLastDirectionChange = { x: pointerPosition.x, y: pointerPosition.y };
  814. this._dragStartTime = Date.now();
  815. this._dragDropRegistry.startDragging(this, event);
  816. }
  817. /**
  818. * Cleans up the DOM artifacts that were added to facilitate the element being dragged.
  819. * @private
  820. * @param {?} event
  821. * @return {?}
  822. */
  823. _cleanupDragArtifacts(event) {
  824. // Restore the element's visibility and insert it at its old position in the DOM.
  825. // It's important that we maintain the position, because moving the element around in the DOM
  826. // can throw off `NgFor` which does smart diffing and re-creates elements only when necessary,
  827. // while moving the existing elements in all other cases.
  828. this._rootElement.style.display = '';
  829. if (this._nextSibling) {
  830. (/** @type {?} */ (this._nextSibling.parentNode)).insertBefore(this._rootElement, this._nextSibling);
  831. }
  832. else {
  833. coerceElement(this._initialContainer.element).appendChild(this._rootElement);
  834. }
  835. this._destroyPreview();
  836. this._destroyPlaceholder();
  837. this._boundaryRect = this._previewRect = undefined;
  838. // Re-enter the NgZone since we bound `document` events on the outside.
  839. this._ngZone.run((/**
  840. * @return {?}
  841. */
  842. () => {
  843. /** @type {?} */
  844. const container = (/** @type {?} */ (this._dropContainer));
  845. /** @type {?} */
  846. const currentIndex = container.getItemIndex(this);
  847. /** @type {?} */
  848. const pointerPosition = this._getPointerPositionOnPage(event);
  849. /** @type {?} */
  850. const distance = this._getDragDistance(this._getPointerPositionOnPage(event));
  851. /** @type {?} */
  852. const isPointerOverContainer = container._isOverContainer(pointerPosition.x, pointerPosition.y);
  853. this.ended.next({ source: this, distance });
  854. this.dropped.next({
  855. item: this,
  856. currentIndex,
  857. previousIndex: this._initialContainer.getItemIndex(this),
  858. container: container,
  859. previousContainer: this._initialContainer,
  860. isPointerOverContainer,
  861. distance
  862. });
  863. container.drop(this, currentIndex, this._initialContainer, isPointerOverContainer, distance);
  864. this._dropContainer = this._initialContainer;
  865. }));
  866. }
  867. /**
  868. * Updates the item's position in its drop container, or moves it
  869. * into a new one, depending on its current drag position.
  870. * @private
  871. * @param {?} __0
  872. * @return {?}
  873. */
  874. _updateActiveDropContainer({ x, y }) {
  875. // Drop container that draggable has been moved into.
  876. /** @type {?} */
  877. let newContainer = this._initialContainer._getSiblingContainerFromPosition(this, x, y);
  878. // If we couldn't find a new container to move the item into, and the item has left its
  879. // initial container, check whether the it's over the initial container. This handles the
  880. // case where two containers are connected one way and the user tries to undo dragging an
  881. // item into a new container.
  882. if (!newContainer && this._dropContainer !== this._initialContainer &&
  883. this._initialContainer._isOverContainer(x, y)) {
  884. newContainer = this._initialContainer;
  885. }
  886. if (newContainer && newContainer !== this._dropContainer) {
  887. this._ngZone.run((/**
  888. * @return {?}
  889. */
  890. () => {
  891. // Notify the old container that the item has left.
  892. this.exited.next({ item: this, container: (/** @type {?} */ (this._dropContainer)) });
  893. (/** @type {?} */ (this._dropContainer)).exit(this);
  894. // Notify the new container that the item has entered.
  895. this._dropContainer = (/** @type {?} */ (newContainer));
  896. this._dropContainer.enter(this, x, y);
  897. this.entered.next({
  898. item: this,
  899. container: (/** @type {?} */ (newContainer)),
  900. currentIndex: (/** @type {?} */ (newContainer)).getItemIndex(this)
  901. });
  902. }));
  903. }
  904. (/** @type {?} */ (this._dropContainer))._startScrollingIfNecessary(x, y);
  905. (/** @type {?} */ (this._dropContainer))._sortItem(this, x, y, this._pointerDirectionDelta);
  906. this._preview.style.transform =
  907. getTransform(x - this._pickupPositionInElement.x, y - this._pickupPositionInElement.y);
  908. }
  909. /**
  910. * Creates the element that will be rendered next to the user's pointer
  911. * and will be used as a preview of the element that is being dragged.
  912. * @private
  913. * @return {?}
  914. */
  915. _createPreviewElement() {
  916. /** @type {?} */
  917. const previewConfig = this._previewTemplate;
  918. /** @type {?} */
  919. const previewTemplate = previewConfig ? previewConfig.template : null;
  920. /** @type {?} */
  921. let preview;
  922. if (previewTemplate) {
  923. /** @type {?} */
  924. const viewRef = (/** @type {?} */ (previewConfig)).viewContainer.createEmbeddedView(previewTemplate, (/** @type {?} */ (previewConfig)).context);
  925. preview = getRootNode(viewRef, this._document);
  926. this._previewRef = viewRef;
  927. preview.style.transform =
  928. getTransform(this._pickupPositionOnPage.x, this._pickupPositionOnPage.y);
  929. }
  930. else {
  931. /** @type {?} */
  932. const element = this._rootElement;
  933. /** @type {?} */
  934. const elementRect = element.getBoundingClientRect();
  935. preview = deepCloneNode(element);
  936. preview.style.width = `${elementRect.width}px`;
  937. preview.style.height = `${elementRect.height}px`;
  938. preview.style.transform = getTransform(elementRect.left, elementRect.top);
  939. }
  940. extendStyles(preview.style, {
  941. // It's important that we disable the pointer events on the preview, because
  942. // it can throw off the `document.elementFromPoint` calls in the `CdkDropList`.
  943. pointerEvents: 'none',
  944. // We have to reset the margin, because can throw off positioning relative to the viewport.
  945. margin: '0',
  946. position: 'fixed',
  947. top: '0',
  948. left: '0',
  949. zIndex: '1000'
  950. });
  951. toggleNativeDragInteractions(preview, false);
  952. preview.classList.add('cdk-drag-preview');
  953. preview.setAttribute('dir', this._direction);
  954. return preview;
  955. }
  956. /**
  957. * Animates the preview element from its current position to the location of the drop placeholder.
  958. * @private
  959. * @return {?} Promise that resolves when the animation completes.
  960. */
  961. _animatePreviewToPlaceholder() {
  962. // If the user hasn't moved yet, the transitionend event won't fire.
  963. if (!this._hasMoved) {
  964. return Promise.resolve();
  965. }
  966. /** @type {?} */
  967. const placeholderRect = this._placeholder.getBoundingClientRect();
  968. // Apply the class that adds a transition to the preview.
  969. this._preview.classList.add('cdk-drag-animating');
  970. // Move the preview to the placeholder position.
  971. this._preview.style.transform = getTransform(placeholderRect.left, placeholderRect.top);
  972. // If the element doesn't have a `transition`, the `transitionend` event won't fire. Since
  973. // we need to trigger a style recalculation in order for the `cdk-drag-animating` class to
  974. // apply its style, we take advantage of the available info to figure out whether we need to
  975. // bind the event in the first place.
  976. /** @type {?} */
  977. const duration = getTransformTransitionDurationInMs(this._preview);
  978. if (duration === 0) {
  979. return Promise.resolve();
  980. }
  981. return this._ngZone.runOutsideAngular((/**
  982. * @return {?}
  983. */
  984. () => {
  985. return new Promise((/**
  986. * @param {?} resolve
  987. * @return {?}
  988. */
  989. resolve => {
  990. /** @type {?} */
  991. const handler = (/** @type {?} */ (((/**
  992. * @param {?} event
  993. * @return {?}
  994. */
  995. (event) => {
  996. if (!event || (event.target === this._preview && event.propertyName === 'transform')) {
  997. this._preview.removeEventListener('transitionend', handler);
  998. resolve();
  999. clearTimeout(timeout);
  1000. }
  1001. }))));
  1002. // If a transition is short enough, the browser might not fire the `transitionend` event.
  1003. // Since we know how long it's supposed to take, add a timeout with a 50% buffer that'll
  1004. // fire if the transition hasn't completed when it was supposed to.
  1005. /** @type {?} */
  1006. const timeout = setTimeout((/** @type {?} */ (handler)), duration * 1.5);
  1007. this._preview.addEventListener('transitionend', handler);
  1008. }));
  1009. }));
  1010. }
  1011. /**
  1012. * Creates an element that will be shown instead of the current element while dragging.
  1013. * @private
  1014. * @return {?}
  1015. */
  1016. _createPlaceholderElement() {
  1017. /** @type {?} */
  1018. const placeholderConfig = this._placeholderTemplate;
  1019. /** @type {?} */
  1020. const placeholderTemplate = placeholderConfig ? placeholderConfig.template : null;
  1021. /** @type {?} */
  1022. let placeholder;
  1023. if (placeholderTemplate) {
  1024. this._placeholderRef = (/** @type {?} */ (placeholderConfig)).viewContainer.createEmbeddedView(placeholderTemplate, (/** @type {?} */ (placeholderConfig)).context);
  1025. placeholder = getRootNode(this._placeholderRef, this._document);
  1026. }
  1027. else {
  1028. placeholder = deepCloneNode(this._rootElement);
  1029. }
  1030. placeholder.classList.add('cdk-drag-placeholder');
  1031. return placeholder;
  1032. }
  1033. /**
  1034. * Figures out the coordinates at which an element was picked up.
  1035. * @private
  1036. * @param {?} referenceElement Element that initiated the dragging.
  1037. * @param {?} event Event that initiated the dragging.
  1038. * @return {?}
  1039. */
  1040. _getPointerPositionInElement(referenceElement, event) {
  1041. /** @type {?} */
  1042. const elementRect = this._rootElement.getBoundingClientRect();
  1043. /** @type {?} */
  1044. const handleElement = referenceElement === this._rootElement ? null : referenceElement;
  1045. /** @type {?} */
  1046. const referenceRect = handleElement ? handleElement.getBoundingClientRect() : elementRect;
  1047. /** @type {?} */
  1048. const point = isTouchEvent(event) ? event.targetTouches[0] : event;
  1049. /** @type {?} */
  1050. const x = point.pageX - referenceRect.left - this._scrollPosition.left;
  1051. /** @type {?} */
  1052. const y = point.pageY - referenceRect.top - this._scrollPosition.top;
  1053. return {
  1054. x: referenceRect.left - elementRect.left + x,
  1055. y: referenceRect.top - elementRect.top + y
  1056. };
  1057. }
  1058. /**
  1059. * Determines the point of the page that was touched by the user.
  1060. * @private
  1061. * @param {?} event
  1062. * @return {?}
  1063. */
  1064. _getPointerPositionOnPage(event) {
  1065. // `touches` will be empty for start/end events so we have to fall back to `changedTouches`.
  1066. /** @type {?} */
  1067. const point = isTouchEvent(event) ? (event.touches[0] || event.changedTouches[0]) : event;
  1068. return {
  1069. x: point.pageX - this._scrollPosition.left,
  1070. y: point.pageY - this._scrollPosition.top
  1071. };
  1072. }
  1073. /**
  1074. * Gets the pointer position on the page, accounting for any position constraints.
  1075. * @private
  1076. * @param {?} event
  1077. * @return {?}
  1078. */
  1079. _getConstrainedPointerPosition(event) {
  1080. /** @type {?} */
  1081. const point = this._getPointerPositionOnPage(event);
  1082. /** @type {?} */
  1083. const constrainedPoint = this.constrainPosition ? this.constrainPosition(point, this) : point;
  1084. /** @type {?} */
  1085. const dropContainerLock = this._dropContainer ? this._dropContainer.lockAxis : null;
  1086. if (this.lockAxis === 'x' || dropContainerLock === 'x') {
  1087. constrainedPoint.y = this._pickupPositionOnPage.y;
  1088. }
  1089. else if (this.lockAxis === 'y' || dropContainerLock === 'y') {
  1090. constrainedPoint.x = this._pickupPositionOnPage.x;
  1091. }
  1092. if (this._boundaryRect) {
  1093. const { x: pickupX, y: pickupY } = this._pickupPositionInElement;
  1094. /** @type {?} */
  1095. const boundaryRect = this._boundaryRect;
  1096. /** @type {?} */
  1097. const previewRect = (/** @type {?} */ (this._previewRect));
  1098. /** @type {?} */
  1099. const minY = boundaryRect.top + pickupY;
  1100. /** @type {?} */
  1101. const maxY = boundaryRect.bottom - (previewRect.height - pickupY);
  1102. /** @type {?} */
  1103. const minX = boundaryRect.left + pickupX;
  1104. /** @type {?} */
  1105. const maxX = boundaryRect.right - (previewRect.width - pickupX);
  1106. constrainedPoint.x = clamp(constrainedPoint.x, minX, maxX);
  1107. constrainedPoint.y = clamp(constrainedPoint.y, minY, maxY);
  1108. }
  1109. return constrainedPoint;
  1110. }
  1111. /**
  1112. * Updates the current drag delta, based on the user's current pointer position on the page.
  1113. * @private
  1114. * @param {?} pointerPositionOnPage
  1115. * @return {?}
  1116. */
  1117. _updatePointerDirectionDelta(pointerPositionOnPage) {
  1118. const { x, y } = pointerPositionOnPage;
  1119. /** @type {?} */
  1120. const delta = this._pointerDirectionDelta;
  1121. /** @type {?} */
  1122. const positionSinceLastChange = this._pointerPositionAtLastDirectionChange;
  1123. // Amount of pixels the user has dragged since the last time the direction changed.
  1124. /** @type {?} */
  1125. const changeX = Math.abs(x - positionSinceLastChange.x);
  1126. /** @type {?} */
  1127. const changeY = Math.abs(y - positionSinceLastChange.y);
  1128. // Because we handle pointer events on a per-pixel basis, we don't want the delta
  1129. // to change for every pixel, otherwise anything that depends on it can look erratic.
  1130. // To make the delta more consistent, we track how much the user has moved since the last
  1131. // delta change and we only update it after it has reached a certain threshold.
  1132. if (changeX > this._config.pointerDirectionChangeThreshold) {
  1133. delta.x = x > positionSinceLastChange.x ? 1 : -1;
  1134. positionSinceLastChange.x = x;
  1135. }
  1136. if (changeY > this._config.pointerDirectionChangeThreshold) {
  1137. delta.y = y > positionSinceLastChange.y ? 1 : -1;
  1138. positionSinceLastChange.y = y;
  1139. }
  1140. return delta;
  1141. }
  1142. /**
  1143. * Toggles the native drag interactions, based on how many handles are registered.
  1144. * @private
  1145. * @return {?}
  1146. */
  1147. _toggleNativeDragInteractions() {
  1148. if (!this._rootElement || !this._handles) {
  1149. return;
  1150. }
  1151. /** @type {?} */
  1152. const shouldEnable = this._handles.length > 0 || !this.isDragging();
  1153. if (shouldEnable !== this._nativeInteractionsEnabled) {
  1154. this._nativeInteractionsEnabled = shouldEnable;
  1155. toggleNativeDragInteractions(this._rootElement, shouldEnable);
  1156. }
  1157. }
  1158. /**
  1159. * Removes the manually-added event listeners from the root element.
  1160. * @private
  1161. * @param {?} element
  1162. * @return {?}
  1163. */
  1164. _removeRootElementListeners(element) {
  1165. element.removeEventListener('mousedown', this._pointerDown, activeEventListenerOptions);
  1166. element.removeEventListener('touchstart', this._pointerDown, passiveEventListenerOptions);
  1167. }
  1168. /**
  1169. * Applies a `transform` to the root element, taking into account any existing transforms on it.
  1170. * @private
  1171. * @param {?} x New transform value along the X axis.
  1172. * @param {?} y New transform value along the Y axis.
  1173. * @return {?}
  1174. */
  1175. _applyRootElementTransform(x, y) {
  1176. /** @type {?} */
  1177. const transform = getTransform(x, y);
  1178. // Cache the previous transform amount only after the first drag sequence, because
  1179. // we don't want our own transforms to stack on top of each other.
  1180. if (this._initialTransform == null) {
  1181. this._initialTransform = this._rootElement.style.transform || '';
  1182. }
  1183. // Preserve the previous `transform` value, if there was one. Note that we apply our own
  1184. // transform before the user's, because things like rotation can affect which direction
  1185. // the element will be translated towards.
  1186. this._rootElement.style.transform = this._initialTransform ?
  1187. transform + ' ' + this._initialTransform : transform;
  1188. }
  1189. /**
  1190. * Gets the distance that the user has dragged during the current drag sequence.
  1191. * @private
  1192. * @param {?} currentPosition Current position of the user's pointer.
  1193. * @return {?}
  1194. */
  1195. _getDragDistance(currentPosition) {
  1196. /** @type {?} */
  1197. const pickupPosition = this._pickupPositionOnPage;
  1198. if (pickupPosition) {
  1199. return { x: currentPosition.x - pickupPosition.x, y: currentPosition.y - pickupPosition.y };
  1200. }
  1201. return { x: 0, y: 0 };
  1202. }
  1203. /**
  1204. * Cleans up any cached element dimensions that we don't need after dragging has stopped.
  1205. * @private
  1206. * @return {?}
  1207. */
  1208. _cleanupCachedDimensions() {
  1209. this._boundaryRect = this._previewRect = undefined;
  1210. }
  1211. /**
  1212. * Checks whether the element is still inside its boundary after the viewport has been resized.
  1213. * If not, the position is adjusted so that the element fits again.
  1214. * @private
  1215. * @return {?}
  1216. */
  1217. _containInsideBoundaryOnResize() {
  1218. let { x, y } = this._passiveTransform;
  1219. if ((x === 0 && y === 0) || this.isDragging() || !this._boundaryElement) {
  1220. return;
  1221. }
  1222. /** @type {?} */
  1223. const boundaryRect = this._boundaryElement.getBoundingClientRect();
  1224. /** @type {?} */
  1225. const elementRect = this._rootElement.getBoundingClientRect();
  1226. /** @type {?} */
  1227. const leftOverflow = boundaryRect.left - elementRect.left;
  1228. /** @type {?} */
  1229. const rightOverflow = elementRect.right - boundaryRect.right;
  1230. /** @type {?} */
  1231. const topOverflow = boundaryRect.top - elementRect.top;
  1232. /** @type {?} */
  1233. const bottomOverflow = elementRect.bottom - boundaryRect.bottom;
  1234. // If the element has become wider than the boundary, we can't
  1235. // do much to make it fit so we just anchor it to the left.
  1236. if (boundaryRect.width > elementRect.width) {
  1237. if (leftOverflow > 0) {
  1238. x += leftOverflow;
  1239. }
  1240. if (rightOverflow > 0) {
  1241. x -= rightOverflow;
  1242. }
  1243. }
  1244. else {
  1245. x = 0;
  1246. }
  1247. // If the element has become taller than the boundary, we can't
  1248. // do much to make it fit so we just anchor it to the top.
  1249. if (boundaryRect.height > elementRect.height) {
  1250. if (topOverflow > 0) {
  1251. y += topOverflow;
  1252. }
  1253. if (bottomOverflow > 0) {
  1254. y -= bottomOverflow;
  1255. }
  1256. }
  1257. else {
  1258. y = 0;
  1259. }
  1260. if (x !== this._passiveTransform.x || y !== this._passiveTransform.y) {
  1261. this.setFreeDragPosition({ y, x });
  1262. }
  1263. }
  1264. }
  1265. /**
  1266. * Gets a 3d `transform` that can be applied to an element.
  1267. * @param {?} x Desired position of the element along the X axis.
  1268. * @param {?} y Desired position of the element along the Y axis.
  1269. * @return {?}
  1270. */
  1271. function getTransform(x, y) {
  1272. // Round the transforms since some browsers will
  1273. // blur the elements for sub-pixel transforms.
  1274. return `translate3d(${Math.round(x)}px, ${Math.round(y)}px, 0)`;
  1275. }
  1276. /**
  1277. * Creates a deep clone of an element.
  1278. * @param {?} node
  1279. * @return {?}
  1280. */
  1281. function deepCloneNode(node) {
  1282. /** @type {?} */
  1283. const clone = (/** @type {?} */ (node.cloneNode(true)));
  1284. /** @type {?} */
  1285. const descendantsWithId = clone.querySelectorAll('[id]');
  1286. /** @type {?} */
  1287. const descendantCanvases = node.querySelectorAll('canvas');
  1288. // Remove the `id` to avoid having multiple elements with the same id on the page.
  1289. clone.removeAttribute('id');
  1290. for (let i = 0; i < descendantsWithId.length; i++) {
  1291. descendantsWithId[i].removeAttribute('id');
  1292. }
  1293. // `cloneNode` won't transfer the content of `canvas` elements so we have to do it ourselves.
  1294. // We match up the cloned canvas to their sources using their index in the DOM.
  1295. if (descendantCanvases.length) {
  1296. /** @type {?} */
  1297. const cloneCanvases = clone.querySelectorAll('canvas');
  1298. for (let i = 0; i < descendantCanvases.length; i++) {
  1299. /** @type {?} */
  1300. const correspondingCloneContext = cloneCanvases[i].getContext('2d');
  1301. if (correspondingCloneContext) {
  1302. correspondingCloneContext.drawImage(descendantCanvases[i], 0, 0);
  1303. }
  1304. }
  1305. }
  1306. return clone;
  1307. }
  1308. /**
  1309. * Clamps a value between a minimum and a maximum.
  1310. * @param {?} value
  1311. * @param {?} min
  1312. * @param {?} max
  1313. * @return {?}
  1314. */
  1315. function clamp(value, min, max) {
  1316. return Math.max(min, Math.min(max, value));
  1317. }
  1318. /**
  1319. * Helper to remove an element from the DOM and to do all the necessary null checks.
  1320. * @param {?} element Element to be removed.
  1321. * @return {?}
  1322. */
  1323. function removeElement(element) {
  1324. if (element && element.parentNode) {
  1325. element.parentNode.removeChild(element);
  1326. }
  1327. }
  1328. /**
  1329. * Determines whether an event is a touch event.
  1330. * @param {?} event
  1331. * @return {?}
  1332. */
  1333. function isTouchEvent(event) {
  1334. // This function is called for every pixel that the user has dragged so we need it to be
  1335. // as fast as possible. Since we only bind mouse events and touch events, we can assume
  1336. // that if the event's name starts with `t`, it's a touch event.
  1337. return event.type[0] === 't';
  1338. }
  1339. /**
  1340. * Gets the element into which the drag preview should be inserted.
  1341. * @param {?} documentRef
  1342. * @return {?}
  1343. */
  1344. function getPreviewInsertionPoint(documentRef) {
  1345. // We can't use the body if the user is in fullscreen mode,
  1346. // because the preview will render under the fullscreen element.
  1347. // TODO(crisbeto): dedupe this with the `FullscreenOverlayContainer` eventually.
  1348. return documentRef.fullscreenElement ||
  1349. documentRef.webkitFullscreenElement ||
  1350. documentRef.mozFullScreenElement ||
  1351. documentRef.msFullscreenElement ||
  1352. documentRef.body;
  1353. }
  1354. /**
  1355. * Gets the root HTML element of an embedded view.
  1356. * If the root is not an HTML element it gets wrapped in one.
  1357. * @param {?} viewRef
  1358. * @param {?} _document
  1359. * @return {?}
  1360. */
  1361. function getRootNode(viewRef, _document) {
  1362. /** @type {?} */
  1363. const rootNode = viewRef.rootNodes[0];
  1364. if (rootNode.nodeType !== _document.ELEMENT_NODE) {
  1365. /** @type {?} */
  1366. const wrapper = _document.createElement('div');
  1367. wrapper.appendChild(rootNode);
  1368. return wrapper;
  1369. }
  1370. return (/** @type {?} */ (rootNode));
  1371. }
  1372. /**
  1373. * @fileoverview added by tsickle
  1374. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  1375. */
  1376. /**
  1377. * Moves an item one index in an array to another.
  1378. * @template T
  1379. * @param {?} array Array in which to move the item.
  1380. * @param {?} fromIndex Starting index of the item.
  1381. * @param {?} toIndex Index to which the item should be moved.
  1382. * @return {?}
  1383. */
  1384. function moveItemInArray(array, fromIndex, toIndex) {
  1385. /** @type {?} */
  1386. const from = clamp$1(fromIndex, array.length - 1);
  1387. /** @type {?} */
  1388. const to = clamp$1(toIndex, array.length - 1);
  1389. if (from === to) {
  1390. return;
  1391. }
  1392. /** @type {?} */
  1393. const target = array[from];
  1394. /** @type {?} */
  1395. const delta = to < from ? -1 : 1;
  1396. for (let i = from; i !== to; i += delta) {
  1397. array[i] = array[i + delta];
  1398. }
  1399. array[to] = target;
  1400. }
  1401. /**
  1402. * Moves an item from one array to another.
  1403. * @template T
  1404. * @param {?} currentArray Array from which to transfer the item.
  1405. * @param {?} targetArray Array into which to put the item.
  1406. * @param {?} currentIndex Index of the item in its current array.
  1407. * @param {?} targetIndex Index at which to insert the item.
  1408. * @return {?}
  1409. */
  1410. function transferArrayItem(currentArray, targetArray, currentIndex, targetIndex) {
  1411. /** @type {?} */
  1412. const from = clamp$1(currentIndex, currentArray.length - 1);
  1413. /** @type {?} */
  1414. const to = clamp$1(targetIndex, targetArray.length);
  1415. if (currentArray.length) {
  1416. targetArray.splice(to, 0, currentArray.splice(from, 1)[0]);
  1417. }
  1418. }
  1419. /**
  1420. * Copies an item from one array to another, leaving it in its
  1421. * original position in current array.
  1422. * @template T
  1423. * @param {?} currentArray Array from which to copy the item.
  1424. * @param {?} targetArray Array into which is copy the item.
  1425. * @param {?} currentIndex Index of the item in its current array.
  1426. * @param {?} targetIndex Index at which to insert the item.
  1427. *
  1428. * @return {?}
  1429. */
  1430. function copyArrayItem(currentArray, targetArray, currentIndex, targetIndex) {
  1431. /** @type {?} */
  1432. const to = clamp$1(targetIndex, targetArray.length);
  1433. if (currentArray.length) {
  1434. targetArray.splice(to, 0, currentArray[currentIndex]);
  1435. }
  1436. }
  1437. /**
  1438. * Clamps a number between zero and a maximum.
  1439. * @param {?} value
  1440. * @param {?} max
  1441. * @return {?}
  1442. */
  1443. function clamp$1(value, max) {
  1444. return Math.max(0, Math.min(max, value));
  1445. }
  1446. /**
  1447. * @fileoverview added by tsickle
  1448. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  1449. */
  1450. /**
  1451. * Counter used to generate unique ids for drop refs.
  1452. * @type {?}
  1453. */
  1454. let _uniqueIdCounter = 0;
  1455. /**
  1456. * Proximity, as a ratio to width/height, at which a
  1457. * dragged item will affect the drop container.
  1458. * @type {?}
  1459. */
  1460. const DROP_PROXIMITY_THRESHOLD = 0.05;
  1461. /**
  1462. * Proximity, as a ratio to width/height at which to start auto-scrolling the drop list or the
  1463. * viewport. The value comes from trying it out manually until it feels right.
  1464. * @type {?}
  1465. */
  1466. const SCROLL_PROXIMITY_THRESHOLD = 0.05;
  1467. /**
  1468. * Number of pixels to scroll for each frame when auto-scrolling an element.
  1469. * The value comes from trying it out manually until it feels right.
  1470. * @type {?}
  1471. */
  1472. const AUTO_SCROLL_STEP = 2;
  1473. /**
  1474. * Reference to a drop list. Used to manipulate or dispose of the container.
  1475. * \@docs-private
  1476. * @template T
  1477. */
  1478. class DropListRef {
  1479. /**
  1480. * @param {?} element
  1481. * @param {?} _dragDropRegistry
  1482. * @param {?} _document
  1483. * @param {?=} _ngZone
  1484. * @param {?=} _viewportRuler
  1485. */
  1486. constructor(element, _dragDropRegistry, _document, _ngZone, _viewportRuler) {
  1487. this._dragDropRegistry = _dragDropRegistry;
  1488. this._ngZone = _ngZone;
  1489. this._viewportRuler = _viewportRuler;
  1490. /**
  1491. * Unique ID for the drop list.
  1492. * @deprecated No longer being used. To be removed.
  1493. * \@breaking-change 8.0.0
  1494. */
  1495. this.id = `cdk-drop-list-ref-${_uniqueIdCounter++}`;
  1496. /**
  1497. * Whether starting a dragging sequence from this container is disabled.
  1498. */
  1499. this.disabled = false;
  1500. /**
  1501. * Whether sorting items within the list is disabled.
  1502. */
  1503. this.sortingDisabled = false;
  1504. /**
  1505. * Whether auto-scrolling the view when the user
  1506. * moves their pointer close to the edges is disabled.
  1507. */
  1508. this.autoScrollDisabled = false;
  1509. /**
  1510. * Function that is used to determine whether an item
  1511. * is allowed to be moved into a drop container.
  1512. */
  1513. this.enterPredicate = (/**
  1514. * @return {?}
  1515. */
  1516. () => true);
  1517. /**
  1518. * Emits right before dragging has started.
  1519. */
  1520. this.beforeStarted = new Subject();
  1521. /**
  1522. * Emits when the user has moved a new drag item into this container.
  1523. */
  1524. this.entered = new Subject();
  1525. /**
  1526. * Emits when the user removes an item from the container
  1527. * by dragging it into another container.
  1528. */
  1529. this.exited = new Subject();
  1530. /**
  1531. * Emits when the user drops an item inside the container.
  1532. */
  1533. this.dropped = new Subject();
  1534. /**
  1535. * Emits as the user is swapping items while actively dragging.
  1536. */
  1537. this.sorted = new Subject();
  1538. /**
  1539. * Whether an item in the list is being dragged.
  1540. */
  1541. this._isDragging = false;
  1542. /**
  1543. * Cache of the dimensions of all the items inside the container.
  1544. */
  1545. this._itemPositions = [];
  1546. /**
  1547. * Keeps track of the container's scroll position.
  1548. */
  1549. this._scrollPosition = { top: 0, left: 0 };
  1550. /**
  1551. * Keeps track of the scroll position of the viewport.
  1552. */
  1553. this._viewportScrollPosition = { top: 0, left: 0 };
  1554. /**
  1555. * Keeps track of the item that was last swapped with the dragged item, as
  1556. * well as what direction the pointer was moving in when the swap occured.
  1557. */
  1558. this._previousSwap = { drag: (/** @type {?} */ (null)), delta: 0 };
  1559. /**
  1560. * Drop lists that are connected to the current one.
  1561. */
  1562. this._siblings = [];
  1563. /**
  1564. * Direction in which the list is oriented.
  1565. */
  1566. this._orientation = 'vertical';
  1567. /**
  1568. * Connected siblings that currently have a dragged item.
  1569. */
  1570. this._activeSiblings = new Set();
  1571. /**
  1572. * Layout direction of the drop list.
  1573. */
  1574. this._direction = 'ltr';
  1575. /**
  1576. * Subscription to the window being scrolled.
  1577. */
  1578. this._viewportScrollSubscription = Subscription.EMPTY;
  1579. /**
  1580. * Vertical direction in which the list is currently scrolling.
  1581. */
  1582. this._verticalScrollDirection = 0 /* NONE */;
  1583. /**
  1584. * Horizontal direction in which the list is currently scrolling.
  1585. */
  1586. this._horizontalScrollDirection = 0 /* NONE */;
  1587. /**
  1588. * Used to signal to the current auto-scroll sequence when to stop.
  1589. */
  1590. this._stopScrollTimers = new Subject();
  1591. /**
  1592. * Handles the container being scrolled. Has to be an arrow function to preserve the context.
  1593. */
  1594. this._handleScroll = (/**
  1595. * @return {?}
  1596. */
  1597. () => {
  1598. if (!this.isDragging()) {
  1599. return;
  1600. }
  1601. /** @type {?} */
  1602. const element = coerceElement(this.element);
  1603. this._updateAfterScroll(this._scrollPosition, element.scrollTop, element.scrollLeft);
  1604. });
  1605. /**
  1606. * Starts the interval that'll auto-scroll the element.
  1607. */
  1608. this._startScrollInterval = (/**
  1609. * @return {?}
  1610. */
  1611. () => {
  1612. this._stopScrolling();
  1613. interval(0, animationFrameScheduler)
  1614. .pipe(takeUntil(this._stopScrollTimers))
  1615. .subscribe((/**
  1616. * @return {?}
  1617. */
  1618. () => {
  1619. /** @type {?} */
  1620. const node = this._scrollNode;
  1621. if (this._verticalScrollDirection === 1 /* UP */) {
  1622. incrementVerticalScroll(node, -AUTO_SCROLL_STEP);
  1623. }
  1624. else if (this._verticalScrollDirection === 2 /* DOWN */) {
  1625. incrementVerticalScroll(node, AUTO_SCROLL_STEP);
  1626. }
  1627. if (this._horizontalScrollDirection === 1 /* LEFT */) {
  1628. incrementHorizontalScroll(node, -AUTO_SCROLL_STEP);
  1629. }
  1630. else if (this._horizontalScrollDirection === 2 /* RIGHT */) {
  1631. incrementHorizontalScroll(node, AUTO_SCROLL_STEP);
  1632. }
  1633. }));
  1634. });
  1635. /** @type {?} */
  1636. const nativeNode = this.element = coerceElement(element);
  1637. this._shadowRoot = getShadowRoot(nativeNode) || _document;
  1638. _dragDropRegistry.registerDropContainer(this);
  1639. }
  1640. /**
  1641. * Removes the drop list functionality from the DOM element.
  1642. * @return {?}
  1643. */
  1644. dispose() {
  1645. this._stopScrolling();
  1646. this._stopScrollTimers.complete();
  1647. this._removeListeners();
  1648. this.beforeStarted.complete();
  1649. this.entered.complete();
  1650. this.exited.complete();
  1651. this.dropped.complete();
  1652. this.sorted.complete();
  1653. this._activeSiblings.clear();
  1654. this._scrollNode = (/** @type {?} */ (null));
  1655. this._dragDropRegistry.removeDropContainer(this);
  1656. }
  1657. /**
  1658. * Whether an item from this list is currently being dragged.
  1659. * @return {?}
  1660. */
  1661. isDragging() {
  1662. return this._isDragging;
  1663. }
  1664. /**
  1665. * Starts dragging an item.
  1666. * @return {?}
  1667. */
  1668. start() {
  1669. /** @type {?} */
  1670. const element = coerceElement(this.element);
  1671. this.beforeStarted.next();
  1672. this._isDragging = true;
  1673. this._cacheItems();
  1674. this._siblings.forEach((/**
  1675. * @param {?} sibling
  1676. * @return {?}
  1677. */
  1678. sibling => sibling._startReceiving(this)));
  1679. this._removeListeners();
  1680. // @breaking-change 9.0.0 Remove check for _ngZone once it's marked as a required param.
  1681. if (this._ngZone) {
  1682. this._ngZone.runOutsideAngular((/**
  1683. * @return {?}
  1684. */
  1685. () => element.addEventListener('scroll', this._handleScroll)));
  1686. }
  1687. else {
  1688. element.addEventListener('scroll', this._handleScroll);
  1689. }
  1690. // @breaking-change 9.0.0 Remove check for _viewportRuler once it's marked as a required param.
  1691. if (this._viewportRuler) {
  1692. this._listenToScrollEvents();
  1693. }
  1694. }
  1695. /**
  1696. * Emits an event to indicate that the user moved an item into the container.
  1697. * @param {?} item Item that was moved into the container.
  1698. * @param {?} pointerX Position of the item along the X axis.
  1699. * @param {?} pointerY Position of the item along the Y axis.
  1700. * @return {?}
  1701. */
  1702. enter(item, pointerX, pointerY) {
  1703. this.start();
  1704. // If sorting is disabled, we want the item to return to its starting
  1705. // position if the user is returning it to its initial container.
  1706. /** @type {?} */
  1707. let newIndex = this.sortingDisabled ? this._draggables.indexOf(item) : -1;
  1708. if (newIndex === -1) {
  1709. // We use the coordinates of where the item entered the drop
  1710. // zone to figure out at which index it should be inserted.
  1711. newIndex = this._getItemIndexFromPointerPosition(item, pointerX, pointerY);
  1712. }
  1713. /** @type {?} */
  1714. const activeDraggables = this._activeDraggables;
  1715. /** @type {?} */
  1716. const currentIndex = activeDraggables.indexOf(item);
  1717. /** @type {?} */
  1718. const placeholder = item.getPlaceholderElement();
  1719. /** @type {?} */
  1720. let newPositionReference = activeDraggables[newIndex];
  1721. // If the item at the new position is the same as the item that is being dragged,
  1722. // it means that we're trying to restore the item to its initial position. In this
  1723. // case we should use the next item from the list as the reference.
  1724. if (newPositionReference === item) {
  1725. newPositionReference = activeDraggables[newIndex + 1];
  1726. }
  1727. // Since the item may be in the `activeDraggables` already (e.g. if the user dragged it
  1728. // into another container and back again), we have to ensure that it isn't duplicated.
  1729. if (currentIndex > -1) {
  1730. activeDraggables.splice(currentIndex, 1);
  1731. }
  1732. // Don't use items that are being dragged as a reference, because
  1733. // their element has been moved down to the bottom of the body.
  1734. if (newPositionReference && !this._dragDropRegistry.isDragging(newPositionReference)) {
  1735. /** @type {?} */
  1736. const element = newPositionReference.getRootElement();
  1737. (/** @type {?} */ (element.parentElement)).insertBefore(placeholder, element);
  1738. activeDraggables.splice(newIndex, 0, item);
  1739. }
  1740. else {
  1741. coerceElement(this.element).appendChild(placeholder);
  1742. activeDraggables.push(item);
  1743. }
  1744. // The transform needs to be cleared so it doesn't throw off the measurements.
  1745. placeholder.style.transform = '';
  1746. // Note that the positions were already cached when we called `start` above,
  1747. // but we need to refresh them since the amount of items has changed.
  1748. this._cacheItemPositions();
  1749. this.entered.next({ item, container: this, currentIndex: this.getItemIndex(item) });
  1750. }
  1751. /**
  1752. * Removes an item from the container after it was dragged into another container by the user.
  1753. * @param {?} item Item that was dragged out.
  1754. * @return {?}
  1755. */
  1756. exit(item) {
  1757. this._reset();
  1758. this.exited.next({ item, container: this });
  1759. }
  1760. /**
  1761. * Drops an item into this container.
  1762. * \@breaking-change 9.0.0 `distance` parameter to become required.
  1763. * @param {?} item Item being dropped into the container.
  1764. * @param {?} currentIndex Index at which the item should be inserted.
  1765. * @param {?} previousContainer Container from which the item got dragged in.
  1766. * @param {?} isPointerOverContainer Whether the user's pointer was over the
  1767. * container when the item was dropped.
  1768. * @param {?=} distance Distance the user has dragged since the start of the dragging sequence.
  1769. * @return {?}
  1770. */
  1771. drop(item, currentIndex, previousContainer, isPointerOverContainer, distance = { x: 0, y: 0 }) {
  1772. this._reset();
  1773. this.dropped.next({
  1774. item,
  1775. currentIndex,
  1776. previousIndex: previousContainer.getItemIndex(item),
  1777. container: this,
  1778. previousContainer,
  1779. isPointerOverContainer,
  1780. distance
  1781. });
  1782. }
  1783. /**
  1784. * Sets the draggable items that are a part of this list.
  1785. * @template THIS
  1786. * @this {THIS}
  1787. * @param {?} items Items that are a part of this list.
  1788. * @return {THIS}
  1789. */
  1790. withItems(items) {
  1791. (/** @type {?} */ (this))._draggables = items;
  1792. items.forEach((/**
  1793. * @param {?} item
  1794. * @return {?}
  1795. */
  1796. item => item._withDropContainer((/** @type {?} */ (this)))));
  1797. if ((/** @type {?} */ (this)).isDragging()) {
  1798. (/** @type {?} */ (this))._cacheItems();
  1799. }
  1800. return (/** @type {?} */ (this));
  1801. }
  1802. /**
  1803. * Sets the layout direction of the drop list.
  1804. * @template THIS
  1805. * @this {THIS}
  1806. * @param {?} direction
  1807. * @return {THIS}
  1808. */
  1809. withDirection(direction) {
  1810. (/** @type {?} */ (this))._direction = direction;
  1811. return (/** @type {?} */ (this));
  1812. }
  1813. /**
  1814. * Sets the containers that are connected to this one. When two or more containers are
  1815. * connected, the user will be allowed to transfer items between them.
  1816. * @template THIS
  1817. * @this {THIS}
  1818. * @param {?} connectedTo Other containers that the current containers should be connected to.
  1819. * @return {THIS}
  1820. */
  1821. connectedTo(connectedTo) {
  1822. (/** @type {?} */ (this))._siblings = connectedTo.slice();
  1823. return (/** @type {?} */ (this));
  1824. }
  1825. /**
  1826. * Sets the orientation of the container.
  1827. * @template THIS
  1828. * @this {THIS}
  1829. * @param {?} orientation New orientation for the container.
  1830. * @return {THIS}
  1831. */
  1832. withOrientation(orientation) {
  1833. (/** @type {?} */ (this))._orientation = orientation;
  1834. return (/** @type {?} */ (this));
  1835. }
  1836. /**
  1837. * Figures out the index of an item in the container.
  1838. * @param {?} item Item whose index should be determined.
  1839. * @return {?}
  1840. */
  1841. getItemIndex(item) {
  1842. if (!this._isDragging) {
  1843. return this._draggables.indexOf(item);
  1844. }
  1845. // Items are sorted always by top/left in the cache, however they flow differently in RTL.
  1846. // The rest of the logic still stands no matter what orientation we're in, however
  1847. // we need to invert the array when determining the index.
  1848. /** @type {?} */
  1849. const items = this._orientation === 'horizontal' && this._direction === 'rtl' ?
  1850. this._itemPositions.slice().reverse() : this._itemPositions;
  1851. return findIndex(items, (/**
  1852. * @param {?} currentItem
  1853. * @return {?}
  1854. */
  1855. currentItem => currentItem.drag === item));
  1856. }
  1857. /**
  1858. * Whether the list is able to receive the item that
  1859. * is currently being dragged inside a connected drop list.
  1860. * @return {?}
  1861. */
  1862. isReceiving() {
  1863. return this._activeSiblings.size > 0;
  1864. }
  1865. /**
  1866. * Sorts an item inside the container based on its position.
  1867. * @param {?} item Item to be sorted.
  1868. * @param {?} pointerX Position of the item along the X axis.
  1869. * @param {?} pointerY Position of the item along the Y axis.
  1870. * @param {?} pointerDelta Direction in which the pointer is moving along each axis.
  1871. * @return {?}
  1872. */
  1873. _sortItem(item, pointerX, pointerY, pointerDelta) {
  1874. // Don't sort the item if sorting is disabled or it's out of range.
  1875. if (this.sortingDisabled || !this._isPointerNearDropContainer(pointerX, pointerY)) {
  1876. return;
  1877. }
  1878. /** @type {?} */
  1879. const siblings = this._itemPositions;
  1880. /** @type {?} */
  1881. const newIndex = this._getItemIndexFromPointerPosition(item, pointerX, pointerY, pointerDelta);
  1882. if (newIndex === -1 && siblings.length > 0) {
  1883. return;
  1884. }
  1885. /** @type {?} */
  1886. const isHorizontal = this._orientation === 'horizontal';
  1887. /** @type {?} */
  1888. const currentIndex = findIndex(siblings, (/**
  1889. * @param {?} currentItem
  1890. * @return {?}
  1891. */
  1892. currentItem => currentItem.drag === item));
  1893. /** @type {?} */
  1894. const siblingAtNewPosition = siblings[newIndex];
  1895. /** @type {?} */
  1896. const currentPosition = siblings[currentIndex].clientRect;
  1897. /** @type {?} */
  1898. const newPosition = siblingAtNewPosition.clientRect;
  1899. /** @type {?} */
  1900. const delta = currentIndex > newIndex ? 1 : -1;
  1901. this._previousSwap.drag = siblingAtNewPosition.drag;
  1902. this._previousSwap.delta = isHorizontal ? pointerDelta.x : pointerDelta.y;
  1903. // How many pixels the item's placeholder should be offset.
  1904. /** @type {?} */
  1905. const itemOffset = this._getItemOffsetPx(currentPosition, newPosition, delta);
  1906. // How many pixels all the other items should be offset.
  1907. /** @type {?} */
  1908. const siblingOffset = this._getSiblingOffsetPx(currentIndex, siblings, delta);
  1909. // Save the previous order of the items before moving the item to its new index.
  1910. // We use this to check whether an item has been moved as a result of the sorting.
  1911. /** @type {?} */
  1912. const oldOrder = siblings.slice();
  1913. // Shuffle the array in place.
  1914. moveItemInArray(siblings, currentIndex, newIndex);
  1915. this.sorted.next({
  1916. previousIndex: currentIndex,
  1917. currentIndex: newIndex,
  1918. container: this,
  1919. item
  1920. });
  1921. siblings.forEach((/**
  1922. * @param {?} sibling
  1923. * @param {?} index
  1924. * @return {?}
  1925. */
  1926. (sibling, index) => {
  1927. // Don't do anything if the position hasn't changed.
  1928. if (oldOrder[index] === sibling) {
  1929. return;
  1930. }
  1931. /** @type {?} */
  1932. const isDraggedItem = sibling.drag === item;
  1933. /** @type {?} */
  1934. const offset = isDraggedItem ? itemOffset : siblingOffset;
  1935. /** @type {?} */
  1936. const elementToOffset = isDraggedItem ? item.getPlaceholderElement() :
  1937. sibling.drag.getRootElement();
  1938. // Update the offset to reflect the new position.
  1939. sibling.offset += offset;
  1940. // Since we're moving the items with a `transform`, we need to adjust their cached
  1941. // client rects to reflect their new position, as well as swap their positions in the cache.
  1942. // Note that we shouldn't use `getBoundingClientRect` here to update the cache, because the
  1943. // elements may be mid-animation which will give us a wrong result.
  1944. if (isHorizontal) {
  1945. // Round the transforms since some browsers will
  1946. // blur the elements, for sub-pixel transforms.
  1947. elementToOffset.style.transform = `translate3d(${Math.round(sibling.offset)}px, 0, 0)`;
  1948. adjustClientRect(sibling.clientRect, 0, offset);
  1949. }
  1950. else {
  1951. elementToOffset.style.transform = `translate3d(0, ${Math.round(sibling.offset)}px, 0)`;
  1952. adjustClientRect(sibling.clientRect, offset, 0);
  1953. }
  1954. }));
  1955. }
  1956. /**
  1957. * Checks whether the user's pointer is close to the edges of either the
  1958. * viewport or the drop list and starts the auto-scroll sequence.
  1959. * @param {?} pointerX User's pointer position along the x axis.
  1960. * @param {?} pointerY User's pointer position along the y axis.
  1961. * @return {?}
  1962. */
  1963. _startScrollingIfNecessary(pointerX, pointerY) {
  1964. if (this.autoScrollDisabled) {
  1965. return;
  1966. }
  1967. /** @type {?} */
  1968. let scrollNode;
  1969. /** @type {?} */
  1970. let verticalScrollDirection = 0 /* NONE */;
  1971. /** @type {?} */
  1972. let horizontalScrollDirection = 0 /* NONE */;
  1973. // Check whether we should start scrolling the container.
  1974. if (this._isPointerNearDropContainer(pointerX, pointerY)) {
  1975. /** @type {?} */
  1976. const element = coerceElement(this.element);
  1977. [verticalScrollDirection, horizontalScrollDirection] =
  1978. getElementScrollDirections(element, this._clientRect, pointerX, pointerY);
  1979. if (verticalScrollDirection || horizontalScrollDirection) {
  1980. scrollNode = element;
  1981. }
  1982. }
  1983. // @breaking-change 9.0.0 Remove null check for _viewportRuler once it's a required parameter.
  1984. // Otherwise check if we can start scrolling the viewport.
  1985. if (this._viewportRuler && !verticalScrollDirection && !horizontalScrollDirection) {
  1986. const { width, height } = this._viewportRuler.getViewportSize();
  1987. /** @type {?} */
  1988. const clientRect = { width, height, top: 0, right: width, bottom: height, left: 0 };
  1989. verticalScrollDirection = getVerticalScrollDirection(clientRect, pointerY);
  1990. horizontalScrollDirection = getHorizontalScrollDirection(clientRect, pointerX);
  1991. scrollNode = window;
  1992. }
  1993. if (scrollNode && (verticalScrollDirection !== this._verticalScrollDirection ||
  1994. horizontalScrollDirection !== this._horizontalScrollDirection ||
  1995. scrollNode !== this._scrollNode)) {
  1996. this._verticalScrollDirection = verticalScrollDirection;
  1997. this._horizontalScrollDirection = horizontalScrollDirection;
  1998. this._scrollNode = scrollNode;
  1999. if ((verticalScrollDirection || horizontalScrollDirection) && scrollNode) {
  2000. // @breaking-change 9.0.0 Remove null check for `_ngZone` once it is made required.
  2001. if (this._ngZone) {
  2002. this._ngZone.runOutsideAngular(this._startScrollInterval);
  2003. }
  2004. else {
  2005. this._startScrollInterval();
  2006. }
  2007. }
  2008. else {
  2009. this._stopScrolling();
  2010. }
  2011. }
  2012. }
  2013. /**
  2014. * Stops any currently-running auto-scroll sequences.
  2015. * @return {?}
  2016. */
  2017. _stopScrolling() {
  2018. this._stopScrollTimers.next();
  2019. }
  2020. /**
  2021. * Caches the position of the drop list.
  2022. * @private
  2023. * @return {?}
  2024. */
  2025. _cacheOwnPosition() {
  2026. /** @type {?} */
  2027. const element = coerceElement(this.element);
  2028. this._clientRect = getMutableClientRect(element);
  2029. this._scrollPosition = { top: element.scrollTop, left: element.scrollLeft };
  2030. }
  2031. /**
  2032. * Refreshes the position cache of the items and sibling containers.
  2033. * @private
  2034. * @return {?}
  2035. */
  2036. _cacheItemPositions() {
  2037. /** @type {?} */
  2038. const isHorizontal = this._orientation === 'horizontal';
  2039. this._itemPositions = this._activeDraggables.map((/**
  2040. * @param {?} drag
  2041. * @return {?}
  2042. */
  2043. drag => {
  2044. /** @type {?} */
  2045. const elementToMeasure = this._dragDropRegistry.isDragging(drag) ?
  2046. // If the element is being dragged, we have to measure the
  2047. // placeholder, because the element is hidden.
  2048. drag.getPlaceholderElement() :
  2049. drag.getRootElement();
  2050. return { drag, offset: 0, clientRect: getMutableClientRect(elementToMeasure) };
  2051. })).sort((/**
  2052. * @param {?} a
  2053. * @param {?} b
  2054. * @return {?}
  2055. */
  2056. (a, b) => {
  2057. return isHorizontal ? a.clientRect.left - b.clientRect.left :
  2058. a.clientRect.top - b.clientRect.top;
  2059. }));
  2060. }
  2061. /**
  2062. * Resets the container to its initial state.
  2063. * @private
  2064. * @return {?}
  2065. */
  2066. _reset() {
  2067. this._isDragging = false;
  2068. // TODO(crisbeto): may have to wait for the animations to finish.
  2069. this._activeDraggables.forEach((/**
  2070. * @param {?} item
  2071. * @return {?}
  2072. */
  2073. item => item.getRootElement().style.transform = ''));
  2074. this._siblings.forEach((/**
  2075. * @param {?} sibling
  2076. * @return {?}
  2077. */
  2078. sibling => sibling._stopReceiving(this)));
  2079. this._activeDraggables = [];
  2080. this._itemPositions = [];
  2081. this._previousSwap.drag = null;
  2082. this._previousSwap.delta = 0;
  2083. this._stopScrolling();
  2084. this._removeListeners();
  2085. }
  2086. /**
  2087. * Gets the offset in pixels by which the items that aren't being dragged should be moved.
  2088. * @private
  2089. * @param {?} currentIndex Index of the item currently being dragged.
  2090. * @param {?} siblings All of the items in the list.
  2091. * @param {?} delta Direction in which the user is moving.
  2092. * @return {?}
  2093. */
  2094. _getSiblingOffsetPx(currentIndex, siblings, delta) {
  2095. /** @type {?} */
  2096. const isHorizontal = this._orientation === 'horizontal';
  2097. /** @type {?} */
  2098. const currentPosition = siblings[currentIndex].clientRect;
  2099. /** @type {?} */
  2100. const immediateSibling = siblings[currentIndex + delta * -1];
  2101. /** @type {?} */
  2102. let siblingOffset = currentPosition[isHorizontal ? 'width' : 'height'] * delta;
  2103. if (immediateSibling) {
  2104. /** @type {?} */
  2105. const start = isHorizontal ? 'left' : 'top';
  2106. /** @type {?} */
  2107. const end = isHorizontal ? 'right' : 'bottom';
  2108. // Get the spacing between the start of the current item and the end of the one immediately
  2109. // after it in the direction in which the user is dragging, or vice versa. We add it to the
  2110. // offset in order to push the element to where it will be when it's inline and is influenced
  2111. // by the `margin` of its siblings.
  2112. if (delta === -1) {
  2113. siblingOffset -= immediateSibling.clientRect[start] - currentPosition[end];
  2114. }
  2115. else {
  2116. siblingOffset += currentPosition[start] - immediateSibling.clientRect[end];
  2117. }
  2118. }
  2119. return siblingOffset;
  2120. }
  2121. /**
  2122. * Checks whether the pointer coordinates are close to the drop container.
  2123. * @private
  2124. * @param {?} pointerX Coordinates along the X axis.
  2125. * @param {?} pointerY Coordinates along the Y axis.
  2126. * @return {?}
  2127. */
  2128. _isPointerNearDropContainer(pointerX, pointerY) {
  2129. const { top, right, bottom, left, width, height } = this._clientRect;
  2130. /** @type {?} */
  2131. const xThreshold = width * DROP_PROXIMITY_THRESHOLD;
  2132. /** @type {?} */
  2133. const yThreshold = height * DROP_PROXIMITY_THRESHOLD;
  2134. return pointerY > top - yThreshold && pointerY < bottom + yThreshold &&
  2135. pointerX > left - xThreshold && pointerX < right + xThreshold;
  2136. }
  2137. /**
  2138. * Gets the offset in pixels by which the item that is being dragged should be moved.
  2139. * @private
  2140. * @param {?} currentPosition Current position of the item.
  2141. * @param {?} newPosition Position of the item where the current item should be moved.
  2142. * @param {?} delta Direction in which the user is moving.
  2143. * @return {?}
  2144. */
  2145. _getItemOffsetPx(currentPosition, newPosition, delta) {
  2146. /** @type {?} */
  2147. const isHorizontal = this._orientation === 'horizontal';
  2148. /** @type {?} */
  2149. let itemOffset = isHorizontal ? newPosition.left - currentPosition.left :
  2150. newPosition.top - currentPosition.top;
  2151. // Account for differences in the item width/height.
  2152. if (delta === -1) {
  2153. itemOffset += isHorizontal ? newPosition.width - currentPosition.width :
  2154. newPosition.height - currentPosition.height;
  2155. }
  2156. return itemOffset;
  2157. }
  2158. /**
  2159. * Gets the index of an item in the drop container, based on the position of the user's pointer.
  2160. * @private
  2161. * @param {?} item Item that is being sorted.
  2162. * @param {?} pointerX Position of the user's pointer along the X axis.
  2163. * @param {?} pointerY Position of the user's pointer along the Y axis.
  2164. * @param {?=} delta Direction in which the user is moving their pointer.
  2165. * @return {?}
  2166. */
  2167. _getItemIndexFromPointerPosition(item, pointerX, pointerY, delta) {
  2168. /** @type {?} */
  2169. const isHorizontal = this._orientation === 'horizontal';
  2170. return findIndex(this._itemPositions, (/**
  2171. * @param {?} __0
  2172. * @param {?} _
  2173. * @param {?} array
  2174. * @return {?}
  2175. */
  2176. ({ drag, clientRect }, _, array) => {
  2177. if (drag === item) {
  2178. // If there's only one item left in the container, it must be
  2179. // the dragged item itself so we use it as a reference.
  2180. return array.length < 2;
  2181. }
  2182. if (delta) {
  2183. /** @type {?} */
  2184. const direction = isHorizontal ? delta.x : delta.y;
  2185. // If the user is still hovering over the same item as last time, and they didn't change
  2186. // the direction in which they're dragging, we don't consider it a direction swap.
  2187. if (drag === this._previousSwap.drag && direction === this._previousSwap.delta) {
  2188. return false;
  2189. }
  2190. }
  2191. return isHorizontal ?
  2192. // Round these down since most browsers report client rects with
  2193. // sub-pixel precision, whereas the pointer coordinates are rounded to pixels.
  2194. pointerX >= Math.floor(clientRect.left) && pointerX <= Math.floor(clientRect.right) :
  2195. pointerY >= Math.floor(clientRect.top) && pointerY <= Math.floor(clientRect.bottom);
  2196. }));
  2197. }
  2198. /**
  2199. * Caches the current items in the list and their positions.
  2200. * @private
  2201. * @return {?}
  2202. */
  2203. _cacheItems() {
  2204. this._activeDraggables = this._draggables.slice();
  2205. this._cacheItemPositions();
  2206. this._cacheOwnPosition();
  2207. }
  2208. /**
  2209. * Updates the internal state of the container after a scroll event has happened.
  2210. * @private
  2211. * @param {?} scrollPosition Object that is keeping track of the scroll position.
  2212. * @param {?} newTop New top scroll position.
  2213. * @param {?} newLeft New left scroll position.
  2214. * @param {?=} extraClientRect Extra `ClientRect` object that should be updated, in addition to the
  2215. * ones of the drag items. Useful when the viewport has been scrolled and we also need to update
  2216. * the `ClientRect` of the list.
  2217. * @return {?}
  2218. */
  2219. _updateAfterScroll(scrollPosition, newTop, newLeft, extraClientRect) {
  2220. /** @type {?} */
  2221. const topDifference = scrollPosition.top - newTop;
  2222. /** @type {?} */
  2223. const leftDifference = scrollPosition.left - newLeft;
  2224. if (extraClientRect) {
  2225. adjustClientRect(extraClientRect, topDifference, leftDifference);
  2226. }
  2227. // Since we know the amount that the user has scrolled we can shift all of the client rectangles
  2228. // ourselves. This is cheaper than re-measuring everything and we can avoid inconsistent
  2229. // behavior where we might be measuring the element before its position has changed.
  2230. this._itemPositions.forEach((/**
  2231. * @param {?} __0
  2232. * @return {?}
  2233. */
  2234. ({ clientRect }) => {
  2235. adjustClientRect(clientRect, topDifference, leftDifference);
  2236. }));
  2237. // We need two loops for this, because we want all of the cached
  2238. // positions to be up-to-date before we re-sort the item.
  2239. this._itemPositions.forEach((/**
  2240. * @param {?} __0
  2241. * @return {?}
  2242. */
  2243. ({ drag }) => {
  2244. if (this._dragDropRegistry.isDragging(drag)) {
  2245. // We need to re-sort the item manually, because the pointer move
  2246. // events won't be dispatched while the user is scrolling.
  2247. drag._sortFromLastPointerPosition();
  2248. }
  2249. }));
  2250. scrollPosition.top = newTop;
  2251. scrollPosition.left = newLeft;
  2252. }
  2253. /**
  2254. * Removes the event listeners associated with this drop list.
  2255. * @private
  2256. * @return {?}
  2257. */
  2258. _removeListeners() {
  2259. coerceElement(this.element).removeEventListener('scroll', this._handleScroll);
  2260. this._viewportScrollSubscription.unsubscribe();
  2261. }
  2262. /**
  2263. * Checks whether the user's pointer is positioned over the container.
  2264. * @param {?} x Pointer position along the X axis.
  2265. * @param {?} y Pointer position along the Y axis.
  2266. * @return {?}
  2267. */
  2268. _isOverContainer(x, y) {
  2269. return isInsideClientRect(this._clientRect, x, y);
  2270. }
  2271. /**
  2272. * Figures out whether an item should be moved into a sibling
  2273. * drop container, based on its current position.
  2274. * @param {?} item Drag item that is being moved.
  2275. * @param {?} x Position of the item along the X axis.
  2276. * @param {?} y Position of the item along the Y axis.
  2277. * @return {?}
  2278. */
  2279. _getSiblingContainerFromPosition(item, x, y) {
  2280. return this._siblings.find((/**
  2281. * @param {?} sibling
  2282. * @return {?}
  2283. */
  2284. sibling => sibling._canReceive(item, x, y)));
  2285. }
  2286. /**
  2287. * Checks whether the drop list can receive the passed-in item.
  2288. * @param {?} item Item that is being dragged into the list.
  2289. * @param {?} x Position of the item along the X axis.
  2290. * @param {?} y Position of the item along the Y axis.
  2291. * @return {?}
  2292. */
  2293. _canReceive(item, x, y) {
  2294. if (!this.enterPredicate(item, this) || !isInsideClientRect(this._clientRect, x, y)) {
  2295. return false;
  2296. }
  2297. /** @type {?} */
  2298. const elementFromPoint = (/** @type {?} */ (this._shadowRoot.elementFromPoint(x, y)));
  2299. // If there's no element at the pointer position, then
  2300. // the client rect is probably scrolled out of the view.
  2301. if (!elementFromPoint) {
  2302. return false;
  2303. }
  2304. /** @type {?} */
  2305. const nativeElement = coerceElement(this.element);
  2306. // The `ClientRect`, that we're using to find the container over which the user is
  2307. // hovering, doesn't give us any information on whether the element has been scrolled
  2308. // out of the view or whether it's overlapping with other containers. This means that
  2309. // we could end up transferring the item into a container that's invisible or is positioned
  2310. // below another one. We use the result from `elementFromPoint` to get the top-most element
  2311. // at the pointer position and to find whether it's one of the intersecting drop containers.
  2312. return elementFromPoint === nativeElement || nativeElement.contains(elementFromPoint);
  2313. }
  2314. /**
  2315. * Called by one of the connected drop lists when a dragging sequence has started.
  2316. * @param {?} sibling Sibling in which dragging has started.
  2317. * @return {?}
  2318. */
  2319. _startReceiving(sibling) {
  2320. /** @type {?} */
  2321. const activeSiblings = this._activeSiblings;
  2322. if (!activeSiblings.has(sibling)) {
  2323. activeSiblings.add(sibling);
  2324. this._cacheOwnPosition();
  2325. this._listenToScrollEvents();
  2326. }
  2327. }
  2328. /**
  2329. * Called by a connected drop list when dragging has stopped.
  2330. * @param {?} sibling Sibling whose dragging has stopped.
  2331. * @return {?}
  2332. */
  2333. _stopReceiving(sibling) {
  2334. this._activeSiblings.delete(sibling);
  2335. this._viewportScrollSubscription.unsubscribe();
  2336. }
  2337. /**
  2338. * Starts listening to scroll events on the viewport.
  2339. * Used for updating the internal state of the list.
  2340. * @private
  2341. * @return {?}
  2342. */
  2343. _listenToScrollEvents() {
  2344. this._viewportScrollPosition = (/** @type {?} */ (this._viewportRuler)).getViewportScrollPosition();
  2345. this._viewportScrollSubscription = this._dragDropRegistry.scroll.subscribe((/**
  2346. * @return {?}
  2347. */
  2348. () => {
  2349. if (this.isDragging()) {
  2350. /** @type {?} */
  2351. const newPosition = (/** @type {?} */ (this._viewportRuler)).getViewportScrollPosition();
  2352. this._updateAfterScroll(this._viewportScrollPosition, newPosition.top, newPosition.left, this._clientRect);
  2353. }
  2354. else if (this.isReceiving()) {
  2355. this._cacheOwnPosition();
  2356. }
  2357. }));
  2358. }
  2359. }
  2360. /**
  2361. * Updates the top/left positions of a `ClientRect`, as well as their bottom/right counterparts.
  2362. * @param {?} clientRect `ClientRect` that should be updated.
  2363. * @param {?} top Amount to add to the `top` position.
  2364. * @param {?} left Amount to add to the `left` position.
  2365. * @return {?}
  2366. */
  2367. function adjustClientRect(clientRect, top, left) {
  2368. clientRect.top += top;
  2369. clientRect.bottom = clientRect.top + clientRect.height;
  2370. clientRect.left += left;
  2371. clientRect.right = clientRect.left + clientRect.width;
  2372. }
  2373. /**
  2374. * Finds the index of an item that matches a predicate function. Used as an equivalent
  2375. * of `Array.prototype.findIndex` which isn't part of the standard Google typings.
  2376. * @template T
  2377. * @param {?} array Array in which to look for matches.
  2378. * @param {?} predicate Function used to determine whether an item is a match.
  2379. * @return {?}
  2380. */
  2381. function findIndex(array, predicate) {
  2382. for (let i = 0; i < array.length; i++) {
  2383. if (predicate(array[i], i, array)) {
  2384. return i;
  2385. }
  2386. }
  2387. return -1;
  2388. }
  2389. /**
  2390. * Checks whether some coordinates are within a `ClientRect`.
  2391. * @param {?} clientRect ClientRect that is being checked.
  2392. * @param {?} x Coordinates along the X axis.
  2393. * @param {?} y Coordinates along the Y axis.
  2394. * @return {?}
  2395. */
  2396. function isInsideClientRect(clientRect, x, y) {
  2397. const { top, bottom, left, right } = clientRect;
  2398. return y >= top && y <= bottom && x >= left && x <= right;
  2399. }
  2400. /**
  2401. * Gets a mutable version of an element's bounding `ClientRect`.
  2402. * @param {?} element
  2403. * @return {?}
  2404. */
  2405. function getMutableClientRect(element) {
  2406. /** @type {?} */
  2407. const clientRect = element.getBoundingClientRect();
  2408. // We need to clone the `clientRect` here, because all the values on it are readonly
  2409. // and we need to be able to update them. Also we can't use a spread here, because
  2410. // the values on a `ClientRect` aren't own properties. See:
  2411. // https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect#Notes
  2412. return {
  2413. top: clientRect.top,
  2414. right: clientRect.right,
  2415. bottom: clientRect.bottom,
  2416. left: clientRect.left,
  2417. width: clientRect.width,
  2418. height: clientRect.height
  2419. };
  2420. }
  2421. /**
  2422. * Increments the vertical scroll position of a node.
  2423. * @param {?} node Node whose scroll position should change.
  2424. * @param {?} amount Amount of pixels that the `node` should be scrolled.
  2425. * @return {?}
  2426. */
  2427. function incrementVerticalScroll(node, amount) {
  2428. if (node === window) {
  2429. ((/** @type {?} */ (node))).scrollBy(0, amount);
  2430. }
  2431. else {
  2432. // Ideally we could use `Element.scrollBy` here as well, but IE and Edge don't support it.
  2433. ((/** @type {?} */ (node))).scrollTop += amount;
  2434. }
  2435. }
  2436. /**
  2437. * Increments the horizontal scroll position of a node.
  2438. * @param {?} node Node whose scroll position should change.
  2439. * @param {?} amount Amount of pixels that the `node` should be scrolled.
  2440. * @return {?}
  2441. */
  2442. function incrementHorizontalScroll(node, amount) {
  2443. if (node === window) {
  2444. ((/** @type {?} */ (node))).scrollBy(amount, 0);
  2445. }
  2446. else {
  2447. // Ideally we could use `Element.scrollBy` here as well, but IE and Edge don't support it.
  2448. ((/** @type {?} */ (node))).scrollLeft += amount;
  2449. }
  2450. }
  2451. /**
  2452. * Gets whether the vertical auto-scroll direction of a node.
  2453. * @param {?} clientRect Dimensions of the node.
  2454. * @param {?} pointerY Position of the user's pointer along the y axis.
  2455. * @return {?}
  2456. */
  2457. function getVerticalScrollDirection(clientRect, pointerY) {
  2458. const { top, bottom, height } = clientRect;
  2459. /** @type {?} */
  2460. const yThreshold = height * SCROLL_PROXIMITY_THRESHOLD;
  2461. if (pointerY >= top - yThreshold && pointerY <= top + yThreshold) {
  2462. return 1 /* UP */;
  2463. }
  2464. else if (pointerY >= bottom - yThreshold && pointerY <= bottom + yThreshold) {
  2465. return 2 /* DOWN */;
  2466. }
  2467. return 0 /* NONE */;
  2468. }
  2469. /**
  2470. * Gets whether the horizontal auto-scroll direction of a node.
  2471. * @param {?} clientRect Dimensions of the node.
  2472. * @param {?} pointerX Position of the user's pointer along the x axis.
  2473. * @return {?}
  2474. */
  2475. function getHorizontalScrollDirection(clientRect, pointerX) {
  2476. const { left, right, width } = clientRect;
  2477. /** @type {?} */
  2478. const xThreshold = width * SCROLL_PROXIMITY_THRESHOLD;
  2479. if (pointerX >= left - xThreshold && pointerX <= left + xThreshold) {
  2480. return 1 /* LEFT */;
  2481. }
  2482. else if (pointerX >= right - xThreshold && pointerX <= right + xThreshold) {
  2483. return 2 /* RIGHT */;
  2484. }
  2485. return 0 /* NONE */;
  2486. }
  2487. /**
  2488. * Gets the directions in which an element node should be scrolled,
  2489. * assuming that the user's pointer is already within it scrollable region.
  2490. * @param {?} element Element for which we should calculate the scroll direction.
  2491. * @param {?} clientRect Bounding client rectangle of the element.
  2492. * @param {?} pointerX Position of the user's pointer along the x axis.
  2493. * @param {?} pointerY Position of the user's pointer along the y axis.
  2494. * @return {?}
  2495. */
  2496. function getElementScrollDirections(element, clientRect, pointerX, pointerY) {
  2497. /** @type {?} */
  2498. const computedVertical = getVerticalScrollDirection(clientRect, pointerY);
  2499. /** @type {?} */
  2500. const computedHorizontal = getHorizontalScrollDirection(clientRect, pointerX);
  2501. /** @type {?} */
  2502. let verticalScrollDirection = 0 /* NONE */;
  2503. /** @type {?} */
  2504. let horizontalScrollDirection = 0 /* NONE */;
  2505. // Note that we here we do some extra checks for whether the element is actually scrollable in
  2506. // a certain direction and we only assign the scroll direction if it is. We do this so that we
  2507. // can allow other elements to be scrolled, if the current element can't be scrolled anymore.
  2508. // This allows us to handle cases where the scroll regions of two scrollable elements overlap.
  2509. if (computedVertical) {
  2510. /** @type {?} */
  2511. const scrollTop = element.scrollTop;
  2512. if (computedVertical === 1 /* UP */) {
  2513. if (scrollTop > 0) {
  2514. verticalScrollDirection = 1 /* UP */;
  2515. }
  2516. }
  2517. else if (element.scrollHeight - scrollTop > element.clientHeight) {
  2518. verticalScrollDirection = 2 /* DOWN */;
  2519. }
  2520. }
  2521. if (computedHorizontal) {
  2522. /** @type {?} */
  2523. const scrollLeft = element.scrollLeft;
  2524. if (computedHorizontal === 1 /* LEFT */) {
  2525. if (scrollLeft > 0) {
  2526. horizontalScrollDirection = 1 /* LEFT */;
  2527. }
  2528. }
  2529. else if (element.scrollWidth - scrollLeft > element.clientWidth) {
  2530. horizontalScrollDirection = 2 /* RIGHT */;
  2531. }
  2532. }
  2533. return [verticalScrollDirection, horizontalScrollDirection];
  2534. }
  2535. /**
  2536. * Gets the shadow root of an element, if any.
  2537. * @param {?} element
  2538. * @return {?}
  2539. */
  2540. function getShadowRoot(element) {
  2541. if (_supportsShadowDom()) {
  2542. /** @type {?} */
  2543. const rootNode = element.getRootNode ? element.getRootNode() : null;
  2544. if (rootNode instanceof ShadowRoot) {
  2545. return rootNode;
  2546. }
  2547. }
  2548. return null;
  2549. }
  2550. /**
  2551. * @fileoverview added by tsickle
  2552. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  2553. */
  2554. /**
  2555. * Event options that can be used to bind an active, capturing event.
  2556. * @type {?}
  2557. */
  2558. const activeCapturingEventOptions = normalizePassiveListenerOptions({
  2559. passive: false,
  2560. capture: true
  2561. });
  2562. /**
  2563. * Service that keeps track of all the drag item and drop container
  2564. * instances, and manages global event listeners on the `document`.
  2565. * \@docs-private
  2566. * @template I, C
  2567. */
  2568. // Note: this class is generic, rather than referencing CdkDrag and CdkDropList directly, in order
  2569. // to avoid circular imports. If we were to reference them here, importing the registry into the
  2570. // classes that are registering themselves will introduce a circular import.
  2571. class DragDropRegistry {
  2572. /**
  2573. * @param {?} _ngZone
  2574. * @param {?} _document
  2575. */
  2576. constructor(_ngZone, _document) {
  2577. this._ngZone = _ngZone;
  2578. /**
  2579. * Registered drop container instances.
  2580. */
  2581. this._dropInstances = new Set();
  2582. /**
  2583. * Registered drag item instances.
  2584. */
  2585. this._dragInstances = new Set();
  2586. /**
  2587. * Drag item instances that are currently being dragged.
  2588. */
  2589. this._activeDragInstances = new Set();
  2590. /**
  2591. * Keeps track of the event listeners that we've bound to the `document`.
  2592. */
  2593. this._globalListeners = new Map();
  2594. /**
  2595. * Emits the `touchmove` or `mousemove` events that are dispatched
  2596. * while the user is dragging a drag item instance.
  2597. */
  2598. this.pointerMove = new Subject();
  2599. /**
  2600. * Emits the `touchend` or `mouseup` events that are dispatched
  2601. * while the user is dragging a drag item instance.
  2602. */
  2603. this.pointerUp = new Subject();
  2604. /**
  2605. * Emits when the viewport has been scrolled while the user is dragging an item.
  2606. */
  2607. this.scroll = new Subject();
  2608. /**
  2609. * Event listener that will prevent the default browser action while the user is dragging.
  2610. * @param event Event whose default action should be prevented.
  2611. */
  2612. this._preventDefaultWhileDragging = (/**
  2613. * @param {?} event
  2614. * @return {?}
  2615. */
  2616. (event) => {
  2617. if (this._activeDragInstances.size) {
  2618. event.preventDefault();
  2619. }
  2620. });
  2621. this._document = _document;
  2622. }
  2623. /**
  2624. * Adds a drop container to the registry.
  2625. * @param {?} drop
  2626. * @return {?}
  2627. */
  2628. registerDropContainer(drop) {
  2629. if (!this._dropInstances.has(drop)) {
  2630. if (this.getDropContainer(drop.id)) {
  2631. throw Error(`Drop instance with id "${drop.id}" has already been registered.`);
  2632. }
  2633. this._dropInstances.add(drop);
  2634. }
  2635. }
  2636. /**
  2637. * Adds a drag item instance to the registry.
  2638. * @param {?} drag
  2639. * @return {?}
  2640. */
  2641. registerDragItem(drag) {
  2642. this._dragInstances.add(drag);
  2643. // The `touchmove` event gets bound once, ahead of time, because WebKit
  2644. // won't preventDefault on a dynamically-added `touchmove` listener.
  2645. // See https://bugs.webkit.org/show_bug.cgi?id=184250.
  2646. if (this._dragInstances.size === 1) {
  2647. this._ngZone.runOutsideAngular((/**
  2648. * @return {?}
  2649. */
  2650. () => {
  2651. // The event handler has to be explicitly active,
  2652. // because newer browsers make it passive by default.
  2653. this._document.addEventListener('touchmove', this._preventDefaultWhileDragging, activeCapturingEventOptions);
  2654. }));
  2655. }
  2656. }
  2657. /**
  2658. * Removes a drop container from the registry.
  2659. * @param {?} drop
  2660. * @return {?}
  2661. */
  2662. removeDropContainer(drop) {
  2663. this._dropInstances.delete(drop);
  2664. }
  2665. /**
  2666. * Removes a drag item instance from the registry.
  2667. * @param {?} drag
  2668. * @return {?}
  2669. */
  2670. removeDragItem(drag) {
  2671. this._dragInstances.delete(drag);
  2672. this.stopDragging(drag);
  2673. if (this._dragInstances.size === 0) {
  2674. this._document.removeEventListener('touchmove', this._preventDefaultWhileDragging, activeCapturingEventOptions);
  2675. }
  2676. }
  2677. /**
  2678. * Starts the dragging sequence for a drag instance.
  2679. * @param {?} drag Drag instance which is being dragged.
  2680. * @param {?} event Event that initiated the dragging.
  2681. * @return {?}
  2682. */
  2683. startDragging(drag, event) {
  2684. // Do not process the same drag twice to avoid memory leaks and redundant listeners
  2685. if (this._activeDragInstances.has(drag)) {
  2686. return;
  2687. }
  2688. this._activeDragInstances.add(drag);
  2689. if (this._activeDragInstances.size === 1) {
  2690. /** @type {?} */
  2691. const isTouchEvent = event.type.startsWith('touch');
  2692. /** @type {?} */
  2693. const moveEvent = isTouchEvent ? 'touchmove' : 'mousemove';
  2694. /** @type {?} */
  2695. const upEvent = isTouchEvent ? 'touchend' : 'mouseup';
  2696. // We explicitly bind __active__ listeners here, because newer browsers will default to
  2697. // passive ones for `mousemove` and `touchmove`. The events need to be active, because we
  2698. // use `preventDefault` to prevent the page from scrolling while the user is dragging.
  2699. this._globalListeners
  2700. .set(moveEvent, {
  2701. handler: (/**
  2702. * @param {?} e
  2703. * @return {?}
  2704. */
  2705. (e) => this.pointerMove.next((/** @type {?} */ (e)))),
  2706. options: activeCapturingEventOptions
  2707. })
  2708. .set(upEvent, {
  2709. handler: (/**
  2710. * @param {?} e
  2711. * @return {?}
  2712. */
  2713. (e) => this.pointerUp.next((/** @type {?} */ (e)))),
  2714. options: true
  2715. })
  2716. .set('scroll', {
  2717. handler: (/**
  2718. * @param {?} e
  2719. * @return {?}
  2720. */
  2721. (e) => this.scroll.next(e)),
  2722. // Use capturing so that we pick up scroll changes in any scrollable nodes that aren't
  2723. // the document. See https://github.com/angular/components/issues/17144.
  2724. options: true
  2725. })
  2726. // Preventing the default action on `mousemove` isn't enough to disable text selection
  2727. // on Safari so we need to prevent the selection event as well. Alternatively this can
  2728. // be done by setting `user-select: none` on the `body`, however it has causes a style
  2729. // recalculation which can be expensive on pages with a lot of elements.
  2730. .set('selectstart', {
  2731. handler: this._preventDefaultWhileDragging,
  2732. options: activeCapturingEventOptions
  2733. });
  2734. this._ngZone.runOutsideAngular((/**
  2735. * @return {?}
  2736. */
  2737. () => {
  2738. this._globalListeners.forEach((/**
  2739. * @param {?} config
  2740. * @param {?} name
  2741. * @return {?}
  2742. */
  2743. (config, name) => {
  2744. this._document.addEventListener(name, config.handler, config.options);
  2745. }));
  2746. }));
  2747. }
  2748. }
  2749. /**
  2750. * Stops dragging a drag item instance.
  2751. * @param {?} drag
  2752. * @return {?}
  2753. */
  2754. stopDragging(drag) {
  2755. this._activeDragInstances.delete(drag);
  2756. if (this._activeDragInstances.size === 0) {
  2757. this._clearGlobalListeners();
  2758. }
  2759. }
  2760. /**
  2761. * Gets whether a drag item instance is currently being dragged.
  2762. * @param {?} drag
  2763. * @return {?}
  2764. */
  2765. isDragging(drag) {
  2766. return this._activeDragInstances.has(drag);
  2767. }
  2768. /**
  2769. * Gets a drop container by its id.
  2770. * @deprecated No longer being used. To be removed.
  2771. * \@breaking-change 8.0.0
  2772. * @param {?} id
  2773. * @return {?}
  2774. */
  2775. getDropContainer(id) {
  2776. return Array.from(this._dropInstances).find((/**
  2777. * @param {?} instance
  2778. * @return {?}
  2779. */
  2780. instance => instance.id === id));
  2781. }
  2782. /**
  2783. * @return {?}
  2784. */
  2785. ngOnDestroy() {
  2786. this._dragInstances.forEach((/**
  2787. * @param {?} instance
  2788. * @return {?}
  2789. */
  2790. instance => this.removeDragItem(instance)));
  2791. this._dropInstances.forEach((/**
  2792. * @param {?} instance
  2793. * @return {?}
  2794. */
  2795. instance => this.removeDropContainer(instance)));
  2796. this._clearGlobalListeners();
  2797. this.pointerMove.complete();
  2798. this.pointerUp.complete();
  2799. }
  2800. /**
  2801. * Clears out the global event listeners from the `document`.
  2802. * @private
  2803. * @return {?}
  2804. */
  2805. _clearGlobalListeners() {
  2806. this._globalListeners.forEach((/**
  2807. * @param {?} config
  2808. * @param {?} name
  2809. * @return {?}
  2810. */
  2811. (config, name) => {
  2812. this._document.removeEventListener(name, config.handler, config.options);
  2813. }));
  2814. this._globalListeners.clear();
  2815. }
  2816. }
  2817. DragDropRegistry.decorators = [
  2818. { type: Injectable, args: [{ providedIn: 'root' },] },
  2819. ];
  2820. /** @nocollapse */
  2821. DragDropRegistry.ctorParameters = () => [
  2822. { type: NgZone },
  2823. { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] }
  2824. ];
  2825. /** @nocollapse */ DragDropRegistry.ngInjectableDef = ɵɵdefineInjectable({ factory: function DragDropRegistry_Factory() { return new DragDropRegistry(ɵɵinject(NgZone), ɵɵinject(DOCUMENT)); }, token: DragDropRegistry, providedIn: "root" });
  2826. /**
  2827. * @fileoverview added by tsickle
  2828. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  2829. */
  2830. /**
  2831. * Default configuration to be used when creating a `DragRef`.
  2832. * @type {?}
  2833. */
  2834. const DEFAULT_CONFIG = {
  2835. dragStartThreshold: 5,
  2836. pointerDirectionChangeThreshold: 5
  2837. };
  2838. /**
  2839. * Service that allows for drag-and-drop functionality to be attached to DOM elements.
  2840. */
  2841. class DragDrop {
  2842. /**
  2843. * @param {?} _document
  2844. * @param {?} _ngZone
  2845. * @param {?} _viewportRuler
  2846. * @param {?} _dragDropRegistry
  2847. */
  2848. constructor(_document, _ngZone, _viewportRuler, _dragDropRegistry) {
  2849. this._document = _document;
  2850. this._ngZone = _ngZone;
  2851. this._viewportRuler = _viewportRuler;
  2852. this._dragDropRegistry = _dragDropRegistry;
  2853. }
  2854. /**
  2855. * Turns an element into a draggable item.
  2856. * @template T
  2857. * @param {?} element Element to which to attach the dragging functionality.
  2858. * @param {?=} config Object used to configure the dragging behavior.
  2859. * @return {?}
  2860. */
  2861. createDrag(element, config = DEFAULT_CONFIG) {
  2862. return new DragRef(element, config, this._document, this._ngZone, this._viewportRuler, this._dragDropRegistry);
  2863. }
  2864. /**
  2865. * Turns an element into a drop list.
  2866. * @template T
  2867. * @param {?} element Element to which to attach the drop list functionality.
  2868. * @return {?}
  2869. */
  2870. createDropList(element) {
  2871. return new DropListRef(element, this._dragDropRegistry, this._document, this._ngZone, this._viewportRuler);
  2872. }
  2873. }
  2874. DragDrop.decorators = [
  2875. { type: Injectable, args: [{ providedIn: 'root' },] },
  2876. ];
  2877. /** @nocollapse */
  2878. DragDrop.ctorParameters = () => [
  2879. { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] },
  2880. { type: NgZone },
  2881. { type: ViewportRuler },
  2882. { type: DragDropRegistry }
  2883. ];
  2884. /** @nocollapse */ DragDrop.ngInjectableDef = ɵɵdefineInjectable({ factory: function DragDrop_Factory() { return new DragDrop(ɵɵinject(DOCUMENT), ɵɵinject(NgZone), ɵɵinject(ViewportRuler), ɵɵinject(DragDropRegistry)); }, token: DragDrop, providedIn: "root" });
  2885. /**
  2886. * @fileoverview added by tsickle
  2887. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  2888. */
  2889. /**
  2890. * Injection token that is used to provide a CdkDropList instance to CdkDrag.
  2891. * Used for avoiding circular imports.
  2892. * @type {?}
  2893. */
  2894. const CDK_DROP_LIST = new InjectionToken('CDK_DROP_LIST');
  2895. /**
  2896. * Injection token that is used to provide a CdkDropList instance to CdkDrag.
  2897. * Used for avoiding circular imports.
  2898. * @deprecated Use `CDK_DROP_LIST` instead.
  2899. * \@breaking-change 8.0.0
  2900. * @type {?}
  2901. */
  2902. const CDK_DROP_LIST_CONTAINER = CDK_DROP_LIST;
  2903. /**
  2904. * @fileoverview added by tsickle
  2905. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  2906. */
  2907. /**
  2908. * @fileoverview added by tsickle
  2909. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  2910. */
  2911. /**
  2912. * Injection token that can be used for a `CdkDrag` to provide itself as a parent to the
  2913. * drag-specific child directive (`CdkDragHandle`, `CdkDragPreview` etc.). Used primarily
  2914. * to avoid circular imports.
  2915. * \@docs-private
  2916. * @type {?}
  2917. */
  2918. const CDK_DRAG_PARENT = new InjectionToken('CDK_DRAG_PARENT');
  2919. /**
  2920. * @fileoverview added by tsickle
  2921. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  2922. */
  2923. /**
  2924. * Handle that can be used to drag and CdkDrag instance.
  2925. */
  2926. class CdkDragHandle {
  2927. /**
  2928. * @param {?} element
  2929. * @param {?=} parentDrag
  2930. */
  2931. constructor(element, parentDrag) {
  2932. this.element = element;
  2933. /**
  2934. * Emits when the state of the handle has changed.
  2935. */
  2936. this._stateChanges = new Subject();
  2937. this._disabled = false;
  2938. this._parentDrag = parentDrag;
  2939. toggleNativeDragInteractions(element.nativeElement, false);
  2940. }
  2941. /**
  2942. * Whether starting to drag through this handle is disabled.
  2943. * @return {?}
  2944. */
  2945. get disabled() { return this._disabled; }
  2946. /**
  2947. * @param {?} value
  2948. * @return {?}
  2949. */
  2950. set disabled(value) {
  2951. this._disabled = coerceBooleanProperty(value);
  2952. this._stateChanges.next(this);
  2953. }
  2954. /**
  2955. * @return {?}
  2956. */
  2957. ngOnDestroy() {
  2958. this._stateChanges.complete();
  2959. }
  2960. }
  2961. CdkDragHandle.decorators = [
  2962. { type: Directive, args: [{
  2963. selector: '[cdkDragHandle]',
  2964. host: {
  2965. 'class': 'cdk-drag-handle'
  2966. }
  2967. },] },
  2968. ];
  2969. /** @nocollapse */
  2970. CdkDragHandle.ctorParameters = () => [
  2971. { type: ElementRef },
  2972. { type: undefined, decorators: [{ type: Inject, args: [CDK_DRAG_PARENT,] }, { type: Optional }] }
  2973. ];
  2974. CdkDragHandle.propDecorators = {
  2975. disabled: [{ type: Input, args: ['cdkDragHandleDisabled',] }]
  2976. };
  2977. /**
  2978. * @fileoverview added by tsickle
  2979. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  2980. */
  2981. /**
  2982. * Element that will be used as a template for the placeholder of a CdkDrag when
  2983. * it is being dragged. The placeholder is displayed in place of the element being dragged.
  2984. * @template T
  2985. */
  2986. class CdkDragPlaceholder {
  2987. /**
  2988. * @param {?} templateRef
  2989. */
  2990. constructor(templateRef) {
  2991. this.templateRef = templateRef;
  2992. }
  2993. }
  2994. CdkDragPlaceholder.decorators = [
  2995. { type: Directive, args: [{
  2996. selector: 'ng-template[cdkDragPlaceholder]'
  2997. },] },
  2998. ];
  2999. /** @nocollapse */
  3000. CdkDragPlaceholder.ctorParameters = () => [
  3001. { type: TemplateRef }
  3002. ];
  3003. CdkDragPlaceholder.propDecorators = {
  3004. data: [{ type: Input }]
  3005. };
  3006. /**
  3007. * @fileoverview added by tsickle
  3008. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  3009. */
  3010. /**
  3011. * Element that will be used as a template for the preview
  3012. * of a CdkDrag when it is being dragged.
  3013. * @template T
  3014. */
  3015. class CdkDragPreview {
  3016. /**
  3017. * @param {?} templateRef
  3018. */
  3019. constructor(templateRef) {
  3020. this.templateRef = templateRef;
  3021. }
  3022. }
  3023. CdkDragPreview.decorators = [
  3024. { type: Directive, args: [{
  3025. selector: 'ng-template[cdkDragPreview]'
  3026. },] },
  3027. ];
  3028. /** @nocollapse */
  3029. CdkDragPreview.ctorParameters = () => [
  3030. { type: TemplateRef }
  3031. ];
  3032. CdkDragPreview.propDecorators = {
  3033. data: [{ type: Input }]
  3034. };
  3035. /**
  3036. * @fileoverview added by tsickle
  3037. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  3038. */
  3039. /**
  3040. * Injection token that can be used to configure the behavior of `CdkDrag`.
  3041. * @type {?}
  3042. */
  3043. const CDK_DRAG_CONFIG = new InjectionToken('CDK_DRAG_CONFIG', {
  3044. providedIn: 'root',
  3045. factory: CDK_DRAG_CONFIG_FACTORY
  3046. });
  3047. /**
  3048. * \@docs-private
  3049. * @return {?}
  3050. */
  3051. function CDK_DRAG_CONFIG_FACTORY() {
  3052. return { dragStartThreshold: 5, pointerDirectionChangeThreshold: 5 };
  3053. }
  3054. /**
  3055. * Element that can be moved inside a CdkDropList container.
  3056. * @template T
  3057. */
  3058. class CdkDrag {
  3059. /**
  3060. * @param {?} element
  3061. * @param {?} dropContainer
  3062. * @param {?} _document
  3063. * @param {?} _ngZone
  3064. * @param {?} _viewContainerRef
  3065. * @param {?} config
  3066. * @param {?} _dir
  3067. * @param {?} dragDrop
  3068. * @param {?} _changeDetectorRef
  3069. */
  3070. constructor(element, dropContainer, _document, _ngZone, _viewContainerRef, config, _dir, dragDrop, _changeDetectorRef) {
  3071. this.element = element;
  3072. this.dropContainer = dropContainer;
  3073. this._document = _document;
  3074. this._ngZone = _ngZone;
  3075. this._viewContainerRef = _viewContainerRef;
  3076. this._dir = _dir;
  3077. this._changeDetectorRef = _changeDetectorRef;
  3078. this._destroyed = new Subject();
  3079. /**
  3080. * Amount of milliseconds to wait after the user has put their
  3081. * pointer down before starting to drag the element.
  3082. */
  3083. this.dragStartDelay = 0;
  3084. this._disabled = false;
  3085. /**
  3086. * Emits when the user starts dragging the item.
  3087. */
  3088. this.started = new EventEmitter();
  3089. /**
  3090. * Emits when the user has released a drag item, before any animations have started.
  3091. */
  3092. this.released = new EventEmitter();
  3093. /**
  3094. * Emits when the user stops dragging an item in the container.
  3095. */
  3096. this.ended = new EventEmitter();
  3097. /**
  3098. * Emits when the user has moved the item into a new container.
  3099. */
  3100. this.entered = new EventEmitter();
  3101. /**
  3102. * Emits when the user removes the item its container by dragging it into another container.
  3103. */
  3104. this.exited = new EventEmitter();
  3105. /**
  3106. * Emits when the user drops the item inside a container.
  3107. */
  3108. this.dropped = new EventEmitter();
  3109. /**
  3110. * Emits as the user is dragging the item. Use with caution,
  3111. * because this event will fire for every pixel that the user has dragged.
  3112. */
  3113. this.moved = new Observable((/**
  3114. * @param {?} observer
  3115. * @return {?}
  3116. */
  3117. (observer) => {
  3118. /** @type {?} */
  3119. const subscription = this._dragRef.moved.pipe(map((/**
  3120. * @param {?} movedEvent
  3121. * @return {?}
  3122. */
  3123. movedEvent => ({
  3124. source: this,
  3125. pointerPosition: movedEvent.pointerPosition,
  3126. event: movedEvent.event,
  3127. delta: movedEvent.delta,
  3128. distance: movedEvent.distance
  3129. })))).subscribe(observer);
  3130. return (/**
  3131. * @return {?}
  3132. */
  3133. () => {
  3134. subscription.unsubscribe();
  3135. });
  3136. }));
  3137. this._dragRef = dragDrop.createDrag(element, config);
  3138. this._dragRef.data = this;
  3139. this._syncInputs(this._dragRef);
  3140. this._handleEvents(this._dragRef);
  3141. }
  3142. /**
  3143. * Selector that will be used to determine the element to which the draggable's position will
  3144. * be constrained. Matching starts from the element's parent and goes up the DOM until a matching
  3145. * element has been found
  3146. * @deprecated Use `boundaryElement` instead.
  3147. * \@breaking-change 9.0.0
  3148. * @return {?}
  3149. */
  3150. get boundaryElementSelector() {
  3151. return typeof this.boundaryElement === 'string' ? this.boundaryElement : (/** @type {?} */ (undefined));
  3152. }
  3153. /**
  3154. * @param {?} selector
  3155. * @return {?}
  3156. */
  3157. set boundaryElementSelector(selector) {
  3158. this.boundaryElement = selector;
  3159. }
  3160. /**
  3161. * Whether starting to drag this element is disabled.
  3162. * @return {?}
  3163. */
  3164. get disabled() {
  3165. return this._disabled || (this.dropContainer && this.dropContainer.disabled);
  3166. }
  3167. /**
  3168. * @param {?} value
  3169. * @return {?}
  3170. */
  3171. set disabled(value) {
  3172. this._disabled = coerceBooleanProperty(value);
  3173. this._dragRef.disabled = this._disabled;
  3174. }
  3175. /**
  3176. * Returns the element that is being used as a placeholder
  3177. * while the current element is being dragged.
  3178. * @return {?}
  3179. */
  3180. getPlaceholderElement() {
  3181. return this._dragRef.getPlaceholderElement();
  3182. }
  3183. /**
  3184. * Returns the root draggable element.
  3185. * @return {?}
  3186. */
  3187. getRootElement() {
  3188. return this._dragRef.getRootElement();
  3189. }
  3190. /**
  3191. * Resets a standalone drag item to its initial position.
  3192. * @return {?}
  3193. */
  3194. reset() {
  3195. this._dragRef.reset();
  3196. }
  3197. /**
  3198. * Gets the pixel coordinates of the draggable outside of a drop container.
  3199. * @return {?}
  3200. */
  3201. getFreeDragPosition() {
  3202. return this._dragRef.getFreeDragPosition();
  3203. }
  3204. /**
  3205. * @return {?}
  3206. */
  3207. ngAfterViewInit() {
  3208. // We need to wait for the zone to stabilize, in order for the reference
  3209. // element to be in the proper place in the DOM. This is mostly relevant
  3210. // for draggable elements inside portals since they get stamped out in
  3211. // their original DOM position and then they get transferred to the portal.
  3212. this._ngZone.onStable.asObservable()
  3213. .pipe(take(1), takeUntil(this._destroyed))
  3214. .subscribe((/**
  3215. * @return {?}
  3216. */
  3217. () => {
  3218. this._updateRootElement();
  3219. // Listen for any newly-added handles.
  3220. this._handles.changes.pipe(startWith(this._handles),
  3221. // Sync the new handles with the DragRef.
  3222. tap((/**
  3223. * @param {?} handles
  3224. * @return {?}
  3225. */
  3226. (handles) => {
  3227. /** @type {?} */
  3228. const childHandleElements = handles
  3229. .filter((/**
  3230. * @param {?} handle
  3231. * @return {?}
  3232. */
  3233. handle => handle._parentDrag === this))
  3234. .map((/**
  3235. * @param {?} handle
  3236. * @return {?}
  3237. */
  3238. handle => handle.element));
  3239. this._dragRef.withHandles(childHandleElements);
  3240. })),
  3241. // Listen if the state of any of the handles changes.
  3242. switchMap((/**
  3243. * @param {?} handles
  3244. * @return {?}
  3245. */
  3246. (handles) => {
  3247. return merge(...handles.map((/**
  3248. * @param {?} item
  3249. * @return {?}
  3250. */
  3251. item => item._stateChanges)));
  3252. })), takeUntil(this._destroyed)).subscribe((/**
  3253. * @param {?} handleInstance
  3254. * @return {?}
  3255. */
  3256. handleInstance => {
  3257. // Enabled/disable the handle that changed in the DragRef.
  3258. /** @type {?} */
  3259. const dragRef = this._dragRef;
  3260. /** @type {?} */
  3261. const handle = handleInstance.element.nativeElement;
  3262. handleInstance.disabled ? dragRef.disableHandle(handle) : dragRef.enableHandle(handle);
  3263. }));
  3264. if (this.freeDragPosition) {
  3265. this._dragRef.setFreeDragPosition(this.freeDragPosition);
  3266. }
  3267. }));
  3268. }
  3269. /**
  3270. * @param {?} changes
  3271. * @return {?}
  3272. */
  3273. ngOnChanges(changes) {
  3274. /** @type {?} */
  3275. const rootSelectorChange = changes['rootElementSelector'];
  3276. /** @type {?} */
  3277. const positionChange = changes['freeDragPosition'];
  3278. // We don't have to react to the first change since it's being
  3279. // handled in `ngAfterViewInit` where it needs to be deferred.
  3280. if (rootSelectorChange && !rootSelectorChange.firstChange) {
  3281. this._updateRootElement();
  3282. }
  3283. // Skip the first change since it's being handled in `ngAfterViewInit`.
  3284. if (positionChange && !positionChange.firstChange && this.freeDragPosition) {
  3285. this._dragRef.setFreeDragPosition(this.freeDragPosition);
  3286. }
  3287. }
  3288. /**
  3289. * @return {?}
  3290. */
  3291. ngOnDestroy() {
  3292. this._destroyed.next();
  3293. this._destroyed.complete();
  3294. this._dragRef.dispose();
  3295. }
  3296. /**
  3297. * Syncs the root element with the `DragRef`.
  3298. * @private
  3299. * @return {?}
  3300. */
  3301. _updateRootElement() {
  3302. /** @type {?} */
  3303. const element = this.element.nativeElement;
  3304. /** @type {?} */
  3305. const rootElement = this.rootElementSelector ?
  3306. getClosestMatchingAncestor(element, this.rootElementSelector) : element;
  3307. if (rootElement && rootElement.nodeType !== this._document.ELEMENT_NODE) {
  3308. throw Error(`cdkDrag must be attached to an element node. ` +
  3309. `Currently attached to "${rootElement.nodeName}".`);
  3310. }
  3311. this._dragRef.withRootElement(rootElement || element);
  3312. }
  3313. /**
  3314. * Gets the boundary element, based on the `boundaryElement` value.
  3315. * @private
  3316. * @return {?}
  3317. */
  3318. _getBoundaryElement() {
  3319. /** @type {?} */
  3320. const boundary = this.boundaryElement;
  3321. if (!boundary) {
  3322. return null;
  3323. }
  3324. if (typeof boundary === 'string') {
  3325. return getClosestMatchingAncestor(this.element.nativeElement, boundary);
  3326. }
  3327. /** @type {?} */
  3328. const element = coerceElement(boundary);
  3329. if (isDevMode() && !element.contains(this.element.nativeElement)) {
  3330. throw Error('Draggable element is not inside of the node passed into cdkDragBoundary.');
  3331. }
  3332. return element;
  3333. }
  3334. /**
  3335. * Syncs the inputs of the CdkDrag with the options of the underlying DragRef.
  3336. * @private
  3337. * @param {?} ref
  3338. * @return {?}
  3339. */
  3340. _syncInputs(ref) {
  3341. ref.beforeStarted.subscribe((/**
  3342. * @return {?}
  3343. */
  3344. () => {
  3345. if (!ref.isDragging()) {
  3346. /** @type {?} */
  3347. const dir = this._dir;
  3348. /** @type {?} */
  3349. const placeholder = this._placeholderTemplate ? {
  3350. template: this._placeholderTemplate.templateRef,
  3351. context: this._placeholderTemplate.data,
  3352. viewContainer: this._viewContainerRef
  3353. } : null;
  3354. /** @type {?} */
  3355. const preview = this._previewTemplate ? {
  3356. template: this._previewTemplate.templateRef,
  3357. context: this._previewTemplate.data,
  3358. viewContainer: this._viewContainerRef
  3359. } : null;
  3360. ref.disabled = this.disabled;
  3361. ref.lockAxis = this.lockAxis;
  3362. ref.dragStartDelay = coerceNumberProperty(this.dragStartDelay);
  3363. ref.constrainPosition = this.constrainPosition;
  3364. ref
  3365. .withBoundaryElement(this._getBoundaryElement())
  3366. .withPlaceholderTemplate(placeholder)
  3367. .withPreviewTemplate(preview);
  3368. if (dir) {
  3369. ref.withDirection(dir.value);
  3370. }
  3371. }
  3372. }));
  3373. }
  3374. /**
  3375. * Handles the events from the underlying `DragRef`.
  3376. * @private
  3377. * @param {?} ref
  3378. * @return {?}
  3379. */
  3380. _handleEvents(ref) {
  3381. ref.started.subscribe((/**
  3382. * @return {?}
  3383. */
  3384. () => {
  3385. this.started.emit({ source: this });
  3386. // Since all of these events run outside of change detection,
  3387. // we need to ensure that everything is marked correctly.
  3388. this._changeDetectorRef.markForCheck();
  3389. }));
  3390. ref.released.subscribe((/**
  3391. * @return {?}
  3392. */
  3393. () => {
  3394. this.released.emit({ source: this });
  3395. }));
  3396. ref.ended.subscribe((/**
  3397. * @param {?} event
  3398. * @return {?}
  3399. */
  3400. event => {
  3401. this.ended.emit({ source: this, distance: event.distance });
  3402. // Since all of these events run outside of change detection,
  3403. // we need to ensure that everything is marked correctly.
  3404. this._changeDetectorRef.markForCheck();
  3405. }));
  3406. ref.entered.subscribe((/**
  3407. * @param {?} event
  3408. * @return {?}
  3409. */
  3410. event => {
  3411. this.entered.emit({
  3412. container: event.container.data,
  3413. item: this,
  3414. currentIndex: event.currentIndex
  3415. });
  3416. }));
  3417. ref.exited.subscribe((/**
  3418. * @param {?} event
  3419. * @return {?}
  3420. */
  3421. event => {
  3422. this.exited.emit({
  3423. container: event.container.data,
  3424. item: this
  3425. });
  3426. }));
  3427. ref.dropped.subscribe((/**
  3428. * @param {?} event
  3429. * @return {?}
  3430. */
  3431. event => {
  3432. this.dropped.emit({
  3433. previousIndex: event.previousIndex,
  3434. currentIndex: event.currentIndex,
  3435. previousContainer: event.previousContainer.data,
  3436. container: event.container.data,
  3437. isPointerOverContainer: event.isPointerOverContainer,
  3438. item: this,
  3439. distance: event.distance
  3440. });
  3441. }));
  3442. }
  3443. }
  3444. CdkDrag.decorators = [
  3445. { type: Directive, args: [{
  3446. selector: '[cdkDrag]',
  3447. exportAs: 'cdkDrag',
  3448. host: {
  3449. 'class': 'cdk-drag',
  3450. '[class.cdk-drag-disabled]': 'disabled',
  3451. '[class.cdk-drag-dragging]': '_dragRef.isDragging()',
  3452. },
  3453. providers: [{ provide: CDK_DRAG_PARENT, useExisting: CdkDrag }]
  3454. },] },
  3455. ];
  3456. /** @nocollapse */
  3457. CdkDrag.ctorParameters = () => [
  3458. { type: ElementRef },
  3459. { type: undefined, decorators: [{ type: Inject, args: [CDK_DROP_LIST,] }, { type: Optional }, { type: SkipSelf }] },
  3460. { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] },
  3461. { type: NgZone },
  3462. { type: ViewContainerRef },
  3463. { type: undefined, decorators: [{ type: Inject, args: [CDK_DRAG_CONFIG,] }] },
  3464. { type: Directionality, decorators: [{ type: Optional }] },
  3465. { type: DragDrop },
  3466. { type: ChangeDetectorRef }
  3467. ];
  3468. CdkDrag.propDecorators = {
  3469. _handles: [{ type: ContentChildren, args: [CdkDragHandle, { descendants: true },] }],
  3470. _previewTemplate: [{ type: ContentChild, args: [CdkDragPreview, { static: false },] }],
  3471. _placeholderTemplate: [{ type: ContentChild, args: [CdkDragPlaceholder, { static: false },] }],
  3472. data: [{ type: Input, args: ['cdkDragData',] }],
  3473. lockAxis: [{ type: Input, args: ['cdkDragLockAxis',] }],
  3474. rootElementSelector: [{ type: Input, args: ['cdkDragRootElement',] }],
  3475. boundaryElement: [{ type: Input, args: ['cdkDragBoundary',] }],
  3476. dragStartDelay: [{ type: Input, args: ['cdkDragStartDelay',] }],
  3477. freeDragPosition: [{ type: Input, args: ['cdkDragFreeDragPosition',] }],
  3478. disabled: [{ type: Input, args: ['cdkDragDisabled',] }],
  3479. constrainPosition: [{ type: Input, args: ['cdkDragConstrainPosition',] }],
  3480. started: [{ type: Output, args: ['cdkDragStarted',] }],
  3481. released: [{ type: Output, args: ['cdkDragReleased',] }],
  3482. ended: [{ type: Output, args: ['cdkDragEnded',] }],
  3483. entered: [{ type: Output, args: ['cdkDragEntered',] }],
  3484. exited: [{ type: Output, args: ['cdkDragExited',] }],
  3485. dropped: [{ type: Output, args: ['cdkDragDropped',] }],
  3486. moved: [{ type: Output, args: ['cdkDragMoved',] }]
  3487. };
  3488. /**
  3489. * Gets the closest ancestor of an element that matches a selector.
  3490. * @param {?} element
  3491. * @param {?} selector
  3492. * @return {?}
  3493. */
  3494. function getClosestMatchingAncestor(element, selector) {
  3495. /** @type {?} */
  3496. let currentElement = (/** @type {?} */ (element.parentElement));
  3497. while (currentElement) {
  3498. // IE doesn't support `matches` so we have to fall back to `msMatchesSelector`.
  3499. if (currentElement.matches ? currentElement.matches(selector) :
  3500. ((/** @type {?} */ (currentElement))).msMatchesSelector(selector)) {
  3501. return currentElement;
  3502. }
  3503. currentElement = currentElement.parentElement;
  3504. }
  3505. return null;
  3506. }
  3507. /**
  3508. * @fileoverview added by tsickle
  3509. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  3510. */
  3511. /**
  3512. * Declaratively connects sibling `cdkDropList` instances together. All of the `cdkDropList`
  3513. * elements that are placed inside a `cdkDropListGroup` will be connected to each other
  3514. * automatically. Can be used as an alternative to the `cdkDropListConnectedTo` input
  3515. * from `cdkDropList`.
  3516. * @template T
  3517. */
  3518. class CdkDropListGroup {
  3519. constructor() {
  3520. /**
  3521. * Drop lists registered inside the group.
  3522. */
  3523. this._items = new Set();
  3524. this._disabled = false;
  3525. }
  3526. /**
  3527. * Whether starting a dragging sequence from inside this group is disabled.
  3528. * @return {?}
  3529. */
  3530. get disabled() { return this._disabled; }
  3531. /**
  3532. * @param {?} value
  3533. * @return {?}
  3534. */
  3535. set disabled(value) {
  3536. this._disabled = coerceBooleanProperty(value);
  3537. }
  3538. /**
  3539. * @return {?}
  3540. */
  3541. ngOnDestroy() {
  3542. this._items.clear();
  3543. }
  3544. }
  3545. CdkDropListGroup.decorators = [
  3546. { type: Directive, args: [{
  3547. selector: '[cdkDropListGroup]',
  3548. exportAs: 'cdkDropListGroup',
  3549. },] },
  3550. ];
  3551. CdkDropListGroup.propDecorators = {
  3552. disabled: [{ type: Input, args: ['cdkDropListGroupDisabled',] }]
  3553. };
  3554. /**
  3555. * @fileoverview added by tsickle
  3556. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  3557. */
  3558. /**
  3559. * Counter used to generate unique ids for drop zones.
  3560. * @type {?}
  3561. */
  3562. let _uniqueIdCounter$1 = 0;
  3563. const ɵ0 = undefined;
  3564. // @breaking-change 8.0.0 `CdkDropList` implements `CdkDropListContainer` for backwards
  3565. // compatiblity. The implements clause, as well as all the methods that it enforces can
  3566. // be removed when `CdkDropListContainer` is deleted.
  3567. /**
  3568. * Container that wraps a set of draggable items.
  3569. * @template T
  3570. */
  3571. class CdkDropList {
  3572. /**
  3573. * @param {?} element
  3574. * @param {?} dragDrop
  3575. * @param {?} _changeDetectorRef
  3576. * @param {?=} _dir
  3577. * @param {?=} _group
  3578. */
  3579. constructor(element, dragDrop, _changeDetectorRef, _dir, _group) {
  3580. this.element = element;
  3581. this._changeDetectorRef = _changeDetectorRef;
  3582. this._dir = _dir;
  3583. this._group = _group;
  3584. /**
  3585. * Emits when the list has been destroyed.
  3586. */
  3587. this._destroyed = new Subject();
  3588. /**
  3589. * Other draggable containers that this container is connected to and into which the
  3590. * container's items can be transferred. Can either be references to other drop containers,
  3591. * or their unique IDs.
  3592. */
  3593. this.connectedTo = [];
  3594. /**
  3595. * Direction in which the list is oriented.
  3596. */
  3597. this.orientation = 'vertical';
  3598. /**
  3599. * Unique ID for the drop zone. Can be used as a reference
  3600. * in the `connectedTo` of another `CdkDropList`.
  3601. */
  3602. this.id = `cdk-drop-list-${_uniqueIdCounter$1++}`;
  3603. this._disabled = false;
  3604. this._sortingDisabled = false;
  3605. /**
  3606. * Function that is used to determine whether an item
  3607. * is allowed to be moved into a drop container.
  3608. */
  3609. this.enterPredicate = (/**
  3610. * @return {?}
  3611. */
  3612. () => true);
  3613. /**
  3614. * Whether to auto-scroll the view when the user moves their pointer close to the edges.
  3615. */
  3616. this.autoScrollDisabled = false;
  3617. /**
  3618. * Emits when the user drops an item inside the container.
  3619. */
  3620. this.dropped = new EventEmitter();
  3621. /**
  3622. * Emits when the user has moved a new drag item into this container.
  3623. */
  3624. this.entered = new EventEmitter();
  3625. /**
  3626. * Emits when the user removes an item from the container
  3627. * by dragging it into another container.
  3628. */
  3629. this.exited = new EventEmitter();
  3630. /**
  3631. * Emits as the user is swapping items while actively dragging.
  3632. */
  3633. this.sorted = new EventEmitter();
  3634. this._dropListRef = dragDrop.createDropList(element);
  3635. this._dropListRef.data = this;
  3636. this._dropListRef.enterPredicate = (/**
  3637. * @param {?} drag
  3638. * @param {?} drop
  3639. * @return {?}
  3640. */
  3641. (drag, drop) => {
  3642. return this.enterPredicate(drag.data, drop.data);
  3643. });
  3644. this._syncInputs(this._dropListRef);
  3645. this._handleEvents(this._dropListRef);
  3646. CdkDropList._dropLists.push(this);
  3647. if (_group) {
  3648. _group._items.add(this);
  3649. }
  3650. }
  3651. /**
  3652. * Whether starting a dragging sequence from this container is disabled.
  3653. * @return {?}
  3654. */
  3655. get disabled() {
  3656. return this._disabled || (!!this._group && this._group.disabled);
  3657. }
  3658. /**
  3659. * @param {?} value
  3660. * @return {?}
  3661. */
  3662. set disabled(value) {
  3663. this._disabled = coerceBooleanProperty(value);
  3664. }
  3665. /**
  3666. * Whether sorting within this drop list is disabled.
  3667. * @return {?}
  3668. */
  3669. get sortingDisabled() { return this._sortingDisabled; }
  3670. /**
  3671. * @param {?} value
  3672. * @return {?}
  3673. */
  3674. set sortingDisabled(value) {
  3675. this._sortingDisabled = coerceBooleanProperty(value);
  3676. }
  3677. /**
  3678. * @return {?}
  3679. */
  3680. ngAfterContentInit() {
  3681. this._draggables.changes
  3682. .pipe(startWith(this._draggables), takeUntil(this._destroyed))
  3683. .subscribe((/**
  3684. * @param {?} items
  3685. * @return {?}
  3686. */
  3687. (items) => {
  3688. this._dropListRef.withItems(items.map((/**
  3689. * @param {?} drag
  3690. * @return {?}
  3691. */
  3692. drag => drag._dragRef)));
  3693. }));
  3694. }
  3695. /**
  3696. * @return {?}
  3697. */
  3698. ngOnDestroy() {
  3699. /** @type {?} */
  3700. const index = CdkDropList._dropLists.indexOf(this);
  3701. if (index > -1) {
  3702. CdkDropList._dropLists.splice(index, 1);
  3703. }
  3704. if (this._group) {
  3705. this._group._items.delete(this);
  3706. }
  3707. this._dropListRef.dispose();
  3708. this._destroyed.next();
  3709. this._destroyed.complete();
  3710. }
  3711. /**
  3712. * Starts dragging an item.
  3713. * @return {?}
  3714. */
  3715. start() {
  3716. this._dropListRef.start();
  3717. }
  3718. /**
  3719. * Drops an item into this container.
  3720. * @param {?} item Item being dropped into the container.
  3721. * @param {?} currentIndex Index at which the item should be inserted.
  3722. * @param {?} previousContainer Container from which the item got dragged in.
  3723. * @param {?} isPointerOverContainer Whether the user's pointer was over the
  3724. * container when the item was dropped.
  3725. * @return {?}
  3726. */
  3727. drop(item, currentIndex, previousContainer, isPointerOverContainer) {
  3728. this._dropListRef.drop(item._dragRef, currentIndex, ((/** @type {?} */ (previousContainer)))._dropListRef, isPointerOverContainer);
  3729. }
  3730. /**
  3731. * Emits an event to indicate that the user moved an item into the container.
  3732. * @param {?} item Item that was moved into the container.
  3733. * @param {?} pointerX Position of the item along the X axis.
  3734. * @param {?} pointerY Position of the item along the Y axis.
  3735. * @return {?}
  3736. */
  3737. enter(item, pointerX, pointerY) {
  3738. this._dropListRef.enter(item._dragRef, pointerX, pointerY);
  3739. }
  3740. /**
  3741. * Removes an item from the container after it was dragged into another container by the user.
  3742. * @param {?} item Item that was dragged out.
  3743. * @return {?}
  3744. */
  3745. exit(item) {
  3746. this._dropListRef.exit(item._dragRef);
  3747. }
  3748. /**
  3749. * Figures out the index of an item in the container.
  3750. * @param {?} item Item whose index should be determined.
  3751. * @return {?}
  3752. */
  3753. getItemIndex(item) {
  3754. return this._dropListRef.getItemIndex(item._dragRef);
  3755. }
  3756. /**
  3757. * Sorts an item inside the container based on its position.
  3758. * @param {?} item Item to be sorted.
  3759. * @param {?} pointerX Position of the item along the X axis.
  3760. * @param {?} pointerY Position of the item along the Y axis.
  3761. * @param {?} pointerDelta Direction in which the pointer is moving along each axis.
  3762. * @return {?}
  3763. */
  3764. _sortItem(item, pointerX, pointerY, pointerDelta) {
  3765. return this._dropListRef._sortItem(item._dragRef, pointerX, pointerY, pointerDelta);
  3766. }
  3767. /**
  3768. * Figures out whether an item should be moved into a sibling
  3769. * drop container, based on its current position.
  3770. * @param {?} item Drag item that is being moved.
  3771. * @param {?} x Position of the item along the X axis.
  3772. * @param {?} y Position of the item along the Y axis.
  3773. * @return {?}
  3774. */
  3775. _getSiblingContainerFromPosition(item, x, y) {
  3776. /** @type {?} */
  3777. const result = this._dropListRef._getSiblingContainerFromPosition(item._dragRef, x, y);
  3778. return result ? result.data : null;
  3779. }
  3780. /**
  3781. * Checks whether the user's pointer is positioned over the container.
  3782. * @param {?} x Pointer position along the X axis.
  3783. * @param {?} y Pointer position along the Y axis.
  3784. * @return {?}
  3785. */
  3786. _isOverContainer(x, y) {
  3787. return this._dropListRef._isOverContainer(x, y);
  3788. }
  3789. /**
  3790. * Syncs the inputs of the CdkDropList with the options of the underlying DropListRef.
  3791. * @private
  3792. * @param {?} ref
  3793. * @return {?}
  3794. */
  3795. _syncInputs(ref) {
  3796. if (this._dir) {
  3797. this._dir.change
  3798. .pipe(startWith(this._dir.value), takeUntil(this._destroyed))
  3799. .subscribe((/**
  3800. * @param {?} value
  3801. * @return {?}
  3802. */
  3803. value => ref.withDirection(value)));
  3804. }
  3805. ref.beforeStarted.subscribe((/**
  3806. * @return {?}
  3807. */
  3808. () => {
  3809. /** @type {?} */
  3810. const siblings = coerceArray(this.connectedTo).map((/**
  3811. * @param {?} drop
  3812. * @return {?}
  3813. */
  3814. drop => {
  3815. return typeof drop === 'string' ?
  3816. (/** @type {?} */ (CdkDropList._dropLists.find((/**
  3817. * @param {?} list
  3818. * @return {?}
  3819. */
  3820. list => list.id === drop)))) : drop;
  3821. }));
  3822. if (this._group) {
  3823. this._group._items.forEach((/**
  3824. * @param {?} drop
  3825. * @return {?}
  3826. */
  3827. drop => {
  3828. if (siblings.indexOf(drop) === -1) {
  3829. siblings.push(drop);
  3830. }
  3831. }));
  3832. }
  3833. ref.disabled = this.disabled;
  3834. ref.lockAxis = this.lockAxis;
  3835. ref.sortingDisabled = this.sortingDisabled;
  3836. ref.autoScrollDisabled = this.autoScrollDisabled;
  3837. ref
  3838. .connectedTo(siblings.filter((/**
  3839. * @param {?} drop
  3840. * @return {?}
  3841. */
  3842. drop => drop && drop !== this)).map((/**
  3843. * @param {?} list
  3844. * @return {?}
  3845. */
  3846. list => list._dropListRef)))
  3847. .withOrientation(this.orientation);
  3848. }));
  3849. }
  3850. /**
  3851. * Handles events from the underlying DropListRef.
  3852. * @private
  3853. * @param {?} ref
  3854. * @return {?}
  3855. */
  3856. _handleEvents(ref) {
  3857. ref.beforeStarted.subscribe((/**
  3858. * @return {?}
  3859. */
  3860. () => {
  3861. this._changeDetectorRef.markForCheck();
  3862. }));
  3863. ref.entered.subscribe((/**
  3864. * @param {?} event
  3865. * @return {?}
  3866. */
  3867. event => {
  3868. this.entered.emit({
  3869. container: this,
  3870. item: event.item.data,
  3871. currentIndex: event.currentIndex
  3872. });
  3873. }));
  3874. ref.exited.subscribe((/**
  3875. * @param {?} event
  3876. * @return {?}
  3877. */
  3878. event => {
  3879. this.exited.emit({
  3880. container: this,
  3881. item: event.item.data
  3882. });
  3883. this._changeDetectorRef.markForCheck();
  3884. }));
  3885. ref.sorted.subscribe((/**
  3886. * @param {?} event
  3887. * @return {?}
  3888. */
  3889. event => {
  3890. this.sorted.emit({
  3891. previousIndex: event.previousIndex,
  3892. currentIndex: event.currentIndex,
  3893. container: this,
  3894. item: event.item.data
  3895. });
  3896. }));
  3897. ref.dropped.subscribe((/**
  3898. * @param {?} event
  3899. * @return {?}
  3900. */
  3901. event => {
  3902. this.dropped.emit({
  3903. previousIndex: event.previousIndex,
  3904. currentIndex: event.currentIndex,
  3905. previousContainer: event.previousContainer.data,
  3906. container: event.container.data,
  3907. item: event.item.data,
  3908. isPointerOverContainer: event.isPointerOverContainer,
  3909. distance: event.distance
  3910. });
  3911. // Mark for check since all of these events run outside of change
  3912. // detection and we're not guaranteed for something else to have triggered it.
  3913. this._changeDetectorRef.markForCheck();
  3914. }));
  3915. }
  3916. }
  3917. /**
  3918. * Keeps track of the drop lists that are currently on the page.
  3919. */
  3920. CdkDropList._dropLists = [];
  3921. CdkDropList.decorators = [
  3922. { type: Directive, args: [{
  3923. selector: '[cdkDropList], cdk-drop-list',
  3924. exportAs: 'cdkDropList',
  3925. providers: [
  3926. // Prevent child drop lists from picking up the same group as their parent.
  3927. { provide: CdkDropListGroup, useValue: ɵ0 },
  3928. { provide: CDK_DROP_LIST_CONTAINER, useExisting: CdkDropList },
  3929. ],
  3930. host: {
  3931. 'class': 'cdk-drop-list',
  3932. '[id]': 'id',
  3933. '[class.cdk-drop-list-disabled]': 'disabled',
  3934. '[class.cdk-drop-list-dragging]': '_dropListRef.isDragging()',
  3935. '[class.cdk-drop-list-receiving]': '_dropListRef.isReceiving()',
  3936. }
  3937. },] },
  3938. ];
  3939. /** @nocollapse */
  3940. CdkDropList.ctorParameters = () => [
  3941. { type: ElementRef },
  3942. { type: DragDrop },
  3943. { type: ChangeDetectorRef },
  3944. { type: Directionality, decorators: [{ type: Optional }] },
  3945. { type: CdkDropListGroup, decorators: [{ type: Optional }, { type: SkipSelf }] }
  3946. ];
  3947. CdkDropList.propDecorators = {
  3948. _draggables: [{ type: ContentChildren, args: [forwardRef((/**
  3949. * @return {?}
  3950. */
  3951. () => CdkDrag)), {
  3952. // Explicitly set to false since some of the logic below makes assumptions about it.
  3953. // The `.withItems` call below should be updated if we ever need to switch this to `true`.
  3954. descendants: false
  3955. },] }],
  3956. connectedTo: [{ type: Input, args: ['cdkDropListConnectedTo',] }],
  3957. data: [{ type: Input, args: ['cdkDropListData',] }],
  3958. orientation: [{ type: Input, args: ['cdkDropListOrientation',] }],
  3959. id: [{ type: Input }],
  3960. lockAxis: [{ type: Input, args: ['cdkDropListLockAxis',] }],
  3961. disabled: [{ type: Input, args: ['cdkDropListDisabled',] }],
  3962. sortingDisabled: [{ type: Input, args: ['cdkDropListSortingDisabled',] }],
  3963. enterPredicate: [{ type: Input, args: ['cdkDropListEnterPredicate',] }],
  3964. autoScrollDisabled: [{ type: Input, args: ['cdkDropListAutoScrollDisabled',] }],
  3965. dropped: [{ type: Output, args: ['cdkDropListDropped',] }],
  3966. entered: [{ type: Output, args: ['cdkDropListEntered',] }],
  3967. exited: [{ type: Output, args: ['cdkDropListExited',] }],
  3968. sorted: [{ type: Output, args: ['cdkDropListSorted',] }]
  3969. };
  3970. /**
  3971. * @fileoverview added by tsickle
  3972. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  3973. */
  3974. class DragDropModule {
  3975. }
  3976. DragDropModule.decorators = [
  3977. { type: NgModule, args: [{
  3978. declarations: [
  3979. CdkDropList,
  3980. CdkDropListGroup,
  3981. CdkDrag,
  3982. CdkDragHandle,
  3983. CdkDragPreview,
  3984. CdkDragPlaceholder,
  3985. ],
  3986. exports: [
  3987. CdkDropList,
  3988. CdkDropListGroup,
  3989. CdkDrag,
  3990. CdkDragHandle,
  3991. CdkDragPreview,
  3992. CdkDragPlaceholder,
  3993. ],
  3994. providers: [
  3995. DragDrop,
  3996. ]
  3997. },] },
  3998. ];
  3999. /**
  4000. * @fileoverview added by tsickle
  4001. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  4002. */
  4003. /**
  4004. * @fileoverview added by tsickle
  4005. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  4006. */
  4007. export { DragDrop, DragRef, DropListRef, CdkDropList, CDK_DROP_LIST, CDK_DROP_LIST_CONTAINER, moveItemInArray, transferArrayItem, copyArrayItem, DragDropModule, DragDropRegistry, CdkDropListGroup, CDK_DRAG_CONFIG_FACTORY, CDK_DRAG_CONFIG, CdkDrag, CdkDragHandle, CdkDragPreview, CdkDragPlaceholder, CDK_DRAG_PARENT as ɵb };
  4008. //# sourceMappingURL=drag-drop.js.map