Skip to content
This repository has been archived by the owner on Dec 15, 2018. It is now read-only.

Placeholder Fragment #81

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import createStoreWithRouter, {
import provideRouter, { RouterProvider } from './provider';
import { Link, PersistentQueryLink } from './link';
import { AbsoluteFragment, RelativeFragment } from './fragment';
import PlaceholderFragment from './placeholder-fragment';

import routerReducer from './reducer';
import createMatcher from './create-matcher';
Expand Down Expand Up @@ -35,6 +36,7 @@ export {
Fragment,
AbsoluteFragment,
RelativeFragment,
PlaceholderFragment,

// Public action types
LOCATION_CHANGED,
Expand Down
77 changes: 77 additions & 0 deletions src/placeholder-fragment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// @flow
import type { Location } from 'history';
import type { RouterContext } from './provider';
import React, { PropTypes } from 'react';

type Props = {
forRoute?: string,
forRoutes?: Array<string>,
withConditions?: (location: Location) => bool,
children: React.Element<*>,
componentKey: string,
componentPropsKey?: string
};

type Context = {
router?: RouterContext
};

const PlaceholderFragment = (props: Props, context: Context ) => {
const {
forRoute,
forRoutes,
withConditions,
children,
componentKey = 'component',
componentPropsKey = 'componentProps'
} = props;

const { store } = context.router;
const { matchRoute } = store;
const { router: location } = store.getState();

const matchResult = matchRoute(location.pathname);

if (!matchResult) {
return null;
}

if (
forRoute &&
matchResult.route !== forRoute
) {
return null;
}

if (Array.isArray(forRoutes)) {
const anyMatch = forRoutes.some(route =>
matchResult.route === route
);

if (!anyMatch) {
return null;
}
}

if (withConditions && !withConditions(location)) {
return null;
}

if (matchResult && matchResult.result && matchResult.result.hasOwnProperty(componentKey)) {
return React.createElement(
matchResult.result[componentKey],
matchResult.result.hasOwnProperty(componentPropsKey) ?
matchResult.result[componentPropsKey] :
{},
children
);
}

return null;
};

PlaceholderFragment.contextTypes = {
router: PropTypes.object
};

export default PlaceholderFragment;