boardBody.js 42 KB

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