UNPKG

fractal-core

Version:

A minimalist and well crafted app, content or component is our conviction

87 lines 3.31 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.routeHandler = (root, mode = 'history', locationObj) => mod => { let state = { parts: undefined, pathname: '', path: [], query: '', queryObj: {}, }; function checkAppChanges(parts, isInit) { return __awaiter(this, void 0, void 0, function* () { // build actual app route let pathname = '', path = []; for (let i = 0, part; part = parts[i]; i++) { pathname += (pathname ? '/' : '') + part[1]; path.push([part[0], part[1]]); } state.pathname = root + pathname; state.path = path; if (isInit) { yield checkUrlChanges(); } else { if (mode === 'history') { history.pushState(null, null, state.pathname); } else { locationObj.href = locationObj.href.replace(/#(.*)$/, '') + '#' + state.pathname; } } }); } function checkUrlChanges() { return __awaiter(this, void 0, void 0, function* () { let pathname; if (mode === 'history') { pathname = locationObj.pathname; } else { pathname = locationObj.hash.substr(1); } if (pathname !== state.pathname) { let parts = pathname.substr(1).split('/'); let changed = false; for (let i = 0, pathPart, part; pathPart = state.path[i]; i++) { part = parts[i]; if (part !== pathPart[1] && !changed) { changed = true; yield mod.dispatchEv(part, [pathPart[0], 'onRouteActive', [part]]); } else { if (changed) { yield mod.dispatchEv(part, [pathPart[0], 'onRouteInactive']); } } } } }); } if (!locationObj) { locationObj = window.location; } if (typeof window !== undefined) { setInterval(() => { if (!state.parts) return; }, 50); } return { state, handle: (id, parts) => __awaiter(this, void 0, void 0, function* () { yield checkAppChanges(parts, !state.parts); state.parts = parts; }), destroy: () => __awaiter(this, void 0, void 0, function* () { }), }; }; //# sourceMappingURL=route.js.map