autosave.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. UE.plugin.register("autosave", function() {
  2. var me = this,
  3. //无限循环保护
  4. lastSaveTime = new Date(),
  5. //最小保存间隔时间
  6. MIN_TIME = 20,
  7. //auto save key
  8. saveKey = null;
  9. function save(editor) {
  10. var saveData;
  11. if (new Date() - lastSaveTime < MIN_TIME) {
  12. return;
  13. }
  14. if (!editor.hasContents()) {
  15. //这里不能调用命令来删除, 会造成事件死循环
  16. saveKey && me.removePreferences(saveKey);
  17. return;
  18. }
  19. lastSaveTime = new Date();
  20. editor._saveFlag = null;
  21. saveData = me.body.innerHTML;
  22. if (
  23. editor.fireEvent("beforeautosave", {
  24. content: saveData
  25. }) === false
  26. ) {
  27. return;
  28. }
  29. me.setPreferences(saveKey, saveData);
  30. editor.fireEvent("afterautosave", {
  31. content: saveData
  32. });
  33. }
  34. return {
  35. defaultOptions: {
  36. //默认间隔时间
  37. saveInterval: 500,
  38. enableAutoSave: true
  39. },
  40. bindEvents: {
  41. ready: function() {
  42. var _suffix = "-drafts-data",
  43. key = null;
  44. if (me.key) {
  45. key = me.key + _suffix;
  46. } else {
  47. key = (me.container.parentNode.id || "ue-common") + _suffix;
  48. }
  49. //页面地址+编辑器ID 保持唯一
  50. saveKey =
  51. (location.protocol + location.host + location.pathname).replace(
  52. /[.:\/]/g,
  53. "_"
  54. ) + key;
  55. },
  56. contentchange: function() {
  57. if (!me.getOpt("enableAutoSave")) {
  58. return;
  59. }
  60. if (!saveKey) {
  61. return;
  62. }
  63. if (me._saveFlag) {
  64. window.clearTimeout(me._saveFlag);
  65. }
  66. if (me.options.saveInterval > 0) {
  67. me._saveFlag = window.setTimeout(function() {
  68. save(me);
  69. }, me.options.saveInterval);
  70. } else {
  71. save(me);
  72. }
  73. }
  74. },
  75. commands: {
  76. clearlocaldata: {
  77. execCommand: function(cmd, name) {
  78. if (saveKey && me.getPreferences(saveKey)) {
  79. me.removePreferences(saveKey);
  80. }
  81. },
  82. notNeedUndo: true,
  83. ignoreContentChange: true
  84. },
  85. getlocaldata: {
  86. execCommand: function(cmd, name) {
  87. return saveKey ? me.getPreferences(saveKey) || "" : "";
  88. },
  89. notNeedUndo: true,
  90. ignoreContentChange: true
  91. },
  92. drafts: {
  93. execCommand: function(cmd, name) {
  94. if (saveKey) {
  95. me.body.innerHTML =
  96. me.getPreferences(saveKey) || "<p>" + domUtils.fillHtml + "</p>";
  97. me.focus(true);
  98. }
  99. },
  100. queryCommandState: function() {
  101. return saveKey ? (me.getPreferences(saveKey) === null ? -1 : 0) : -1;
  102. },
  103. notNeedUndo: true,
  104. ignoreContentChange: true
  105. }
  106. }
  107. };
  108. });