listBody.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  1. import { ReactiveCache } from '/imports/reactiveCache';
  2. import { TAPi18n } from '/imports/i18n';
  3. import { Spinner } from '/client/lib/spinner';
  4. const subManager = new SubsManager();
  5. const InfiniteScrollIter = 10;
  6. BlazeComponent.extendComponent({
  7. onCreated() {
  8. // for infinite scrolling
  9. this.cardlimit = new ReactiveVar(InfiniteScrollIter);
  10. },
  11. mixins() {
  12. return [];
  13. },
  14. customFieldsSum() {
  15. const list = Template.currentData();
  16. if (!list) return [];
  17. const boardId = Session.get('currentBoard');
  18. const fields = ReactiveCache.getCustomFields({
  19. boardIds: { $in: [boardId] },
  20. showSumAtTopOfList: true,
  21. });
  22. if (!fields || !fields.length) return [];
  23. const cards = ReactiveCache.getCards({
  24. listId: list._id,
  25. archived: false,
  26. });
  27. const result = fields.map(field => {
  28. let sum = 0;
  29. if (cards && cards.length) {
  30. cards.forEach(card => {
  31. const cfs = (card.customFields || []);
  32. const cf = cfs.find(f => f && f._id === field._id);
  33. if (!cf || cf.value === null || cf.value === undefined) return;
  34. let v = cf.value;
  35. if (typeof v === 'string') {
  36. // try to parse string numbers, accept comma decimal
  37. const parsed = parseFloat(v.replace(',', '.'));
  38. if (isNaN(parsed)) return;
  39. v = parsed;
  40. }
  41. if (typeof v === 'number' && isFinite(v)) {
  42. sum += v;
  43. }
  44. });
  45. }
  46. return {
  47. _id: field._id,
  48. name: field.name,
  49. type: field.type,
  50. settings: field.settings || {},
  51. value: sum,
  52. };
  53. });
  54. return result;
  55. },
  56. openForm(options) {
  57. options = options || {};
  58. options.position = options.position || 'top';
  59. const forms = this.childComponents('inlinedForm');
  60. let form = forms.find(component => {
  61. return component.data().position === options.position;
  62. });
  63. if (!form && forms.length > 0) {
  64. form = forms[0];
  65. }
  66. form.open();
  67. },
  68. addCard(evt) {
  69. evt.preventDefault();
  70. const firstCardDom = this.find('.js-minicard:first');
  71. const lastCardDom = this.find('.js-minicard:last');
  72. const textarea = $(evt.currentTarget).find('textarea');
  73. const position = this.currentData().position;
  74. const title = textarea.val().trim();
  75. let sortIndex;
  76. if (position === 'top') {
  77. sortIndex = Utils.calculateIndex(null, firstCardDom).base;
  78. } else if (position === 'bottom') {
  79. sortIndex = Utils.calculateIndex(lastCardDom, null).base;
  80. }
  81. const formComponent = this.cardFormComponent();
  82. const members = formComponent.members.get();
  83. const labelIds = formComponent.labels.get();
  84. const customFields = formComponent.customFields.get();
  85. const board = this.data().board();
  86. let linkedId = '';
  87. let swimlaneId = '';
  88. let cardType = 'cardType-card';
  89. if (title) {
  90. if (board.isTemplatesBoard()) {
  91. swimlaneId = this.parentComponent()
  92. .parentComponent()
  93. .data()._id; // Always swimlanes view
  94. const swimlane = ReactiveCache.getSwimlane(swimlaneId);
  95. // If this is the card templates swimlane, insert a card template
  96. if (swimlane.isCardTemplatesSwimlane()) cardType = 'template-card';
  97. // If this is the board templates swimlane, insert a board template and a linked card
  98. else if (swimlane.isBoardTemplatesSwimlane()) {
  99. linkedId = Boards.insert({
  100. title,
  101. permission: 'private',
  102. type: 'template-board',
  103. });
  104. Swimlanes.insert({
  105. title: TAPi18n.__('default'),
  106. boardId: linkedId,
  107. });
  108. cardType = 'cardType-linkedBoard';
  109. }
  110. } else if (Utils.boardView() === 'board-view-swimlanes')
  111. swimlaneId = this.parentComponent()
  112. .parentComponent()
  113. .data()._id;
  114. else if (
  115. Utils.boardView() === 'board-view-lists' ||
  116. Utils.boardView() === 'board-view-cal' ||
  117. !Utils.boardView()
  118. )
  119. swimlaneId = board.getDefaultSwimline()._id;
  120. const nextCardNumber = board.getNextCardNumber();
  121. const _id = Cards.insert({
  122. title,
  123. members,
  124. labelIds,
  125. customFields,
  126. listId: this.data()._id,
  127. boardId: board._id,
  128. sort: sortIndex,
  129. swimlaneId,
  130. type: cardType,
  131. cardNumber: nextCardNumber,
  132. linkedId,
  133. });
  134. // if the displayed card count is less than the total cards in the list,
  135. // we need to increment the displayed card count to prevent the spinner
  136. // to appear
  137. const cardCount = this.data()
  138. .cards(this.idOrNull(swimlaneId))
  139. .length;
  140. if (this.cardlimit.get() < cardCount) {
  141. this.cardlimit.set(this.cardlimit.get() + InfiniteScrollIter);
  142. }
  143. // In case the filter is active we need to add the newly inserted card in
  144. // the list of exceptions -- cards that are not filtered. Otherwise the
  145. // card will disappear instantly.
  146. // See https://github.com/wekan/wekan/issues/80
  147. Filter.addException(_id);
  148. // We keep the form opened, empty it, and scroll to it.
  149. textarea.val('').focus();
  150. autosize.update(textarea);
  151. if (position === 'bottom') {
  152. this.scrollToBottom();
  153. }
  154. }
  155. },
  156. cardFormComponent() {
  157. for (const inlinedForm of this.childComponents('inlinedForm')) {
  158. const [addCardForm] = inlinedForm.childComponents('addCardForm');
  159. if (addCardForm) {
  160. return addCardForm;
  161. }
  162. }
  163. return null;
  164. },
  165. scrollToBottom() {
  166. const container = this.firstNode();
  167. $(container).animate({
  168. scrollTop: container.scrollHeight,
  169. });
  170. },
  171. clickOnMiniCard(evt) {
  172. if (MultiSelection.isActive() || evt.shiftKey) {
  173. evt.stopImmediatePropagation();
  174. evt.preventDefault();
  175. const methodName = evt.shiftKey ? 'toggleRange' : 'toggle';
  176. MultiSelection[methodName](this.currentData()._id);
  177. // If the card is already selected, we want to de-select it.
  178. // XXX We should probably modify the minicard href attribute instead of
  179. // overwriting the event in case the card is already selected.
  180. } else if (Utils.isMiniScreen()) {
  181. evt.preventDefault();
  182. Session.set('popupCardId', this.currentData()._id);
  183. this.cardDetailsPopup(evt);
  184. } else if (Session.equals('currentCard', this.currentData()._id)) {
  185. evt.stopImmediatePropagation();
  186. evt.preventDefault();
  187. Utils.goBoardId(Session.get('currentBoard'));
  188. }
  189. },
  190. cardIsSelected() {
  191. return Session.equals('currentCard', this.currentData()._id);
  192. },
  193. toggleMultiSelection(evt) {
  194. evt.stopPropagation();
  195. evt.preventDefault();
  196. MultiSelection.toggle(this.currentData()._id);
  197. },
  198. idOrNull(swimlaneId) {
  199. if (
  200. Utils.boardView() === 'board-view-swimlanes' ||
  201. this.data()
  202. .board()
  203. .isTemplatesBoard()
  204. )
  205. return swimlaneId;
  206. return undefined;
  207. },
  208. cardsWithLimit(swimlaneId) {
  209. const limit = this.cardlimit.get();
  210. const defaultSort = { sort: 1 };
  211. const sortBy = Session.get('sortBy') ? Session.get('sortBy') : defaultSort;
  212. const selector = {
  213. listId: this.currentData()._id,
  214. archived: false,
  215. };
  216. if (swimlaneId) selector.swimlaneId = swimlaneId;
  217. const ret = ReactiveCache.getCards(Filter.mongoSelector(selector), {
  218. // sort: ['sort'],
  219. sort: sortBy,
  220. limit,
  221. }, true);
  222. return ret;
  223. },
  224. showSpinner(swimlaneId) {
  225. const list = Template.currentData();
  226. return list.cards(swimlaneId).length > this.cardlimit.get();
  227. },
  228. canSeeAddCard() {
  229. return (
  230. !this.reachedWipLimit() &&
  231. Utils.canModifyCard()
  232. );
  233. },
  234. reachedWipLimit() {
  235. const list = Template.currentData();
  236. return (
  237. !list.getWipLimit('soft') &&
  238. list.getWipLimit('enabled') &&
  239. list.getWipLimit('value') <= list.cards().length
  240. );
  241. },
  242. isVerticalScrollbars() {
  243. const user = ReactiveCache.getCurrentUser();
  244. return user && user.isVerticalScrollbars();
  245. },
  246. cardDetailsPopup(event) {
  247. if (!Popup.isOpen()) {
  248. Popup.open("cardDetails")(event);
  249. }
  250. },
  251. events() {
  252. return [
  253. {
  254. 'click .js-minicard': this.clickOnMiniCard,
  255. 'click .js-toggle-multi-selection': this.toggleMultiSelection,
  256. 'click .open-minicard-composer': this.scrollToBottom,
  257. submit: this.addCard,
  258. },
  259. ];
  260. },
  261. }).register('listBody');
  262. // Helpers for listBody template context
  263. Template.listBody.helpers({
  264. formattedCurrencyCustomFieldValue(val) {
  265. // `this` is the custom field sum object from customFieldsSum each-iteration
  266. const field = this || {};
  267. const code = (field.settings && field.settings.currencyCode) || 'USD';
  268. try {
  269. const n = typeof val === 'number' ? val : parseFloat(val);
  270. if (!isFinite(n)) return val;
  271. return new Intl.NumberFormat(undefined, { style: 'currency', currency: code }).format(n);
  272. } catch (e) {
  273. return `${code} ${val}`;
  274. }
  275. },
  276. });
  277. function toggleValueInReactiveArray(reactiveValue, value) {
  278. const array = reactiveValue.get();
  279. const valueIndex = array.indexOf(value);
  280. if (valueIndex === -1) {
  281. array.push(value);
  282. } else {
  283. array.splice(valueIndex, 1);
  284. }
  285. reactiveValue.set(array);
  286. }
  287. BlazeComponent.extendComponent({
  288. onCreated() {
  289. this.labels = new ReactiveVar([]);
  290. this.members = new ReactiveVar([]);
  291. this.customFields = new ReactiveVar([]);
  292. const currentBoardId = Session.get('currentBoard');
  293. arr = [];
  294. _.forEach(
  295. ReactiveCache.getBoard(currentBoardId)
  296. .customFields(),
  297. function (field) {
  298. if (field.automaticallyOnCard || field.alwaysOnCard)
  299. arr.push({ _id: field._id, value: null });
  300. },
  301. );
  302. this.customFields.set(arr);
  303. },
  304. reset() {
  305. this.labels.set([]);
  306. this.members.set([]);
  307. this.customFields.set([]);
  308. },
  309. getLabels() {
  310. const currentBoardId = Session.get('currentBoard');
  311. if (ReactiveCache.getBoard(currentBoardId).labels) {
  312. return ReactiveCache.getBoard(currentBoardId).labels.filter(label => {
  313. return this.labels.get().indexOf(label._id) > -1;
  314. });
  315. }
  316. return false;
  317. },
  318. pressKey(evt) {
  319. // Pressing Enter should submit the card
  320. if (evt.keyCode === 13 && !evt.shiftKey) {
  321. evt.preventDefault();
  322. const $form = $(evt.currentTarget).closest('form');
  323. // XXX For some reason $form.submit() does not work (it's probably a bug
  324. // of blaze-component related to the fact that the submit event is non-
  325. // bubbling). This is why we click on the submit button instead -- which
  326. // work.
  327. $form.find('button[type=submit]').click();
  328. // Pressing Tab should open the form of the next column, and Maj+Tab go
  329. // in the reverse order
  330. } else if (evt.keyCode === 9) {
  331. // Prevent custom focus movement on Tab key for accessibility
  332. // evt.preventDefault();
  333. const isReverse = evt.shiftKey;
  334. const list = $(`#js-list-${this.data().listId}`);
  335. const listSelector = '.js-list:not(.js-list-composer)';
  336. let nextList = list[isReverse ? 'prev' : 'next'](listSelector).get(0);
  337. // If there is no next list, loop back to the beginning.
  338. if (!nextList) {
  339. nextList = $(listSelector + (isReverse ? ':last' : ':first')).get(0);
  340. }
  341. BlazeComponent.getComponentForElement(nextList).openForm({
  342. position: this.data().position,
  343. });
  344. }
  345. },
  346. events() {
  347. return [
  348. {
  349. keydown: this.pressKey,
  350. 'click .js-link': Popup.open('linkCard'),
  351. 'click .js-search': Popup.open('searchElement'),
  352. 'click .js-card-template': Popup.open('searchElement'),
  353. },
  354. ];
  355. },
  356. onRendered() {
  357. const editor = this;
  358. const $textarea = this.$('textarea');
  359. autosize($textarea);
  360. $textarea.escapeableTextComplete(
  361. [
  362. // User mentions
  363. {
  364. match: /\B@([\w.-]*)$/,
  365. search(term, callback) {
  366. const currentBoard = Utils.getCurrentBoard();
  367. callback(
  368. $.map(currentBoard.activeMembers(), member => {
  369. const user = ReactiveCache.getUser(member.userId);
  370. return user.username.indexOf(term) === 0 ? user : null;
  371. }),
  372. );
  373. },
  374. template(user) {
  375. if (user.profile && user.profile.fullname) {
  376. return (user.username + " (" + user.profile.fullname + ")");
  377. }
  378. return user.username;
  379. },
  380. replace(user) {
  381. toggleValueInReactiveArray(editor.members, user._id);
  382. return '';
  383. },
  384. index: 1,
  385. },
  386. // Labels
  387. {
  388. match: /\B#(\w*)$/,
  389. search(term, callback) {
  390. const currentBoard = Utils.getCurrentBoard();
  391. callback(
  392. $.map(currentBoard.labels, label => {
  393. if (label.name == undefined) {
  394. label.name = "";
  395. }
  396. if (
  397. label.name.indexOf(term) > -1 ||
  398. label.color.indexOf(term) > -1
  399. ) {
  400. return label;
  401. }
  402. return null;
  403. }),
  404. );
  405. },
  406. template(label) {
  407. return Blaze.toHTMLWithData(Template.autocompleteLabelLine, {
  408. hasNoName: !label.name,
  409. colorName: label.color,
  410. labelName: label.name || label.color,
  411. });
  412. },
  413. replace(label) {
  414. toggleValueInReactiveArray(editor.labels, label._id);
  415. return '';
  416. },
  417. index: 1,
  418. },
  419. ],
  420. {
  421. // When the autocomplete menu is shown we want both a press of both `Tab`
  422. // or `Enter` to validation the auto-completion. We also need to stop the
  423. // event propagation to prevent the card from submitting (on `Enter`) or
  424. // going on the next column (on `Tab`).
  425. /*
  426. onKeydown(evt, commands) {
  427. // Prevent custom focus movement on Tab key for accessibility
  428. // if (evt.keyCode === 9 || evt.keyCode === 13) {
  429. // evt.stopPropagation();
  430. // return commands.KEY_ENTER;
  431. //}
  432. return null;
  433. },
  434. */
  435. },
  436. );
  437. },
  438. }).register('addCardForm');
  439. BlazeComponent.extendComponent({
  440. onCreated() {
  441. this.selectedBoardId = new ReactiveVar('');
  442. this.selectedSwimlaneId = new ReactiveVar('');
  443. this.selectedListId = new ReactiveVar('');
  444. this.boardId = Session.get('currentBoard');
  445. // In order to get current board info
  446. subManager.subscribe('board', this.boardId, false);
  447. this.board = ReactiveCache.getBoard(this.boardId);
  448. // List where to insert card
  449. this.list = $(Popup._getTopStack().openerElement).closest('.js-list');
  450. this.listId = Blaze.getData(this.list[0])._id;
  451. // Swimlane where to insert card
  452. const swimlane = $(Popup._getTopStack().openerElement).closest(
  453. '.js-swimlane',
  454. );
  455. this.swimlaneId = '';
  456. if (Utils.boardView() === 'board-view-swimlanes')
  457. this.swimlaneId = Blaze.getData(swimlane[0])._id;
  458. else if (Utils.boardView() === 'board-view-lists' || !Utils.boardView)
  459. this.swimlaneId = ReactiveCache.getSwimlane({ boardId: this.boardId })._id;
  460. },
  461. boards() {
  462. const ret = ReactiveCache.getBoards(
  463. {
  464. archived: false,
  465. 'members.userId': Meteor.userId(),
  466. _id: { $ne: Session.get('currentBoard') },
  467. type: 'board',
  468. },
  469. {
  470. sort: { sort: 1 /* boards default sorting */ },
  471. },
  472. );
  473. return ret;
  474. },
  475. swimlanes() {
  476. if (!this.selectedBoardId.get()) {
  477. return [];
  478. }
  479. const board = ReactiveCache.getBoard(this.selectedBoardId.get());
  480. if (!board) {
  481. return [];
  482. }
  483. // Ensure default swimlane exists
  484. board.getDefaultSwimline();
  485. const swimlanes = ReactiveCache.getSwimlanes(
  486. {
  487. boardId: this.selectedBoardId.get()
  488. },
  489. {
  490. sort: { sort: 1 },
  491. });
  492. return swimlanes;
  493. },
  494. lists() {
  495. if (!this.selectedBoardId.get()) {
  496. return [];
  497. }
  498. const lists = ReactiveCache.getLists(
  499. {
  500. boardId: this.selectedBoardId.get()
  501. },
  502. {
  503. sort: { sort: 1 },
  504. });
  505. return lists;
  506. },
  507. cards() {
  508. if (!this.board) {
  509. return [];
  510. }
  511. const ownCardsIds = this.board.cards().map(card => card.getRealId());
  512. const selector = {
  513. archived: false,
  514. linkedId: { $nin: ownCardsIds },
  515. _id: { $nin: ownCardsIds },
  516. type: { $nin: ['template-card'] },
  517. };
  518. if (this.selectedBoardId.get()) selector.boardId = this.selectedBoardId.get();
  519. if (this.selectedSwimlaneId.get()) selector.swimlaneId = this.selectedSwimlaneId.get();
  520. if (this.selectedListId.get()) selector.listId = this.selectedListId.get();
  521. const ret = ReactiveCache.getCards(selector, { sort: { sort: 1 } });
  522. return ret;
  523. },
  524. getSortIndex() {
  525. const position = this.currentData().position;
  526. let ret;
  527. if (position === 'top') {
  528. const firstCardDom = this.list.find('.js-minicard:first')[0];
  529. ret = Utils.calculateIndex(null, firstCardDom).base;
  530. } else if (position === 'bottom') {
  531. const lastCardDom = this.list.find('.js-minicard:last')[0];
  532. ret = Utils.calculateIndex(lastCardDom, null).base;
  533. }
  534. return ret;
  535. },
  536. events() {
  537. return [
  538. {
  539. 'change .js-select-boards'(evt) {
  540. const val = $(evt.currentTarget).val();
  541. subManager.subscribe('board', val, false);
  542. // Clear selections to allow linking only board or re-choose swimlane/list
  543. this.selectedSwimlaneId.set('');
  544. this.selectedListId.set('');
  545. this.selectedBoardId.set(val);
  546. },
  547. 'change .js-select-swimlanes'(evt) {
  548. this.selectedSwimlaneId.set($(evt.currentTarget).val());
  549. },
  550. 'change .js-select-lists'(evt) {
  551. this.selectedListId.set($(evt.currentTarget).val());
  552. },
  553. 'click .js-done'(evt) {
  554. // LINK CARD
  555. evt.stopPropagation();
  556. evt.preventDefault();
  557. const linkedId = $('.js-select-cards option:selected').val();
  558. if (!linkedId) {
  559. Popup.back();
  560. return;
  561. }
  562. const nextCardNumber = this.board.getNextCardNumber();
  563. const sortIndex = this.getSortIndex();
  564. const _id = Cards.insert({
  565. title: $('.js-select-cards option:selected').text(), //dummy
  566. listId: this.listId,
  567. swimlaneId: this.swimlaneId,
  568. boardId: this.boardId,
  569. sort: sortIndex,
  570. type: 'cardType-linkedCard',
  571. linkedId,
  572. cardNumber: nextCardNumber,
  573. });
  574. Filter.addException(_id);
  575. Popup.back();
  576. },
  577. 'click .js-link-board'(evt) {
  578. //LINK BOARD
  579. evt.stopPropagation();
  580. evt.preventDefault();
  581. const impBoardId = $('.js-select-boards option:selected').val();
  582. if (
  583. !impBoardId ||
  584. ReactiveCache.getCard({ linkedId: impBoardId, archived: false })
  585. ) {
  586. Popup.back();
  587. return;
  588. }
  589. const nextCardNumber = this.board.getNextCardNumber();
  590. const sortIndex = this.getSortIndex();
  591. const _id = Cards.insert({
  592. title: $('.js-select-boards option:selected').text(), //dummy
  593. listId: this.listId,
  594. swimlaneId: this.swimlaneId,
  595. boardId: this.boardId,
  596. sort: sortIndex,
  597. type: 'cardType-linkedBoard',
  598. linkedId: impBoardId,
  599. cardNumber: nextCardNumber,
  600. });
  601. Filter.addException(_id);
  602. Popup.back();
  603. },
  604. },
  605. ];
  606. },
  607. }).register('linkCardPopup');
  608. Template.linkCardPopup.helpers({
  609. isTitleDefault(title) {
  610. // https://github.com/wekan/wekan/issues/4763
  611. // https://github.com/wekan/wekan/issues/4742
  612. // Translation text for "default" does not work, it returns an object.
  613. // When that happens, try use translation "defaultdefault" that has same content of default, or return text "Default".
  614. // This can happen, if swimlane does not have name.
  615. // Yes, this is fixing the symptom (Swimlane title does not have title)
  616. // instead of fixing the problem (Add Swimlane title when creating swimlane)
  617. // because there could be thousands of swimlanes, adding name Default to all of them
  618. // would be very slow.
  619. if (title.startsWith("key 'default") && title.endsWith('returned an object instead of string.')) {
  620. if (`${TAPi18n.__('defaultdefault')}`.startsWith("key 'default") && `${TAPi18n.__('defaultdefault')}`.endsWith('returned an object instead of string.')) {
  621. return 'Default';
  622. } else {
  623. return `${TAPi18n.__('defaultdefault')}`;
  624. }
  625. } else if (title === 'Default') {
  626. return `${TAPi18n.__('defaultdefault')}`;
  627. } else {
  628. return title;
  629. }
  630. },
  631. });
  632. BlazeComponent.extendComponent({
  633. mixins() {
  634. return [];
  635. },
  636. onCreated() {
  637. this.isCardTemplateSearch = $(Popup._getTopStack().openerElement).hasClass(
  638. 'js-card-template',
  639. );
  640. this.isListTemplateSearch = $(Popup._getTopStack().openerElement).hasClass(
  641. 'js-list-template',
  642. );
  643. this.isSwimlaneTemplateSearch = $(
  644. Popup._getTopStack().openerElement,
  645. ).hasClass('js-open-add-swimlane-menu');
  646. this.isBoardTemplateSearch = $(Popup._getTopStack().openerElement).hasClass(
  647. 'js-add-board',
  648. );
  649. this.isTemplateSearch =
  650. this.isCardTemplateSearch ||
  651. this.isListTemplateSearch ||
  652. this.isSwimlaneTemplateSearch ||
  653. this.isBoardTemplateSearch;
  654. this.board = {};
  655. if (this.isTemplateSearch) {
  656. const boardId = (ReactiveCache.getCurrentUser().profile || {}).templatesBoardId;
  657. if (boardId) {
  658. subManager.subscribe('board', boardId, false);
  659. this.board = ReactiveCache.getBoard(boardId);
  660. }
  661. } else {
  662. this.board = Utils.getCurrentBoard();
  663. }
  664. if (!this.board) {
  665. Popup.back();
  666. return;
  667. }
  668. this.boardId = this.board._id;
  669. // Subscribe to this board
  670. subManager.subscribe('board', this.boardId, false);
  671. this.selectedBoardId = new ReactiveVar(this.boardId);
  672. this.list = $(Popup._getTopStack().openerElement).closest('.js-list');
  673. if (!this.isBoardTemplateSearch) {
  674. this.swimlaneId = '';
  675. // Swimlane where to insert card
  676. const swimlane = $(Popup._getTopStack().openerElement).parents(
  677. '.js-swimlane',
  678. );
  679. if (Utils.boardView() === 'board-view-swimlanes')
  680. this.swimlaneId = Blaze.getData(swimlane[0])._id;
  681. else this.swimlaneId = ReactiveCache.getSwimlane({ boardId: this.boardId })._id;
  682. // List where to insert card
  683. this.listId = Blaze.getData(this.list[0])._id;
  684. }
  685. this.term = new ReactiveVar('');
  686. },
  687. boards() {
  688. const ret = ReactiveCache.getBoards(
  689. {
  690. archived: false,
  691. 'members.userId': Meteor.userId(),
  692. _id: { $ne: Session.get('currentBoard') },
  693. type: 'board',
  694. },
  695. {
  696. sort: { sort: 1 /* boards default sorting */ },
  697. },
  698. );
  699. return ret;
  700. },
  701. results() {
  702. if (!this.selectedBoardId) {
  703. return [];
  704. }
  705. const board = ReactiveCache.getBoard(this.selectedBoardId.get());
  706. if (!this.isTemplateSearch || this.isCardTemplateSearch) {
  707. return board.searchCards(this.term.get(), false);
  708. } else if (this.isListTemplateSearch) {
  709. return board.searchLists(this.term.get());
  710. } else if (this.isSwimlaneTemplateSearch) {
  711. return board.searchSwimlanes(this.term.get());
  712. } else if (this.isBoardTemplateSearch) {
  713. const boards = board.searchBoards(this.term.get());
  714. boards.forEach(board => {
  715. subManager.subscribe('board', board.linkedId, false);
  716. });
  717. return boards;
  718. } else {
  719. return [];
  720. }
  721. },
  722. getSortIndex() {
  723. const position = this.data().position;
  724. let ret;
  725. if (position === 'top') {
  726. const firstCardDom = this.list.find('.js-minicard:first')[0];
  727. ret = Utils.calculateIndex(null, firstCardDom).base;
  728. } else if (position === 'bottom') {
  729. const lastCardDom = this.list.find('.js-minicard:last')[0];
  730. ret = Utils.calculateIndex(lastCardDom, null).base;
  731. }
  732. return ret;
  733. },
  734. events() {
  735. return [
  736. {
  737. 'change .js-select-boards'(evt) {
  738. subManager.subscribe('board', $(evt.currentTarget).val(), false);
  739. this.selectedBoardId.set($(evt.currentTarget).val());
  740. },
  741. 'submit .js-search-term-form'(evt) {
  742. evt.preventDefault();
  743. this.term.set(evt.target.searchTerm.value);
  744. },
  745. 'click .js-minicard'(evt) {
  746. // 0. Common
  747. const title = $('.js-element-title')
  748. .val()
  749. .trim();
  750. if (!title) return;
  751. const element = Blaze.getData(evt.currentTarget);
  752. element.title = title;
  753. let _id = '';
  754. if (!this.isTemplateSearch || this.isCardTemplateSearch) {
  755. // Card insertion
  756. // 1. Common
  757. element.cardNumber = this.board.getNextCardNumber();
  758. element.sort = this.getSortIndex();
  759. // 1.A From template
  760. if (this.isTemplateSearch) {
  761. element.type = 'cardType-card';
  762. element.linkedId = '';
  763. _id = element.copy(this.boardId, this.swimlaneId, this.listId);
  764. // 1.B Linked card
  765. } else {
  766. _id = element.link(this.boardId, this.swimlaneId, this.listId);
  767. }
  768. Filter.addException(_id);
  769. // List insertion
  770. } else if (this.isListTemplateSearch) {
  771. element.sort = ReactiveCache.getSwimlane(this.swimlaneId)
  772. .lists()
  773. .length;
  774. element.type = 'list';
  775. _id = element.copy(this.boardId, this.swimlaneId);
  776. } else if (this.isSwimlaneTemplateSearch) {
  777. element.sort = ReactiveCache.getBoard(this.boardId)
  778. .swimlanes()
  779. .length;
  780. element.type = 'swimlane';
  781. _id = element.copy(this.boardId);
  782. } else if (this.isBoardTemplateSearch) {
  783. Meteor.call(
  784. 'copyBoard',
  785. element.linkedId,
  786. {
  787. sort: ReactiveCache.getBoards({ archived: false }).length,
  788. type: 'board',
  789. title: element.title,
  790. },
  791. (err, data) => {
  792. _id = data;
  793. subManager.subscribe('board', _id, false);
  794. FlowRouter.go('board', {
  795. id: _id,
  796. slug: getSlug(element.title),
  797. });
  798. },
  799. );
  800. }
  801. Popup.back();
  802. },
  803. },
  804. ];
  805. },
  806. }).register('searchElementPopup');
  807. (class extends Spinner {
  808. onCreated() {
  809. this.cardlimit = this.parentComponent().cardlimit;
  810. this.listId = this.parentComponent().data()._id;
  811. this.swimlaneId = '';
  812. const isSandstorm =
  813. Meteor.settings &&
  814. Meteor.settings.public &&
  815. Meteor.settings.public.sandstorm;
  816. if (isSandstorm) {
  817. const user = ReactiveCache.getCurrentUser();
  818. if (user) {
  819. if (Utils.boardView() === 'board-view-swimlanes') {
  820. this.swimlaneId = this.parentComponent()
  821. .parentComponent()
  822. .parentComponent()
  823. .data()._id;
  824. }
  825. }
  826. } else if (Utils.boardView() === 'board-view-swimlanes') {
  827. this.swimlaneId = this.parentComponent()
  828. .parentComponent()
  829. .parentComponent()
  830. .data()._id;
  831. }
  832. }
  833. onRendered() {
  834. this.spinner = this.find('.sk-spinner-list');
  835. this.container = this.$(this.spinner).parents('.list-body')[0];
  836. $(this.container).on(
  837. `scroll.spinner_${this.swimlaneId}_${this.listId}`,
  838. () => this.updateList(),
  839. );
  840. $(window).on(`resize.spinner_${this.swimlaneId}_${this.listId}`, () =>
  841. this.updateList(),
  842. );
  843. this.updateList();
  844. }
  845. onDestroyed() {
  846. $(this.container).off(`scroll.spinner_${this.swimlaneId}_${this.listId}`);
  847. $(window).off(`resize.spinner_${this.swimlaneId}_${this.listId}`);
  848. }
  849. checkIdleTime() {
  850. return window.requestIdleCallback ||
  851. function (handler) {
  852. const startTime = Date.now();
  853. return setTimeout(function () {
  854. handler({
  855. didTimeout: false,
  856. timeRemaining() {
  857. return Math.max(0, 50.0 - (Date.now() - startTime));
  858. },
  859. });
  860. }, 1);
  861. };
  862. }
  863. updateList() {
  864. // Use fallback when requestIdleCallback is not available on iOS and Safari
  865. // https://www.afasterweb.com/2017/11/20/utilizing-idle-moments/
  866. if (this.spinnerInView()) {
  867. this.cardlimit.set(this.cardlimit.get() + InfiniteScrollIter);
  868. this.checkIdleTime(() => this.updateList());
  869. }
  870. }
  871. spinnerInView() {
  872. // spinner deleted
  873. if (!this.spinner.offsetTop) {
  874. return false;
  875. }
  876. const spinnerViewPosition = this.spinner.offsetTop - this.container.offsetTop + this.spinner.clientHeight;
  877. const parentViewHeight = this.container.clientHeight;
  878. const bottomViewPosition = this.container.scrollTop + parentViewHeight;
  879. return bottomViewPosition > spinnerViewPosition;
  880. }
  881. getSkSpinnerName() {
  882. return "sk-spinner-" + super.getSpinnerName().toLowerCase();
  883. }
  884. }.register('spinnerList'));