diff --git a/example/pages/a.html b/example/pages/a.html index f0302bd..52543fd 100644 --- a/example/pages/a.html +++ b/example/pages/a.html @@ -2,13 +2,16 @@ Page A - +
Loading...
-
+
- - + + diff --git a/example/site.js b/example/site.js index 8fbdd1e..d9f9270 100644 --- a/example/site.js +++ b/example/site.js @@ -3,6 +3,7 @@ const indicator = document.getElementById('indicator') let timeout = 0 pill('#page', { onLoading() { + if (timeout) { clearTimeout(timeout) timeout = 0 @@ -10,12 +11,48 @@ pill('#page', { indicator.style.display = 'block' }, - onReady() { + onUnmounting(page, url, element){ + PreserveFormPlugin(element); + }, + onReady(page, element) { timeout = setTimeout(() => { indicator.style.display = 'none' }, 1000) + PopulateFormPlugin(element); }, onMounting(){ console.log('updating content') } }) + +const PopulateFormPlugin = element =>{ + const key = location.pathname; + const fields = Array.from(element.querySelectorAll('input, textarea, select')); + if(fields.length > 0){ + const obj = JSON.parse(localStorage.getItem(key)); + obj.forEach(field=>{ + const input = document.querySelector('[name='+field.fieldName+']'); + if(input.type == 'checkbox' || input.type=='radio'){ + input.checked = field.value + } else if (input.nodeName == 'TEXTAREA'){ + input.textContent = field.value + } else { + input.value = field.value + } + }); + } +} + +const PreserveFormPlugin = (element) =>{ + const key = location.pathname; + const fields = Array.from(element.querySelectorAll('input, textarea, select')); + if(fields.length > 0){ + const values = fields.map(val=>{ + return { + fieldName: val.name, + value: val.type == 'checkbox' || val.type == 'radio'? val.checked : val.value + } + }); + localStorage.setItem(key, JSON.stringify(values)); + } +} \ No newline at end of file diff --git a/src/pill.js b/src/pill.js index 630b5ae..7ebf5b1 100644 --- a/src/pill.js +++ b/src/pill.js @@ -80,6 +80,7 @@ export default function pill(selector, options) { options = options || {} var onReady = options.onReady || noop var onLoading = options.onLoading || noop + var onUnmounting = options.onUnmounting || noop var onMounting = options.onMounting || noop var onError = options.onError || console.error.bind(console) var keyFromUrl = options.keyFromUrl || keyFromUrlDefault @@ -99,10 +100,11 @@ export default function pill(selector, options) { var cache = {} cache[keyFromUrl(currentUrl)] = currentPage function render (url, page, push) { + onUnmounting(page, url, element) updateState(null, url, page.title, push) - onMounting(page, url) + onMounting(page, url, element) setContent(element, page) - onReady(page) + onReady(page, element) if (push && url.hash.length > 1) { scrollToAnchor(url.hash.slice(1)) } @@ -208,4 +210,4 @@ export default function pill(selector, options) { document.body.addEventListener('click', onClick) window.addEventListener('popstate', onPopState) window.addEventListener('scroll', onScroll) -} +} \ No newline at end of file