page.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /*
  2. * Based on github.com/visionmedia/page.js
  3. * Licensed under the MIT license
  4. * Copyright 2012 TJ Holowaychuk <tj@vision-media.ca>
  5. */
  6. let running = false;
  7. let currentState = null;
  8. const callbacks = [];
  9. this.page = function (value, fn) {
  10. if (typeof value === "function") {
  11. page("*", value);
  12. } else if (typeof fn === "function") {
  13. const route = new Route(value);
  14. callbacks.push(route.middleware(fn));
  15. } else if (typeof value === "string") {
  16. page.show(value, fn);
  17. } else {
  18. page.start(value);
  19. }
  20. };
  21. page.start = function (options) {
  22. if (options == null) {
  23. options = {};
  24. }
  25. if (!running) {
  26. running = true;
  27. addEventListener("popstate", onpopstate);
  28. addEventListener("click", onclick);
  29. page.replace(currentPath(), null, null, true);
  30. }
  31. };
  32. page.stop = function () {
  33. if (running) {
  34. running = false;
  35. removeEventListener("click", onclick);
  36. removeEventListener("popstate", onpopstate);
  37. }
  38. };
  39. page.show = function (path, state) {
  40. let res;
  41. if (path === currentState?.path) {
  42. return;
  43. }
  44. const context = new Context(path, state);
  45. const previousState = currentState;
  46. currentState = context.state;
  47. if ((res = page.dispatch(context))) {
  48. currentState = previousState;
  49. location.assign(res);
  50. } else {
  51. context.pushState();
  52. updateCanonicalLink();
  53. track();
  54. }
  55. return context;
  56. };
  57. page.replace = function (path, state, skipDispatch, init) {
  58. let result;
  59. let context = new Context(path, state || currentState);
  60. context.init = init;
  61. currentState = context.state;
  62. if (!skipDispatch) {
  63. result = page.dispatch(context);
  64. }
  65. if (result) {
  66. context = new Context(result);
  67. context.init = init;
  68. currentState = context.state;
  69. page.dispatch(context);
  70. }
  71. context.replaceState();
  72. updateCanonicalLink();
  73. if (!skipDispatch) {
  74. track();
  75. }
  76. return context;
  77. };
  78. page.dispatch = function (context) {
  79. let i = 0;
  80. var next = function () {
  81. let fn, res;
  82. if ((fn = callbacks[i++])) {
  83. res = fn(context, next);
  84. }
  85. return res;
  86. };
  87. return next();
  88. };
  89. page.canGoBack = () => !Context.isIntialState(currentState);
  90. page.canGoForward = () => !Context.isLastState(currentState);
  91. const currentPath = () => location.pathname + location.search + location.hash;
  92. class Context {
  93. static isIntialState(state) {
  94. return state.id === 0;
  95. }
  96. static isLastState(state) {
  97. return state.id === this.stateId - 1;
  98. }
  99. static isInitialPopState(state) {
  100. return state.path === this.initialPath && this.stateId === 1;
  101. }
  102. static isSameSession(state) {
  103. return state.sessionId === this.sessionId;
  104. }
  105. constructor(path, state) {
  106. this.initialPath = currentPath();
  107. this.sessionId = Date.now();
  108. this.stateId = 0;
  109. if (path == null) {
  110. path = "/";
  111. }
  112. this.path = path;
  113. if (state == null) {
  114. state = {};
  115. }
  116. this.state = state;
  117. this.pathname = this.path.replace(
  118. /(?:\?([^#]*))?(?:#(.*))?$/,
  119. (_, query, hash) => {
  120. this.query = query;
  121. this.hash = hash;
  122. return "";
  123. },
  124. );
  125. if (this.state.id == null) {
  126. this.state.id = this.constructor.stateId++;
  127. }
  128. if (this.state.sessionId == null) {
  129. this.state.sessionId = this.constructor.sessionId;
  130. }
  131. this.state.path = this.path;
  132. }
  133. pushState() {
  134. history.pushState(this.state, "", this.path);
  135. }
  136. replaceState() {
  137. try {
  138. history.replaceState(this.state, "", this.path);
  139. } catch (error) {} // NS_ERROR_FAILURE in Firefox
  140. }
  141. }
  142. class Route {
  143. constructor(path, options) {
  144. this.path = path;
  145. if (options == null) {
  146. options = {};
  147. }
  148. this.keys = [];
  149. this.regexp = pathToRegexp(this.path, this.keys);
  150. }
  151. middleware(fn) {
  152. return (context, next) => {
  153. let params;
  154. if (this.match(context.pathname, (params = []))) {
  155. context.params = params;
  156. return fn(context, next);
  157. } else {
  158. return next();
  159. }
  160. };
  161. }
  162. match(path, params) {
  163. let matchData;
  164. if (!(matchData = this.regexp.exec(path))) {
  165. return;
  166. }
  167. const iterable = matchData.slice(1);
  168. for (let i = 0; i < iterable.length; i++) {
  169. var key;
  170. var value = iterable[i];
  171. if (typeof value === "string") {
  172. value = decodeURIComponent(value);
  173. }
  174. if ((key = this.keys[i])) {
  175. params[key.name] = value;
  176. } else {
  177. params.push(value);
  178. }
  179. }
  180. return true;
  181. }
  182. }
  183. var pathToRegexp = function (path, keys) {
  184. if (path instanceof RegExp) {
  185. return path;
  186. }
  187. if (path instanceof Array) {
  188. path = `(${path.join("|")})`;
  189. }
  190. path = path
  191. .replace(/\/\(/g, "(?:/")
  192. .replace(
  193. /(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g,
  194. function (_, slash, format, key, capture, optional) {
  195. if (slash == null) {
  196. slash = "";
  197. }
  198. if (format == null) {
  199. format = "";
  200. }
  201. keys.push({ name: key, optional: !!optional });
  202. let str = optional ? "" : slash;
  203. str += "(?:";
  204. if (optional) {
  205. str += slash;
  206. }
  207. str += format;
  208. str += capture || (format ? "([^/.]+?)" : "([^/]+?)");
  209. str += ")";
  210. if (optional) {
  211. str += optional;
  212. }
  213. return str;
  214. },
  215. )
  216. .replace(/([\/.])/g, "\\$1")
  217. .replace(/\*/g, "(.*)");
  218. return new RegExp(`^${path}$`);
  219. };
  220. var onpopstate = function (event) {
  221. if (!event.state || Context.isInitialPopState(event.state)) {
  222. return;
  223. }
  224. if (Context.isSameSession(event.state)) {
  225. page.replace(event.state.path, event.state);
  226. } else {
  227. location.reload();
  228. }
  229. };
  230. var onclick = function (event) {
  231. try {
  232. if (
  233. event.which !== 1 ||
  234. event.metaKey ||
  235. event.ctrlKey ||
  236. event.shiftKey ||
  237. event.defaultPrevented
  238. ) {
  239. return;
  240. }
  241. } catch (error) {
  242. return;
  243. }
  244. let link = $.eventTarget(event);
  245. while (link && link.tagName !== "A") {
  246. link = link.parentNode;
  247. }
  248. if (link && !link.target && isSameOrigin(link.href)) {
  249. event.preventDefault();
  250. let path = link.pathname + link.search + link.hash;
  251. path = path.replace(/^\/\/+/, "/"); // IE11 bug
  252. page.show(path);
  253. }
  254. };
  255. var isSameOrigin = (url) =>
  256. url.startsWith(`${location.protocol}//${location.hostname}`);
  257. var updateCanonicalLink = function () {
  258. if (!this.canonicalLink) {
  259. this.canonicalLink = document.head.querySelector('link[rel="canonical"]');
  260. }
  261. return this.canonicalLink.setAttribute(
  262. "href",
  263. `https://${location.host}${location.pathname}`,
  264. );
  265. };
  266. const trackers = [];
  267. page.track = function (fn) {
  268. trackers.push(fn);
  269. };
  270. var track = function () {
  271. if (app.config.env !== "production") {
  272. return;
  273. }
  274. if (navigator.doNotTrack === "1") {
  275. return;
  276. }
  277. if (navigator.globalPrivacyControl) {
  278. return;
  279. }
  280. const consentGiven = Cookies.get("analyticsConsent");
  281. const consentAsked = Cookies.get("analyticsConsentAsked");
  282. if (consentGiven === "1") {
  283. for (var tracker of trackers) {
  284. tracker.call();
  285. }
  286. } else if (consentGiven === undefined && consentAsked === undefined) {
  287. // Only ask for consent once per browser session
  288. Cookies.set("analyticsConsentAsked", "1");
  289. new app.views.Notif("AnalyticsConsent", { autoHide: null });
  290. }
  291. };
  292. this.resetAnalytics = function () {
  293. for (var cookie of document.cookie.split(/;\s?/)) {
  294. var name = cookie.split("=")[0];
  295. if (name[0] === "_" && name[1] !== "_") {
  296. Cookies.expire(name);
  297. }
  298. }
  299. };