drag-drop.mjs 200 KB

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