boardBody.js 50 KB

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