lib/editor/tiny/plugins/autosave/amd/src/storage.js

  1. // This file is part of Moodle - http://moodle.org/
  2. //
  3. // Moodle is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation, either version 3 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // Moodle is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  15. /**
  16. * Storage helper for the Moodle Tiny Autosave plugin.
  17. *
  18. * @module tiny_autosave/storage
  19. * @copyright 2022 Andrew Lyons <andrew@nicols.co.uk>
  20. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  21. */
  22. import * as Repository from "./repository";
  23. import Pending from 'core/pending';
  24. import {
  25. markInitialised,
  26. getBackoffTime,
  27. } from "./options";
  28. import Log from 'core/log';
  29. import {getLogSource} from './common';
  30. /** @property {Map} A map of debounced draft saves */
  31. const saveDebounceMap = new Map();
  32. /**
  33. * Attempt to restore a draft into the editor
  34. *
  35. * @param {TinyMCE} editor The Editor to restore a draft for
  36. */
  37. export const restoreDraft = async(editor) => {
  38. const pendingPromise = new Pending('tiny_autosave/restoreDraft');
  39. try {
  40. const session = await Repository.resumeAutosaveSession(editor);
  41. if (session && session.drafttext) {
  42. editor.undoManager.ignore(() => {
  43. editor.setContent(session.drafttext);
  44. editor.save();
  45. });
  46. }
  47. } catch (error) {
  48. // Ignore any errors as drafts are optional.
  49. Log.warn(`Failed to restore draft: ${error}`, getLogSource(editor));
  50. }
  51. markInitialised(editor);
  52. pendingPromise.resolve();
  53. };
  54. /**
  55. * Save the current content of the editor as a draft.
  56. *
  57. * @param {TinyMCE} editor
  58. */
  59. export const saveDraft = (editor) => {
  60. const timerId = saveDebounceMap.get(editor);
  61. if (timerId) {
  62. clearTimeout(timerId);
  63. }
  64. saveDebounceMap.set(editor, setTimeout(() => {
  65. Log.debug(`Saving draft`, getLogSource(editor));
  66. Repository.updateAutosaveSession(editor)
  67. .catch((error) => window.console.warn(error));
  68. }, getBackoffTime(editor)));
  69. };
  70. /**
  71. * Delete the draft for the current editor.
  72. *
  73. * @param {TinyMCE} editor
  74. */
  75. export const removeAutosaveSession = (editor) => {
  76. Log.debug(`Removing Autosave session`, getLogSource(editor));
  77. Repository.removeAutosaveSession(editor);
  78. };