github.com/Ilhicas/nomad@v1.0.4-0.20210304152020-e86851182bc3/ui/app/mixins/sortable-factory.js (about)

     1  import Mixin from '@ember/object/mixin';
     2  import Ember from 'ember';
     3  import { computed } from '@ember/object';
     4  import { warn } from '@ember/debug';
     5  
     6  /**
     7    Sortable mixin factory
     8  
     9    Simple sorting behavior for a list of objects. Pass the list of properties
    10    you want the list to be live-sorted based on, or use the generic sortable.js
    11    if you don’t need that.
    12  
    13    Properties to override:
    14      - sortProperty: the property to sort by
    15      - sortDescending: when true, the list is reversed
    16      - listToSort: the list of objects to sort
    17  
    18    Properties provided:
    19      - listSorted: a copy of listToSort that has been sorted
    20  */
    21  export default function sortableFactory(properties, fromSortableMixin) {
    22    const eachProperties = properties.map(property => `listToSort.@each.${property}`);
    23  
    24    // eslint-disable-next-line ember/no-new-mixins
    25    return Mixin.create({
    26      // Override in mixin consumer
    27      sortProperty: null,
    28      sortDescending: true,
    29      listToSort: computed(function() {
    30        return [];
    31      }),
    32  
    33      _sortableFactoryWarningPrinted: false,
    34  
    35      listSorted: computed(
    36        ...eachProperties,
    37        '_sortableFactoryWarningPrinted',
    38        'listToSort.[]',
    39        'sortDescending',
    40        'sortProperty',
    41        function() {
    42          if (!this._sortableFactoryWarningPrinted && !Ember.testing) {
    43            let message =
    44              'Using SortableFactory without property keys means the list will only sort when the members change, not when any of their properties change.';
    45  
    46            if (fromSortableMixin) {
    47              message += ' The Sortable mixin is deprecated in favor of SortableFactory.';
    48            }
    49  
    50            warn(message, properties.length > 0, { id: 'nomad.no-sortable-properties' });
    51            // eslint-disable-next-line ember/no-side-effects
    52            this.set('_sortableFactoryWarningPrinted', true);
    53          }
    54  
    55          const sorted = this.listToSort.compact().sortBy(this.sortProperty);
    56          if (this.sortDescending) {
    57            return sorted.reverse();
    58          }
    59          return sorted;
    60        }
    61      ),
    62    });
    63  }