bootstrap-table-group-by.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /**
  2. * @author: Yura Knoxville
  3. * @version: v1.1.0
  4. */
  5. let initBodyCaller
  6. const groupBy = (array, f) => {
  7. const tmpGroups = {}
  8. array.forEach(o => {
  9. const groups = f(o)
  10. tmpGroups[groups] = tmpGroups[groups] || []
  11. tmpGroups[groups].push(o)
  12. })
  13. return tmpGroups
  14. }
  15. $.extend($.fn.bootstrapTable.defaults.icons, {
  16. collapseGroup: {
  17. bootstrap3: 'glyphicon-chevron-up',
  18. materialize: 'arrow_drop_down'
  19. }[$.fn.bootstrapTable.theme] || 'fa-angle-up',
  20. expandGroup: {
  21. bootstrap3: 'glyphicon-chevron-down',
  22. materialize: 'arrow_drop_up'
  23. }[$.fn.bootstrapTable.theme] || 'fa-angle-down'
  24. })
  25. $.extend($.fn.bootstrapTable.defaults, {
  26. groupBy: false,
  27. groupByField: '',
  28. groupByFormatter: undefined,
  29. groupByToggle: false,
  30. groupByShowToggleIcon: false,
  31. groupByCollapsedGroups: []
  32. })
  33. const Utils = $.fn.bootstrapTable.utils
  34. const BootstrapTable = $.fn.bootstrapTable.Constructor
  35. const _initSort = BootstrapTable.prototype.initSort
  36. const _initBody = BootstrapTable.prototype.initBody
  37. const _updateSelected = BootstrapTable.prototype.updateSelected
  38. BootstrapTable.prototype.initSort = function (...args) {
  39. _initSort.apply(this, Array.prototype.slice.apply(args))
  40. const that = this
  41. this.tableGroups = []
  42. if ((this.options.groupBy) && (this.options.groupByField !== '')) {
  43. if ((this.options.sortName !== this.options.groupByField)) {
  44. if (this.options.customSort) {
  45. Utils.calculateObjectValue(this.options, this.options.customSort, [
  46. this.options.sortName,
  47. this.options.sortOrder,
  48. this.data
  49. ])
  50. } else {
  51. this.data.sort((a, b) => {
  52. const groupByFields = this.getGroupByFields()
  53. const fieldValuesA = []
  54. const fieldValuesB = []
  55. $.each(groupByFields, (i, field) => {
  56. fieldValuesA.push(a[field])
  57. fieldValuesB.push(b[field])
  58. })
  59. a = fieldValuesA.join()
  60. b = fieldValuesB.join()
  61. return a.localeCompare(b, undefined, {numeric: true})
  62. })
  63. }
  64. }
  65. const groups = groupBy(that.data, (item) => {
  66. const groupByFields = this.getGroupByFields()
  67. const groupValues = []
  68. $.each(groupByFields, (i, field) => {
  69. groupValues.push(item[field])
  70. })
  71. return groupValues.join(', ')
  72. })
  73. let index = 0
  74. $.each(groups, (key, value) => {
  75. this.tableGroups.push({
  76. id: index,
  77. name: key,
  78. data: value
  79. })
  80. value.forEach(item => {
  81. if (!item._data) {
  82. item._data = {}
  83. }
  84. if (this.isCollapsed(key, value)) {
  85. item._class = 'hidden'
  86. }
  87. item._data['parent-index'] = index
  88. })
  89. index++
  90. })
  91. }
  92. }
  93. BootstrapTable.prototype.initBody = function (...args) {
  94. initBodyCaller = true
  95. _initBody.apply(this, Array.prototype.slice.apply(args))
  96. if ((this.options.groupBy) && (this.options.groupByField !== '')) {
  97. const that = this
  98. let checkBox = false
  99. let visibleColumns = 0
  100. this.columns.forEach(column => {
  101. if (column.checkbox) {
  102. checkBox = true
  103. } else {
  104. if (column.visible) {
  105. visibleColumns += 1
  106. }
  107. }
  108. })
  109. if (this.options.detailView && !this.options.cardView) {
  110. visibleColumns += 1
  111. }
  112. this.tableGroups.forEach(item => {
  113. const html = []
  114. html.push(Utils.sprintf('<tr class="info groupBy %s" data-group-index="%s">', this.options.groupByToggle ? 'expanded' : '', item.id))
  115. if (that.options.detailView && !that.options.cardView) {
  116. html.push('<td class="detail"></td>')
  117. }
  118. if (checkBox) {
  119. html.push('<td class="bs-checkbox">',
  120. '<input name="btSelectGroup" type="checkbox" />',
  121. '</td>'
  122. )
  123. }
  124. let formattedValue = item.name
  125. if (typeof (that.options.groupByFormatter) === 'function') {
  126. formattedValue = that.options.groupByFormatter(item.name, item.id, item.data)
  127. }
  128. html.push('<td',
  129. Utils.sprintf(' colspan="%s"', visibleColumns),
  130. '>', formattedValue
  131. )
  132. let icon = this.options.icons.collapseGroup
  133. if (this.isCollapsed(item.name, item.data)) {
  134. icon = this.options.icons.expandGroup
  135. }
  136. if (this.options.groupByToggle && this.options.groupByShowToggleIcon) {
  137. html.push(`<span class="float-right ${this.options.iconsPrefix} ${icon}"></span>`)
  138. }
  139. html.push('</td></tr>')
  140. that.$body.find(`tr[data-parent-index=${item.id}]:first`).before($(html.join('')))
  141. })
  142. this.$selectGroup = []
  143. this.$body.find('[name="btSelectGroup"]').each(function () {
  144. const self = $(this)
  145. that.$selectGroup.push({
  146. group: self,
  147. item: that.$selectItem.filter(function () {
  148. return ($(this).closest('tr').data('parent-index') ===
  149. self.closest('tr').data('group-index'))
  150. })
  151. })
  152. })
  153. if (this.options.groupByToggle) {
  154. this.$container.off('click', '.groupBy')
  155. .on('click', '.groupBy', function () {
  156. $(this).toggleClass('expanded collapsed')
  157. $(this).find('span').toggleClass(`${that.options.icons.collapseGroup} ${that.options.icons.expandGroup}`)
  158. that.$body.find(`tr[data-parent-index=${$(this).closest('tr').data('group-index')}]`).toggleClass('hidden')
  159. })
  160. }
  161. this.$container.off('click', '[name="btSelectGroup"]')
  162. .on('click', '[name="btSelectGroup"]', function (event) {
  163. event.stopImmediatePropagation()
  164. const self = $(this)
  165. const checked = self.prop('checked')
  166. that[checked ? 'checkGroup' : 'uncheckGroup']($(this).closest('tr').data('group-index'))
  167. })
  168. }
  169. initBodyCaller = false
  170. this.updateSelected()
  171. }
  172. BootstrapTable.prototype.updateSelected = function (...args) {
  173. if (!initBodyCaller) {
  174. _updateSelected.apply(this, Array.prototype.slice.apply(args))
  175. if ((this.options.groupBy) && (this.options.groupByField !== '')) {
  176. this.$selectGroup.forEach(item => {
  177. const checkGroup = item.item.filter(':enabled').length ===
  178. item.item.filter(':enabled').filter(':checked').length
  179. item.group.prop('checked', checkGroup)
  180. })
  181. }
  182. }
  183. }
  184. BootstrapTable.prototype.checkGroup = function (index) {
  185. this.checkGroup_(index, true)
  186. }
  187. BootstrapTable.prototype.uncheckGroup = function (index) {
  188. this.checkGroup_(index, false)
  189. }
  190. BootstrapTable.prototype.isCollapsed = function (groupKey, items) {
  191. if (this.options.groupByCollapsedGroups) {
  192. const collapsedGroups = Utils.calculateObjectValue(this, this.options.groupByCollapsedGroups, [groupKey, items], true)
  193. if ($.inArray(groupKey, collapsedGroups) > -1) {
  194. return true
  195. }
  196. }
  197. return false
  198. }
  199. BootstrapTable.prototype.checkGroup_ = function (index, checked) {
  200. const rowsBefore = this.getSelections()
  201. let rows
  202. const filter = function () {
  203. return ($(this).closest('tr').data('parent-index') === index)
  204. }
  205. this.$selectItem.filter(filter).prop('checked', checked)
  206. this.updateRows()
  207. this.updateSelected()
  208. const rowsAfter = this.getSelections()
  209. if (checked) {
  210. this.trigger('check-all', rowsAfter, rowsBefore)
  211. return
  212. }
  213. this.trigger('uncheck-all', rowsAfter, rowsBefore)
  214. }
  215. BootstrapTable.prototype.getGroupByFields = function () {
  216. let groupByFields = this.options.groupByField
  217. if (!$.isArray(this.options.groupByField)) {
  218. groupByFields = [this.options.groupByField]
  219. }
  220. return groupByFields
  221. }
  222. $.BootstrapTable = class extends $.BootstrapTable {
  223. scrollTo (params) {
  224. if (this.options.groupBy) {
  225. let options = {unit: 'px', value: 0}
  226. if (typeof params === 'object') {
  227. options = Object.assign(options, params)
  228. }
  229. if (options.unit === 'rows') {
  230. let scrollTo = 0
  231. this.$body.find(`> tr:not(.groupBy):lt(${options.value})`).each((i, el) => {
  232. scrollTo += $(el).outerHeight(true)
  233. })
  234. const $targetColumn = this.$body.find(`> tr:not(.groupBy):eq(${options.value})`)
  235. $targetColumn.prevAll('.groupBy').each((i, el) => {
  236. scrollTo += $(el).outerHeight(true)
  237. })
  238. this.$tableBody.scrollTop(scrollTo)
  239. return
  240. }
  241. }
  242. super.scrollTo(params)
  243. }
  244. }