list.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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 immediately
  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 ($cards.data('uiSortable') || $cards.data('sortable')) {
  142. if (Utils.isTouchScreenOrShowDesktopDragHandles()) {
  143. $cards.sortable('option', 'handle', '.handle');
  144. } else {
  145. $cards.sortable('option', 'handle', '.minicard');
  146. }
  147. $cards.sortable(
  148. 'option',
  149. 'disabled',
  150. // Disable drag-dropping when user is not member
  151. !Utils.canModifyBoard(),
  152. // Not disable drag-dropping while in multi-selection mode
  153. // MultiSelection.isActive() || !Utils.canModifyBoard(),
  154. );
  155. }
  156. });
  157. // We want to re-run this function any time a card is added.
  158. this.autorun(() => {
  159. const currentBoardId = Tracker.nonreactive(() => {
  160. return Session.get('currentBoard');
  161. });
  162. Tracker.afterFlush(() => {
  163. $cards.find(itemsSelector).droppable({
  164. hoverClass: 'draggable-hover-card',
  165. accept: '.js-member,.js-label',
  166. drop(event, ui) {
  167. const cardId = Blaze.getData(this)._id;
  168. const card = ReactiveCache.getCard(cardId);
  169. if (ui.draggable.hasClass('js-member')) {
  170. const memberId = Blaze.getData(ui.draggable.get(0)).userId;
  171. card.assignMember(memberId);
  172. } else {
  173. const labelId = Blaze.getData(ui.draggable.get(0))._id;
  174. card.addLabel(labelId);
  175. }
  176. },
  177. });
  178. });
  179. });
  180. },
  181. listWidth() {
  182. const user = ReactiveCache.getCurrentUser();
  183. const list = Template.currentData();
  184. if (!user || !list) return 270; // Return default width if user or list is not available
  185. return user.getListWidthFromStorage(list.boardId, list._id);
  186. },
  187. listConstraint() {
  188. const user = ReactiveCache.getCurrentUser();
  189. const list = Template.currentData();
  190. if (!user || !list) return 550; // Return default constraint if user or list is not available
  191. return user.getListConstraintFromStorage(list.boardId, list._id);
  192. },
  193. autoWidth() {
  194. const user = ReactiveCache.getCurrentUser();
  195. const list = Template.currentData();
  196. return user.isAutoWidth(list.boardId);
  197. },
  198. initializeListResize() {
  199. // Check if we're still in a valid template context
  200. if (!Template.currentData()) {
  201. console.warn('No current template data available for list resize initialization');
  202. return;
  203. }
  204. const list = Template.currentData();
  205. const $list = this.$('.js-list');
  206. const $resizeHandle = this.$('.js-list-resize-handle');
  207. // Check if elements exist
  208. if (!$list.length || !$resizeHandle.length) {
  209. console.warn('List or resize handle not found, retrying in 100ms');
  210. Meteor.setTimeout(() => {
  211. if (!this.isDestroyed) {
  212. this.initializeListResize();
  213. }
  214. }, 100);
  215. return;
  216. }
  217. // Only enable resize for non-collapsed, non-auto-width lists
  218. const isAutoWidth = this.autoWidth();
  219. if (list.collapsed || isAutoWidth) {
  220. $resizeHandle.hide();
  221. return;
  222. }
  223. let isResizing = false;
  224. let startX = 0;
  225. let startWidth = 0;
  226. let minWidth = 100; // Minimum width as defined in the existing code
  227. let maxWidth = this.listConstraint() || 1000; // Use constraint as max width
  228. let listConstraint = this.listConstraint(); // Store constraint value for use in event handlers
  229. const component = this; // Store reference to component for use in event handlers
  230. const startResize = (e) => {
  231. isResizing = true;
  232. startX = e.pageX || e.originalEvent.touches[0].pageX;
  233. startWidth = $list.outerWidth();
  234. // Add visual feedback
  235. $list.addClass('list-resizing');
  236. $('body').addClass('list-resizing-active');
  237. // Prevent text selection during resize
  238. $('body').css('user-select', 'none');
  239. e.preventDefault();
  240. e.stopPropagation();
  241. };
  242. const doResize = (e) => {
  243. if (!isResizing) {
  244. return;
  245. }
  246. const currentX = e.pageX || e.originalEvent.touches[0].pageX;
  247. const deltaX = currentX - startX;
  248. const newWidth = Math.max(minWidth, Math.min(maxWidth, startWidth + deltaX));
  249. // Apply the new width immediately for real-time feedback
  250. $list[0].style.setProperty('--list-width', `${newWidth}px`);
  251. $list[0].style.setProperty('width', `${newWidth}px`);
  252. $list[0].style.setProperty('min-width', `${newWidth}px`);
  253. $list[0].style.setProperty('max-width', `${newWidth}px`);
  254. $list[0].style.setProperty('flex', 'none');
  255. $list[0].style.setProperty('flex-basis', 'auto');
  256. $list[0].style.setProperty('flex-grow', '0');
  257. $list[0].style.setProperty('flex-shrink', '0');
  258. e.preventDefault();
  259. e.stopPropagation();
  260. };
  261. const stopResize = (e) => {
  262. if (!isResizing) return;
  263. isResizing = false;
  264. // Calculate final width
  265. const currentX = e.pageX || e.originalEvent.touches[0].pageX;
  266. const deltaX = currentX - startX;
  267. const finalWidth = Math.max(minWidth, Math.min(maxWidth, startWidth + deltaX));
  268. // Ensure the final width is applied
  269. $list[0].style.setProperty('--list-width', `${finalWidth}px`);
  270. $list[0].style.setProperty('width', `${finalWidth}px`);
  271. $list[0].style.setProperty('min-width', `${finalWidth}px`);
  272. $list[0].style.setProperty('max-width', `${finalWidth}px`);
  273. $list[0].style.setProperty('flex', 'none');
  274. $list[0].style.setProperty('flex-basis', 'auto');
  275. $list[0].style.setProperty('flex-grow', '0');
  276. $list[0].style.setProperty('flex-shrink', '0');
  277. // Remove visual feedback but keep the width
  278. $list.removeClass('list-resizing');
  279. $('body').removeClass('list-resizing-active');
  280. $('body').css('user-select', '');
  281. // Keep the CSS custom property for persistent width
  282. // The CSS custom property will remain on the element to maintain the width
  283. // Save the new width using the existing system
  284. const boardId = list.boardId;
  285. const listId = list._id;
  286. // Use the new storage method that handles both logged-in and non-logged-in users
  287. if (process.env.DEBUG === 'true') {
  288. }
  289. Meteor.call('applyListWidthToStorage', boardId, listId, finalWidth, listConstraint, (error, result) => {
  290. if (error) {
  291. console.error('Error saving list width:', error);
  292. } else {
  293. if (process.env.DEBUG === 'true') {
  294. }
  295. }
  296. });
  297. e.preventDefault();
  298. };
  299. // Mouse events
  300. $resizeHandle.on('mousedown', startResize);
  301. $(document).on('mousemove', doResize);
  302. $(document).on('mouseup', stopResize);
  303. // Touch events for mobile
  304. $resizeHandle.on('touchstart', startResize, { passive: false });
  305. $(document).on('touchmove', doResize, { passive: false });
  306. $(document).on('touchend', stopResize, { passive: false });
  307. // Prevent dragscroll interference
  308. $resizeHandle.on('mousedown', (e) => {
  309. e.stopPropagation();
  310. });
  311. // Reactively update resize handle visibility when auto-width changes
  312. component.autorun(() => {
  313. if (component.autoWidth()) {
  314. $resizeHandle.hide();
  315. } else {
  316. $resizeHandle.show();
  317. }
  318. });
  319. // Clean up on component destruction
  320. component.onDestroyed(() => {
  321. $(document).off('mousemove', doResize);
  322. $(document).off('mouseup', stopResize);
  323. $(document).off('touchmove', doResize);
  324. $(document).off('touchend', stopResize);
  325. });
  326. },
  327. }).register('list');
  328. Template.miniList.events({
  329. 'click .js-select-list'() {
  330. const listId = this._id;
  331. Session.set('currentList', listId);
  332. },
  333. });