router.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130
  1. /**
  2. * Durandal 2.1.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved.
  3. * Available via the MIT license.
  4. * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
  5. */
  6. /**
  7. * Connects the history module's url and history tracking support to Durandal's activation and composition engine allowing you to easily build navigation-style applications.
  8. * @module router
  9. * @requires system
  10. * @requires app
  11. * @requires activator
  12. * @requires events
  13. * @requires composition
  14. * @requires history
  15. * @requires knockout
  16. * @requires jquery
  17. */
  18. define(['durandal/system', 'durandal/app', 'durandal/activator', 'durandal/events', 'durandal/composition', 'plugins/history', 'knockout', 'jquery'], function(system, app, activator, events, composition, history, ko, $) {
  19. var optionalParam = /\((.*?)\)/g;
  20. var namedParam = /(\(\?)?:\w+/g;
  21. var splatParam = /\*\w+/g;
  22. var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
  23. var startDeferred, rootRouter;
  24. var trailingSlash = /\/$/;
  25. var routesAreCaseSensitive = false;
  26. var lastUrl = '/', lastTryUrl = '/';
  27. function routeStringToRegExp(routeString) {
  28. routeString = routeString.replace(escapeRegExp, '\\$&')
  29. .replace(optionalParam, '(?:$1)?')
  30. .replace(namedParam, function(match, optional) {
  31. return optional ? match : '([^\/]+)';
  32. })
  33. .replace(splatParam, '(.*?)');
  34. return new RegExp('^' + routeString + '$', routesAreCaseSensitive ? undefined : 'i');
  35. }
  36. function stripParametersFromRoute(route) {
  37. var colonIndex = route.indexOf(':');
  38. var length = colonIndex > 0 ? colonIndex - 1 : route.length;
  39. return route.substring(0, length);
  40. }
  41. function endsWith(str, suffix) {
  42. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  43. }
  44. function compareArrays(first, second) {
  45. if (!first || !second){
  46. return false;
  47. }
  48. if (first.length != second.length) {
  49. return false;
  50. }
  51. for (var i = 0, len = first.length; i < len; i++) {
  52. if (first[i] != second[i]) {
  53. return false;
  54. }
  55. }
  56. return true;
  57. }
  58. function reconstructUrl(instruction){
  59. if(!instruction.queryString){
  60. return instruction.fragment;
  61. }
  62. return instruction.fragment + '?' + instruction.queryString;
  63. }
  64. /**
  65. * @class Router
  66. * @uses Events
  67. */
  68. /**
  69. * Triggered when the navigation logic has completed.
  70. * @event router:navigation:complete
  71. * @param {object} instance The activated instance.
  72. * @param {object} instruction The routing instruction.
  73. * @param {Router} router The router.
  74. */
  75. /**
  76. * Triggered when the navigation has been cancelled.
  77. * @event router:navigation:cancelled
  78. * @param {object} instance The activated instance.
  79. * @param {object} instruction The routing instruction.
  80. * @param {Router} router The router.
  81. */
  82. /**
  83. * Triggered when navigation begins.
  84. * @event router:navigation:processing
  85. * @param {object} instruction The routing instruction.
  86. * @param {Router} router The router.
  87. */
  88. /**
  89. * Triggered right before a route is activated.
  90. * @event router:route:activating
  91. * @param {object} instance The activated instance.
  92. * @param {object} instruction The routing instruction.
  93. * @param {Router} router The router.
  94. */
  95. /**
  96. * Triggered right before a route is configured.
  97. * @event router:route:before-config
  98. * @param {object} config The route config.
  99. * @param {Router} router The router.
  100. */
  101. /**
  102. * Triggered just after a route is configured.
  103. * @event router:route:after-config
  104. * @param {object} config The route config.
  105. * @param {Router} router The router.
  106. */
  107. /**
  108. * Triggered when the view for the activated instance is attached.
  109. * @event router:navigation:attached
  110. * @param {object} instance The activated instance.
  111. * @param {object} instruction The routing instruction.
  112. * @param {Router} router The router.
  113. */
  114. /**
  115. * Triggered when the composition that the activated instance participates in is complete.
  116. * @event router:navigation:composition-complete
  117. * @param {object} instance The activated instance.
  118. * @param {object} instruction The routing instruction.
  119. * @param {Router} router The router.
  120. */
  121. /**
  122. * Triggered when the router does not find a matching route.
  123. * @event router:route:not-found
  124. * @param {string} fragment The url fragment.
  125. * @param {Router} router The router.
  126. */
  127. var createRouter = function() {
  128. var queue = [],
  129. isProcessing = ko.observable(false),
  130. currentActivation,
  131. currentInstruction,
  132. activeItem = activator.create();
  133. var router = {
  134. /**
  135. * The route handlers that are registered. Each handler consists of a `routePattern` and a `callback`.
  136. * @property {object[]} handlers
  137. */
  138. handlers: [],
  139. /**
  140. * The route configs that are registered.
  141. * @property {object[]} routes
  142. */
  143. routes: [],
  144. /**
  145. * The route configurations that have been designated as displayable in a nav ui (nav:true).
  146. * @property {KnockoutObservableArray} navigationModel
  147. */
  148. navigationModel: ko.observableArray([]),
  149. /**
  150. * The active item/screen based on the current navigation state.
  151. * @property {Activator} activeItem
  152. */
  153. activeItem: activeItem,
  154. /**
  155. * Indicates that the router (or a child router) is currently in the process of navigating.
  156. * @property {KnockoutComputed} isNavigating
  157. */
  158. isNavigating: ko.computed(function() {
  159. var current = activeItem();
  160. var processing = isProcessing();
  161. var currentRouterIsProcesing = current
  162. && current.router
  163. && current.router != router
  164. && current.router.isNavigating() ? true : false;
  165. return processing || currentRouterIsProcesing;
  166. }),
  167. /**
  168. * An observable surfacing the active routing instruction that is currently being processed or has recently finished processing.
  169. * The instruction object has `config`, `fragment`, `queryString`, `params` and `queryParams` properties.
  170. * @property {KnockoutObservable} activeInstruction
  171. */
  172. activeInstruction:ko.observable(null),
  173. __router__:true
  174. };
  175. events.includeIn(router);
  176. activeItem.settings.areSameItem = function (currentItem, newItem, currentActivationData, newActivationData) {
  177. if (currentItem == newItem) {
  178. return compareArrays(currentActivationData, newActivationData);
  179. }
  180. return false;
  181. };
  182. activeItem.settings.findChildActivator = function(item) {
  183. if (item && item.router && item.router.parent == router) {
  184. return item.router.activeItem;
  185. }
  186. return null;
  187. };
  188. function hasChildRouter(instance, parentRouter) {
  189. return instance.router && instance.router.parent == parentRouter;
  190. }
  191. function setCurrentInstructionRouteIsActive(flag) {
  192. if (currentInstruction && currentInstruction.config.isActive) {
  193. currentInstruction.config.isActive(flag);
  194. }
  195. }
  196. function completeNavigation(instance, instruction, mode) {
  197. system.log('Navigation Complete', instance, instruction);
  198. var fromModuleId = system.getModuleId(currentActivation);
  199. if (fromModuleId) {
  200. router.trigger('router:navigation:from:' + fromModuleId);
  201. }
  202. currentActivation = instance;
  203. setCurrentInstructionRouteIsActive(false);
  204. currentInstruction = instruction;
  205. setCurrentInstructionRouteIsActive(true);
  206. var toModuleId = system.getModuleId(currentActivation);
  207. if (toModuleId) {
  208. router.trigger('router:navigation:to:' + toModuleId);
  209. }
  210. if (!hasChildRouter(instance, router)) {
  211. router.updateDocumentTitle(instance, instruction);
  212. }
  213. switch (mode) {
  214. case 'rootRouter':
  215. lastUrl = reconstructUrl(currentInstruction);
  216. break;
  217. case 'rootRouterWithChild':
  218. lastTryUrl = reconstructUrl(currentInstruction);
  219. break;
  220. case 'lastChildRouter':
  221. lastUrl = lastTryUrl;
  222. break;
  223. }
  224. rootRouter.explicitNavigation = false;
  225. rootRouter.navigatingBack = false;
  226. router.trigger('router:navigation:complete', instance, instruction, router);
  227. }
  228. function cancelNavigation(instance, instruction) {
  229. system.log('Navigation Cancelled');
  230. router.activeInstruction(currentInstruction);
  231. router.navigate(lastUrl, false);
  232. isProcessing(false);
  233. rootRouter.explicitNavigation = false;
  234. rootRouter.navigatingBack = false;
  235. router.trigger('router:navigation:cancelled', instance, instruction, router);
  236. }
  237. function redirect(url) {
  238. system.log('Navigation Redirecting');
  239. isProcessing(false);
  240. rootRouter.explicitNavigation = false;
  241. rootRouter.navigatingBack = false;
  242. router.navigate(url, { trigger: true, replace: true });
  243. }
  244. function activateRoute(activator, instance, instruction) {
  245. rootRouter.navigatingBack = !rootRouter.explicitNavigation && currentActivation != instruction.fragment;
  246. router.trigger('router:route:activating', instance, instruction, router);
  247. var options = {
  248. canDeactivate: !router.parent
  249. };
  250. activator.activateItem(instance, instruction.params, options).then(function(succeeded) {
  251. if (succeeded) {
  252. var previousActivation = currentActivation;
  253. var withChild = hasChildRouter(instance, router);
  254. var mode = '';
  255. if (router.parent) {
  256. if(!withChild) {
  257. mode = 'lastChildRouter';
  258. }
  259. } else {
  260. if (withChild) {
  261. mode = 'rootRouterWithChild';
  262. } else {
  263. mode = 'rootRouter';
  264. }
  265. }
  266. completeNavigation(instance, instruction, mode);
  267. if (withChild) {
  268. instance.router.trigger('router:route:before-child-routes', instance, instruction, router);
  269. var fullFragment = instruction.fragment;
  270. if (instruction.queryString) {
  271. fullFragment += "?" + instruction.queryString;
  272. }
  273. instance.router.loadUrl(fullFragment);
  274. }
  275. if (previousActivation == instance) {
  276. router.attached();
  277. router.compositionComplete();
  278. }
  279. } else if(activator.settings.lifecycleData && activator.settings.lifecycleData.redirect){
  280. redirect(activator.settings.lifecycleData.redirect);
  281. }else{
  282. cancelNavigation(instance, instruction);
  283. }
  284. if (startDeferred) {
  285. startDeferred.resolve();
  286. startDeferred = null;
  287. }
  288. }).fail(function(err){
  289. system.error(err);
  290. });
  291. }
  292. /**
  293. * Inspects routes and modules before activation. Can be used to protect access by cancelling navigation or redirecting.
  294. * @method guardRoute
  295. * @param {object} instance The module instance that is about to be activated by the router.
  296. * @param {object} instruction The route instruction. The instruction object has config, fragment, queryString, params and queryParams properties.
  297. * @return {Promise|Boolean|String} If a boolean, determines whether or not the route should activate or be cancelled. If a string, causes a redirect to the specified route. Can also be a promise for either of these value types.
  298. */
  299. function handleGuardedRoute(activator, instance, instruction) {
  300. var resultOrPromise = router.guardRoute(instance, instruction);
  301. if (resultOrPromise || resultOrPromise === '') {
  302. if (resultOrPromise.then) {
  303. resultOrPromise.then(function(result) {
  304. if (result) {
  305. if (system.isString(result)) {
  306. redirect(result);
  307. } else {
  308. activateRoute(activator, instance, instruction);
  309. }
  310. } else {
  311. cancelNavigation(instance, instruction);
  312. }
  313. });
  314. } else {
  315. if (system.isString(resultOrPromise)) {
  316. redirect(resultOrPromise);
  317. } else {
  318. activateRoute(activator, instance, instruction);
  319. }
  320. }
  321. } else {
  322. cancelNavigation(instance, instruction);
  323. }
  324. }
  325. function ensureActivation(activator, instance, instruction) {
  326. if (router.guardRoute) {
  327. handleGuardedRoute(activator, instance, instruction);
  328. } else {
  329. activateRoute(activator, instance, instruction);
  330. }
  331. }
  332. function canReuseCurrentActivation(instruction) {
  333. return currentInstruction
  334. && currentInstruction.config.moduleId == instruction.config.moduleId
  335. && currentActivation
  336. && ((currentActivation.canReuseForRoute && currentActivation.canReuseForRoute.apply(currentActivation, instruction.params))
  337. || (!currentActivation.canReuseForRoute && currentActivation.router && currentActivation.router.loadUrl));
  338. }
  339. function dequeueInstruction() {
  340. if (isProcessing()) {
  341. return;
  342. }
  343. var instruction = queue.shift();
  344. queue = [];
  345. if (!instruction) {
  346. return;
  347. }
  348. isProcessing(true);
  349. router.activeInstruction(instruction);
  350. router.trigger('router:navigation:processing', instruction, router);
  351. if (canReuseCurrentActivation(instruction)) {
  352. var tempActivator = activator.create();
  353. tempActivator.forceActiveItem(currentActivation); //enforce lifecycle without re-compose
  354. tempActivator.settings.areSameItem = activeItem.settings.areSameItem;
  355. tempActivator.settings.findChildActivator = activeItem.settings.findChildActivator;
  356. ensureActivation(tempActivator, currentActivation, instruction);
  357. } else if(!instruction.config.moduleId) {
  358. ensureActivation(activeItem, {
  359. viewUrl:instruction.config.viewUrl,
  360. canReuseForRoute:function() {
  361. return true;
  362. }
  363. }, instruction);
  364. } else {
  365. system.acquire(instruction.config.moduleId).then(function(m) {
  366. var instance = system.resolveObject(m);
  367. if(instruction.config.viewUrl) {
  368. instance.viewUrl = instruction.config.viewUrl;
  369. }
  370. ensureActivation(activeItem, instance, instruction);
  371. }).fail(function(err) {
  372. system.error('Failed to load routed module (' + instruction.config.moduleId + '). Details: ' + err.message, err);
  373. });
  374. }
  375. }
  376. function queueInstruction(instruction) {
  377. queue.unshift(instruction);
  378. dequeueInstruction();
  379. }
  380. // Given a route, and a URL fragment that it matches, return the array of
  381. // extracted decoded parameters. Empty or unmatched parameters will be
  382. // treated as `null` to normalize cross-browser behavior.
  383. function createParams(routePattern, fragment, queryString) {
  384. var params = routePattern.exec(fragment).slice(1);
  385. for (var i = 0; i < params.length; i++) {
  386. var current = params[i];
  387. params[i] = current ? decodeURIComponent(current) : null;
  388. }
  389. var queryParams = router.parseQueryString(queryString);
  390. if (queryParams) {
  391. params.push(queryParams);
  392. }
  393. return {
  394. params:params,
  395. queryParams:queryParams
  396. };
  397. }
  398. function configureRoute(config){
  399. router.trigger('router:route:before-config', config, router);
  400. if (!system.isRegExp(config.route)) {
  401. config.title = config.title || router.convertRouteToTitle(config.route);
  402. if (!config.viewUrl) {
  403. config.moduleId = config.moduleId || router.convertRouteToModuleId(config.route);
  404. }
  405. config.hash = config.hash || router.convertRouteToHash(config.route);
  406. if (config.hasChildRoutes) {
  407. config.route = config.route + '*childRoutes';
  408. }
  409. config.routePattern = routeStringToRegExp(config.route);
  410. }else{
  411. config.routePattern = config.route;
  412. }
  413. config.isActive = config.isActive || ko.observable(false);
  414. router.trigger('router:route:after-config', config, router);
  415. router.routes.push(config);
  416. router.route(config.routePattern, function(fragment, queryString) {
  417. var paramInfo = createParams(config.routePattern, fragment, queryString);
  418. queueInstruction({
  419. fragment: fragment,
  420. queryString:queryString,
  421. config: config,
  422. params: paramInfo.params,
  423. queryParams:paramInfo.queryParams
  424. });
  425. });
  426. };
  427. function mapRoute(config) {
  428. if(system.isArray(config.route)){
  429. var isActive = config.isActive || ko.observable(false);
  430. for(var i = 0, length = config.route.length; i < length; i++){
  431. var current = system.extend({}, config);
  432. current.route = config.route[i];
  433. current.isActive = isActive;
  434. if(i > 0){
  435. delete current.nav;
  436. }
  437. configureRoute(current);
  438. }
  439. }else{
  440. configureRoute(config);
  441. }
  442. return router;
  443. }
  444. /**
  445. * Parses a query string into an object.
  446. * @method parseQueryString
  447. * @param {string} queryString The query string to parse.
  448. * @return {object} An object keyed according to the query string parameters.
  449. */
  450. router.parseQueryString = function (queryString) {
  451. var queryObject, pairs;
  452. if (!queryString) {
  453. return null;
  454. }
  455. pairs = queryString.split('&');
  456. if (pairs.length == 0) {
  457. return null;
  458. }
  459. queryObject = {};
  460. for (var i = 0; i < pairs.length; i++) {
  461. var pair = pairs[i];
  462. if (pair === '') {
  463. continue;
  464. }
  465. var parts = pair.split(/=(.+)?/),
  466. key = parts[0],
  467. value = parts[1] && decodeURIComponent(parts[1].replace(/\+/g, ' '));
  468. var existing = queryObject[key];
  469. if (existing) {
  470. if (system.isArray(existing)) {
  471. existing.push(value);
  472. } else {
  473. queryObject[key] = [existing, value];
  474. }
  475. }
  476. else {
  477. queryObject[key] = value;
  478. }
  479. }
  480. return queryObject;
  481. };
  482. /**
  483. * Add a route to be tested when the url fragment changes.
  484. * @method route
  485. * @param {RegEx} routePattern The route pattern to test against.
  486. * @param {function} callback The callback to execute when the route pattern is matched.
  487. */
  488. router.route = function(routePattern, callback) {
  489. router.handlers.push({ routePattern: routePattern, callback: callback });
  490. };
  491. /**
  492. * Attempt to load the specified URL fragment. If a route succeeds with a match, returns `true`. If no defined routes matches the fragment, returns `false`.
  493. * @method loadUrl
  494. * @param {string} fragment The URL fragment to find a match for.
  495. * @return {boolean} True if a match was found, false otherwise.
  496. */
  497. router.loadUrl = function(fragment) {
  498. var handlers = router.handlers,
  499. queryString = null,
  500. coreFragment = fragment,
  501. queryIndex = fragment.indexOf('?');
  502. if (queryIndex != -1) {
  503. coreFragment = fragment.substring(0, queryIndex);
  504. queryString = fragment.substr(queryIndex + 1);
  505. }
  506. if(router.relativeToParentRouter){
  507. var instruction = this.parent.activeInstruction();
  508. coreFragment = queryIndex == -1 ? instruction.params.join('/') : instruction.params.slice(0, -1).join('/');
  509. if(coreFragment && coreFragment.charAt(0) == '/'){
  510. coreFragment = coreFragment.substr(1);
  511. }
  512. if(!coreFragment){
  513. coreFragment = '';
  514. }
  515. coreFragment = coreFragment.replace('//', '/').replace('//', '/');
  516. }
  517. coreFragment = coreFragment.replace(trailingSlash, '');
  518. for (var i = 0; i < handlers.length; i++) {
  519. var current = handlers[i];
  520. if (current.routePattern.test(coreFragment)) {
  521. current.callback(coreFragment, queryString);
  522. return true;
  523. }
  524. }
  525. system.log('Route Not Found', fragment, currentInstruction);
  526. router.trigger('router:route:not-found', fragment, router);
  527. if (router.parent) {
  528. lastUrl = lastTryUrl;
  529. }
  530. history.navigate(lastUrl, { trigger:false, replace:true });
  531. rootRouter.explicitNavigation = false;
  532. rootRouter.navigatingBack = false;
  533. return false;
  534. };
  535. var titleSubscription;
  536. function setTitle(value) {
  537. var appTitle = ko.unwrap(app.title);
  538. if (appTitle) {
  539. document.title = value + " | " + appTitle;
  540. } else {
  541. document.title = value;
  542. }
  543. }
  544. // Allow observable to be used for app.title
  545. if(ko.isObservable(app.title)) {
  546. app.title.subscribe(function () {
  547. var instruction = router.activeInstruction();
  548. var title = instruction != null ? ko.unwrap(instruction.config.title) : '';
  549. setTitle(title);
  550. });
  551. }
  552. /**
  553. * Updates the document title based on the activated module instance, the routing instruction and the app.title.
  554. * @method updateDocumentTitle
  555. * @param {object} instance The activated module.
  556. * @param {object} instruction The routing instruction associated with the action. It has a `config` property that references the original route mapping config.
  557. */
  558. router.updateDocumentTitle = function (instance, instruction) {
  559. var appTitle = ko.unwrap(app.title),
  560. title = instruction.config.title;
  561. if (titleSubscription) {
  562. titleSubscription.dispose();
  563. }
  564. if (title) {
  565. if (ko.isObservable(title)) {
  566. titleSubscription = title.subscribe(setTitle);
  567. setTitle(title());
  568. } else {
  569. setTitle(title);
  570. }
  571. } else if (appTitle) {
  572. document.title = appTitle;
  573. }
  574. };
  575. /**
  576. * Save a fragment into the hash history, or replace the URL state if the
  577. * 'replace' option is passed. You are responsible for properly URL-encoding
  578. * the fragment in advance.
  579. * The options object can contain `trigger: false` if you wish to not have the
  580. * route callback be fired, or `replace: true`, if
  581. * you wish to modify the current URL without adding an entry to the history.
  582. * @method navigate
  583. * @param {string} fragment The url fragment to navigate to.
  584. * @param {object|boolean} options An options object with optional trigger and replace flags. You can also pass a boolean directly to set the trigger option. Trigger is `true` by default.
  585. * @return {boolean} Returns true/false from loading the url.
  586. */
  587. router.navigate = function(fragment, options) {
  588. if(fragment && fragment.indexOf('://') != -1) {
  589. window.location.href = fragment;
  590. return true;
  591. }
  592. if(options === undefined || (system.isBoolean(options) && options) || (system.isObject(options) && options.trigger)) {
  593. rootRouter.explicitNavigation = true;
  594. }
  595. if ((system.isBoolean(options) && !options) || (options && options.trigger != undefined && !options.trigger)) {
  596. lastUrl = fragment;
  597. }
  598. return history.navigate(fragment, options);
  599. };
  600. /**
  601. * Navigates back in the browser history.
  602. * @method navigateBack
  603. */
  604. router.navigateBack = function() {
  605. history.navigateBack();
  606. };
  607. router.attached = function() {
  608. router.trigger('router:navigation:attached', currentActivation, currentInstruction, router);
  609. };
  610. router.compositionComplete = function(){
  611. isProcessing(false);
  612. router.trigger('router:navigation:composition-complete', currentActivation, currentInstruction, router);
  613. dequeueInstruction();
  614. };
  615. /**
  616. * Converts a route to a hash suitable for binding to a link's href.
  617. * @method convertRouteToHash
  618. * @param {string} route
  619. * @return {string} The hash.
  620. */
  621. router.convertRouteToHash = function(route) {
  622. route = route.replace(/\*.*$/, '');
  623. if(router.relativeToParentRouter){
  624. var instruction = router.parent.activeInstruction(),
  625. hash = route ? instruction.config.hash + '/' + route : instruction.config.hash;
  626. if(history._hasPushState){
  627. hash = '/' + hash;
  628. }
  629. hash = hash.replace('//', '/').replace('//', '/');
  630. return hash;
  631. }
  632. if(history._hasPushState){
  633. return route;
  634. }
  635. return "#" + route;
  636. };
  637. /**
  638. * Converts a route to a module id. This is only called if no module id is supplied as part of the route mapping.
  639. * @method convertRouteToModuleId
  640. * @param {string} route
  641. * @return {string} The module id.
  642. */
  643. router.convertRouteToModuleId = function(route) {
  644. return stripParametersFromRoute(route);
  645. };
  646. /**
  647. * Converts a route to a displayable title. This is only called if no title is specified as part of the route mapping.
  648. * @method convertRouteToTitle
  649. * @param {string} route
  650. * @return {string} The title.
  651. */
  652. router.convertRouteToTitle = function(route) {
  653. var value = stripParametersFromRoute(route);
  654. return value.substring(0, 1).toUpperCase() + value.substring(1);
  655. };
  656. /**
  657. * Maps route patterns to modules.
  658. * @method map
  659. * @param {string|object|object[]} route A route, config or array of configs.
  660. * @param {object} [config] The config for the specified route.
  661. * @chainable
  662. * @example
  663. router.map([
  664. { route: '', title:'Home', moduleId: 'homeScreen', nav: true },
  665. { route: 'customer/:id', moduleId: 'customerDetails'}
  666. ]);
  667. */
  668. router.map = function(route, config) {
  669. if (system.isArray(route)) {
  670. for (var i = 0; i < route.length; i++) {
  671. router.map(route[i]);
  672. }
  673. return router;
  674. }
  675. if (system.isString(route) || system.isRegExp(route)) {
  676. if (!config) {
  677. config = {};
  678. } else if (system.isString(config)) {
  679. config = { moduleId: config };
  680. }
  681. config.route = route;
  682. } else {
  683. config = route;
  684. }
  685. return mapRoute(config);
  686. };
  687. /**
  688. * Builds an observable array designed to bind a navigation UI to. The model will exist in the `navigationModel` property.
  689. * @method buildNavigationModel
  690. * @param {number} defaultOrder The default order to use for navigation visible routes that don't specify an order. The default is 100 and each successive route will be one more than that.
  691. * @chainable
  692. */
  693. router.buildNavigationModel = function(defaultOrder) {
  694. var nav = [], routes = router.routes;
  695. var fallbackOrder = defaultOrder || 100;
  696. for (var i = 0; i < routes.length; i++) {
  697. var current = routes[i];
  698. if (current.nav) {
  699. if (!system.isNumber(current.nav)) {
  700. current.nav = ++fallbackOrder;
  701. }
  702. nav.push(current);
  703. }
  704. }
  705. nav.sort(function(a, b) { return a.nav - b.nav; });
  706. router.navigationModel(nav);
  707. return router;
  708. };
  709. /**
  710. * Configures how the router will handle unknown routes.
  711. * @method mapUnknownRoutes
  712. * @param {string|function} [config] If not supplied, then the router will map routes to modules with the same name.
  713. * If a string is supplied, it represents the module id to route all unknown routes to.
  714. * Finally, if config is a function, it will be called back with the route instruction containing the route info. The function can then modify the instruction by adding a moduleId and the router will take over from there.
  715. * @param {string} [replaceRoute] If config is a module id, then you can optionally provide a route to replace the url with.
  716. * @chainable
  717. */
  718. router.mapUnknownRoutes = function(config, replaceRoute) {
  719. var catchAllRoute = "*catchall";
  720. var catchAllPattern = routeStringToRegExp(catchAllRoute);
  721. router.route(catchAllPattern, function (fragment, queryString) {
  722. var paramInfo = createParams(catchAllPattern, fragment, queryString);
  723. var instruction = {
  724. fragment: fragment,
  725. queryString: queryString,
  726. config: {
  727. route: catchAllRoute,
  728. routePattern: catchAllPattern
  729. },
  730. params: paramInfo.params,
  731. queryParams: paramInfo.queryParams
  732. };
  733. if (!config) {
  734. instruction.config.moduleId = fragment;
  735. } else if (system.isString(config)) {
  736. instruction.config.moduleId = config;
  737. if(replaceRoute){
  738. history.navigate(replaceRoute, { trigger:false, replace:true });
  739. }
  740. } else if (system.isFunction(config)) {
  741. var result = config(instruction);
  742. if (result && result.then) {
  743. result.then(function() {
  744. router.trigger('router:route:before-config', instruction.config, router);
  745. router.trigger('router:route:after-config', instruction.config, router);
  746. queueInstruction(instruction);
  747. });
  748. return;
  749. }
  750. } else {
  751. instruction.config = config;
  752. instruction.config.route = catchAllRoute;
  753. instruction.config.routePattern = catchAllPattern;
  754. }
  755. router.trigger('router:route:before-config', instruction.config, router);
  756. router.trigger('router:route:after-config', instruction.config, router);
  757. queueInstruction(instruction);
  758. });
  759. return router;
  760. };
  761. /**
  762. * Resets the router by removing handlers, routes, event handlers and previously configured options.
  763. * @method reset
  764. * @chainable
  765. */
  766. router.reset = function() {
  767. currentInstruction = currentActivation = undefined;
  768. router.handlers = [];
  769. router.routes = [];
  770. router.off();
  771. delete router.options;
  772. return router;
  773. };
  774. /**
  775. * Makes all configured routes and/or module ids relative to a certain base url.
  776. * @method makeRelative
  777. * @param {string|object} settings If string, the value is used as the base for routes and module ids. If an object, you can specify `route` and `moduleId` separately. In place of specifying route, you can set `fromParent:true` to make routes automatically relative to the parent router's active route.
  778. * @chainable
  779. */
  780. router.makeRelative = function(settings){
  781. if(system.isString(settings)){
  782. settings = {
  783. moduleId:settings,
  784. route:settings
  785. };
  786. }
  787. if(settings.moduleId && !endsWith(settings.moduleId, '/')){
  788. settings.moduleId += '/';
  789. }
  790. if(settings.route && !endsWith(settings.route, '/')){
  791. settings.route += '/';
  792. }
  793. if(settings.fromParent){
  794. router.relativeToParentRouter = true;
  795. }
  796. router.on('router:route:before-config').then(function(config){
  797. if(settings.moduleId){
  798. config.moduleId = settings.moduleId + config.moduleId;
  799. }
  800. if(settings.route){
  801. if(config.route === ''){
  802. config.route = settings.route.substring(0, settings.route.length - 1);
  803. }else{
  804. config.route = settings.route + config.route;
  805. }
  806. }
  807. });
  808. if (settings.dynamicHash) {
  809. router.on('router:route:after-config').then(function (config) {
  810. config.routePattern = routeStringToRegExp(config.route ? settings.dynamicHash + '/' + config.route : settings.dynamicHash);
  811. config.dynamicHash = config.dynamicHash || ko.observable(config.hash);
  812. });
  813. router.on('router:route:before-child-routes').then(function(instance, instruction, parentRouter) {
  814. var childRouter = instance.router;
  815. for(var i = 0; i < childRouter.routes.length; i++) {
  816. var route = childRouter.routes[i];
  817. var params = instruction.params.slice(0);
  818. route.hash = childRouter.convertRouteToHash(route.route)
  819. .replace(namedParam, function(match) {
  820. return params.length > 0 ? params.shift() : match;
  821. });
  822. route.dynamicHash(route.hash);
  823. }
  824. });
  825. }
  826. return router;
  827. };
  828. /**
  829. * Creates a child router.
  830. * @method createChildRouter
  831. * @return {Router} The child router.
  832. */
  833. router.createChildRouter = function() {
  834. var childRouter = createRouter();
  835. childRouter.parent = router;
  836. return childRouter;
  837. };
  838. return router;
  839. };
  840. /**
  841. * @class RouterModule
  842. * @extends Router
  843. * @static
  844. */
  845. rootRouter = createRouter();
  846. rootRouter.explicitNavigation = false;
  847. rootRouter.navigatingBack = false;
  848. /**
  849. * Makes the RegExp generated for routes case sensitive, rather than the default of case insensitive.
  850. * @method makeRoutesCaseSensitive
  851. */
  852. rootRouter.makeRoutesCaseSensitive = function(){
  853. routesAreCaseSensitive = true;
  854. };
  855. /**
  856. * Verify that the target is the current window
  857. * @method targetIsThisWindow
  858. * @return {boolean} True if the event's target is the current window, false otherwise.
  859. */
  860. rootRouter.targetIsThisWindow = function(event) {
  861. var targetWindow = $(event.target).attr('target');
  862. if (!targetWindow ||
  863. targetWindow === window.name ||
  864. targetWindow === '_self' ||
  865. (targetWindow === 'top' && window === window.top)) { return true; }
  866. return false;
  867. };
  868. /**
  869. * Activates the router and the underlying history tracking mechanism.
  870. * @method activate
  871. * @return {Promise} A promise that resolves when the router is ready.
  872. */
  873. rootRouter.activate = function(options) {
  874. return system.defer(function(dfd) {
  875. startDeferred = dfd;
  876. rootRouter.options = system.extend({ routeHandler: rootRouter.loadUrl }, rootRouter.options, options);
  877. history.activate(rootRouter.options);
  878. if(history._hasPushState){
  879. var routes = rootRouter.routes,
  880. i = routes.length;
  881. while(i--){
  882. var current = routes[i];
  883. current.hash = current.hash.replace('#', '/');
  884. }
  885. }
  886. var rootStripper = rootRouter.options.root && new RegExp("^" + rootRouter.options.root + "/");
  887. $(document).delegate("a", 'click', function(evt){
  888. if(history._hasPushState){
  889. if(!evt.altKey && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && rootRouter.targetIsThisWindow(evt)){
  890. var href = $(this).attr("href");
  891. // Ensure the protocol is not part of URL, meaning its relative.
  892. // Stop the event bubbling to ensure the link will not cause a page refresh.
  893. if (href != null && !(href.charAt(0) === "#" || /^[a-z]+:/i.test(href))) {
  894. rootRouter.explicitNavigation = true;
  895. evt.preventDefault();
  896. if (rootStripper) {
  897. href = href.replace(rootStripper, "");
  898. }
  899. history.navigate(href);
  900. }
  901. }
  902. }else{
  903. rootRouter.explicitNavigation = true;
  904. }
  905. });
  906. if(history.options.silent && startDeferred){
  907. startDeferred.resolve();
  908. startDeferred = null;
  909. }
  910. }).promise();
  911. };
  912. /**
  913. * Disable history, perhaps temporarily. Not useful in a real app, but possibly useful for unit testing Routers.
  914. * @method deactivate
  915. */
  916. rootRouter.deactivate = function() {
  917. history.deactivate();
  918. };
  919. /**
  920. * Installs the router's custom ko binding handler.
  921. * @method install
  922. */
  923. rootRouter.install = function(){
  924. ko.bindingHandlers.router = {
  925. init: function() {
  926. return { controlsDescendantBindings: true };
  927. },
  928. update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  929. var settings = ko.utils.unwrapObservable(valueAccessor()) || {};
  930. if (settings.__router__) {
  931. settings = {
  932. model:settings.activeItem(),
  933. attached:settings.attached,
  934. compositionComplete:settings.compositionComplete,
  935. activate: false
  936. };
  937. } else {
  938. var theRouter = ko.utils.unwrapObservable(settings.router || viewModel.router) || rootRouter;
  939. settings.model = theRouter.activeItem();
  940. settings.attached = theRouter.attached;
  941. settings.compositionComplete = theRouter.compositionComplete;
  942. settings.activate = false;
  943. }
  944. composition.compose(element, settings, bindingContext);
  945. }
  946. };
  947. ko.virtualElements.allowedBindings.router = true;
  948. };
  949. return rootRouter;
  950. });