edit.js (2110B)
1 (function () { 2 var main = document.querySelector('main'); 3 var link = document.getElementById('edit-link'); 4 if (!main || !link) return; 5 6 var key = 'edit:' + location.pathname; 7 var editing = false; 8 var bar = null; 9 10 function stored() { 11 try { return localStorage.getItem(key); } catch (e) { return null; } 12 } 13 function store(html) { 14 try { localStorage.setItem(key, html); } catch (e) {} 15 } 16 function forget() { 17 try { localStorage.removeItem(key); } catch (e) {} 18 } 19 20 var original = main.innerHTML; 21 var saved = stored(); 22 if (saved) main.innerHTML = saved; 23 24 function button(label, fn) { 25 var b = document.createElement('button'); 26 b.type = 'button'; 27 b.textContent = label; 28 b.onclick = fn; 29 return b; 30 } 31 32 function download() { 33 var doc = '<!doctype html>\n' + document.documentElement.outerHTML; 34 var a = document.createElement('a'); 35 a.href = URL.createObjectURL(new Blob([doc], { type: 'text/html' })); 36 a.download = location.pathname.split('/').pop() || 'index.html'; 37 a.click(); 38 URL.revokeObjectURL(a.href); 39 } 40 41 function stop() { 42 editing = false; 43 main.removeAttribute('contenteditable'); 44 main.classList.remove('editing'); 45 store(main.innerHTML); 46 if (bar) { bar.remove(); bar = null; } 47 link.textContent = 'Edit text'; 48 } 49 50 function start() { 51 editing = true; 52 main.setAttribute('contenteditable', 'true'); 53 main.classList.add('editing'); 54 bar = document.createElement('div'); 55 bar.id = 'editbar'; 56 bar.appendChild(document.createTextNode('Editing this page. Changes stay in your browser. ')); 57 bar.appendChild(button('Done', stop)); 58 bar.appendChild(button('Download page', function () { stop(); download(); })); 59 bar.appendChild(button('Undo all', function () { 60 forget(); 61 main.innerHTML = original; 62 stop(); 63 forget(); 64 })); 65 document.body.insertBefore(bar, document.body.firstChild); 66 link.textContent = 'Stop editing'; 67 main.focus(); 68 } 69 70 link.onclick = function (e) { 71 e.preventDefault(); 72 if (editing) stop(); else start(); 73 }; 74 })();