|
| 1 | +import xs from 'xstream'; |
| 2 | +import {adapt} from '@cycle/run/lib/adapt'; |
| 3 | +import {RouteMatcher} from './interfaces'; |
| 4 | +import {RouterSource} from './RouterSource'; |
| 5 | +import {Location, createPath} from 'history'; |
| 6 | +import {HistoryInput, GenericInput} from '@cycle/history'; |
| 7 | +import {Stream} from 'xstream'; |
| 8 | + |
| 9 | +export declare type HistoryAction = HistoryInput | GenericInput | string; |
| 10 | +export declare type RouterSink = Stream<HistoryAction>; |
| 11 | + |
| 12 | +export interface RouterOptions { |
| 13 | + basename?: string; |
| 14 | + historyName?: string; |
| 15 | + routerName?: string; |
| 16 | + omitHistory?: boolean; |
| 17 | +} |
| 18 | + |
| 19 | +/** |
| 20 | + * Wraps main to provide an advanced interface over @cycle/history |
| 21 | + * @public |
| 22 | + * @method routerify |
| 23 | + * @return {main} The augmented main function |
| 24 | + */ |
| 25 | +function routerify( |
| 26 | + main: (a: any) => any, |
| 27 | + routeMatcher: RouteMatcher, |
| 28 | + options?: RouterOptions |
| 29 | +) { |
| 30 | + if (typeof main !== 'function') { |
| 31 | + throw new Error('First argument to routerify must be a valid cycle app'); |
| 32 | + } |
| 33 | + const opts: RouterOptions = { |
| 34 | + basename: '/', |
| 35 | + historyName: 'history', |
| 36 | + routerName: 'router', |
| 37 | + omitHistory: true, |
| 38 | + ...options |
| 39 | + }; |
| 40 | + const createHref = (location: Location) => |
| 41 | + opts.basename + createPath(location); |
| 42 | + return function(sources: any): any { |
| 43 | + const routerSource = new RouterSource( |
| 44 | + xs.from(sources[opts.historyName]), |
| 45 | + [], |
| 46 | + createHref, |
| 47 | + routeMatcher |
| 48 | + ); |
| 49 | + const sinks = main({ |
| 50 | + ...sources, |
| 51 | + [opts.routerName]: routerSource, |
| 52 | + [opts.historyName]: opts.omitHistory |
| 53 | + ? undefined |
| 54 | + : sources[opts.historyName] |
| 55 | + }); |
| 56 | + return { |
| 57 | + ...sinks, |
| 58 | + [opts.historyName]: adapt( |
| 59 | + xs.merge( |
| 60 | + sinks[opts.historyName] && !opts.omitHistory |
| 61 | + ? xs.fromObservable(sinks[opts.historyName]) |
| 62 | + : xs.never(), |
| 63 | + sinks[opts.routerName] |
| 64 | + ? xs.fromObservable(sinks[opts.routerName]) |
| 65 | + : xs.never() |
| 66 | + ) |
| 67 | + ) |
| 68 | + }; |
| 69 | + }; |
| 70 | +} |
| 71 | + |
| 72 | +export {routerify}; |
0 commit comments