editor-local-storage.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. function LocalStorageDraft() {
  2. this.storageKey = 'ace_sandbox_draft';
  3. this.supportedTypes = ['html', 'javascript', 'css'];
  4. }
  5. LocalStorageDraft.prototype.init = function(slug, sources) {
  6. this.slug = slug;
  7. this.sources = sources || {};
  8. }
  9. LocalStorageDraft.prototype.getSources = function() {
  10. return this.sources;
  11. }
  12. LocalStorageDraft.prototype.getSource = function(key) {
  13. return this.sources[key];
  14. }
  15. LocalStorageDraft.prototype.hasSource = function(key) {
  16. return ! _.isEmpty(this.sources) && this.sources[key];
  17. }
  18. LocalStorageDraft.prototype.restore = function(slug) {
  19. var draft = this.unserialize();
  20. if(! draft) {
  21. // console.log('no draft found for slug `' + slug + '`');
  22. return false;
  23. }
  24. if(draft.slug !== slug) {
  25. // console.log('Saved draft id `' + draft.slug + '` differs from required `' + slug + '`');
  26. return false;
  27. }
  28. // console.log('restore', draft);
  29. this.init(draft.slug, draft.sources);
  30. return draft;
  31. }
  32. LocalStorageDraft.prototype.unserialize = function() {
  33. var draftJSON = localStorage.getItem(this.storageKey);
  34. var draft;
  35. if(! draftJSON) {
  36. return false;
  37. }
  38. try {
  39. draft = JSON.parse(draftJSON);
  40. }
  41. catch(e) {
  42. // console.log('could not unserialize!! ' + e.message);
  43. return false;
  44. }
  45. return draft;
  46. }
  47. LocalStorageDraft.prototype.reset = function() {
  48. this.slug = undefined;
  49. this.sources = undefined;
  50. localStorage.removeItem(this.storageKey);
  51. }
  52. LocalStorageDraft.prototype.serialize = function() {
  53. return JSON.stringify({
  54. slug: this.slug, sources: this.sources
  55. });
  56. }
  57. LocalStorageDraft.prototype.saveSource = function(type, source) {
  58. // console.log(this);
  59. if(this.supportedTypes.indexOf(type) === -1) {
  60. throw new Error('Unsupported type `' + type +
  61. '`, allowed types are: ' + this.supportedTypes.join(', '));
  62. }
  63. this.sources[type] = source;
  64. localStorage.setItem(this.storageKey, this.serialize());
  65. }