boardBody.js 42 KB

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