From 3cfdb07b6ae13abff305f9935b71c38275b2b1c0 Mon Sep 17 00:00:00 2001 From: Tom Hacohen Date: Fri, 8 Dec 2017 16:06:05 +0000 Subject: [PATCH] Persist some component state on route changes. --- src/JournalCalendar.tsx | 5 ++++- src/PimMain.tsx | 8 ++++++-- src/persist-state-history.tsx | 31 +++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 3 deletions(-) create mode 100644 src/persist-state-history.tsx diff --git a/src/JournalCalendar.tsx b/src/JournalCalendar.tsx index 801873f..c5cd0d7 100644 --- a/src/JournalCalendar.tsx +++ b/src/JournalCalendar.tsx @@ -3,6 +3,8 @@ import { Route, Switch, withRouter } from 'react-router'; import { routeResolver } from './App'; +import { historyPersistor } from './persist-state-history'; + import Calendar from './Calendar'; import Event from './Event'; @@ -30,6 +32,7 @@ class JournalCalendar extends React.Component { } render() { + const PersistCalendar = historyPersistor(Calendar, 'Calendar'); let items = this.props.entries; return ( @@ -38,7 +41,7 @@ class JournalCalendar extends React.Component { path={routeResolver.getRoute('journals._id')} exact={true} render={() => ( - + ) } /> diff --git a/src/PimMain.tsx b/src/PimMain.tsx index 73703cb..665cec6 100644 --- a/src/PimMain.tsx +++ b/src/PimMain.tsx @@ -10,6 +10,8 @@ import { EventType, ContactType } from './pim-types'; import { routeResolver } from './App'; +import { historyPersistor } from './persist-state-history'; + const addressBookTitle = 'Address Book'; const calendarTitle = 'Calendar'; @@ -17,6 +19,7 @@ class PimMain extends React.Component { props: { contacts: Array, events: Array, + location?: any, history?: any, }; @@ -46,6 +49,7 @@ class PimMain extends React.Component { } render() { + const PersistCalendar = historyPersistor(Calendar, 'Calendar'); return ( - + ); } } -export default PimMain; +export default historyPersistor(PimMain, 'PimMain'); diff --git a/src/persist-state-history.tsx b/src/persist-state-history.tsx new file mode 100644 index 0000000..8e54913 --- /dev/null +++ b/src/persist-state-history.tsx @@ -0,0 +1,31 @@ +import * as React from 'react'; +import { withRouter } from 'react-router'; + +// FIXME: Should probably tie this to the history object, or at least based on the depth of the history +let stateCache = {}; + +type Constructor = new(...args: any[]) => T; + +export function historyPersistor>(Base: T, tag: string) { + return withRouter(class extends Base { + constructor(...rest: any[]) { + const props = rest[0]; + super(...rest); + const tagName = this.getKeyForTag(props, tag); + if (tagName in stateCache) { + this.state = stateCache[tagName]; + } + } + + componentWillUnmount() { + if (super.componentWillUnmount) { + super.componentWillUnmount(); + } + stateCache[this.getKeyForTag(this.props, tag)] = this.state; + } + + getKeyForTag(props: any, tagName: string) { + return props.location.pathname + ':' + tagName; + } + }); +}