github.com/hernad/nomad@v1.6.112/ui/app/mixins/sortable-factory.js (about)

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