list.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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 (!list) return 270; // Return default width if list is not available
  185. if (user) {
  186. // For logged-in users, get from user profile
  187. return user.getListWidthFromStorage(list.boardId, list._id);
  188. } else {
  189. // For non-logged-in users, get from localStorage
  190. try {
  191. const stored = localStorage.getItem('wekan-list-widths');
  192. if (stored) {
  193. const widths = JSON.parse(stored);
  194. if (widths[list.boardId] && widths[list.boardId][list._id]) {
  195. return widths[list.boardId][list._id];
  196. }
  197. }
  198. } catch (e) {
  199. console.warn('Error reading list width from localStorage:', e);
  200. }
  201. return 270; // Return default width if not found
  202. }
  203. },
  204. listConstraint() {
  205. const user = ReactiveCache.getCurrentUser();
  206. const list = Template.currentData();
  207. if (!list) return 550; // Return default constraint if list is not available
  208. if (user) {
  209. // For logged-in users, get from user profile
  210. return user.getListConstraintFromStorage(list.boardId, list._id);
  211. } else {
  212. // For non-logged-in users, get from localStorage
  213. try {
  214. const stored = localStorage.getItem('wekan-list-constraints');
  215. if (stored) {
  216. const constraints = JSON.parse(stored);
  217. if (constraints[list.boardId] && constraints[list.boardId][list._id]) {
  218. return constraints[list.boardId][list._id];
  219. }
  220. }
  221. } catch (e) {
  222. console.warn('Error reading list constraint from localStorage:', e);
  223. }
  224. return 550; // Return default constraint if not found
  225. }
  226. },
  227. autoWidth() {
  228. const user = ReactiveCache.getCurrentUser();
  229. const list = Template.currentData();
  230. if (!user) {
  231. // For non-logged-in users, auto-width is disabled
  232. return false;
  233. }
  234. return user.isAutoWidth(list.boardId);
  235. },
  236. initializeListResize() {
  237. // Check if we're still in a valid template context
  238. if (!Template.currentData()) {
  239. console.warn('No current template data available for list resize initialization');
  240. return;
  241. }
  242. const list = Template.currentData();
  243. const $list = this.$('.js-list');
  244. const $resizeHandle = this.$('.js-list-resize-handle');
  245. // Check if elements exist
  246. if (!$list.length || !$resizeHandle.length) {
  247. console.warn('List or resize handle not found, retrying in 100ms');
  248. Meteor.setTimeout(() => {
  249. if (!this.isDestroyed) {
  250. this.initializeListResize();
  251. }
  252. }, 100);
  253. return;
  254. }
  255. // Only enable resize for non-collapsed, non-auto-width lists
  256. const isAutoWidth = this.autoWidth();
  257. if (list.collapsed || isAutoWidth) {
  258. $resizeHandle.hide();
  259. return;
  260. }
  261. let isResizing = false;
  262. let startX = 0;
  263. let startWidth = 0;
  264. let minWidth = 100; // Minimum width as defined in the existing code
  265. let maxWidth = this.listConstraint() || 1000; // Use constraint as max width
  266. let listConstraint = this.listConstraint(); // Store constraint value for use in event handlers
  267. const component = this; // Store reference to component for use in event handlers
  268. const startResize = (e) => {
  269. isResizing = true;
  270. startX = e.pageX || e.originalEvent.touches[0].pageX;
  271. startWidth = $list.outerWidth();
  272. // Add visual feedback
  273. $list.addClass('list-resizing');
  274. $('body').addClass('list-resizing-active');
  275. // Prevent text selection during resize
  276. $('body').css('user-select', 'none');
  277. e.preventDefault();
  278. e.stopPropagation();
  279. };
  280. const doResize = (e) => {
  281. if (!isResizing) {
  282. return;
  283. }
  284. const currentX = e.pageX || e.originalEvent.touches[0].pageX;
  285. const deltaX = currentX - startX;
  286. const newWidth = Math.max(minWidth, Math.min(maxWidth, startWidth + deltaX));
  287. // Apply the new width immediately for real-time feedback
  288. $list[0].style.setProperty('--list-width', `${newWidth}px`);
  289. $list[0].style.setProperty('width', `${newWidth}px`);
  290. $list[0].style.setProperty('min-width', `${newWidth}px`);
  291. $list[0].style.setProperty('max-width', `${newWidth}px`);
  292. $list[0].style.setProperty('flex', 'none');
  293. $list[0].style.setProperty('flex-basis', 'auto');
  294. $list[0].style.setProperty('flex-grow', '0');
  295. $list[0].style.setProperty('flex-shrink', '0');
  296. e.preventDefault();
  297. e.stopPropagation();
  298. };
  299. const stopResize = (e) => {
  300. if (!isResizing) return;
  301. isResizing = false;
  302. // Calculate final width
  303. const currentX = e.pageX || e.originalEvent.touches[0].pageX;
  304. const deltaX = currentX - startX;
  305. const finalWidth = Math.max(minWidth, Math.min(maxWidth, startWidth + deltaX));
  306. // Ensure the final width is applied
  307. $list[0].style.setProperty('--list-width', `${finalWidth}px`);
  308. $list[0].style.setProperty('width', `${finalWidth}px`);
  309. $list[0].style.setProperty('min-width', `${finalWidth}px`);
  310. $list[0].style.setProperty('max-width', `${finalWidth}px`);
  311. $list[0].style.setProperty('flex', 'none');
  312. $list[0].style.setProperty('flex-basis', 'auto');
  313. $list[0].style.setProperty('flex-grow', '0');
  314. $list[0].style.setProperty('flex-shrink', '0');
  315. // Remove visual feedback but keep the width
  316. $list.removeClass('list-resizing');
  317. $('body').removeClass('list-resizing-active');
  318. $('body').css('user-select', '');
  319. // Keep the CSS custom property for persistent width
  320. // The CSS custom property will remain on the element to maintain the width
  321. // Save the new width using the existing system
  322. const boardId = list.boardId;
  323. const listId = list._id;
  324. // Use the new storage method that handles both logged-in and non-logged-in users
  325. if (process.env.DEBUG === 'true') {
  326. }
  327. const currentUser = ReactiveCache.getCurrentUser();
  328. if (currentUser) {
  329. // For logged-in users, use server method
  330. Meteor.call('applyListWidthToStorage', boardId, listId, finalWidth, listConstraint, (error, result) => {
  331. if (error) {
  332. console.error('Error saving list width:', error);
  333. } else {
  334. if (process.env.DEBUG === 'true') {
  335. }
  336. }
  337. });
  338. } else {
  339. // For non-logged-in users, save to localStorage directly
  340. try {
  341. // Save list width
  342. const storedWidths = localStorage.getItem('wekan-list-widths');
  343. let widths = storedWidths ? JSON.parse(storedWidths) : {};
  344. if (!widths[boardId]) {
  345. widths[boardId] = {};
  346. }
  347. widths[boardId][listId] = finalWidth;
  348. localStorage.setItem('wekan-list-widths', JSON.stringify(widths));
  349. // Save list constraint
  350. const storedConstraints = localStorage.getItem('wekan-list-constraints');
  351. let constraints = storedConstraints ? JSON.parse(storedConstraints) : {};
  352. if (!constraints[boardId]) {
  353. constraints[boardId] = {};
  354. }
  355. constraints[boardId][listId] = listConstraint;
  356. localStorage.setItem('wekan-list-constraints', JSON.stringify(constraints));
  357. if (process.env.DEBUG === 'true') {
  358. }
  359. } catch (e) {
  360. console.warn('Error saving list width/constraint to localStorage:', e);
  361. }
  362. }
  363. e.preventDefault();
  364. };
  365. // Mouse events
  366. $resizeHandle.on('mousedown', startResize);
  367. $(document).on('mousemove', doResize);
  368. $(document).on('mouseup', stopResize);
  369. // Touch events for mobile
  370. $resizeHandle.on('touchstart', startResize, { passive: false });
  371. $(document).on('touchmove', doResize, { passive: false });
  372. $(document).on('touchend', stopResize, { passive: false });
  373. // Prevent dragscroll interference
  374. $resizeHandle.on('mousedown', (e) => {
  375. e.stopPropagation();
  376. });
  377. // Reactively update resize handle visibility when auto-width changes
  378. component.autorun(() => {
  379. if (component.autoWidth()) {
  380. $resizeHandle.hide();
  381. } else {
  382. $resizeHandle.show();
  383. }
  384. });
  385. // Clean up on component destruction
  386. component.onDestroyed(() => {
  387. $(document).off('mousemove', doResize);
  388. $(document).off('mouseup', stopResize);
  389. $(document).off('touchmove', doResize);
  390. $(document).off('touchend', stopResize);
  391. });
  392. },
  393. }).register('list');
  394. Template.miniList.events({
  395. 'click .js-select-list'() {
  396. const listId = this._id;
  397. Session.set('currentList', listId);
  398. },
  399. });