utils.js 12 KB

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