utils.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. import { Cookies } from 'meteor/ostrio:cookies';
  2. const cookies = new Cookies();
  3. Utils = {
  4. setBoardView(view) {
  5. currentUser = Meteor.user();
  6. if (currentUser) {
  7. Meteor.user().setBoardView(view);
  8. } else if (view === 'board-view-lists') {
  9. cookies.set('boardView', 'board-view-lists'); //true
  10. } else if (view === 'board-view-swimlanes') {
  11. cookies.set('boardView', 'board-view-swimlanes'); //true
  12. } else if (view === 'board-view-cal') {
  13. cookies.set('boardView', 'board-view-cal'); //true
  14. }
  15. },
  16. unsetBoardView() {
  17. cookies.remove('boardView');
  18. cookies.remove('collapseSwimlane');
  19. },
  20. boardView() {
  21. currentUser = Meteor.user();
  22. if (currentUser) {
  23. return (currentUser.profile || {}).boardView;
  24. } else if (cookies.get('boardView') === 'board-view-lists') {
  25. return 'board-view-lists';
  26. } else if (cookies.get('boardView') === 'board-view-swimlanes') {
  27. return 'board-view-swimlanes';
  28. } else if (cookies.get('boardView') === 'board-view-cal') {
  29. return 'board-view-cal';
  30. } else {
  31. return false;
  32. }
  33. },
  34. // XXX We should remove these two methods
  35. goBoardId(_id) {
  36. const board = Boards.findOne(_id);
  37. return (
  38. board &&
  39. FlowRouter.go('board', {
  40. id: board._id,
  41. slug: board.slug,
  42. })
  43. );
  44. },
  45. goCardId(_id) {
  46. const card = Cards.findOne(_id);
  47. const board = Boards.findOne(card.boardId);
  48. return (
  49. board &&
  50. FlowRouter.go('card', {
  51. cardId: card._id,
  52. boardId: board._id,
  53. slug: board.slug,
  54. })
  55. );
  56. },
  57. MAX_IMAGE_PIXEL: Meteor.settings.public.MAX_IMAGE_PIXEL,
  58. COMPRESS_RATIO: Meteor.settings.public.IMAGE_COMPRESS_RATIO,
  59. processUploadedAttachment(card, fileObj, callbacks) {
  60. if (!card) {
  61. return onUploaded();
  62. }
  63. let settings = {
  64. file: fileObj,
  65. streams: 'dynamic',
  66. chunkSize: 'dynamic',
  67. };
  68. settings.meta = {
  69. uploading: true
  70. };
  71. if (card.isLinkedCard()) {
  72. settings.meta.boardId = Cards.findOne(card.linkedId).boardId;
  73. settings.meta.cardId = card.linkedId;
  74. } else {
  75. settings.meta.boardId = card.boardId;
  76. settings.meta.swimlaneId = card.swimlaneId;
  77. settings.meta.listId = card.listId;
  78. settings.meta.cardId = card._id;
  79. }
  80. settings.meta.userId = Meteor.userId();
  81. if (typeof callbacks === 'function') {
  82. settings.onEnd = callbacks;
  83. } else {
  84. for (const key in callbacks) {
  85. if (key.substring(0, 2) === 'on') {
  86. settings[key] = callbacks[key];
  87. }
  88. }
  89. }
  90. Attachments.insert(settings);
  91. },
  92. shrinkImage(options) {
  93. // shrink image to certain size
  94. const dataurl = options.dataurl,
  95. callback = options.callback,
  96. toBlob = options.toBlob;
  97. let canvas = document.createElement('canvas'),
  98. image = document.createElement('img');
  99. const maxSize = options.maxSize || 1024;
  100. const ratio = options.ratio || 1.0;
  101. const next = function(result) {
  102. image = null;
  103. canvas = null;
  104. if (typeof callback === 'function') {
  105. callback(result);
  106. }
  107. };
  108. image.onload = function() {
  109. let width = this.width,
  110. height = this.height;
  111. let changed = false;
  112. if (width > height) {
  113. if (width > maxSize) {
  114. height *= maxSize / width;
  115. width = maxSize;
  116. changed = true;
  117. }
  118. } else if (height > maxSize) {
  119. width *= maxSize / height;
  120. height = maxSize;
  121. changed = true;
  122. }
  123. canvas.width = width;
  124. canvas.height = height;
  125. canvas.getContext('2d').drawImage(this, 0, 0, width, height);
  126. if (changed === true) {
  127. const type = 'image/jpeg';
  128. if (toBlob) {
  129. canvas.toBlob(next, type, ratio);
  130. } else {
  131. next(canvas.toDataURL(type, ratio));
  132. }
  133. } else {
  134. next(changed);
  135. }
  136. };
  137. image.onerror = function() {
  138. next(false);
  139. };
  140. image.src = dataurl;
  141. },
  142. capitalize(string) {
  143. return string.charAt(0).toUpperCase() + string.slice(1);
  144. },
  145. windowResizeDep: new Tracker.Dependency(),
  146. // in fact, what we really care is screen size
  147. // large mobile device like iPad or android Pad has a big screen, it should also behave like a desktop
  148. // in a small window (even on desktop), Wekan run in compact mode.
  149. // we can easily debug with a small window of desktop browser. :-)
  150. isMiniScreen() {
  151. // OLD WINDOW WIDTH DETECTION:
  152. this.windowResizeDep.depend();
  153. return $(window).width() <= 800;
  154. // NEW TOUCH DEVICE DETECTION:
  155. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent
  156. /*
  157. var hasTouchScreen = false;
  158. if ("maxTouchPoints" in navigator) {
  159. hasTouchScreen = navigator.maxTouchPoints > 0;
  160. } else if ("msMaxTouchPoints" in navigator) {
  161. hasTouchScreen = navigator.msMaxTouchPoints > 0;
  162. } else {
  163. var mQ = window.matchMedia && matchMedia("(pointer:coarse)");
  164. if (mQ && mQ.media === "(pointer:coarse)") {
  165. hasTouchScreen = !!mQ.matches;
  166. } else if ('orientation' in window) {
  167. hasTouchScreen = true; // deprecated, but good fallback
  168. } else {
  169. // Only as a last resort, fall back to user agent sniffing
  170. var UA = navigator.userAgent;
  171. hasTouchScreen = (
  172. /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
  173. /\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
  174. );
  175. }
  176. }
  177. */
  178. //if (hasTouchScreen)
  179. // document.getElementById("exampleButton").style.padding="1em";
  180. //return false;
  181. },
  182. calculateIndexData(prevData, nextData, nItems = 1) {
  183. let base, increment;
  184. // If we drop the card to an empty column
  185. if (!prevData && !nextData) {
  186. base = 0;
  187. increment = 1;
  188. // If we drop the card in the first position
  189. } else if (!prevData) {
  190. base = nextData.sort - 1;
  191. increment = -1;
  192. // If we drop the card in the last position
  193. } else if (!nextData) {
  194. base = prevData.sort + 1;
  195. increment = 1;
  196. }
  197. // In the general case take the average of the previous and next element
  198. // sort indexes.
  199. else {
  200. const prevSortIndex = prevData.sort;
  201. const nextSortIndex = nextData.sort;
  202. increment = (nextSortIndex - prevSortIndex) / (nItems + 1);
  203. base = prevSortIndex + increment;
  204. }
  205. // XXX Return a generator that yield values instead of a base with a
  206. // increment number.
  207. return {
  208. base,
  209. increment,
  210. };
  211. },
  212. // Determine the new sort index
  213. calculateIndex(prevCardDomElement, nextCardDomElement, nCards = 1) {
  214. let base, increment;
  215. // If we drop the card to an empty column
  216. if (!prevCardDomElement && !nextCardDomElement) {
  217. base = 0;
  218. increment = 1;
  219. // If we drop the card in the first position
  220. } else if (!prevCardDomElement) {
  221. base = Blaze.getData(nextCardDomElement).sort - 1;
  222. increment = -1;
  223. // If we drop the card in the last position
  224. } else if (!nextCardDomElement) {
  225. base = Blaze.getData(prevCardDomElement).sort + 1;
  226. increment = 1;
  227. }
  228. // In the general case take the average of the previous and next element
  229. // sort indexes.
  230. else {
  231. const prevSortIndex = Blaze.getData(prevCardDomElement).sort;
  232. const nextSortIndex = Blaze.getData(nextCardDomElement).sort;
  233. increment = (nextSortIndex - prevSortIndex) / (nCards + 1);
  234. base = prevSortIndex + increment;
  235. }
  236. // XXX Return a generator that yield values instead of a base with a
  237. // increment number.
  238. return {
  239. base,
  240. increment,
  241. };
  242. },
  243. // Detect touch device
  244. isTouchDevice() {
  245. const isTouchable = (() => {
  246. const prefixes = ' -webkit- -moz- -o- -ms- '.split(' ');
  247. const mq = function(query) {
  248. return window.matchMedia(query).matches;
  249. };
  250. if (
  251. 'ontouchstart' in window ||
  252. (window.DocumentTouch && document instanceof window.DocumentTouch)
  253. ) {
  254. return true;
  255. }
  256. // include the 'heartz' as a way to have a non matching MQ to help terminate the join
  257. // https://git.io/vznFH
  258. const query = [
  259. '(',
  260. prefixes.join('touch-enabled),('),
  261. 'heartz',
  262. ')',
  263. ].join('');
  264. return mq(query);
  265. })();
  266. Utils.isTouchDevice = () => isTouchable;
  267. return isTouchable;
  268. },
  269. calculateTouchDistance(touchA, touchB) {
  270. return Math.sqrt(
  271. Math.pow(touchA.screenX - touchB.screenX, 2) +
  272. Math.pow(touchA.screenY - touchB.screenY, 2),
  273. );
  274. },
  275. enableClickOnTouch(selector) {
  276. let touchStart = null;
  277. let lastTouch = null;
  278. $(document).on('touchstart', selector, function(e) {
  279. touchStart = e.originalEvent.touches[0];
  280. });
  281. $(document).on('touchmove', selector, function(e) {
  282. const touches = e.originalEvent.touches;
  283. lastTouch = touches[touches.length - 1];
  284. });
  285. $(document).on('touchend', selector, function(e) {
  286. if (
  287. touchStart &&
  288. lastTouch &&
  289. Utils.calculateTouchDistance(touchStart, lastTouch) <= 20
  290. ) {
  291. e.preventDefault();
  292. const clickEvent = document.createEvent('MouseEvents');
  293. clickEvent.initEvent('click', true, true);
  294. e.target.dispatchEvent(clickEvent);
  295. }
  296. });
  297. },
  298. manageCustomUI() {
  299. Meteor.call('getCustomUI', (err, data) => {
  300. if (err && err.error[0] === 'var-not-exist') {
  301. Session.set('customUI', false); // siteId || address server not defined
  302. }
  303. if (!err) {
  304. Utils.setCustomUI(data);
  305. }
  306. });
  307. },
  308. setCustomUI(data) {
  309. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  310. if (currentBoard) {
  311. DocHead.setTitle(`${currentBoard.title} - ${data.productName}`);
  312. } else {
  313. DocHead.setTitle(`${data.productName}`);
  314. }
  315. },
  316. setMatomo(data) {
  317. window._paq = window._paq || [];
  318. window._paq.push(['setDoNotTrack', data.doNotTrack]);
  319. if (data.withUserName) {
  320. window._paq.push(['setUserId', Meteor.user().username]);
  321. }
  322. window._paq.push(['trackPageView']);
  323. window._paq.push(['enableLinkTracking']);
  324. (function() {
  325. window._paq.push(['setTrackerUrl', `${data.address}piwik.php`]);
  326. window._paq.push(['setSiteId', data.siteId]);
  327. const script = document.createElement('script');
  328. Object.assign(script, {
  329. id: 'scriptMatomo',
  330. type: 'text/javascript',
  331. async: 'true',
  332. defer: 'true',
  333. src: `${data.address}piwik.js`,
  334. });
  335. const s = document.getElementsByTagName('script')[0];
  336. s.parentNode.insertBefore(script, s);
  337. })();
  338. Session.set('matomo', true);
  339. },
  340. manageMatomo() {
  341. const matomo = Session.get('matomo');
  342. if (matomo === undefined) {
  343. Meteor.call('getMatomoConf', (err, data) => {
  344. if (err && err.error[0] === 'var-not-exist') {
  345. Session.set('matomo', false); // siteId || address server not defined
  346. }
  347. if (!err) {
  348. Utils.setMatomo(data);
  349. }
  350. });
  351. } else if (matomo) {
  352. window._paq.push(['trackPageView']);
  353. }
  354. },
  355. getTriggerActionDesc(event, tempInstance) {
  356. const jqueryEl = tempInstance.$(event.currentTarget.parentNode);
  357. const triggerEls = jqueryEl.find('.trigger-content').children();
  358. let finalString = '';
  359. for (let i = 0; i < triggerEls.length; i++) {
  360. const element = tempInstance.$(triggerEls[i]);
  361. if (element.hasClass('trigger-text')) {
  362. finalString += element.text().toLowerCase();
  363. } else if (element.hasClass('user-details')) {
  364. let username = element.find('input').val();
  365. if (username === undefined || username === '') {
  366. username = '*';
  367. }
  368. finalString += `${element
  369. .find('.trigger-text')
  370. .text()
  371. .toLowerCase()} ${username}`;
  372. } else if (element.find('select').length > 0) {
  373. finalString += element
  374. .find('select option:selected')
  375. .text()
  376. .toLowerCase();
  377. } else if (element.find('input').length > 0) {
  378. let inputvalue = element.find('input').val();
  379. if (inputvalue === undefined || inputvalue === '') {
  380. inputvalue = '*';
  381. }
  382. finalString += inputvalue;
  383. }
  384. // Add space
  385. if (i !== length - 1) {
  386. finalString += ' ';
  387. }
  388. }
  389. return finalString;
  390. },
  391. };
  392. // A simple tracker dependency that we invalidate every time the window is
  393. // resized. This is used to reactively re-calculate the popup position in case
  394. // of a window resize. This is the equivalent of a "Signal" in some other
  395. // programming environments (eg, elm).
  396. $(window).on('resize', () => Utils.windowResizeDep.changed());