boardBody.js 49 KB

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