Created
February 10, 2016 09:21
-
-
Save morten-olsen/22b4af4b947d8421dd97 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React from 'react'; | |
| const routeProperty = Symbol(); | |
| function extractParams(pattern, url) { | |
| pattern = pattern.replace('*', ''); | |
| if (!pattern || !url) { | |
| return {}; | |
| } | |
| const patternParts = pattern.split('/'); | |
| const patternParams = []; | |
| patternParts.forEach((item, index) => { | |
| if (item[0] !== ':') return; | |
| patternParams.push({ | |
| name: item.substring(1), | |
| index, | |
| }); | |
| }); | |
| const urlParts = url.split('/'); | |
| const result = {}; | |
| patternParams.forEach(item => { | |
| result[item.name] = urlParts[item.index]; | |
| }); | |
| return result; | |
| } | |
| export default class Router { | |
| constructor() { | |
| this[routeProperty] = []; | |
| } | |
| add(pattern, fn) { | |
| var regEx = pattern.replace(/\/:[^/*]+/g, '/.+'); | |
| regEx = regEx.replace('*', '.*'); | |
| this[routeProperty].push({ | |
| pattern, | |
| regEx: new RegExp(regEx), | |
| fn, | |
| }); | |
| } | |
| resolve(state) { | |
| const routes = this[routeProperty].filter(route => route.regEx.test(state.path)); | |
| const results = routes.map(route => { | |
| const newState = Object.assign({}, state || {}, { | |
| params: extractParams(route.pattern, state.path), | |
| }); | |
| const response = route.fn(newState); | |
| response.state = newState; | |
| return response; | |
| }); | |
| let component = null; | |
| const actions = []; | |
| for (var i = 0; i < results.length; i++) { | |
| const comp = results[i].component; | |
| const action = results[i].action; | |
| if (comp) { | |
| if (component) { | |
| component = React.cloneElement(comp, { | |
| childRoute: component, | |
| }); | |
| } else { | |
| component = React.cloneElement(comp); | |
| } | |
| } | |
| if (action) { | |
| if (action instanceof Promise) { | |
| actions.push(action); | |
| } else { | |
| action(); | |
| } | |
| } | |
| } | |
| return { | |
| component, | |
| actions: Promise.all(actions), | |
| }; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment