collections.mjs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. import { ConnectableObservable, isObservable, of, Subject } from 'rxjs';
  2. import * as i0 from '@angular/core';
  3. import { Injectable, InjectionToken } from '@angular/core';
  4. class DataSource {
  5. }
  6. /** Checks whether an object is a data source. */
  7. function isDataSource(value) {
  8. // Check if the value is a DataSource by observing if it has a connect function. Cannot
  9. // be checked as an `instanceof DataSource` since people could create their own sources
  10. // that match the interface, but don't extend DataSource. We also can't use `isObservable`
  11. // here, because of some internal apps.
  12. return value && typeof value.connect === 'function' && !(value instanceof ConnectableObservable);
  13. }
  14. /** DataSource wrapper for a native array. */
  15. class ArrayDataSource extends DataSource {
  16. constructor(_data) {
  17. super();
  18. this._data = _data;
  19. }
  20. connect() {
  21. return isObservable(this._data) ? this._data : of(this._data);
  22. }
  23. disconnect() { }
  24. }
  25. /**
  26. * A repeater that destroys views when they are removed from a
  27. * {@link ViewContainerRef}. When new items are inserted into the container,
  28. * the repeater will always construct a new embedded view for each item.
  29. *
  30. * @template T The type for the embedded view's $implicit property.
  31. * @template R The type for the item in each IterableDiffer change record.
  32. * @template C The type for the context passed to each embedded view.
  33. */
  34. class _DisposeViewRepeaterStrategy {
  35. applyChanges(changes, viewContainerRef, itemContextFactory, itemValueResolver, itemViewChanged) {
  36. changes.forEachOperation((record, adjustedPreviousIndex, currentIndex) => {
  37. let view;
  38. let operation;
  39. if (record.previousIndex == null) {
  40. const insertContext = itemContextFactory(record, adjustedPreviousIndex, currentIndex);
  41. view = viewContainerRef.createEmbeddedView(insertContext.templateRef, insertContext.context, insertContext.index);
  42. operation = 1 /* _ViewRepeaterOperation.INSERTED */;
  43. }
  44. else if (currentIndex == null) {
  45. viewContainerRef.remove(adjustedPreviousIndex);
  46. operation = 3 /* _ViewRepeaterOperation.REMOVED */;
  47. }
  48. else {
  49. view = viewContainerRef.get(adjustedPreviousIndex);
  50. viewContainerRef.move(view, currentIndex);
  51. operation = 2 /* _ViewRepeaterOperation.MOVED */;
  52. }
  53. if (itemViewChanged) {
  54. itemViewChanged({
  55. context: view?.context,
  56. operation,
  57. record,
  58. });
  59. }
  60. });
  61. }
  62. detach() { }
  63. }
  64. /**
  65. * A repeater that caches views when they are removed from a
  66. * {@link ViewContainerRef}. When new items are inserted into the container,
  67. * the repeater will reuse one of the cached views instead of creating a new
  68. * embedded view. Recycling cached views reduces the quantity of expensive DOM
  69. * inserts.
  70. *
  71. * @template T The type for the embedded view's $implicit property.
  72. * @template R The type for the item in each IterableDiffer change record.
  73. * @template C The type for the context passed to each embedded view.
  74. */
  75. class _RecycleViewRepeaterStrategy {
  76. constructor() {
  77. /**
  78. * The size of the cache used to store unused views.
  79. * Setting the cache size to `0` will disable caching. Defaults to 20 views.
  80. */
  81. this.viewCacheSize = 20;
  82. /**
  83. * View cache that stores embedded view instances that have been previously stamped out,
  84. * but don't are not currently rendered. The view repeater will reuse these views rather than
  85. * creating brand new ones.
  86. *
  87. * TODO(michaeljamesparsons) Investigate whether using a linked list would improve performance.
  88. */
  89. this._viewCache = [];
  90. }
  91. /** Apply changes to the DOM. */
  92. applyChanges(changes, viewContainerRef, itemContextFactory, itemValueResolver, itemViewChanged) {
  93. // Rearrange the views to put them in the right location.
  94. changes.forEachOperation((record, adjustedPreviousIndex, currentIndex) => {
  95. let view;
  96. let operation;
  97. if (record.previousIndex == null) {
  98. // Item added.
  99. const viewArgsFactory = () => itemContextFactory(record, adjustedPreviousIndex, currentIndex);
  100. view = this._insertView(viewArgsFactory, currentIndex, viewContainerRef, itemValueResolver(record));
  101. operation = view ? 1 /* _ViewRepeaterOperation.INSERTED */ : 0 /* _ViewRepeaterOperation.REPLACED */;
  102. }
  103. else if (currentIndex == null) {
  104. // Item removed.
  105. this._detachAndCacheView(adjustedPreviousIndex, viewContainerRef);
  106. operation = 3 /* _ViewRepeaterOperation.REMOVED */;
  107. }
  108. else {
  109. // Item moved.
  110. view = this._moveView(adjustedPreviousIndex, currentIndex, viewContainerRef, itemValueResolver(record));
  111. operation = 2 /* _ViewRepeaterOperation.MOVED */;
  112. }
  113. if (itemViewChanged) {
  114. itemViewChanged({
  115. context: view?.context,
  116. operation,
  117. record,
  118. });
  119. }
  120. });
  121. }
  122. detach() {
  123. for (const view of this._viewCache) {
  124. view.destroy();
  125. }
  126. this._viewCache = [];
  127. }
  128. /**
  129. * Inserts a view for a new item, either from the cache or by creating a new
  130. * one. Returns `undefined` if the item was inserted into a cached view.
  131. */
  132. _insertView(viewArgsFactory, currentIndex, viewContainerRef, value) {
  133. const cachedView = this._insertViewFromCache(currentIndex, viewContainerRef);
  134. if (cachedView) {
  135. cachedView.context.$implicit = value;
  136. return undefined;
  137. }
  138. const viewArgs = viewArgsFactory();
  139. return viewContainerRef.createEmbeddedView(viewArgs.templateRef, viewArgs.context, viewArgs.index);
  140. }
  141. /** Detaches the view at the given index and inserts into the view cache. */
  142. _detachAndCacheView(index, viewContainerRef) {
  143. const detachedView = viewContainerRef.detach(index);
  144. this._maybeCacheView(detachedView, viewContainerRef);
  145. }
  146. /** Moves view at the previous index to the current index. */
  147. _moveView(adjustedPreviousIndex, currentIndex, viewContainerRef, value) {
  148. const view = viewContainerRef.get(adjustedPreviousIndex);
  149. viewContainerRef.move(view, currentIndex);
  150. view.context.$implicit = value;
  151. return view;
  152. }
  153. /**
  154. * Cache the given detached view. If the cache is full, the view will be
  155. * destroyed.
  156. */
  157. _maybeCacheView(view, viewContainerRef) {
  158. if (this._viewCache.length < this.viewCacheSize) {
  159. this._viewCache.push(view);
  160. }
  161. else {
  162. const index = viewContainerRef.indexOf(view);
  163. // The host component could remove views from the container outside of
  164. // the view repeater. It's unlikely this will occur, but just in case,
  165. // destroy the view on its own, otherwise destroy it through the
  166. // container to ensure that all the references are removed.
  167. if (index === -1) {
  168. view.destroy();
  169. }
  170. else {
  171. viewContainerRef.remove(index);
  172. }
  173. }
  174. }
  175. /** Inserts a recycled view from the cache at the given index. */
  176. _insertViewFromCache(index, viewContainerRef) {
  177. const cachedView = this._viewCache.pop();
  178. if (cachedView) {
  179. viewContainerRef.insert(cachedView, index);
  180. }
  181. return cachedView || null;
  182. }
  183. }
  184. /**
  185. * Class to be used to power selecting one or more options from a list.
  186. */
  187. class SelectionModel {
  188. /** Selected values. */
  189. get selected() {
  190. if (!this._selected) {
  191. this._selected = Array.from(this._selection.values());
  192. }
  193. return this._selected;
  194. }
  195. constructor(_multiple = false, initiallySelectedValues, _emitChanges = true, compareWith) {
  196. this._multiple = _multiple;
  197. this._emitChanges = _emitChanges;
  198. this.compareWith = compareWith;
  199. /** Currently-selected values. */
  200. this._selection = new Set();
  201. /** Keeps track of the deselected options that haven't been emitted by the change event. */
  202. this._deselectedToEmit = [];
  203. /** Keeps track of the selected options that haven't been emitted by the change event. */
  204. this._selectedToEmit = [];
  205. /** Event emitted when the value has changed. */
  206. this.changed = new Subject();
  207. if (initiallySelectedValues && initiallySelectedValues.length) {
  208. if (_multiple) {
  209. initiallySelectedValues.forEach(value => this._markSelected(value));
  210. }
  211. else {
  212. this._markSelected(initiallySelectedValues[0]);
  213. }
  214. // Clear the array in order to avoid firing the change event for preselected values.
  215. this._selectedToEmit.length = 0;
  216. }
  217. }
  218. /**
  219. * Selects a value or an array of values.
  220. * @param values The values to select
  221. * @return Whether the selection changed as a result of this call
  222. * @breaking-change 16.0.0 make return type boolean
  223. */
  224. select(...values) {
  225. this._verifyValueAssignment(values);
  226. values.forEach(value => this._markSelected(value));
  227. const changed = this._hasQueuedChanges();
  228. this._emitChangeEvent();
  229. return changed;
  230. }
  231. /**
  232. * Deselects a value or an array of values.
  233. * @param values The values to deselect
  234. * @return Whether the selection changed as a result of this call
  235. * @breaking-change 16.0.0 make return type boolean
  236. */
  237. deselect(...values) {
  238. this._verifyValueAssignment(values);
  239. values.forEach(value => this._unmarkSelected(value));
  240. const changed = this._hasQueuedChanges();
  241. this._emitChangeEvent();
  242. return changed;
  243. }
  244. /**
  245. * Sets the selected values
  246. * @param values The new selected values
  247. * @return Whether the selection changed as a result of this call
  248. * @breaking-change 16.0.0 make return type boolean
  249. */
  250. setSelection(...values) {
  251. this._verifyValueAssignment(values);
  252. const oldValues = this.selected;
  253. const newSelectedSet = new Set(values);
  254. values.forEach(value => this._markSelected(value));
  255. oldValues
  256. .filter(value => !newSelectedSet.has(value))
  257. .forEach(value => this._unmarkSelected(value));
  258. const changed = this._hasQueuedChanges();
  259. this._emitChangeEvent();
  260. return changed;
  261. }
  262. /**
  263. * Toggles a value between selected and deselected.
  264. * @param value The value to toggle
  265. * @return Whether the selection changed as a result of this call
  266. * @breaking-change 16.0.0 make return type boolean
  267. */
  268. toggle(value) {
  269. return this.isSelected(value) ? this.deselect(value) : this.select(value);
  270. }
  271. /**
  272. * Clears all of the selected values.
  273. * @param flushEvent Whether to flush the changes in an event.
  274. * If false, the changes to the selection will be flushed along with the next event.
  275. * @return Whether the selection changed as a result of this call
  276. * @breaking-change 16.0.0 make return type boolean
  277. */
  278. clear(flushEvent = true) {
  279. this._unmarkAll();
  280. const changed = this._hasQueuedChanges();
  281. if (flushEvent) {
  282. this._emitChangeEvent();
  283. }
  284. return changed;
  285. }
  286. /**
  287. * Determines whether a value is selected.
  288. */
  289. isSelected(value) {
  290. return this._selection.has(this._getConcreteValue(value));
  291. }
  292. /**
  293. * Determines whether the model does not have a value.
  294. */
  295. isEmpty() {
  296. return this._selection.size === 0;
  297. }
  298. /**
  299. * Determines whether the model has a value.
  300. */
  301. hasValue() {
  302. return !this.isEmpty();
  303. }
  304. /**
  305. * Sorts the selected values based on a predicate function.
  306. */
  307. sort(predicate) {
  308. if (this._multiple && this.selected) {
  309. this._selected.sort(predicate);
  310. }
  311. }
  312. /**
  313. * Gets whether multiple values can be selected.
  314. */
  315. isMultipleSelection() {
  316. return this._multiple;
  317. }
  318. /** Emits a change event and clears the records of selected and deselected values. */
  319. _emitChangeEvent() {
  320. // Clear the selected values so they can be re-cached.
  321. this._selected = null;
  322. if (this._selectedToEmit.length || this._deselectedToEmit.length) {
  323. this.changed.next({
  324. source: this,
  325. added: this._selectedToEmit,
  326. removed: this._deselectedToEmit,
  327. });
  328. this._deselectedToEmit = [];
  329. this._selectedToEmit = [];
  330. }
  331. }
  332. /** Selects a value. */
  333. _markSelected(value) {
  334. value = this._getConcreteValue(value);
  335. if (!this.isSelected(value)) {
  336. if (!this._multiple) {
  337. this._unmarkAll();
  338. }
  339. if (!this.isSelected(value)) {
  340. this._selection.add(value);
  341. }
  342. if (this._emitChanges) {
  343. this._selectedToEmit.push(value);
  344. }
  345. }
  346. }
  347. /** Deselects a value. */
  348. _unmarkSelected(value) {
  349. value = this._getConcreteValue(value);
  350. if (this.isSelected(value)) {
  351. this._selection.delete(value);
  352. if (this._emitChanges) {
  353. this._deselectedToEmit.push(value);
  354. }
  355. }
  356. }
  357. /** Clears out the selected values. */
  358. _unmarkAll() {
  359. if (!this.isEmpty()) {
  360. this._selection.forEach(value => this._unmarkSelected(value));
  361. }
  362. }
  363. /**
  364. * Verifies the value assignment and throws an error if the specified value array is
  365. * including multiple values while the selection model is not supporting multiple values.
  366. */
  367. _verifyValueAssignment(values) {
  368. if (values.length > 1 && !this._multiple && (typeof ngDevMode === 'undefined' || ngDevMode)) {
  369. throw getMultipleValuesInSingleSelectionError();
  370. }
  371. }
  372. /** Whether there are queued up change to be emitted. */
  373. _hasQueuedChanges() {
  374. return !!(this._deselectedToEmit.length || this._selectedToEmit.length);
  375. }
  376. /** Returns a value that is comparable to inputValue by applying compareWith function, returns the same inputValue otherwise. */
  377. _getConcreteValue(inputValue) {
  378. if (!this.compareWith) {
  379. return inputValue;
  380. }
  381. else {
  382. for (let selectedValue of this._selection) {
  383. if (this.compareWith(inputValue, selectedValue)) {
  384. return selectedValue;
  385. }
  386. }
  387. return inputValue;
  388. }
  389. }
  390. }
  391. /**
  392. * Returns an error that reports that multiple values are passed into a selection model
  393. * with a single value.
  394. * @docs-private
  395. */
  396. function getMultipleValuesInSingleSelectionError() {
  397. return Error('Cannot pass multiple values into SelectionModel with single-value mode.');
  398. }
  399. /**
  400. * Class to coordinate unique selection based on name.
  401. * Intended to be consumed as an Angular service.
  402. * This service is needed because native radio change events are only fired on the item currently
  403. * being selected, and we still need to uncheck the previous selection.
  404. *
  405. * This service does not *store* any IDs and names because they may change at any time, so it is
  406. * less error-prone if they are simply passed through when the events occur.
  407. */
  408. class UniqueSelectionDispatcher {
  409. constructor() {
  410. this._listeners = [];
  411. }
  412. /**
  413. * Notify other items that selection for the given name has been set.
  414. * @param id ID of the item.
  415. * @param name Name of the item.
  416. */
  417. notify(id, name) {
  418. for (let listener of this._listeners) {
  419. listener(id, name);
  420. }
  421. }
  422. /**
  423. * Listen for future changes to item selection.
  424. * @return Function used to deregister listener
  425. */
  426. listen(listener) {
  427. this._listeners.push(listener);
  428. return () => {
  429. this._listeners = this._listeners.filter((registered) => {
  430. return listener !== registered;
  431. });
  432. };
  433. }
  434. ngOnDestroy() {
  435. this._listeners = [];
  436. }
  437. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: UniqueSelectionDispatcher, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  438. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: UniqueSelectionDispatcher, providedIn: 'root' }); }
  439. }
  440. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: UniqueSelectionDispatcher, decorators: [{
  441. type: Injectable,
  442. args: [{ providedIn: 'root' }]
  443. }] });
  444. /**
  445. * Injection token for {@link _ViewRepeater}. This token is for use by Angular Material only.
  446. * @docs-private
  447. */
  448. const _VIEW_REPEATER_STRATEGY = new InjectionToken('_ViewRepeater');
  449. /**
  450. * Generated bundle index. Do not edit.
  451. */
  452. export { ArrayDataSource, DataSource, SelectionModel, UniqueSelectionDispatcher, _DisposeViewRepeaterStrategy, _RecycleViewRepeaterStrategy, _VIEW_REPEATER_STRATEGY, getMultipleValuesInSingleSelectionError, isDataSource };
  453. //# sourceMappingURL=collections.mjs.map