utils.js 13 KB

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