list.js 14 KB

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