Source: widgets/list.js

Source: widgets/list.js

  1. /*
  2. * This file is part of Toolkit.
  3. *
  4. * Toolkit is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 3 of the License, or (at your option) any later version.
  8. *
  9. * Toolkit is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General
  15. * Public License along with this program; if not, write to the
  16. * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  17. * Boston, MA 02110-1301 USA
  18. */
  19. "use strict";
  20. (function (w, TK) {
  21. TK.List = TK.class({
  22. /**
  23. * TK.List is a sortable {@link TK.Container} for {@TK.ListItems}s.
  24. * the element is a UL instead of a DIV.
  25. *
  26. * @param {Object} [options={ }] - An object containing initial options.
  27. *
  28. * @property {Function|Boolean} [options.sort=false] - A function
  29. * expecting arguments A and B, returning a number <0, if A comes first and >0,
  30. * if B comes first. 0 keeps both elements in place. Please refer to the
  31. * compareFunction at <a href="https://www.w3schools.com/jsref/jsref_sort.asp">W3Schools</a>
  32. * for any further information.
  33. *
  34. * @class TK.List
  35. *
  36. * @extends TK.Container
  37. */
  38. _options: Object.assign(Object.create(TK.Container.prototype._options), {
  39. sort: "function",
  40. }),
  41. _class: "List",
  42. Extends: TK.Container,
  43. initialize: function (options) {
  44. this.element = TK.element("ul", "toolkit-list");
  45. TK.Container.prototype.initialize.call(this, options);
  46. },
  47. static_events: {
  48. set_sort: function(f) {
  49. if (typeof(f) === "function") {
  50. var C = this.children.slice(0);
  51. C.sort(f);
  52. for (var i = 0; i < C.length; i++) {
  53. this.element.appendChild(C[i].element);
  54. }
  55. }
  56. },
  57. },
  58. append_child: function(w) {
  59. TK.Container.prototype.append_child.call(this, w);
  60. var O = this.options;
  61. var C = this.children;
  62. if (O.sort) {
  63. C.sort(O.sort);
  64. var pos = C.indexOf(w);
  65. if (pos !== C.length - 1)
  66. this.element.insertBefore(w.element, C[pos+1].element);
  67. }
  68. },
  69. });
  70. })(this, this.TK);