list.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. import { ReactiveCache } from '/imports/reactiveCache';
  2. import { TAPi18n } from '/imports/i18n';
  3. require('/client/lib/jquery-ui.js')
  4. const { calculateIndex } = Utils;
  5. BlazeComponent.extendComponent({
  6. // Proxy
  7. openForm(options) {
  8. this.childComponents('listBody')[0].openForm(options);
  9. },
  10. onCreated() {
  11. this.newCardFormIsVisible = new ReactiveVar(true);
  12. },
  13. // The jquery UI sortable library is the best solution I've found so far. I
  14. // tried sortable and dragula but they were not powerful enough four our use
  15. // case. I also considered writing/forking a drag-and-drop + sortable library
  16. // but it's probably too much work.
  17. // By calling asking the sortable library to cancel its move on the `stop`
  18. // callback, we basically solve all issues related to reactive updates. A
  19. // comment below provides further details.
  20. onRendered() {
  21. const boardComponent = this.parentComponent().parentComponent();
  22. // Initialize list resize functionality
  23. this.initializeListResize();
  24. const itemsSelector = '.js-minicard:not(.placeholder, .js-card-composer)';
  25. const $cards = this.$('.js-minicards');
  26. $cards.sortable({
  27. connectWith: '.js-minicards:not(.js-list-full)',
  28. tolerance: 'pointer',
  29. appendTo: '.board-canvas',
  30. helper(evt, item) {
  31. const helper = item.clone();
  32. if (MultiSelection.isActive()) {
  33. const andNOthers = $cards.find('.js-minicard.is-checked').length - 1;
  34. if (andNOthers > 0) {
  35. helper.append(
  36. $(
  37. Blaze.toHTML(
  38. HTML.DIV(
  39. { class: 'and-n-other' },
  40. TAPi18n.__('and-n-other-card', { count: andNOthers }),
  41. ),
  42. ),
  43. ),
  44. );
  45. }
  46. }
  47. return helper;
  48. },
  49. distance: 7,
  50. items: itemsSelector,
  51. placeholder: 'minicard-wrapper placeholder',
  52. scrollSpeed: 10,
  53. start(evt, ui) {
  54. ui.helper.css('z-index', 1000);
  55. ui.placeholder.height(ui.helper.height());
  56. EscapeActions.executeUpTo('popup-close');
  57. boardComponent.setIsDragging(true);
  58. },
  59. stop(evt, ui) {
  60. // To attribute the new index number, we need to get the DOM element
  61. // of the previous and the following card -- if any.
  62. const prevCardDom = ui.item.prev('.js-minicard').get(0);
  63. const nextCardDom = ui.item.next('.js-minicard').get(0);
  64. const nCards = MultiSelection.isActive() ? MultiSelection.count() : 1;
  65. const sortIndex = calculateIndex(prevCardDom, nextCardDom, nCards);
  66. const listId = Blaze.getData(ui.item.parents('.list').get(0))._id;
  67. const currentBoard = Utils.getCurrentBoard();
  68. const defaultSwimlaneId = currentBoard.getDefaultSwimline()._id;
  69. let targetSwimlaneId = null;
  70. // only set a new swimelane ID if the swimlanes view is active
  71. if (
  72. Utils.boardView() === 'board-view-swimlanes' ||
  73. currentBoard.isTemplatesBoard()
  74. )
  75. targetSwimlaneId = Blaze.getData(ui.item.parents('.swimlane').get(0))
  76. ._id;
  77. // Normally the jquery-ui sortable library moves the dragged DOM element
  78. // to its new position, which disrupts Blaze reactive updates mechanism
  79. // (especially when we move the last card of a list, or when multiple
  80. // users move some cards at the same time). To prevent these UX glitches
  81. // we ask sortable to gracefully cancel the move, and to put back the
  82. // DOM in its initial state. The card move is then handled reactively by
  83. // Blaze with the below query.
  84. $cards.sortable('cancel');
  85. if (MultiSelection.isActive()) {
  86. ReactiveCache.getCards(MultiSelection.getMongoSelector(), { sort: ['sort'] }).forEach((card, i) => {
  87. const newSwimlaneId = targetSwimlaneId
  88. ? targetSwimlaneId
  89. : card.swimlaneId || defaultSwimlaneId;
  90. card.move(
  91. currentBoard._id,
  92. newSwimlaneId,
  93. listId,
  94. sortIndex.base + i * sortIndex.increment,
  95. );
  96. });
  97. } else {
  98. const cardDomElement = ui.item.get(0);
  99. const card = Blaze.getData(cardDomElement);
  100. const newSwimlaneId = targetSwimlaneId
  101. ? targetSwimlaneId
  102. : card.swimlaneId || defaultSwimlaneId;
  103. card.move(currentBoard._id, newSwimlaneId, listId, sortIndex.base);
  104. }
  105. boardComponent.setIsDragging(false);
  106. },
  107. sort(event, ui) {
  108. const $boardCanvas = $('.board-canvas');
  109. const boardCanvas = $boardCanvas[0];
  110. if (event.pageX < 10) { // scroll to the left
  111. boardCanvas.scrollLeft -= 15;
  112. ui.helper[0].offsetLeft -= 15;
  113. }
  114. if (
  115. event.pageX > boardCanvas.offsetWidth - 10 &&
  116. boardCanvas.scrollLeft < $boardCanvas.data('scrollLeftMax') // don't scroll more than possible
  117. ) { // scroll to the right
  118. boardCanvas.scrollLeft += 15;
  119. }
  120. if (
  121. event.pageY > boardCanvas.offsetHeight - 10 &&
  122. event.pageY + boardCanvas.scrollTop < $boardCanvas.data('scrollTopMax') // don't scroll more than possible
  123. ) { // scroll to the bottom
  124. boardCanvas.scrollTop += 15;
  125. }
  126. if (event.pageY < 10) { // scroll to the top
  127. boardCanvas.scrollTop -= 15;
  128. }
  129. },
  130. activate(event, ui) {
  131. const $boardCanvas = $('.board-canvas');
  132. const boardCanvas = $boardCanvas[0];
  133. // scrollTopMax and scrollLeftMax only available at Firefox (https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTopMax)
  134. // https://www.it-swarm.com.de/de/javascript/so-erhalten-sie-den-maximalen-dokument-scrolltop-wert/1069126844/
  135. $boardCanvas.data('scrollTopMax', boardCanvas.scrollHeight - boardCanvas.clientTop);
  136. // https://stackoverflow.com/questions/5138373/how-do-i-get-the-max-value-of-scrollleft/5704386#5704386
  137. $boardCanvas.data('scrollLeftMax', boardCanvas.scrollWidth - boardCanvas.clientWidth);
  138. },
  139. });
  140. this.autorun(() => {
  141. if (Utils.isTouchScreenOrShowDesktopDragHandles()) {
  142. $cards.sortable({
  143. handle: '.handle',
  144. });
  145. } else {
  146. $cards.sortable({
  147. handle: '.minicard',
  148. });
  149. }
  150. if ($cards.data('uiSortable') || $cards.data('sortable')) {
  151. $cards.sortable(
  152. 'option',
  153. 'disabled',
  154. // Disable drag-dropping when user is not member
  155. !Utils.canModifyBoard(),
  156. // Not disable drag-dropping while in multi-selection mode
  157. // MultiSelection.isActive() || !Utils.canModifyBoard(),
  158. );
  159. }
  160. });
  161. // We want to re-run this function any time a card is added.
  162. this.autorun(() => {
  163. const currentBoardId = Tracker.nonreactive(() => {
  164. return Session.get('currentBoard');
  165. });
  166. Tracker.afterFlush(() => {
  167. $cards.find(itemsSelector).droppable({
  168. hoverClass: 'draggable-hover-card',
  169. accept: '.js-member,.js-label',
  170. drop(event, ui) {
  171. const cardId = Blaze.getData(this)._id;
  172. const card = ReactiveCache.getCard(cardId);
  173. if (ui.draggable.hasClass('js-member')) {
  174. const memberId = Blaze.getData(ui.draggable.get(0)).userId;
  175. card.assignMember(memberId);
  176. } else {
  177. const labelId = Blaze.getData(ui.draggable.get(0))._id;
  178. card.addLabel(labelId);
  179. }
  180. },
  181. });
  182. });
  183. });
  184. },
  185. listWidth() {
  186. const user = ReactiveCache.getCurrentUser();
  187. const list = Template.currentData();
  188. return user.getListWidth(list.boardId, list._id);
  189. },
  190. listConstraint() {
  191. const user = ReactiveCache.getCurrentUser();
  192. const list = Template.currentData();
  193. return user.getListConstraint(list.boardId, list._id);
  194. },
  195. autoWidth() {
  196. const user = ReactiveCache.getCurrentUser();
  197. const list = Template.currentData();
  198. return user.isAutoWidth(list.boardId);
  199. },
  200. initializeListResize() {
  201. const list = Template.currentData();
  202. const $list = this.$('.js-list');
  203. const $resizeHandle = this.$('.js-list-resize-handle');
  204. // Only enable resize for non-collapsed, non-auto-width lists
  205. if (list.collapsed || this.autoWidth()) {
  206. $resizeHandle.hide();
  207. return;
  208. }
  209. let isResizing = false;
  210. let startX = 0;
  211. let startWidth = 0;
  212. let minWidth = 100; // Minimum width as defined in the existing code
  213. let maxWidth = this.listConstraint() || 1000; // Use constraint as max width
  214. let listConstraint = this.listConstraint(); // Store constraint value for use in event handlers
  215. const component = this; // Store reference to component for use in event handlers
  216. const startResize = (e) => {
  217. isResizing = true;
  218. startX = e.pageX || e.originalEvent.touches[0].pageX;
  219. startWidth = $list.outerWidth();
  220. // Add visual feedback
  221. $list.addClass('list-resizing');
  222. $('body').addClass('list-resizing-active');
  223. // Prevent text selection during resize
  224. $('body').css('user-select', 'none');
  225. e.preventDefault();
  226. };
  227. const doResize = (e) => {
  228. if (!isResizing) return;
  229. const currentX = e.pageX || e.originalEvent.touches[0].pageX;
  230. const deltaX = currentX - startX;
  231. const newWidth = Math.max(minWidth, Math.min(maxWidth, startWidth + deltaX));
  232. // Apply the new width immediately for real-time feedback using CSS custom properties
  233. $list[0].style.setProperty('--list-width', `${newWidth}px`);
  234. $list.css({
  235. 'width': `${newWidth}px`,
  236. 'min-width': `${newWidth}px`,
  237. 'max-width': `${newWidth}px`,
  238. 'flex': 'none',
  239. 'flex-basis': 'auto',
  240. 'flex-grow': '0',
  241. 'flex-shrink': '0'
  242. });
  243. // Debug: log the width change
  244. if (process.env.DEBUG === 'true') {
  245. console.log(`Resizing list to ${newWidth}px`);
  246. }
  247. e.preventDefault();
  248. };
  249. const stopResize = (e) => {
  250. if (!isResizing) return;
  251. isResizing = false;
  252. // Calculate final width
  253. const currentX = e.pageX || e.originalEvent.touches[0].pageX;
  254. const deltaX = currentX - startX;
  255. const finalWidth = Math.max(minWidth, Math.min(maxWidth, startWidth + deltaX));
  256. // Ensure the final width is applied using CSS custom properties
  257. $list[0].style.setProperty('--list-width', `${finalWidth}px`);
  258. $list.css({
  259. 'width': `${finalWidth}px`,
  260. 'min-width': `${finalWidth}px`,
  261. 'max-width': `${finalWidth}px`,
  262. 'flex': 'none',
  263. 'flex-basis': 'auto',
  264. 'flex-grow': '0',
  265. 'flex-shrink': '0'
  266. });
  267. // Remove visual feedback but keep the width
  268. $list.removeClass('list-resizing');
  269. $('body').removeClass('list-resizing-active');
  270. $('body').css('user-select', '');
  271. // Keep the CSS custom property for persistent width
  272. // The CSS custom property will remain on the element to maintain the width
  273. // Save the new width using the existing system
  274. const boardId = list.boardId;
  275. const listId = list._id;
  276. // Use the same method as the hamburger menu
  277. if (process.env.DEBUG === 'true') {
  278. console.log(`Saving list width: ${finalWidth}px for list ${listId}`);
  279. }
  280. Meteor.call('applyListWidth', boardId, listId, finalWidth, listConstraint, (error, result) => {
  281. if (error) {
  282. console.error('Error saving list width:', error);
  283. } else {
  284. if (process.env.DEBUG === 'true') {
  285. console.log('List width saved successfully:', result);
  286. }
  287. }
  288. });
  289. e.preventDefault();
  290. };
  291. // Mouse events
  292. $resizeHandle.on('mousedown', startResize);
  293. $(document).on('mousemove', doResize);
  294. $(document).on('mouseup', stopResize);
  295. // Touch events for mobile
  296. $resizeHandle.on('touchstart', startResize);
  297. $(document).on('touchmove', doResize);
  298. $(document).on('touchend', stopResize);
  299. // Reactively update resize handle visibility when auto-width changes
  300. component.autorun(() => {
  301. if (component.autoWidth()) {
  302. $resizeHandle.hide();
  303. } else {
  304. $resizeHandle.show();
  305. }
  306. });
  307. // Clean up on component destruction
  308. component.onDestroyed(() => {
  309. $(document).off('mousemove', doResize);
  310. $(document).off('mouseup', stopResize);
  311. $(document).off('touchmove', doResize);
  312. $(document).off('touchend', stopResize);
  313. });
  314. },
  315. }).register('list');
  316. Template.miniList.events({
  317. 'click .js-select-list'() {
  318. const listId = this._id;
  319. Session.set('currentList', listId);
  320. },
  321. });