url-serializer.js 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. (function (factory) {
  2. if (typeof module === "object" && typeof module.exports === "object") {
  3. var v = factory(require, exports);
  4. if (v !== undefined) module.exports = v;
  5. }
  6. else if (typeof define === "function" && define.amd) {
  7. define(["require", "exports", "@angular/core", "../util/util"], factory);
  8. }
  9. })(function (require, exports) {
  10. "use strict";
  11. Object.defineProperty(exports, "__esModule", { value: true });
  12. var core_1 = require("@angular/core");
  13. var util_1 = require("../util/util");
  14. /**
  15. * @hidden
  16. */
  17. var UrlSerializer = (function () {
  18. function UrlSerializer(_app, config) {
  19. this._app = _app;
  20. if (config && util_1.isArray(config.links)) {
  21. this.links = exports.normalizeLinks(config.links);
  22. }
  23. else {
  24. this.links = [];
  25. }
  26. }
  27. /**
  28. * Parse the URL into a Path, which is made up of multiple NavSegments.
  29. * Match which components belong to each segment.
  30. */
  31. UrlSerializer.prototype.parse = function (browserUrl) {
  32. if (browserUrl.charAt(0) === '/') {
  33. browserUrl = browserUrl.substr(1);
  34. }
  35. // trim off data after ? and #
  36. browserUrl = browserUrl.split('?')[0].split('#')[0];
  37. return convertUrlToSegments(this._app, browserUrl, this.links);
  38. };
  39. UrlSerializer.prototype.createSegmentFromName = function (navContainer, nameOrComponent) {
  40. var configLink = this.getLinkFromName(nameOrComponent);
  41. if (configLink) {
  42. return this._createSegment(this._app, navContainer, configLink, null);
  43. }
  44. return null;
  45. };
  46. UrlSerializer.prototype.getLinkFromName = function (nameOrComponent) {
  47. return this.links.find(function (link) {
  48. return (link.component === nameOrComponent) ||
  49. (link.name === nameOrComponent);
  50. });
  51. };
  52. /**
  53. * Serialize a path, which is made up of multiple NavSegments,
  54. * into a URL string. Turn each segment into a string and concat them to a URL.
  55. */
  56. UrlSerializer.prototype.serialize = function (segments) {
  57. if (!segments || !segments.length) {
  58. return '/';
  59. }
  60. var sections = segments.map(function (segment) {
  61. if (segment.type === 'tabs') {
  62. if (segment.requiresExplicitNavPrefix) {
  63. return "/" + segment.type + "/" + segment.navId + "/" + segment.secondaryId + "/" + segment.id;
  64. }
  65. return "/" + segment.secondaryId + "/" + segment.id;
  66. }
  67. // it's a nav
  68. if (segment.requiresExplicitNavPrefix) {
  69. return "/" + segment.type + "/" + segment.navId + "/" + segment.id;
  70. }
  71. return "/" + segment.id;
  72. });
  73. return sections.join('');
  74. };
  75. /**
  76. * Serializes a component and its data into a NavSegment.
  77. */
  78. UrlSerializer.prototype.serializeComponent = function (navContainer, component, data) {
  79. if (component) {
  80. var link = exports.findLinkByComponentData(this.links, component, data);
  81. if (link) {
  82. return this._createSegment(this._app, navContainer, link, data);
  83. }
  84. }
  85. return null;
  86. };
  87. /**
  88. * @internal
  89. */
  90. UrlSerializer.prototype._createSegment = function (app, navContainer, configLink, data) {
  91. var urlParts = configLink.segmentParts;
  92. if (util_1.isPresent(data)) {
  93. // create a copy of the original parts in the link config
  94. urlParts = urlParts.slice();
  95. // loop through all the data and convert it to a string
  96. var keys = Object.keys(data);
  97. var keysLength = keys.length;
  98. if (keysLength) {
  99. for (var i = 0; i < urlParts.length; i++) {
  100. if (urlParts[i].charAt(0) === ':') {
  101. for (var j = 0; j < keysLength; j++) {
  102. if (urlParts[i] === ":" + keys[j]) {
  103. // this data goes into the URL part (between slashes)
  104. urlParts[i] = encodeURIComponent(data[keys[j]]);
  105. break;
  106. }
  107. }
  108. }
  109. }
  110. }
  111. }
  112. var requiresExplicitPrefix = true;
  113. if (navContainer.parent) {
  114. requiresExplicitPrefix = navContainer.parent && navContainer.parent.getAllChildNavs().length > 1;
  115. }
  116. else {
  117. // if it's a root nav, and there are multiple root navs, we need an explicit prefix
  118. requiresExplicitPrefix = app.getRootNavById(navContainer.id) && app.getRootNavs().length > 1;
  119. }
  120. return {
  121. id: urlParts.join('/'),
  122. name: configLink.name,
  123. component: configLink.component,
  124. loadChildren: configLink.loadChildren,
  125. data: data,
  126. defaultHistory: configLink.defaultHistory,
  127. navId: navContainer.name || navContainer.id,
  128. type: navContainer.getType(),
  129. secondaryId: navContainer.getSecondaryIdentifier(),
  130. requiresExplicitNavPrefix: requiresExplicitPrefix
  131. };
  132. };
  133. return UrlSerializer;
  134. }());
  135. exports.UrlSerializer = UrlSerializer;
  136. function formatUrlPart(name) {
  137. name = name.replace(URL_REPLACE_REG, '-');
  138. name = name.charAt(0).toLowerCase() + name.substring(1).replace(/[A-Z]/g, function (match) {
  139. return '-' + match.toLowerCase();
  140. });
  141. while (name.indexOf('--') > -1) {
  142. name = name.replace('--', '-');
  143. }
  144. if (name.charAt(0) === '-') {
  145. name = name.substring(1);
  146. }
  147. if (name.substring(name.length - 1) === '-') {
  148. name = name.substring(0, name.length - 1);
  149. }
  150. return encodeURIComponent(name);
  151. }
  152. exports.formatUrlPart = formatUrlPart;
  153. exports.isPartMatch = function (urlPart, configLinkPart) {
  154. if (util_1.isPresent(urlPart) && util_1.isPresent(configLinkPart)) {
  155. if (configLinkPart.charAt(0) === ':') {
  156. return true;
  157. }
  158. return (urlPart === configLinkPart);
  159. }
  160. return false;
  161. };
  162. exports.createMatchedData = function (matchedUrlParts, link) {
  163. var data = null;
  164. for (var i = 0; i < link.segmentPartsLen; i++) {
  165. if (link.segmentParts[i].charAt(0) === ':') {
  166. data = data || {};
  167. data[link.segmentParts[i].substring(1)] = decodeURIComponent(matchedUrlParts[i]);
  168. }
  169. }
  170. return data;
  171. };
  172. exports.findLinkByComponentData = function (links, component, instanceData) {
  173. var foundLink = null;
  174. var foundLinkDataMatches = -1;
  175. for (var i = 0; i < links.length; i++) {
  176. var link = links[i];
  177. if (link.component === component) {
  178. // ok, so the component matched, but multiple links can point
  179. // to the same component, so let's make sure this is the right link
  180. var dataMatches = 0;
  181. if (instanceData) {
  182. var instanceDataKeys = Object.keys(instanceData);
  183. // this link has data
  184. for (var j = 0; j < instanceDataKeys.length; j++) {
  185. if (util_1.isPresent(link.dataKeys[instanceDataKeys[j]])) {
  186. dataMatches++;
  187. }
  188. }
  189. }
  190. else if (link.dataLen) {
  191. // this component does not have data but the link does
  192. continue;
  193. }
  194. if (dataMatches >= foundLinkDataMatches) {
  195. foundLink = link;
  196. foundLinkDataMatches = dataMatches;
  197. }
  198. }
  199. }
  200. return foundLink;
  201. };
  202. exports.normalizeLinks = function (links) {
  203. for (var i = 0, ilen = links.length; i < ilen; i++) {
  204. var link = links[i];
  205. if (util_1.isBlank(link.segment)) {
  206. link.segment = link.name;
  207. }
  208. link.dataKeys = {};
  209. link.segmentParts = link.segment.split('/');
  210. link.segmentPartsLen = link.segmentParts.length;
  211. // used for sorting
  212. link.staticLen = link.dataLen = 0;
  213. var stillCountingStatic = true;
  214. for (var j = 0; j < link.segmentPartsLen; j++) {
  215. if (link.segmentParts[j].charAt(0) === ':') {
  216. link.dataLen++;
  217. stillCountingStatic = false;
  218. link.dataKeys[link.segmentParts[j].substring(1)] = true;
  219. }
  220. else if (stillCountingStatic) {
  221. link.staticLen++;
  222. }
  223. }
  224. }
  225. // sort by the number of parts, with the links
  226. // with the most parts first
  227. return links.sort(sortConfigLinks);
  228. };
  229. function sortConfigLinks(a, b) {
  230. // sort by the number of parts
  231. if (a.segmentPartsLen > b.segmentPartsLen) {
  232. return -1;
  233. }
  234. if (a.segmentPartsLen < b.segmentPartsLen) {
  235. return 1;
  236. }
  237. // sort by the number of static parts in a row
  238. if (a.staticLen > b.staticLen) {
  239. return -1;
  240. }
  241. if (a.staticLen < b.staticLen) {
  242. return 1;
  243. }
  244. // sort by the number of total data parts
  245. if (a.dataLen < b.dataLen) {
  246. return -1;
  247. }
  248. if (a.dataLen > b.dataLen) {
  249. return 1;
  250. }
  251. return 0;
  252. }
  253. var URL_REPLACE_REG = /\s+|\?|\!|\$|\,|\.|\+|\"|\'|\*|\^|\||\/|\\|\[|\]|#|%|`|>|<|;|:|@|&|=/g;
  254. /**
  255. * @hidden
  256. */
  257. exports.DeepLinkConfigToken = new core_1.InjectionToken('USERLINKS');
  258. function setupUrlSerializer(app, userDeepLinkConfig) {
  259. return new UrlSerializer(app, userDeepLinkConfig);
  260. }
  261. exports.setupUrlSerializer = setupUrlSerializer;
  262. function navGroupStringtoObjects(navGroupStrings) {
  263. // each string has a known format-ish, convert it to it
  264. return navGroupStrings.map(function (navGroupString) {
  265. var sections = navGroupString.split('/');
  266. if (sections[0] === 'nav') {
  267. return {
  268. type: 'nav',
  269. navId: sections[1],
  270. niceId: sections[1],
  271. secondaryId: null,
  272. segmentPieces: sections.splice(2)
  273. };
  274. }
  275. else if (sections[0] === 'tabs') {
  276. return {
  277. type: 'tabs',
  278. navId: sections[1],
  279. niceId: sections[1],
  280. secondaryId: sections[2],
  281. segmentPieces: sections.splice(3)
  282. };
  283. }
  284. return {
  285. type: null,
  286. navId: null,
  287. niceId: null,
  288. secondaryId: null,
  289. segmentPieces: sections
  290. };
  291. });
  292. }
  293. exports.navGroupStringtoObjects = navGroupStringtoObjects;
  294. function urlToNavGroupStrings(url) {
  295. var tokens = url.split('/');
  296. var keywordIndexes = [];
  297. for (var i = 0; i < tokens.length; i++) {
  298. if (i !== 0 && (tokens[i] === 'nav' || tokens[i] === 'tabs')) {
  299. keywordIndexes.push(i);
  300. }
  301. }
  302. // append the last index + 1 to the list no matter what
  303. keywordIndexes.push(tokens.length);
  304. var groupings = [];
  305. var activeKeywordIndex = 0;
  306. var tmpArray = [];
  307. for (var i = 0; i < tokens.length; i++) {
  308. if (i >= keywordIndexes[activeKeywordIndex]) {
  309. groupings.push(tmpArray.join('/'));
  310. tmpArray = [];
  311. activeKeywordIndex++;
  312. }
  313. tmpArray.push(tokens[i]);
  314. }
  315. // okay, after the loop we've gotta push one more time just to be safe
  316. groupings.push(tmpArray.join('/'));
  317. return groupings;
  318. }
  319. exports.urlToNavGroupStrings = urlToNavGroupStrings;
  320. function convertUrlToSegments(app, url, navLinks) {
  321. var pairs = convertUrlToDehydratedSegments(url, navLinks);
  322. return hydrateSegmentsWithNav(app, pairs);
  323. }
  324. exports.convertUrlToSegments = convertUrlToSegments;
  325. function convertUrlToDehydratedSegments(url, navLinks) {
  326. var navGroupStrings = urlToNavGroupStrings(url);
  327. var navGroups = navGroupStringtoObjects(navGroupStrings);
  328. return getSegmentsFromNavGroups(navGroups, navLinks);
  329. }
  330. exports.convertUrlToDehydratedSegments = convertUrlToDehydratedSegments;
  331. function hydrateSegmentsWithNav(app, dehydratedSegmentPairs) {
  332. var segments = [];
  333. for (var i = 0; i < dehydratedSegmentPairs.length; i++) {
  334. var navs = getNavFromNavGroup(dehydratedSegmentPairs[i].navGroup, app);
  335. // okay, cool, let's walk through the segments and hydrate them
  336. for (var _i = 0, _a = dehydratedSegmentPairs[i].segments; _i < _a.length; _i++) {
  337. var dehydratedSegment = _a[_i];
  338. if (navs.length === 1) {
  339. segments.push(hydrateSegment(dehydratedSegment, navs[0]));
  340. navs = navs[0].getActiveChildNavs();
  341. }
  342. else if (navs.length > 1) {
  343. // this is almost certainly an async race condition bug in userland
  344. // if you're in this state, it would be nice to just bail here
  345. // but alas we must perservere and handle the issue
  346. // the simple solution is to just use the last child
  347. // because that is probably what the user wants anyway
  348. // remember, do not harm, even if it makes our shizzle ugly
  349. segments.push(hydrateSegment(dehydratedSegment, navs[navs.length - 1]));
  350. navs = navs[navs.length - 1].getActiveChildNavs();
  351. }
  352. else {
  353. break;
  354. }
  355. }
  356. }
  357. return segments;
  358. }
  359. exports.hydrateSegmentsWithNav = hydrateSegmentsWithNav;
  360. function getNavFromNavGroup(navGroup, app) {
  361. if (navGroup.navId) {
  362. var rootNav = app.getNavByIdOrName(navGroup.navId);
  363. if (rootNav) {
  364. return [rootNav];
  365. }
  366. return [];
  367. }
  368. // we don't know what nav to use, so just use the root nav.
  369. // if there is more than one root nav, throw an error
  370. return app.getRootNavs();
  371. }
  372. exports.getNavFromNavGroup = getNavFromNavGroup;
  373. /*
  374. * Let's face the facts: Getting a dehydrated segment from the url is really hard
  375. * because we need to do a ton of crazy looping
  376. * the are chunks of a url that are totally irrelevant at this stage, such as the secondary identifier
  377. * stating which tab is selected, etc.
  378. * but is necessary.
  379. * We look at segment pieces in reverse order to try to build segments
  380. * as in, if you had an array like this
  381. * ['my', 'super', 'cool', 'url']
  382. * we want to look at the pieces in reverse order:
  383. * url
  384. * cool url
  385. * super cool url
  386. * my super cool url
  387. * cool
  388. * super cool
  389. * my super cool
  390. * super
  391. * my super
  392. * my
  393. **/
  394. function getSegmentsFromNavGroups(navGroups, navLinks) {
  395. var pairs = [];
  396. var usedNavLinks = new Set();
  397. for (var _i = 0, navGroups_1 = navGroups; _i < navGroups_1.length; _i++) {
  398. var navGroup = navGroups_1[_i];
  399. var segments = [];
  400. var segmentPieces = navGroup.segmentPieces.concat([]);
  401. for (var i = segmentPieces.length; i >= 0; i--) {
  402. var created = false;
  403. for (var j = 0; j < i; j++) {
  404. var startIndex = i - j - 1;
  405. var endIndex = i;
  406. var subsetOfUrl = segmentPieces.slice(startIndex, endIndex);
  407. for (var _a = 0, navLinks_1 = navLinks; _a < navLinks_1.length; _a++) {
  408. var navLink = navLinks_1[_a];
  409. if (!usedNavLinks.has(navLink.name)) {
  410. var segment = getSegmentsFromUrlPieces(subsetOfUrl, navLink);
  411. if (segment) {
  412. i = startIndex + 1;
  413. usedNavLinks.add(navLink.name);
  414. created = true;
  415. // sweet, we found a segment
  416. segments.push(segment);
  417. // now we want to null out the url subsection in the segmentPieces
  418. for (var k = startIndex; k < endIndex; k++) {
  419. segmentPieces[k] = null;
  420. }
  421. break;
  422. }
  423. }
  424. }
  425. if (created) {
  426. break;
  427. }
  428. }
  429. if (!created && segmentPieces[i - 1]) {
  430. // this is very likely a tab's secondary identifier
  431. segments.push({
  432. id: null,
  433. name: null,
  434. secondaryId: segmentPieces[i - 1],
  435. component: null,
  436. loadChildren: null,
  437. data: null,
  438. defaultHistory: null
  439. });
  440. }
  441. }
  442. // since we're getting segments in from right-to-left in the url, reverse them
  443. // so they're in the correct order. Also filter out and bogus segments
  444. var orderedSegments = segments.reverse();
  445. // okay, this is the lazy persons approach here.
  446. // so here's the deal! Right now if section of the url is not a part of a segment
  447. // it is almost certainly the secondaryId for a tabs component
  448. // basically, knowing the segment for the `tab` itself is good, but we also need to know
  449. // which tab is selected, so we have an identifer in the url that is associated with the tabs component
  450. // telling us which tab is selected. With that in mind, we are going to go through and find the segments with only secondary identifiers,
  451. // and simply add the secondaryId to the next segment, and then remove the empty segment from the list
  452. for (var i = 0; i < orderedSegments.length; i++) {
  453. if (orderedSegments[i].secondaryId && !orderedSegments[i].id && ((i + 1) <= orderedSegments.length - 1)) {
  454. orderedSegments[i + 1].secondaryId = orderedSegments[i].secondaryId;
  455. orderedSegments[i] = null;
  456. }
  457. }
  458. var cleanedSegments = segments.filter(function (segment) { return !!segment; });
  459. // if the nav group has a secondary id, make sure the first segment also has it set
  460. if (navGroup.secondaryId && segments.length) {
  461. cleanedSegments[0].secondaryId = navGroup.secondaryId;
  462. }
  463. pairs.push({
  464. navGroup: navGroup,
  465. segments: cleanedSegments
  466. });
  467. }
  468. return pairs;
  469. }
  470. exports.getSegmentsFromNavGroups = getSegmentsFromNavGroups;
  471. function getSegmentsFromUrlPieces(urlSections, navLink) {
  472. if (navLink.segmentPartsLen !== urlSections.length) {
  473. return null;
  474. }
  475. for (var i = 0; i < urlSections.length; i++) {
  476. if (!exports.isPartMatch(urlSections[i], navLink.segmentParts[i])) {
  477. // just return an empty array if the part doesn't match
  478. return null;
  479. }
  480. }
  481. return {
  482. id: urlSections.join('/'),
  483. name: navLink.name,
  484. component: navLink.component,
  485. loadChildren: navLink.loadChildren,
  486. data: exports.createMatchedData(urlSections, navLink),
  487. defaultHistory: navLink.defaultHistory
  488. };
  489. }
  490. exports.getSegmentsFromUrlPieces = getSegmentsFromUrlPieces;
  491. function hydrateSegment(segment, nav) {
  492. var hydratedSegment = Object.assign({}, segment);
  493. hydratedSegment.type = nav.getType();
  494. hydratedSegment.navId = nav.name || nav.id;
  495. // secondaryId is set on an empty dehydrated segment in the case of tabs to identify which tab is selected
  496. hydratedSegment.secondaryId = segment.secondaryId;
  497. return hydratedSegment;
  498. }
  499. exports.hydrateSegment = hydrateSegment;
  500. function getNonHydratedSegmentIfLinkAndUrlMatch(urlChunks, navLink) {
  501. var allSegmentsMatch = true;
  502. for (var i = 0; i < urlChunks.length; i++) {
  503. if (!exports.isPartMatch(urlChunks[i], navLink.segmentParts[i])) {
  504. allSegmentsMatch = false;
  505. break;
  506. }
  507. }
  508. if (allSegmentsMatch) {
  509. return {
  510. id: navLink.segmentParts.join('/'),
  511. name: navLink.name,
  512. component: navLink.component,
  513. loadChildren: navLink.loadChildren,
  514. data: exports.createMatchedData(urlChunks, navLink),
  515. defaultHistory: navLink.defaultHistory
  516. };
  517. }
  518. return null;
  519. }
  520. exports.getNonHydratedSegmentIfLinkAndUrlMatch = getNonHydratedSegmentIfLinkAndUrlMatch;
  521. });
  522. //# sourceMappingURL=url-serializer.js.map