Commit 2770be22 by Wee

reafactor: migrate to TypeScript

parent 9e6b616f
export { LiveRoute } from './LiveRoute'; "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LiveRoute_1 = require("./LiveRoute");
exports.default = LiveRoute_1.LiveRoute;
//# sourceMappingURL=index.js.map //# sourceMappingURL=index.js.map
\ No newline at end of file
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA"} {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.tsx"],"names":[],"mappings":";;AAAA,yCAAuC;AAEvC,kBAAe,qBAAS,CAAA"}
\ No newline at end of file \ No newline at end of file
console.log(233);
var a = 3;
export default a;
//# sourceMappingURL=test.js.map
\ No newline at end of file
{"version":3,"file":"test.js","sourceRoot":"","sources":["../src/test.tsx"],"names":[],"mappings":"AAAA,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;AAEhB,IAAM,CAAC,GAAG,CAAC,CAAA;AAEX,eAAe,CAAC,CAAA"}
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
"dependencies": { "dependencies": {
"react": "16.4.1", "react": "16.4.1",
"react-dom": "16.4.1", "react-dom": "16.4.1",
"react-live-route": "1.2.4", "react-live-route": "../",
"react-router-dom": "4.3.1", "react-router-dom": "4.3.1",
"react-scripts": "1.1.4" "react-scripts": "1.1.4"
}, },
......
...@@ -8,10 +8,10 @@ const List = props => { ...@@ -8,10 +8,10 @@ const List = props => {
<div>&gt;&gt; back to List</div> <div>&gt;&gt; back to List</div>
</Link> </Link>
<div className="detailContent">{`hello, I'm item - ${props.match.params.id}`}</div> <div className="detailContent">{`hello, I'm item - ${props.match.params.id}`}</div>
<Link className="pagination" to={`/item/${Number.parseInt(props.match.params.id) - 1}`}> <Link className="pagination" to={`/item/${Number.parseInt(props.match.params.id, 10) - 1}`}>
Prev item Prev item
</Link> </Link>
<Link className="pagination" to={`/item/${Number.parseInt(props.match.params.id) + 1}`}> <Link className="pagination" to={`/item/${Number.parseInt(props.match.params.id, 10) + 1}`}>
Next item Next item
</Link> </Link>
</div> </div>
......
import React from 'react' import React from 'react'
import ReactDOM from 'react-dom' import ReactDOM from 'react-dom'
import { Route, BrowserRouter } from 'react-router-dom' import { Route, BrowserRouter } from 'react-router-dom'
import LiveRoute from '../../dist/index' import LiveRoute from 'react-live-route'
import List from './list' import List from './list'
import Detail from './detail' import Detail from './detail'
import Bar from './bar' import Bar from './bar'
...@@ -13,7 +13,20 @@ function App() { ...@@ -13,7 +13,20 @@ function App() {
return ( return (
<div className="App"> <div className="App">
<Route exact path="/" component={Home} /> <Route exact path="/" component={Home} />
<LiveRoute path="/items" component={List} livePath="/item/:id" name="items" /> <LiveRoute
path="/items"
component={List}
livePath="/item/:id"
name="items"
onHide={routeState => {
console.log('[on hide]')
console.log(routeState)
}}
onReappear={routeState => {
console.log('[on reappear]')
console.log(routeState)
}}
/>
<Route path="/item/:id" component={Detail} /> <Route path="/item/:id" component={Detail} />
<LiveRoute path="/about" alwaysLive={true} component={About} name="about" /> <LiveRoute path="/about" alwaysLive={true} component={About} name="about" />
<Bar /> <Bar />
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -5,10 +5,6 @@ ...@@ -5,10 +5,6 @@
"repository": "fi3ework/react-live-route", "repository": "fi3ework/react-live-route",
"license": "MIT", "license": "MIT",
"authors": "fi3ework", "authors": "fi3ework",
"files": [
"index.js",
"LiveRoute.js"
],
"main": "dist/index.js", "main": "dist/index.js",
"module": "es/index.js", "module": "es/index.js",
"sideEffects": false, "sideEffects": false,
...@@ -25,9 +21,9 @@ ...@@ -25,9 +21,9 @@
"dependencies": { "dependencies": {
"invariant": "^2.2.4", "invariant": "^2.2.4",
"prop-types": "^15.6.1", "prop-types": "^15.6.1",
"react-is": "^16.7.0",
"react": "^16.3.2", "react": "^16.3.2",
"react-dom": "^16.3.2", "react-dom": "^16.3.2",
"react-is": "^16.7.0",
"react-router": "^4.3.1", "react-router": "^4.3.1",
"react-router-dom": "^4.3.1", "react-router-dom": "^4.3.1",
"warning": "^4.0.1" "warning": "^4.0.1"
......
import warning from 'warning' import * as warning from 'warning'
import invariant from 'invariant' import * as invariant from 'invariant'
import React, { ReactNode } from 'react' import * as React from 'react'
import PropTypes, { ReactComponentLike } from 'prop-types' import * as PropTypes from 'prop-types'
import ReactDOM from 'react-dom' import * as ReactDOM from 'react-dom'
import { matchPath } from 'react-router' import { matchPath } from 'react-router'
import { isValidElementType } from 'react-is' import { isValidElementType } from 'react-is'
...@@ -23,14 +23,20 @@ interface IProps { ...@@ -23,14 +23,20 @@ interface IProps {
exact?: boolean exact?: boolean
strict?: boolean strict?: boolean
sensitive?: boolean sensitive?: boolean
component?: ReactComponentLike component?: PropTypes.ReactComponentLike
render?: React.StatelessComponent render?: React.StatelessComponent
location: string location: string
livePath?: string livePath?: string
alwaysLive: boolean alwaysLive: boolean
onHide?: Function
onReappear?: Function
name?: string name?: string
} }
const debugLog = (message: any) => {
// console.log(message)
}
/** /**
* The public API for matching a single path and rendering. * The public API for matching a single path and rendering.
*/ */
...@@ -49,6 +55,7 @@ class LiveRoute extends React.Component<IProps, any> { ...@@ -49,6 +55,7 @@ class LiveRoute extends React.Component<IProps, any> {
render: PropTypes.func, render: PropTypes.func,
children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]), children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),
location: PropTypes.object, location: PropTypes.object,
onHide: PropTypes.func,
livePath: PropTypes.oneOfType([PropTypes.string, PropTypes.array]), livePath: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
alwaysLive: PropTypes.bool, alwaysLive: PropTypes.bool,
name: PropTypes.string // for LiveRoute debug name: PropTypes.string // for LiveRoute debug
...@@ -142,14 +149,14 @@ class LiveRoute extends React.Component<IProps, any> { ...@@ -142,14 +149,14 @@ class LiveRoute extends React.Component<IProps, any> {
}) })
} }
// 获取 Route 对应的 DOM // get route of DOM
componentDidUpdate(prevProps, prevState) { componentDidUpdate(prevProps, prevState) {
if (!this.doesRouteEnableLive()) { if (!this.doesRouteEnableLive()) {
return return
} }
// restore display when matched normally // restore display when matched normally
console.log(this.liveState) debugLog(this.liveState)
if (this.liveState === LiveState.NORMAL_RENDER_MATCHED) { if (this.liveState === LiveState.NORMAL_RENDER_MATCHED) {
this.showRoute() this.showRoute()
this.restoreScrollPosition() this.restoreScrollPosition()
...@@ -185,36 +192,45 @@ class LiveRoute extends React.Component<IProps, any> { ...@@ -185,36 +192,45 @@ class LiveRoute extends React.Component<IProps, any> {
* Back up current router every time it is rendered normally, backing up to the next livePath rendering * Back up current router every time it is rendered normally, backing up to the next livePath rendering
*/ */
computeMatchWithLive(props, nextProps, nextContext, match) { computeMatchWithLive(props, nextProps, nextContext, match) {
// console.log(`>>> ` + this.props.name + ` <<<`) debugLog(`>>> ` + this.props.name + ` <<<`)
// compute if livePath match // compute if livePath match
const livePath = nextProps.livePath const { livePath, alwaysLive } = nextProps
const nextPropsWithLivePath = { ...nextProps, paths: livePath } const nextPropsWithLivePath = { ...nextProps, paths: livePath }
const prevMatch = this.computeMatch(props, this.context.router) const prevMatch = this.computeMatch(props, this.context.router)
const livePathMatch = this.computePathsMatch(nextPropsWithLivePath, nextContext.router) const livePathMatch = this.computePathsMatch(nextPropsWithLivePath, nextContext.router)
if (match) {
// normal matched render // normal matched render
console.log('--- NORMAL MATCH FLAG ---') if (match) {
debugLog('--- NORMAL MATCH FLAG ---')
if (this.liveState === LiveState.HIDE_RENDER && typeof this.props.onReappear === 'function') {
this.props.onReappear({ location, livePath, alwaysLive })
}
this.liveState = LiveState.NORMAL_RENDER_MATCHED this.liveState = LiveState.NORMAL_RENDER_MATCHED
return match return match
} else if ((livePathMatch || props.alwaysLive) && this.routeDom) { }
// hide render
if ((livePathMatch || props.alwaysLive) && this.routeDom) {
// backup router when from normal match render to hide render // backup router when from normal match render to hide render
if (prevMatch) { if (prevMatch) {
this._latestMatchedRouter = this.context.router this._latestMatchedRouter = this.context.router
} }
// hide render if (typeof this.props.onHide === 'function') {
console.log('--- HIDE FLAG ---') this.props.onHide({ location, livePath, alwaysLive })
}
debugLog('--- HIDE FLAG ---')
this.liveState = LiveState.HIDE_RENDER this.liveState = LiveState.HIDE_RENDER
this.saveScrollPosition() this.saveScrollPosition()
this.hideRoute() this.hideRoute()
return prevMatch return prevMatch
} else { }
// normal unmatched unmount // normal unmatched unmount
console.log('--- NORMAL UNMATCH FLAG ---') debugLog('--- NORMAL UNMATCH FLAG ---')
this.liveState = LiveState.NORMAL_RENDER_UNMATCHED this.liveState = LiveState.NORMAL_RENDER_UNMATCHED
this.clearScroll() this.clearScroll()
this.clearDomData() this.clearDomData()
} }
}
computePathsMatch({ computedMatch, location, paths, strict, exact, sensitive }, router) { computePathsMatch({ computedMatch, location, paths, strict, exact, sensitive }, router) {
invariant(router, 'You should not use <Route> or withRouter() outside a <Router>') invariant(router, 'You should not use <Route> or withRouter() outside a <Router>')
...@@ -260,7 +276,7 @@ class LiveRoute extends React.Component<IProps, any> { ...@@ -260,7 +276,7 @@ class LiveRoute extends React.Component<IProps, any> {
// backup scroll and hide DOM // backup scroll and hide DOM
hideRoute() { hideRoute() {
if (this.routeDom && this.routeDom.style.display !== 'none') { if (this.routeDom && this.routeDom.style.display !== 'none') {
console.log('--- hide route ---') debugLog('--- hide route ---')
this.previousDisplayStyle = this.routeDom.style.display this.previousDisplayStyle = this.routeDom.style.display
this.routeDom.style.display = 'none' this.routeDom.style.display = 'none'
} }
...@@ -278,7 +294,7 @@ class LiveRoute extends React.Component<IProps, any> { ...@@ -278,7 +294,7 @@ class LiveRoute extends React.Component<IProps, any> {
if (this.routeDom && this.scrollPosBackup === null) { if (this.routeDom && this.scrollPosBackup === null) {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
const scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft const scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft
console.log(`saved top = ${scrollTop}, left = ${scrollLeft}`) debugLog(`saved top = ${scrollTop}, left = ${scrollLeft}`)
this.scrollPosBackup = { top: scrollTop, left: scrollLeft } this.scrollPosBackup = { top: scrollTop, left: scrollLeft }
} }
} }
...@@ -286,7 +302,7 @@ class LiveRoute extends React.Component<IProps, any> { ...@@ -286,7 +302,7 @@ class LiveRoute extends React.Component<IProps, any> {
// restore the scroll position before hide // restore the scroll position before hide
restoreScrollPosition() { restoreScrollPosition() {
const scroll = this.scrollPosBackup const scroll = this.scrollPosBackup
console.log(scroll) debugLog(scroll)
if (scroll && this.routeDom) { if (scroll && this.routeDom) {
window.scrollTo(scroll.left, scroll.top) window.scrollTo(scroll.left, scroll.top)
} }
...@@ -309,19 +325,21 @@ class LiveRoute extends React.Component<IProps, any> { ...@@ -309,19 +325,21 @@ class LiveRoute extends React.Component<IProps, any> {
// normally render or unmount Route // normally render or unmount Route
renderRoute(component, render, props, match) { renderRoute(component, render, props, match) {
console.log(match) debugLog(match)
if (component) return match ? React.createElement(component, props) : null if (component) return match ? React.createElement(component, props) : null
if (render) return match ? render(props) : null if (render) return match ? render(props) : null
} }
render() { render() {
const { match } = this.state const { match } = this.state
const { children, component, render, livePath, alwaysLive } = this.props const { children, component, render, livePath, alwaysLive, onHide } = this.props
const { history, route, staticContext } = this.context.router const { history, route, staticContext } = this.context.router
const location = this.props.location || route.location const location = this.props.location || route.location
const props = { match, location, history, staticContext } const props = { match, location, history, staticContext }
// only affect LiveRoute
if ((livePath || alwaysLive) && (component || render)) { if ((livePath || alwaysLive) && (component || render)) {
console.log('=== RENDER FLAG: ' + this.liveState + ' ===') debugLog('=== RENDER FLAG: ' + this.liveState + ' ===')
if ( if (
this.liveState === LiveState.NORMAL_RENDER_MATCHED || this.liveState === LiveState.NORMAL_RENDER_MATCHED ||
this.liveState === LiveState.NORMAL_RENDER_UNMATCHED || this.liveState === LiveState.NORMAL_RENDER_UNMATCHED ||
...@@ -332,9 +350,7 @@ class LiveRoute extends React.Component<IProps, any> { ...@@ -332,9 +350,7 @@ class LiveRoute extends React.Component<IProps, any> {
} else if (this.liveState === LiveState.HIDE_RENDER) { } else if (this.liveState === LiveState.HIDE_RENDER) {
// hide render // hide render
const prevRouter = this._latestMatchedRouter const prevRouter = this._latestMatchedRouter
// load properties from prevRouter and fake props of latest normal render const { history, route, staticContext } = prevRouter // load properties from prevRouter and fake props of latest normal render
const { history, route, staticContext } = prevRouter
const location = this.props.location || route.location
const liveProps = { match, location, history, staticContext } const liveProps = { match, location, history, staticContext }
return this.renderRoute(component, render, liveProps, true) return this.renderRoute(component, render, liveProps, true)
} }
......
export { LiveRoute } from './LiveRoute' import { LiveRoute } from './LiveRoute'
export default LiveRoute
...@@ -3,16 +3,11 @@ ...@@ -3,16 +3,11 @@
"strict": true, "strict": true,
"experimentalDecorators": true, "experimentalDecorators": true,
"allowSyntheticDefaultImports": true, "allowSyntheticDefaultImports": true,
"baseUrl": ".",
"paths": {
"@/*": ["src/index/*"]
},
"outDir": "dist/", "outDir": "dist/",
"module": "esnext", "module": "commonjs",
"target": "es5", "target": "es5",
"lib": ["es6", "dom"], "lib": ["es6", "dom"],
"sourceMap": true, "sourceMap": true,
"allowJs": true,
"jsx": "react", "jsx": "react",
"moduleResolution": "node", "moduleResolution": "node",
"rootDir": "src", "rootDir": "src",
......
{
"extends": "./tsconfig.json"
}
\ No newline at end of file
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs"
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment