boardBody.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. import { ReactiveCache } from '/imports/reactiveCache';
  2. import { TAPi18n } from '/imports/i18n';
  3. import dragscroll from '@wekanteam/dragscroll';
  4. import { boardConverter } from '/client/lib/boardConverter';
  5. import { migrationManager } from '/client/lib/migrationManager';
  6. import { attachmentMigrationManager } from '/client/lib/attachmentMigrationManager';
  7. import Swimlanes from '/models/swimlanes';
  8. import Lists from '/models/lists';
  9. const subManager = new SubsManager();
  10. const { calculateIndex } = Utils;
  11. const swimlaneWhileSortingHeight = 150;
  12. BlazeComponent.extendComponent({
  13. onCreated() {
  14. this.isBoardReady = new ReactiveVar(false);
  15. this.isConverting = new ReactiveVar(false);
  16. this.isMigrating = new ReactiveVar(false);
  17. this._swimlaneCreated = new Set(); // Track boards where we've created swimlanes
  18. // The pattern we use to manually handle data loading is described here:
  19. // https://kadira.io/academy/meteor-routing-guide/content/subscriptions-and-data-management/using-subs-manager
  20. // XXX The boardId should be readed from some sort the component "props",
  21. // unfortunatly, Blaze doesn't have this notion.
  22. this.autorun(() => {
  23. const currentBoardId = Session.get('currentBoard');
  24. if (!currentBoardId) return;
  25. const handle = subManager.subscribe('board', currentBoardId, false);
  26. Tracker.nonreactive(() => {
  27. Tracker.autorun(() => {
  28. if (handle.ready()) {
  29. // Ensure default swimlane exists (only once per board)
  30. this.ensureDefaultSwimlane(currentBoardId);
  31. // Check if board needs conversion
  32. this.checkAndConvertBoard(currentBoardId);
  33. } else {
  34. this.isBoardReady.set(false);
  35. }
  36. });
  37. });
  38. });
  39. },
  40. ensureDefaultSwimlane(boardId) {
  41. // Only create swimlane once per board
  42. if (this._swimlaneCreated.has(boardId)) {
  43. return;
  44. }
  45. try {
  46. const board = ReactiveCache.getBoard(boardId);
  47. if (!board) return;
  48. const swimlanes = board.swimlanes();
  49. if (swimlanes.length === 0) {
  50. const swimlaneId = Swimlanes.insert({
  51. title: 'Default',
  52. boardId: boardId,
  53. });
  54. this._swimlaneCreated.add(boardId);
  55. } else {
  56. this._swimlaneCreated.add(boardId);
  57. }
  58. } catch (error) {
  59. console.error('Error creating default swimlane:', error);
  60. }
  61. },
  62. async checkAndConvertBoard(boardId) {
  63. try {
  64. const board = ReactiveCache.getBoard(boardId);
  65. if (!board) {
  66. this.isBoardReady.set(true);
  67. return;
  68. }
  69. // Check if board needs migration based on migration version
  70. const needsMigration = !board.migrationVersion || board.migrationVersion < 1;
  71. if (needsMigration) {
  72. // Start background migration for old boards
  73. this.isMigrating.set(true);
  74. await this.startBackgroundMigration(boardId);
  75. this.isMigrating.set(false);
  76. }
  77. // Check if board needs conversion (for old structure)
  78. if (boardConverter.isBoardConverted(boardId)) {
  79. if (process.env.DEBUG === 'true') {
  80. console.log(`Board ${boardId} has already been converted, skipping conversion`);
  81. }
  82. this.isBoardReady.set(true);
  83. } else {
  84. const needsConversion = boardConverter.needsConversion(boardId);
  85. if (needsConversion) {
  86. this.isConverting.set(true);
  87. const success = await boardConverter.convertBoard(boardId);
  88. this.isConverting.set(false);
  89. if (success) {
  90. this.isBoardReady.set(true);
  91. } else {
  92. console.error('Board conversion failed, setting ready to true anyway');
  93. this.isBoardReady.set(true); // Still show board even if conversion failed
  94. }
  95. } else {
  96. this.isBoardReady.set(true);
  97. }
  98. }
  99. // Convert shared lists to per-swimlane lists if needed
  100. await this.convertSharedListsToPerSwimlane(boardId);
  101. // Start attachment migration in background if needed
  102. this.startAttachmentMigrationIfNeeded(boardId);
  103. } catch (error) {
  104. console.error('Error during board conversion check:', error);
  105. this.isConverting.set(false);
  106. this.isMigrating.set(false);
  107. this.isBoardReady.set(true); // Show board even if conversion check failed
  108. }
  109. },
  110. async startBackgroundMigration(boardId) {
  111. try {
  112. // Start background migration using the cron system
  113. Meteor.call('boardMigration.startBoardMigration', boardId, (error, result) => {
  114. if (error) {
  115. console.error('Failed to start background migration:', error);
  116. } else {
  117. if (process.env.DEBUG === 'true') {
  118. console.log('Background migration started for board:', boardId);
  119. }
  120. }
  121. });
  122. } catch (error) {
  123. console.error('Error starting background migration:', error);
  124. }
  125. },
  126. async convertSharedListsToPerSwimlane(boardId) {
  127. try {
  128. const board = ReactiveCache.getBoard(boardId);
  129. if (!board) return;
  130. // Check if board has already been processed for shared lists conversion
  131. if (board.hasSharedListsConverted) {
  132. if (process.env.DEBUG === 'true') {
  133. console.log(`Board ${boardId} has already been processed for shared lists conversion`);
  134. }
  135. return;
  136. }
  137. // Get all lists for this board
  138. const allLists = board.lists();
  139. const swimlanes = board.swimlanes();
  140. if (swimlanes.length === 0) {
  141. if (process.env.DEBUG === 'true') {
  142. console.log(`Board ${boardId} has no swimlanes, skipping shared lists conversion`);
  143. }
  144. return;
  145. }
  146. // Find shared lists (lists with empty swimlaneId or null swimlaneId)
  147. const sharedLists = allLists.filter(list => !list.swimlaneId || list.swimlaneId === '');
  148. if (sharedLists.length === 0) {
  149. if (process.env.DEBUG === 'true') {
  150. console.log(`Board ${boardId} has no shared lists to convert`);
  151. }
  152. // Mark as processed even if no shared lists
  153. Meteor.call('boards.update', boardId, { $set: { hasSharedListsConverted: true } });
  154. return;
  155. }
  156. if (process.env.DEBUG === 'true') {
  157. console.log(`Converting ${sharedLists.length} shared lists to per-swimlane lists for board ${boardId}`);
  158. }
  159. // Convert each shared list to per-swimlane lists
  160. for (const sharedList of sharedLists) {
  161. // Create a copy of the list for each swimlane
  162. for (const swimlane of swimlanes) {
  163. // Check if this list already exists in this swimlane
  164. const existingList = Lists.findOne({
  165. boardId: boardId,
  166. swimlaneId: swimlane._id,
  167. title: sharedList.title
  168. });
  169. if (!existingList) {
  170. // Create a new list in this swimlane
  171. const newListData = {
  172. title: sharedList.title,
  173. boardId: boardId,
  174. swimlaneId: swimlane._id,
  175. sort: sharedList.sort || 0,
  176. archived: sharedList.archived || false,
  177. createdAt: new Date(),
  178. modifiedAt: new Date()
  179. };
  180. // Copy other properties if they exist
  181. if (sharedList.color) newListData.color = sharedList.color;
  182. if (sharedList.wipLimit) newListData.wipLimit = sharedList.wipLimit;
  183. if (sharedList.wipLimitEnabled) newListData.wipLimitEnabled = sharedList.wipLimitEnabled;
  184. if (sharedList.wipLimitSoft) newListData.wipLimitSoft = sharedList.wipLimitSoft;
  185. Lists.insert(newListData);
  186. }
  187. }
  188. // Archive or remove the original shared list
  189. Lists.update(sharedList._id, {
  190. $set: {
  191. archived: true,
  192. modifiedAt: new Date()
  193. }
  194. });
  195. }
  196. // Mark board as processed
  197. Meteor.call('boards.update', boardId, { $set: { hasSharedListsConverted: true } });
  198. if (process.env.DEBUG === 'true') {
  199. console.log(`Successfully converted ${sharedLists.length} shared lists to per-swimlane lists for board ${boardId}`);
  200. }
  201. } catch (error) {
  202. console.error('Error converting shared lists to per-swimlane:', error);
  203. }
  204. },
  205. async startAttachmentMigrationIfNeeded(boardId) {
  206. try {
  207. // Check if board has already been migrated
  208. if (attachmentMigrationManager.isBoardMigrated(boardId)) {
  209. if (process.env.DEBUG === 'true') {
  210. console.log(`Board ${boardId} has already been migrated, skipping`);
  211. }
  212. return;
  213. }
  214. // Check if there are unconverted attachments
  215. const unconvertedAttachments = attachmentMigrationManager.getUnconvertedAttachments(boardId);
  216. if (unconvertedAttachments.length > 0) {
  217. if (process.env.DEBUG === 'true') {
  218. console.log(`Starting attachment migration for ${unconvertedAttachments.length} attachments in board ${boardId}`);
  219. }
  220. await attachmentMigrationManager.startAttachmentMigration(boardId);
  221. } else {
  222. // No attachments to migrate, mark board as migrated
  223. // This will be handled by the migration manager itself
  224. if (process.env.DEBUG === 'true') {
  225. console.log(`Board ${boardId} has no attachments to migrate`);
  226. }
  227. }
  228. } catch (error) {
  229. console.error('Error starting attachment migration:', error);
  230. }
  231. },
  232. onlyShowCurrentCard() {
  233. const isMiniScreen = Utils.isMiniScreen();
  234. const currentCardId = Utils.getCurrentCardId(true);
  235. return isMiniScreen && currentCardId;
  236. },
  237. goHome() {
  238. FlowRouter.go('home');
  239. },
  240. isConverting() {
  241. return this.isConverting.get();
  242. },
  243. isMigrating() {
  244. return this.isMigrating.get();
  245. },
  246. isBoardReady() {
  247. return this.isBoardReady.get();
  248. },
  249. currentBoard() {
  250. return Utils.getCurrentBoard();
  251. },
  252. }).register('board');
  253. BlazeComponent.extendComponent({
  254. onCreated() {
  255. Meteor.subscribe('tableVisibilityModeSettings');
  256. this.showOverlay = new ReactiveVar(false);
  257. this.draggingActive = new ReactiveVar(false);
  258. this._isDragging = false;
  259. // Used to set the overlay
  260. this.mouseHasEnterCardDetails = false;
  261. // fix swimlanes sort field if there are null values
  262. const currentBoardData = Utils.getCurrentBoard();
  263. if (currentBoardData && Swimlanes) {
  264. const nullSortSwimlanes = currentBoardData.nullSortSwimlanes();
  265. if (nullSortSwimlanes.length > 0) {
  266. const swimlanes = currentBoardData.swimlanes();
  267. let count = 0;
  268. swimlanes.forEach(s => {
  269. Swimlanes.update(s._id, {
  270. $set: {
  271. sort: count,
  272. },
  273. });
  274. count += 1;
  275. });
  276. }
  277. }
  278. // fix lists sort field if there are null values
  279. if (currentBoardData && Lists) {
  280. const nullSortLists = currentBoardData.nullSortLists();
  281. if (nullSortLists.length > 0) {
  282. const lists = currentBoardData.lists();
  283. let count = 0;
  284. lists.forEach(l => {
  285. Lists.update(l._id, {
  286. $set: {
  287. sort: count,
  288. },
  289. });
  290. count += 1;
  291. });
  292. }
  293. }
  294. },
  295. onRendered() {
  296. // Initialize user settings (zoom and mobile mode)
  297. Utils.initializeUserSettings();
  298. // Detect iPhone devices and add class for better CSS targeting
  299. const isIPhone = /iPhone|iPod/.test(navigator.userAgent);
  300. if (isIPhone) {
  301. document.body.classList.add('iphone-device');
  302. }
  303. // Accessibility: Focus management for popups and menus
  304. function focusFirstInteractive(container) {
  305. if (!container) return;
  306. // Find first focusable element
  307. const focusable = container.querySelectorAll('button, [role="button"], a[href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
  308. for (let i = 0; i < focusable.length; i++) {
  309. if (!focusable[i].disabled && focusable[i].offsetParent !== null) {
  310. focusable[i].focus();
  311. break;
  312. }
  313. }
  314. }
  315. // Observe for new popups/menus and set focus (but exclude swimlane content)
  316. const popupObserver = new MutationObserver(function(mutations) {
  317. mutations.forEach(function(mutation) {
  318. mutation.addedNodes.forEach(function(node) {
  319. if (node.nodeType === 1 &&
  320. (node.classList.contains('popup') || node.classList.contains('modal') || node.classList.contains('menu')) &&
  321. !node.closest('.js-swimlanes') &&
  322. !node.closest('.swimlane') &&
  323. !node.closest('.list') &&
  324. !node.closest('.minicard')) {
  325. setTimeout(function() { focusFirstInteractive(node); }, 10);
  326. }
  327. });
  328. });
  329. });
  330. popupObserver.observe(document.body, { childList: true, subtree: true });
  331. // Remove tabindex from non-interactive elements (e.g., user abbreviations, labels)
  332. document.querySelectorAll('.user-abbreviation, .user-label, .card-header-label, .edit-label, .private-label').forEach(function(el) {
  333. if (el.hasAttribute('tabindex')) {
  334. el.removeAttribute('tabindex');
  335. }
  336. });
  337. /*
  338. // Add a toggle button for keyboard shortcuts accessibility
  339. if (!document.getElementById('wekan-shortcuts-toggle')) {
  340. const toggleContainer = document.createElement('div');
  341. toggleContainer.id = 'wekan-shortcuts-toggle';
  342. toggleContainer.style.position = 'fixed';
  343. toggleContainer.style.top = '10px';
  344. toggleContainer.style.right = '10px';
  345. toggleContainer.style.zIndex = '1000';
  346. toggleContainer.style.background = '#fff';
  347. toggleContainer.style.border = '2px solid #005fcc';
  348. toggleContainer.style.borderRadius = '6px';
  349. toggleContainer.style.padding = '8px 12px';
  350. toggleContainer.style.boxShadow = '0 2px 8px rgba(0,0,0,0.1)';
  351. toggleContainer.style.fontSize = '16px';
  352. toggleContainer.style.color = '#005fcc';
  353. toggleContainer.setAttribute('role', 'region');
  354. toggleContainer.setAttribute('aria-label', 'Keyboard Shortcuts Settings');
  355. toggleContainer.innerHTML = `
  356. <label for="shortcuts-toggle-checkbox" style="cursor:pointer;">
  357. <input type="checkbox" id="shortcuts-toggle-checkbox" ${window.wekanShortcutsEnabled ? 'checked' : ''} style="margin-right:8px;" />
  358. Enable keyboard shortcuts
  359. </label>
  360. `;
  361. document.body.appendChild(toggleContainer);
  362. const checkbox = document.getElementById('shortcuts-toggle-checkbox');
  363. checkbox.addEventListener('change', function(e) {
  364. window.toggleWekanShortcuts(e.target.checked);
  365. });
  366. }
  367. */
  368. // Ensure toggle-buttons, color choices, reactions, renaming, and calendar controls are focusable and have ARIA roles
  369. document.querySelectorAll('.js-toggle').forEach(function(el) {
  370. el.setAttribute('tabindex', '0');
  371. el.setAttribute('role', 'button');
  372. // Short, descriptive label for favorite/star toggle
  373. if (el.classList.contains('js-favorite-toggle')) {
  374. el.setAttribute('aria-label', TAPi18n.__('favorite-toggle-label'));
  375. } else {
  376. el.setAttribute('aria-label', 'Toggle');
  377. }
  378. });
  379. document.querySelectorAll('.js-color-choice').forEach(function(el) {
  380. el.setAttribute('tabindex', '0');
  381. el.setAttribute('role', 'button');
  382. el.setAttribute('aria-label', 'Choose color');
  383. });
  384. document.querySelectorAll('.js-reaction').forEach(function(el) {
  385. el.setAttribute('tabindex', '0');
  386. el.setAttribute('role', 'button');
  387. el.setAttribute('aria-label', 'React');
  388. });
  389. document.querySelectorAll('.js-rename-swimlane').forEach(function(el) {
  390. el.setAttribute('tabindex', '0');
  391. el.setAttribute('role', 'button');
  392. el.setAttribute('aria-label', 'Rename swimlane');
  393. });
  394. document.querySelectorAll('.js-rename-list').forEach(function(el) {
  395. el.setAttribute('tabindex', '0');
  396. el.setAttribute('role', 'button');
  397. el.setAttribute('aria-label', 'Rename list');
  398. });
  399. document.querySelectorAll('.fc-button').forEach(function(el) {
  400. el.setAttribute('tabindex', '0');
  401. el.setAttribute('role', 'button');
  402. });
  403. // Set the language attribute on the <html> element for accessibility
  404. document.documentElement.lang = TAPi18n.getLanguage();
  405. // Ensure the accessible name for the board view switcher matches the visible label "Swimlanes"
  406. // This fixes WCAG 2.5.3: Label in Name
  407. const swimlanesSwitcher = this.$('.js-board-view-swimlanes');
  408. if (swimlanesSwitcher.length) {
  409. swimlanesSwitcher.attr('aria-label', swimlanesSwitcher.text().trim() || 'Swimlanes');
  410. }
  411. // Add a highly visible focus indicator and improve contrast for interactive elements
  412. if (!document.getElementById('wekan-accessible-focus-style')) {
  413. const style = document.createElement('style');
  414. style.id = 'wekan-accessible-focus-style';
  415. style.innerHTML = `
  416. /* Focus indicator */
  417. button:focus, [role="button"]:focus, a:focus, input:focus, select:focus, textarea:focus, .dropdown-menu:focus, .js-board-view-swimlanes:focus, .js-add-card:focus {
  418. outline: 3px solid #005fcc !important;
  419. outline-offset: 2px !important;
  420. }
  421. /* Input borders */
  422. input, textarea, select {
  423. border: 2px solid #222 !important;
  424. }
  425. /* Plus icon for adding a new card */
  426. .js-add-card {
  427. color: #005fcc !important; /* dark blue for contrast */
  428. cursor: pointer;
  429. outline: none;
  430. }
  431. .js-add-card[tabindex] {
  432. outline: none;
  433. }
  434. /* Hamburger menu */
  435. .fa-bars, .icon-hamburger {
  436. color: #222 !important;
  437. }
  438. /* Grey icons in card detail header */
  439. .card-detail-header .fa, .card-detail-header .icon {
  440. color: #444 !important;
  441. }
  442. /* Grey operating elements in card detail */
  443. .card-detail .fa, .card-detail .icon {
  444. color: #444 !important;
  445. }
  446. /* Blue bar in checklists */
  447. .checklist-progress-bar {
  448. background-color: #005fcc !important;
  449. }
  450. /* Green checkmark in checklists */
  451. .checklist .fa-check {
  452. color: #007a33 !important;
  453. }
  454. /* X-Button and arrow button in menus */
  455. .close, .fa-arrow-left, .icon-arrow-left {
  456. color: #005fcc !important;
  457. }
  458. /* Cross icon to move boards */
  459. .js-move-board {
  460. color: #005fcc !important;
  461. }
  462. /* Current date background */
  463. .current-date {
  464. background-color: #005fcc !important;
  465. color: #fff !important;
  466. }
  467. `;
  468. document.head.appendChild(style);
  469. }
  470. // Ensure plus/add elements are focusable and have ARIA roles
  471. document.querySelectorAll('.js-add-card').forEach(function(el) {
  472. el.setAttribute('tabindex', '0');
  473. el.setAttribute('role', 'button');
  474. el.setAttribute('aria-label', 'Add new card');
  475. });
  476. const boardComponent = this;
  477. const $swimlanesDom = boardComponent.$('.js-swimlanes');
  478. $swimlanesDom.sortable({
  479. tolerance: 'pointer',
  480. appendTo: '.board-canvas',
  481. helper(evt, item) {
  482. const helper = $(`<div class="swimlane"
  483. style="flex-direction: column;
  484. height: ${swimlaneWhileSortingHeight}px;
  485. width: $(boardComponent.width)px;
  486. overflow: hidden;"/>`);
  487. helper.append(item.clone());
  488. // Also grab the list of lists of cards
  489. const list = item.next();
  490. helper.append(list.clone());
  491. return helper;
  492. },
  493. items: '.swimlane:not(.placeholder)',
  494. placeholder: 'swimlane placeholder',
  495. distance: 7,
  496. start(evt, ui) {
  497. const listDom = ui.placeholder.next('.js-swimlane');
  498. const parentOffset = ui.item.parent().offset();
  499. ui.placeholder.height(ui.helper.height());
  500. EscapeActions.executeUpTo('popup-close');
  501. listDom.addClass('moving-swimlane');
  502. boardComponent.setIsDragging(true);
  503. ui.placeholder.insertAfter(ui.placeholder.next());
  504. boardComponent.origPlaceholderIndex = ui.placeholder.index();
  505. // resize all swimlanes + headers to be a total of 150 px per row
  506. // this could be achieved by setIsDragging(true) but we want immediate
  507. // result
  508. ui.item
  509. .siblings('.js-swimlane')
  510. .css('height', `${swimlaneWhileSortingHeight - 26}px`);
  511. // set the new scroll height after the resize and insertion of
  512. // the placeholder. We want the element under the cursor to stay
  513. // at the same place on the screen
  514. ui.item.parent().get(0).scrollTop =
  515. ui.placeholder.get(0).offsetTop + parentOffset.top - evt.pageY;
  516. },
  517. beforeStop(evt, ui) {
  518. const parentOffset = ui.item.parent().offset();
  519. const siblings = ui.item.siblings('.js-swimlane');
  520. siblings.css('height', '');
  521. // compute the new scroll height after the resize and removal of
  522. // the placeholder
  523. const scrollTop =
  524. ui.placeholder.get(0).offsetTop + parentOffset.top - evt.pageY;
  525. // then reset the original view of the swimlane
  526. siblings.removeClass('moving-swimlane');
  527. // and apply the computed scrollheight
  528. ui.item.parent().get(0).scrollTop = scrollTop;
  529. },
  530. stop(evt, ui) {
  531. // To attribute the new index number, we need to get the DOM element
  532. // of the previous and the following card -- if any.
  533. const prevSwimlaneDom = ui.item.prevAll('.js-swimlane').get(0);
  534. const nextSwimlaneDom = ui.item.nextAll('.js-swimlane').get(0);
  535. const sortIndex = calculateIndex(prevSwimlaneDom, nextSwimlaneDom, 1);
  536. $swimlanesDom.sortable('cancel');
  537. const swimlaneDomElement = ui.item.get(0);
  538. const swimlane = Blaze.getData(swimlaneDomElement);
  539. Swimlanes.update(swimlane._id, {
  540. $set: {
  541. sort: sortIndex.base,
  542. },
  543. });
  544. boardComponent.setIsDragging(false);
  545. },
  546. sort(evt, ui) {
  547. // get the mouse position in the sortable
  548. const parentOffset = ui.item.parent().offset();
  549. const cursorY =
  550. evt.pageY - parentOffset.top + ui.item.parent().scrollTop();
  551. // compute the intended index of the placeholder (we need to skip the
  552. // slots between the headers and the list of cards)
  553. const newplaceholderIndex = Math.floor(
  554. cursorY / swimlaneWhileSortingHeight,
  555. );
  556. let destPlaceholderIndex = (newplaceholderIndex + 1) * 2;
  557. // if we are scrolling far away from the bottom of the list
  558. if (destPlaceholderIndex >= ui.item.parent().get(0).childElementCount) {
  559. destPlaceholderIndex = ui.item.parent().get(0).childElementCount - 1;
  560. }
  561. // update the placeholder position in the DOM tree
  562. if (destPlaceholderIndex !== ui.placeholder.index()) {
  563. if (destPlaceholderIndex < boardComponent.origPlaceholderIndex) {
  564. ui.placeholder.insertBefore(
  565. ui.placeholder
  566. .siblings()
  567. .slice(destPlaceholderIndex - 2, destPlaceholderIndex - 1),
  568. );
  569. } else {
  570. ui.placeholder.insertAfter(
  571. ui.placeholder
  572. .siblings()
  573. .slice(destPlaceholderIndex - 1, destPlaceholderIndex),
  574. );
  575. }
  576. }
  577. },
  578. });
  579. this.autorun(() => {
  580. // Always reset dragscroll on view switch
  581. dragscroll.reset();
  582. if ($swimlanesDom.data('uiSortable') || $swimlanesDom.data('sortable')) {
  583. if (Utils.isTouchScreenOrShowDesktopDragHandles()) {
  584. $swimlanesDom.sortable('option', 'handle', '.js-swimlane-header-handle');
  585. } else {
  586. $swimlanesDom.sortable('option', 'handle', '.swimlane-header');
  587. }
  588. // Disable drag-dropping if the current user is not a board member
  589. $swimlanesDom.sortable(
  590. 'option',
  591. 'disabled',
  592. !ReactiveCache.getCurrentUser()?.isBoardAdmin(),
  593. );
  594. }
  595. });
  596. // If there is no data in the board (ie, no lists) we autofocus the list
  597. // creation form by clicking on the corresponding element.
  598. const currentBoard = Utils.getCurrentBoard();
  599. if (Utils.canModifyBoard() && currentBoard.lists().length === 0) {
  600. boardComponent.openNewListForm();
  601. }
  602. dragscroll.reset();
  603. Utils.setBackgroundImage();
  604. },
  605. notDisplayThisBoard() {
  606. let allowPrivateVisibilityOnly = TableVisibilityModeSettings.findOne('tableVisibilityMode-allowPrivateOnly');
  607. let currentBoard = Utils.getCurrentBoard();
  608. return allowPrivateVisibilityOnly !== undefined && allowPrivateVisibilityOnly.booleanValue && currentBoard && currentBoard.permission == 'public';
  609. },
  610. isViewSwimlanes() {
  611. const currentUser = ReactiveCache.getCurrentUser();
  612. let boardView;
  613. if (currentUser) {
  614. boardView = (currentUser.profile || {}).boardView;
  615. } else {
  616. boardView = window.localStorage.getItem('boardView');
  617. }
  618. // If no board view is set, default to swimlanes
  619. if (!boardView) {
  620. boardView = 'board-view-swimlanes';
  621. }
  622. return boardView === 'board-view-swimlanes';
  623. },
  624. isViewLists() {
  625. const currentUser = ReactiveCache.getCurrentUser();
  626. let boardView;
  627. if (currentUser) {
  628. boardView = (currentUser.profile || {}).boardView;
  629. } else {
  630. boardView = window.localStorage.getItem('boardView');
  631. }
  632. return boardView === 'board-view-lists';
  633. },
  634. isViewCalendar() {
  635. const currentUser = ReactiveCache.getCurrentUser();
  636. let boardView;
  637. if (currentUser) {
  638. boardView = (currentUser.profile || {}).boardView;
  639. } else {
  640. boardView = window.localStorage.getItem('boardView');
  641. }
  642. return boardView === 'board-view-cal';
  643. },
  644. hasSwimlanes() {
  645. const currentBoard = Utils.getCurrentBoard();
  646. if (!currentBoard) {
  647. if (process.env.DEBUG === 'true') {
  648. console.log('hasSwimlanes: No current board');
  649. }
  650. return false;
  651. }
  652. try {
  653. const swimlanes = currentBoard.swimlanes();
  654. const hasSwimlanes = swimlanes && swimlanes.length > 0;
  655. if (process.env.DEBUG === 'true') {
  656. console.log('hasSwimlanes: Board has', swimlanes ? swimlanes.length : 0, 'swimlanes');
  657. }
  658. return hasSwimlanes;
  659. } catch (error) {
  660. console.error('hasSwimlanes: Error getting swimlanes:', error);
  661. return false;
  662. }
  663. },
  664. isVerticalScrollbars() {
  665. const user = ReactiveCache.getCurrentUser();
  666. return user && user.isVerticalScrollbars();
  667. },
  668. boardView() {
  669. return Utils.boardView();
  670. },
  671. debugBoardState() {
  672. // Enable debug mode by setting ?debug=1 in URL
  673. const urlParams = new URLSearchParams(window.location.search);
  674. return urlParams.get('debug') === '1';
  675. },
  676. debugBoardStateData() {
  677. const currentBoard = Utils.getCurrentBoard();
  678. const currentBoardId = Session.get('currentBoard');
  679. const isBoardReady = this.isBoardReady.get();
  680. const isConverting = this.isConverting.get();
  681. const isMigrating = this.isMigrating.get();
  682. const boardView = Utils.boardView();
  683. if (process.env.DEBUG === 'true') {
  684. console.log('=== BOARD DEBUG STATE ===');
  685. console.log('currentBoardId:', currentBoardId);
  686. console.log('currentBoard:', !!currentBoard, currentBoard ? currentBoard.title : 'none');
  687. console.log('isBoardReady:', isBoardReady);
  688. console.log('isConverting:', isConverting);
  689. console.log('isMigrating:', isMigrating);
  690. console.log('boardView:', boardView);
  691. console.log('========================');
  692. }
  693. return {
  694. currentBoardId,
  695. hasCurrentBoard: !!currentBoard,
  696. currentBoardTitle: currentBoard ? currentBoard.title : 'none',
  697. isBoardReady,
  698. isConverting,
  699. isMigrating,
  700. boardView
  701. };
  702. },
  703. openNewListForm() {
  704. if (this.isViewSwimlanes()) {
  705. // The form had been removed in 416b17062e57f215206e93a85b02ef9eb1ab4902
  706. // this.childComponents('swimlane')[0]
  707. // .childComponents('addListAndSwimlaneForm')[0]
  708. // .open();
  709. } else if (this.isViewLists()) {
  710. this.childComponents('listsGroup')[0]
  711. .childComponents('addListForm')[0]
  712. .open();
  713. }
  714. },
  715. events() {
  716. return [
  717. {
  718. // XXX The board-overlay div should probably be moved to the parent
  719. // component.
  720. mouseup() {
  721. if (this._isDragging) {
  722. this._isDragging = false;
  723. }
  724. },
  725. 'click .js-empty-board-add-swimlane': Popup.open('swimlaneAdd'),
  726. // Global drag and drop file upload handlers for better visual feedback
  727. 'dragover .board-canvas'(event) {
  728. const dataTransfer = event.originalEvent.dataTransfer;
  729. if (dataTransfer && dataTransfer.types && dataTransfer.types.includes('Files')) {
  730. event.preventDefault();
  731. // Add visual indicator that files can be dropped
  732. $('.board-canvas').addClass('file-drag-over');
  733. }
  734. },
  735. 'dragleave .board-canvas'(event) {
  736. const dataTransfer = event.originalEvent.dataTransfer;
  737. if (dataTransfer && dataTransfer.types && dataTransfer.types.includes('Files')) {
  738. // Only remove class if we're leaving the board canvas entirely
  739. if (!event.currentTarget.contains(event.relatedTarget)) {
  740. $('.board-canvas').removeClass('file-drag-over');
  741. }
  742. }
  743. },
  744. 'drop .board-canvas'(event) {
  745. const dataTransfer = event.originalEvent.dataTransfer;
  746. if (dataTransfer && dataTransfer.types && dataTransfer.types.includes('Files')) {
  747. event.preventDefault();
  748. $('.board-canvas').removeClass('file-drag-over');
  749. }
  750. },
  751. },
  752. ];
  753. },
  754. // XXX Flow components allow us to avoid creating these two setter methods by
  755. // exposing a public API to modify the component state. We need to investigate
  756. // best practices here.
  757. setIsDragging(bool) {
  758. this.draggingActive.set(bool);
  759. },
  760. scrollLeft(position = 0) {
  761. const swimlanes = this.$('.js-swimlanes');
  762. swimlanes &&
  763. swimlanes.animate({
  764. scrollLeft: position,
  765. });
  766. },
  767. scrollTop(position = 0) {
  768. const swimlanes = this.$('.js-swimlanes');
  769. swimlanes &&
  770. swimlanes.animate({
  771. scrollTop: position,
  772. });
  773. },
  774. }).register('boardBody');
  775. // Accessibility: Allow users to enable/disable keyboard shortcuts
  776. window.wekanShortcutsEnabled = true;
  777. window.toggleWekanShortcuts = function(enabled) {
  778. window.wekanShortcutsEnabled = !!enabled;
  779. };
  780. // Example: Wrap your character key shortcut handler like this
  781. document.addEventListener('keydown', function(e) {
  782. // Example: "W" key shortcut (replace with your actual shortcut logic)
  783. if (!window.wekanShortcutsEnabled) return;
  784. if (e.key === 'w' || e.key === 'W') {
  785. // ...existing shortcut logic...
  786. // e.g. open swimlanes view, etc.
  787. }
  788. });
  789. // Keyboard accessibility for card actions (favorite, archive, duplicate, etc.)
  790. document.addEventListener('keydown', function(e) {
  791. if (!window.wekanShortcutsEnabled) return;
  792. // Only proceed if focus is on a card action element
  793. const active = document.activeElement;
  794. if (active && active.classList.contains('js-card-action')) {
  795. if (e.key === 'Enter' || e.key === ' ') {
  796. e.preventDefault();
  797. active.click();
  798. }
  799. // Move card up/down with arrow keys
  800. if (e.key === 'ArrowUp') {
  801. e.preventDefault();
  802. if (active.dataset.cardId) {
  803. Meteor.call('moveCardUp', active.dataset.cardId);
  804. }
  805. }
  806. if (e.key === 'ArrowDown') {
  807. e.preventDefault();
  808. if (active.dataset.cardId) {
  809. Meteor.call('moveCardDown', active.dataset.cardId);
  810. }
  811. }
  812. }
  813. // Make plus/add elements keyboard accessible
  814. if (active && active.classList.contains('js-add-card')) {
  815. if (e.key === 'Enter' || e.key === ' ') {
  816. e.preventDefault();
  817. active.click();
  818. }
  819. }
  820. // Keyboard move for cards (alternative to drag & drop)
  821. if (active && active.classList.contains('js-move-card')) {
  822. if (e.key === 'ArrowUp') {
  823. e.preventDefault();
  824. if (active.dataset.cardId) {
  825. Meteor.call('moveCardUp', active.dataset.cardId);
  826. }
  827. }
  828. if (e.key === 'ArrowDown') {
  829. e.preventDefault();
  830. if (active.dataset.cardId) {
  831. Meteor.call('moveCardDown', active.dataset.cardId);
  832. }
  833. }
  834. }
  835. // Ensure move card buttons are focusable and have ARIA roles
  836. document.querySelectorAll('.js-move-card').forEach(function(el) {
  837. el.setAttribute('tabindex', '0');
  838. el.setAttribute('role', 'button');
  839. el.setAttribute('aria-label', 'Move card');
  840. });
  841. // Make toggle-buttons, color choices, reactions, and X-buttons keyboard accessible
  842. if (active && (active.classList.contains('js-toggle') || active.classList.contains('js-color-choice') || active.classList.contains('js-reaction') || active.classList.contains('close'))) {
  843. if (e.key === 'Enter' || e.key === ' ') {
  844. e.preventDefault();
  845. active.click();
  846. }
  847. }
  848. // Prevent scripts from removing focus when received
  849. if (active) {
  850. active.addEventListener('focus', function(e) {
  851. // Do not remove focus
  852. // No-op: This prevents F55 failure
  853. }, { once: true });
  854. }
  855. // Make swimlane/list renaming keyboard accessible
  856. if (active && (active.classList.contains('js-rename-swimlane') || active.classList.contains('js-rename-list'))) {
  857. if (e.key === 'Enter') {
  858. e.preventDefault();
  859. active.click();
  860. }
  861. }
  862. // Calendar navigation buttons
  863. if (active && active.classList.contains('fc-button')) {
  864. if (e.key === 'Enter' || e.key === ' ') {
  865. e.preventDefault();
  866. active.click();
  867. }
  868. }
  869. });
  870. BlazeComponent.extendComponent({
  871. onRendered() {
  872. // Set the language attribute on the <html> element for accessibility
  873. document.documentElement.lang = TAPi18n.getLanguage();
  874. this.autorun(function () {
  875. $('#calendar-view').fullCalendar('refetchEvents');
  876. });
  877. },
  878. calendarOptions() {
  879. return {
  880. id: 'calendar-view',
  881. defaultView: 'month',
  882. editable: true,
  883. selectable: true,
  884. timezone: 'local',
  885. weekNumbers: true,
  886. header: {
  887. left: 'title today prev,next',
  888. center:
  889. 'agendaDay,listDay,timelineDay agendaWeek,listWeek,timelineWeek month,listMonth',
  890. right: '',
  891. },
  892. buttonText: {
  893. prev: TAPi18n.__('calendar-previous-month-label'), // e.g. "Previous month"
  894. next: TAPi18n.__('calendar-next-month-label'), // e.g. "Next month"
  895. },
  896. ariaLabel: {
  897. prev: TAPi18n.__('calendar-previous-month-label'),
  898. next: TAPi18n.__('calendar-next-month-label'),
  899. },
  900. // height: 'parent', nope, doesn't work as the parent might be small
  901. height: 'auto',
  902. /* TODO: lists as resources: https://fullcalendar.io/docs/vertical-resource-view */
  903. navLinks: true,
  904. nowIndicator: true,
  905. businessHours: {
  906. // days of week. an array of zero-based day of week integers (0=Sunday)
  907. dow: [1, 2, 3, 4, 5], // Monday - Friday
  908. start: '8:00',
  909. end: '18:00',
  910. },
  911. locale: TAPi18n.getLanguage(),
  912. events(start, end, timezone, callback) {
  913. const currentBoard = Utils.getCurrentBoard();
  914. const events = [];
  915. const pushEvent = function (card, title, start, end, extraCls) {
  916. start = start || card.startAt;
  917. end = end || card.endAt;
  918. title = title || card.title;
  919. const className =
  920. (extraCls ? `${extraCls} ` : '') +
  921. (card.color ? `calendar-event-${card.color}` : '');
  922. events.push({
  923. id: card._id,
  924. title,
  925. start,
  926. end: end || card.endAt,
  927. allDay:
  928. Math.abs(end.getTime() - start.getTime()) / 1000 === 24 * 3600,
  929. url: FlowRouter.path('card', {
  930. boardId: currentBoard._id,
  931. slug: currentBoard.slug,
  932. cardId: card._id,
  933. }),
  934. className,
  935. });
  936. };
  937. currentBoard
  938. .cardsInInterval(start.toDate(), end.toDate())
  939. .forEach(function (card) {
  940. pushEvent(card);
  941. });
  942. currentBoard
  943. .cardsDueInBetween(start.toDate(), end.toDate())
  944. .forEach(function (card) {
  945. pushEvent(
  946. card,
  947. `${card.title} ${TAPi18n.__('card-due')}`,
  948. card.dueAt,
  949. new Date(card.dueAt.getTime() + 36e5),
  950. );
  951. });
  952. events.sort(function (first, second) {
  953. return first.id > second.id ? 1 : -1;
  954. });
  955. callback(events);
  956. },
  957. eventResize(event, delta, revertFunc) {
  958. let isOk = false;
  959. const card = ReactiveCache.getCard(event.id);
  960. if (card) {
  961. card.setEnd(event.end.toDate());
  962. isOk = true;
  963. }
  964. if (!isOk) {
  965. revertFunc();
  966. }
  967. },
  968. eventDrop(event, delta, revertFunc) {
  969. let isOk = false;
  970. const card = ReactiveCache.getCard(event.id);
  971. if (card) {
  972. // TODO: add a flag for allDay events
  973. if (!event.allDay) {
  974. // https://github.com/wekan/wekan/issues/2917#issuecomment-1236753962
  975. //card.setStart(event.start.toDate());
  976. //card.setEnd(event.end.toDate());
  977. card.setDue(event.start.toDate());
  978. isOk = true;
  979. }
  980. }
  981. if (!isOk) {
  982. revertFunc();
  983. }
  984. },
  985. select: function (startDate) {
  986. const currentBoard = Utils.getCurrentBoard();
  987. const currentUser = ReactiveCache.getCurrentUser();
  988. const modalElement = document.createElement('div');
  989. modalElement.classList.add('modal', 'fade');
  990. modalElement.setAttribute('tabindex', '-1');
  991. modalElement.setAttribute('role', 'dialog');
  992. modalElement.innerHTML = `
  993. <div class="modal-dialog justify-content-center align-items-center" role="document">
  994. <div class="modal-content">
  995. <div class="modal-header">
  996. <h5 class="modal-title">${TAPi18n.__('r-create-card')}</h5>
  997. <button type="button" class="close" data-dismiss="modal" aria-label="Close">
  998. <span aria-hidden="true">&times;</span>
  999. </button>
  1000. </div>
  1001. <div class="modal-body text-center">
  1002. <input type="text" class="form-control" id="card-title-input" placeholder="">
  1003. </div>
  1004. <div class="modal-footer">
  1005. <button type="button" class="btn btn-primary" id="create-card-button">${TAPi18n.__('add-card')}</button>
  1006. </div>
  1007. </div>
  1008. </div>
  1009. `;
  1010. const createCardButton = modalElement.querySelector('#create-card-button');
  1011. createCardButton.addEventListener('click', function () {
  1012. const myTitle = modalElement.querySelector('#card-title-input').value;
  1013. if (myTitle) {
  1014. const firstList = currentBoard.draggableLists()[0];
  1015. const firstSwimlane = currentBoard.swimlanes()[0];
  1016. Meteor.call('createCardWithDueDate', currentBoard._id, firstList._id, myTitle, startDate.toDate(), firstSwimlane._id, function(error, result) {
  1017. if (error) {
  1018. console.log(error);
  1019. } else {
  1020. console.log("Card Created", result);
  1021. }
  1022. });
  1023. closeModal();
  1024. }
  1025. });
  1026. document.body.appendChild(modalElement);
  1027. const openModal = function() {
  1028. modalElement.style.display = 'flex';
  1029. // Set focus to the input field for better keyboard accessibility
  1030. const input = modalElement.querySelector('#card-title-input');
  1031. if (input) input.focus();
  1032. };
  1033. const closeModal = function() {
  1034. modalElement.style.display = 'none';
  1035. };
  1036. const closeButton = modalElement.querySelector('[data-dismiss="modal"]');
  1037. closeButton.addEventListener('click', closeModal);
  1038. openModal();
  1039. }
  1040. };
  1041. },
  1042. isViewCalendar() {
  1043. const currentUser = ReactiveCache.getCurrentUser();
  1044. if (currentUser) {
  1045. return (currentUser.profile || {}).boardView === 'board-view-cal';
  1046. } else {
  1047. return window.localStorage.getItem('boardView') === 'board-view-cal';
  1048. }
  1049. },
  1050. }).register('calendarView');