diff --git a/lib/util.js b/lib/util.js new file mode 100644 index 0000000..9f56745 --- /dev/null +++ b/lib/util.js @@ -0,0 +1,13 @@ +import morph from 'morphmorph' +const KEY = 'CARBON_STATE' + +const assign = morph.assign(KEY) + +const parse = v => { + try { + return JSON.parse(v) + } catch (e) {} +} + +export const getState = morph.compose(parse, morph.get(KEY)) +export const saveState = (window, v) => assign(window, JSON.stringify(v)) diff --git a/package.json b/package.json index 80829ae..a8b191d 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,7 @@ "highlight.js": "^9.12.0", "lodash.debounce": "^4.0.8", "morgan": "^1.8.2", - "morphmorph": "0.0.2", + "morphmorph": "^0.0.2", "ms": "^2.0.0", "next": "^3.2.2", "react": "^15.6.1", diff --git a/pages/editor.js b/pages/editor.js index 19e8f68..8a5a5a9 100644 --- a/pages/editor.js +++ b/pages/editor.js @@ -23,6 +23,7 @@ import { COLORS, DEFAULT_CODE } from '../lib/constants' +import { getState, saveState } from '../lib/util' class Editor extends React.Component { /* pathname, asPath, err, req, res */ @@ -50,7 +51,7 @@ class Editor extends React.Component { paddingVertical: '48px', paddingHorizontal: '32px', uploading: false, - code: props.content || DEFAULT_CODE + code: props.content } this.save = this.save.bind(this) @@ -58,7 +59,20 @@ class Editor extends React.Component { this.updateCode = this.updateCode.bind(this) } - getCarbonImage() { + componentDidMount() { + const state = getState(localStorage) + if (state) { + this.setState(state) + } + } + + componentDidUpdate() { + const s = Object.assign({}, this.state) + delete s.code + saveState(localStorage, s) + } + + getCarbonImage () { const node = document.getElementById('section') const config = { @@ -140,7 +154,7 @@ class Editor extends React.Component { title={`Drop your file here to import ${isOver ? '✋' : '✊'}`} > - {this.state.code} + {this.state.code || DEFAULT_CODE} )} diff --git a/yarn.lock b/yarn.lock index e2f763b..f9a15a3 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2877,7 +2877,7 @@ morgan@^1.8.2: on-finished "~2.3.0" on-headers "~1.0.1" -morphmorph@0.0.2: +morphmorph@^0.0.2: version "0.0.2" resolved "https://registry.yarnpkg.com/morphmorph/-/morphmorph-0.0.2.tgz#b2401b5e976ca4f4e068b730145aa64634aaa689"