From 1e81c428180e9525edb2b1ccd0f6b129e27d0ce7 Mon Sep 17 00:00:00 2001 From: Mark Harrison Date: Thu, 4 Jun 2020 21:37:55 -0400 Subject: [PATCH] Add auto save functionality Fixes #527 This adds auto saving to gollum using local storage. --- .../gollum/javascript/editor/gollum.editor.js | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/lib/gollum/public/gollum/javascript/editor/gollum.editor.js b/lib/gollum/public/gollum/javascript/editor/gollum.editor.js index 41ce7dec..d96d4ce4 100755 --- a/lib/gollum/public/gollum/javascript/editor/gollum.editor.js +++ b/lib/gollum/public/gollum/javascript/editor/gollum.editor.js @@ -51,10 +51,37 @@ }).insertAfter(textarea); textarea.css('display', 'none'); + // Create a div for the autosave status message + var autoSaveMessage = document.createElement('div'); + $(autoSaveMessage).addClass('div position-fixed bottom-0 left-0'); + $('body').append(autoSaveMessage); + + var autoSaveTimer = null; + // NOTE: This requires the page to have only one 'gollum-editor-body'. var editor = ace.edit(editDiv[0], {rtlText: true}); window.ace_editor = editor; + // Check to see if we have any autosaved text and show a message to + // restore it if present. + var storageKey = 'gollum_autorecover_' + window.location; + var savedText = localStorage.getItem(storageKey); + + if (savedText) { + var savedMsg = document.createElement('div'); + var restoreButton = document.createElement('button'); + $(restoreButton).addClass('btn btn-sm primary flash-action') + .text('Restore Text') + .click(function() { + editor.getSession().setValue(savedText); + $(savedMsg).remove() + }); + $(savedMsg).addClass('flash flash-full') + .text('Autosaved text is available. Click the button to restore it.') + .append(restoreButton); + $('body').prepend(savedMsg); + } + editor.setTheme("ace/theme/tomorrow"); editor.setKeyboardHandler(); editor.renderer.setShowGutter(false); @@ -64,6 +91,20 @@ editor.getSession().on('change', function(){ textarea.val(editor.getSession().getValue()); + + // Autosave + if (autoSaveTimer) { + // Reset the timer because we just changed the text + clearTimeout(autoSaveTimer); + } + + $(autoSaveMessage).text('Saving...'); + + // Wait 2 seconds, then actualy save the text to local storage + autoSaveTimer = setTimeout(function() { + localStorage.setItem(storageKey, editor.getSession().getValue()); + $(autoSaveMessage).text('Saved recovery text'); + }, 2000); }); if (isRTL(editor.getSession().getLine(0))) { @@ -114,6 +155,12 @@ editor.focus(); }); + // Remove any autosaved text when we hit save or cancel + $("#gollum-editor-submit, #gollum-editor-cancel").click(function() { + var storageKey = 'gollum_autorecover_' + window.location; + localStorage.removeItem(storageKey); + }); + debug('GollumEditor loading'); if ( EditorHas.baseEditorMarkup() ) {