boardBody.js 50 KB

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