editor-local-storage.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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.restore = function(slug) {
  13. var draft = this.unserialize();
  14. if(! draft) {
  15. console.log('no draft found for slug `' + slug + '`');
  16. return false;
  17. }
  18. if(draft.slug !== slug) {
  19. console.log('Saved draft id `' + draft.slug + '` differs from required `' + slug + '`');
  20. return false;
  21. }
  22. console.log('restore', draft);
  23. this.init(draft.slug, draft.sources);
  24. return draft;
  25. }
  26. LocalStorageDraft.prototype.unserialize = function() {
  27. var draftJSON = localStorage.getItem(this.storageKey);
  28. var draft;
  29. if(! draftJSON) {
  30. return false;
  31. }
  32. try {
  33. draft = JSON.parse(draftJSON);
  34. }
  35. catch(e) {
  36. console.log('could not unserialize!! ' + e.message);
  37. return false;
  38. }
  39. return draft;
  40. }
  41. LocalStorageDraft.prototype.reset = function() {
  42. this.slug = undefined;
  43. this.sources = undefined;
  44. localStorage.removeItem(this.storageKey);
  45. }
  46. LocalStorageDraft.prototype.serialize = function() {
  47. return JSON.stringify({
  48. slug: this.slug, sources: this.sources
  49. });
  50. }
  51. LocalStorageDraft.prototype.saveSource = function(type, source) {
  52. console.log(this);
  53. if(this.supportedTypes.indexOf(type) === -1) {
  54. throw new Error('Unsupported type `' + type +
  55. '`, allowed types are: ' + this.supportedTypes.join(', '));
  56. }
  57. this.sources[type] = source;
  58. localStorage.setItem(this.storageKey, this.serialize());
  59. }