ext-storage.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. /*globals svgEditor, svgCanvas, $, widget*/
  2. /*jslint vars: true, eqeq: true, regexp: true, continue: true*/
  3. /*
  4. * ext-storage.js
  5. *
  6. * Licensed under the MIT License
  7. *
  8. * Copyright(c) 2010 Brett Zamir
  9. *
  10. */
  11. /**
  12. * This extension allows automatic saving of the SVG canvas contents upon
  13. * page unload (which can later be automatically retrieved upon future
  14. * editor loads).
  15. *
  16. * The functionality was originally part of the SVG Editor, but moved to a
  17. * separate extension to make the setting behavior optional, and adapted
  18. * to inform the user of its setting of local data.
  19. */
  20. /*
  21. TODOS
  22. 1. Revisit on whether to use $.pref over directly setting curConfig in all
  23. extensions for a more public API (not only for extPath and imagePath,
  24. but other currently used config in the extensions)
  25. 2. We might provide control of storage settings through the UI besides the
  26. initial (or URL-forced) dialog.
  27. */
  28. svgEditor.addExtension('storage', function() {
  29. // We could empty any already-set data for users when they decline storage,
  30. // but it would be a risk for users who wanted to store but accidentally
  31. // said "no"; instead, we'll let those who already set it, delete it themselves;
  32. // to change, set the "emptyStorageOnDecline" config setting to true
  33. // in config.js.
  34. var emptyStorageOnDecline = svgEditor.curConfig.emptyStorageOnDecline,
  35. // When the code in svg-editor.js prevents local storage on load per
  36. // user request, we also prevent storing on unload here so as to
  37. // avoid third-party sites making XSRF requests or providing links
  38. // which would cause the user's local storage not to load and then
  39. // upon page unload (such as the user closing the window), the storage
  40. // would thereby be set with an empty value, erasing any of the
  41. // user's prior work. To change this behavior so that no use of storage
  42. // or adding of new storage takes place regardless of settings, set
  43. // the "noStorageOnLoad" config setting to true in config.js.
  44. noStorageOnLoad = svgEditor.curConfig.noStorageOnLoad,
  45. forceStorage = svgEditor.curConfig.forceStorage,
  46. storage = svgEditor.storage;
  47. function replaceStoragePrompt (val) {
  48. val = val ? 'storagePrompt=' + val : '';
  49. var loc = top.location; // Allow this to work with the embedded editor as well
  50. if (loc.href.indexOf('storagePrompt=') > -1) {
  51. loc.href = loc.href.replace(/([&?])storagePrompt=[^&]*(&?)/, function (n0, n1, amp) {
  52. return (val ? n1 : '') + val + (!val && amp ? n1 : (amp || ''));
  53. });
  54. }
  55. else {
  56. loc.href += (loc.href.indexOf('?') > -1 ? '&' : '?') + val;
  57. }
  58. }
  59. function setSVGContentStorage (val) {
  60. if (storage) {
  61. var name = 'svgedit-' + svgEditor.curConfig.canvasName;
  62. if (!val) {
  63. storage.removeItem(name);
  64. }
  65. else {
  66. storage.setItem(name, val);
  67. }
  68. }
  69. }
  70. function expireCookie (cookie) {
  71. document.cookie = encodeURIComponent(cookie) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
  72. }
  73. function removeStoragePrefCookie () {
  74. expireCookie('store');
  75. }
  76. function emptyStorage() {
  77. setSVGContentStorage('');
  78. var name;
  79. for (name in svgEditor.curPrefs) {
  80. if (svgEditor.curPrefs.hasOwnProperty(name)) {
  81. name = 'svg-edit-' + name;
  82. if (storage) {
  83. storage.removeItem(name);
  84. }
  85. expireCookie(name);
  86. }
  87. }
  88. }
  89. // emptyStorage();
  90. /**
  91. * Listen for unloading: If and only if opted in by the user, set the content
  92. * document and preferences into storage:
  93. * 1. Prevent save warnings (since we're automatically saving unsaved
  94. * content into storage)
  95. * 2. Use localStorage to set SVG contents (potentially too large to allow in cookies)
  96. * 3. Use localStorage (where available) or cookies to set preferences.
  97. */
  98. function setupBeforeUnloadListener () {
  99. window.addEventListener('beforeunload', function(e) {
  100. // Don't save anything unless the user opted in to storage
  101. if (!document.cookie.match(/(?:^|;\s*)store=(?:prefsAndContent|prefsOnly)/)) {
  102. return;
  103. }
  104. var key;
  105. if (document.cookie.match(/(?:^|;\s*)store=prefsAndContent/)) {
  106. setSVGContentStorage(svgCanvas.getSvgString());
  107. }
  108. svgEditor.setConfig({no_save_warning: true}); // No need for explicit saving at all once storage is on
  109. // svgEditor.showSaveWarning = false;
  110. var curPrefs = svgEditor.curPrefs;
  111. for (key in curPrefs) {
  112. if (curPrefs.hasOwnProperty(key)) { // It's our own config, so we don't need to iterate up the prototype chain
  113. var val = curPrefs[key],
  114. store = (val != undefined);
  115. key = 'svg-edit-' + key;
  116. if (!store) {
  117. continue;
  118. }
  119. if (storage) {
  120. storage.setItem(key, val);
  121. }
  122. else if (window.widget) {
  123. widget.setPreferenceForKey(val, key);
  124. }
  125. else {
  126. val = encodeURIComponent(val);
  127. document.cookie = encodeURIComponent(key) + '=' + val + '; expires=Fri, 31 Dec 9999 23:59:59 GMT';
  128. }
  129. }
  130. }
  131. }, false);
  132. }
  133. /*
  134. // We could add locales here instead (and also thereby avoid the need
  135. // to keep our content within "langReady"), but this would be less
  136. // convenient for translators.
  137. $.extend(uiStrings, {confirmSetStorage: {
  138. message: "By default and where supported, SVG-Edit can store your editor "+
  139. "preferences and SVG content locally on your machine so you do not "+
  140. "need to add these back each time you load SVG-Edit. If, for privacy "+
  141. "reasons, you do not wish to store this information on your machine, "+
  142. "you can change away from the default option below.",
  143. storagePrefsAndContent: "Store preferences and SVG content locally",
  144. storagePrefsOnly: "Only store preferences locally",
  145. storagePrefs: "Store preferences locally",
  146. storageNoPrefsOrContent: "Do not store my preferences or SVG content locally",
  147. storageNoPrefs: "Do not store my preferences locally",
  148. rememberLabel: "Remember this choice?",
  149. rememberTooltip: "If you choose to opt out of storage while remembering this choice, the URL will change so as to avoid asking again."
  150. }});
  151. */
  152. var loaded = false;
  153. return {
  154. name: 'storage',
  155. langReady: function (data) {
  156. var // lang = data.lang,
  157. uiStrings = data.uiStrings, // No need to store as dialog should only run once
  158. storagePrompt = $.deparam.querystring(true).storagePrompt;
  159. // No need to run this one-time dialog again just because the user
  160. // changes the language
  161. if (loaded) {
  162. return;
  163. }
  164. loaded = true;
  165. // Note that the following can load even if "noStorageOnLoad" is
  166. // set to false; to avoid any chance of storage, avoid this
  167. // extension! (and to avoid using any prior storage, set the
  168. // config option "noStorageOnLoad" to true).
  169. if (!forceStorage && (
  170. // If the URL has been explicitly set to always prompt the
  171. // user (e.g., so one can be pointed to a URL where one
  172. // can alter one's settings, say to prevent future storage)...
  173. storagePrompt === true ||
  174. (
  175. // ...or...if the URL at least doesn't explicitly prevent a
  176. // storage prompt (as we use for users who
  177. // don't want to set cookies at all but who don't want
  178. // continual prompts about it)...
  179. storagePrompt !== false &&
  180. // ...and this user hasn't previously indicated a desire for storage
  181. !document.cookie.match(/(?:^|;\s*)store=(?:prefsAndContent|prefsOnly)/)
  182. )
  183. // ...then show the storage prompt.
  184. )) {
  185. var options = [];
  186. if (storage) {
  187. options.unshift(
  188. {value: 'prefsAndContent', text: uiStrings.confirmSetStorage.storagePrefsAndContent},
  189. {value: 'prefsOnly', text: uiStrings.confirmSetStorage.storagePrefsOnly},
  190. {value: 'noPrefsOrContent', text: uiStrings.confirmSetStorage.storageNoPrefsOrContent}
  191. );
  192. }
  193. else {
  194. options.unshift(
  195. {value: 'prefsOnly', text: uiStrings.confirmSetStorage.storagePrefs},
  196. {value: 'noPrefsOrContent', text: uiStrings.confirmSetStorage.storageNoPrefs}
  197. );
  198. }
  199. // Hack to temporarily provide a wide and high enough dialog
  200. var oldContainerWidth = $('#dialog_container')[0].style.width,
  201. oldContainerMarginLeft = $('#dialog_container')[0].style.marginLeft,
  202. oldContentHeight = $('#dialog_content')[0].style.height,
  203. oldContainerHeight = $('#dialog_container')[0].style.height;
  204. $('#dialog_content')[0].style.height = '120px';
  205. $('#dialog_container')[0].style.height = '170px';
  206. $('#dialog_container')[0].style.width = '800px';
  207. $('#dialog_container')[0].style.marginLeft = '-400px';
  208. // Open select-with-checkbox dialog
  209. $.select(
  210. uiStrings.confirmSetStorage.message,
  211. options,
  212. function (pref, checked) {
  213. if (pref && pref !== 'noPrefsOrContent') {
  214. // Regardless of whether the user opted
  215. // to remember the choice (and move to a URL which won't
  216. // ask them again), we have to assume the user
  217. // doesn't even want to remember their not wanting
  218. // storage, so we don't set the cookie or continue on with
  219. // setting storage on beforeunload
  220. document.cookie = 'store=' + encodeURIComponent(pref) + '; expires=Fri, 31 Dec 9999 23:59:59 GMT'; // 'prefsAndContent' | 'prefsOnly'
  221. // If the URL was configured to always insist on a prompt, if
  222. // the user does indicate a wish to store their info, we
  223. // don't want ask them again upon page refresh so move
  224. // them instead to a URL which does not always prompt
  225. if (storagePrompt === true && checked) {
  226. replaceStoragePrompt();
  227. return;
  228. }
  229. }
  230. else { // The user does not wish storage (or cancelled, which we treat equivalently)
  231. removeStoragePrefCookie();
  232. if (pref && // If the user explicitly expresses wish for no storage
  233. emptyStorageOnDecline
  234. ) {
  235. emptyStorage();
  236. }
  237. if (pref && checked) {
  238. // Open a URL which won't set storage and won't prompt user about storage
  239. replaceStoragePrompt('false');
  240. return;
  241. }
  242. }
  243. // Reset width/height of dialog (e.g., for use by Export)
  244. $('#dialog_container')[0].style.width = oldContainerWidth;
  245. $('#dialog_container')[0].style.marginLeft = oldContainerMarginLeft;
  246. $('#dialog_content')[0].style.height = oldContentHeight;
  247. $('#dialog_container')[0].style.height = oldContainerHeight;
  248. // It should be enough to (conditionally) add to storage on
  249. // beforeunload, but if we wished to update immediately,
  250. // we might wish to try setting:
  251. // svgEditor.setConfig({noStorageOnLoad: true});
  252. // and then call:
  253. // svgEditor.loadContentAndPrefs();
  254. // We don't check for noStorageOnLoad here because
  255. // the prompt gives the user the option to store data
  256. setupBeforeUnloadListener();
  257. svgEditor.storagePromptClosed = true;
  258. },
  259. null,
  260. null,
  261. {
  262. label: uiStrings.confirmSetStorage.rememberLabel,
  263. checked: false,
  264. tooltip: uiStrings.confirmSetStorage.rememberTooltip
  265. }
  266. );
  267. }
  268. else if (!noStorageOnLoad || forceStorage) {
  269. setupBeforeUnloadListener();
  270. }
  271. }
  272. };
  273. });