summaryrefslogtreecommitdiff
path: root/htdocs/js/tiny_mce/plugins/autosave/editor_plugin_src.js
blob: 061cf13519653d9ec4bd5bb30ae07ab479cd46b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/**
 * editor_plugin_src.js
 *
 * Copyright 2009, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://tinymce.moxiecode.com/license
 * Contributing: http://tinymce.moxiecode.com/contributing
 *
 * Adds auto-save capability to the TinyMCE text editor to rescue content
 * inadvertently lost. This plugin was originally developed by Speednet
 * and that project can be found here: http://code.google.com/p/tinyautosave/
 *
 * TECHNOLOGY DISCUSSION:
 * 
 * The plugin attempts to use the most advanced features available in the current browser to save
 * as much content as possible.  There are a total of four different methods used to autosave the
 * content.  In order of preference, they are:
 * 
 * 1. localStorage - A new feature of HTML 5, localStorage can store megabytes of data per domain
 * on the client computer. Data stored in the localStorage area has no expiration date, so we must
 * manage expiring the data ourselves.  localStorage is fully supported by IE8, and it is supposed
 * to be working in Firefox 3 and Safari 3.2, but in reality is is flaky in those browsers.  As
 * HTML 5 gets wider support, the AutoSave plugin will use it automatically. In Windows Vista/7,
 * localStorage is stored in the following folder:
 * C:\Users\[username]\AppData\Local\Microsoft\Internet Explorer\DOMStore\[tempFolder]
 * 
 * 2. sessionStorage - A new feature of HTML 5, sessionStorage works similarly to localStorage,
 * except it is designed to expire after a certain amount of time.  Because the specification
 * around expiration date/time is very loosely-described, it is preferrable to use locaStorage and
 * manage the expiration ourselves.  sessionStorage has similar storage characteristics to
 * localStorage, although it seems to have better support by Firefox 3 at the moment.  (That will
 * certainly change as Firefox continues getting better at HTML 5 adoption.)
 * 
 * 3. UserData - A very under-exploited feature of Microsoft Internet Explorer, UserData is a
 * way to store up to 128K of data per "document", or up to 1MB of data per domain, on the client
 * computer.  The feature is available for IE 5+, which makes it available for every version of IE
 * supported by TinyMCE.  The content is persistent across browser restarts and expires on the
 * date/time specified, just like a cookie.  However, the data is not cleared when the user clears
 * cookies on the browser, which makes it well-suited for rescuing autosaved content.  UserData,
 * like other Microsoft IE browser technologies, is implemented as a behavior attached to a
 * specific DOM object, so in this case we attach the behavior to the same DOM element that the
 * TinyMCE editor instance is attached to.
 */

(function(tinymce) {
	// Setup constants to help the compressor to reduce script size
	var PLUGIN_NAME = 'autosave',
		RESTORE_DRAFT = 'restoredraft',
		TRUE = true,
		undefined,
		unloadHandlerAdded,
		Dispatcher = tinymce.util.Dispatcher;

	/**
	 * This plugin adds auto-save capability to the TinyMCE text editor to rescue content
	 * inadvertently lost. By using localStorage.
	 *
	 * @class tinymce.plugins.AutoSave
	 */
	tinymce.create('tinymce.plugins.AutoSave', {
		/**
		 * Initializes the plugin, this will be executed after the plugin has been created.
		 * This call is done before the editor instance has finished it's initialization so use the onInit event
		 * of the editor instance to intercept that event.
		 *
		 * @method init
		 * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in.
		 * @param {string} url Absolute URL to where the plugin is located.
		 */
		init : function(ed, url) {
			var self = this, settings = ed.settings;

			self.editor = ed;

			// Parses the specified time string into a milisecond number 10m, 10s etc.
			function parseTime(time) {
				var multipels = {
					s : 1000,
					m : 60000
				};

				time = /^(\d+)([ms]?)$/.exec('' + time);

				return (time[2] ? multipels[time[2]] : 1) * parseInt(time);
			};

			// Default config
			tinymce.each({
				ask_before_unload : TRUE,
				interval : '30s',
				retention : '20m',
				minlength : 50
			}, function(value, key) {
				key = PLUGIN_NAME + '_' + key;

				if (settings[key] === undefined)
					settings[key] = value;
			});

			// Parse times
			settings.autosave_interval = parseTime(settings.autosave_interval);
			settings.autosave_retention = parseTime(settings.autosave_retention);

			// Register restore button
			ed.addButton(RESTORE_DRAFT, {
				title : PLUGIN_NAME + ".restore_content",
				onclick : function() {
					if (ed.getContent({draft: true}).replace(/\s|&nbsp;|<\/?p[^>]*>|<br[^>]*>/gi, "").length > 0) {
						// Show confirm dialog if the editor isn't empty
						ed.windowManager.confirm(
							PLUGIN_NAME + ".warning_message",
							function(ok) {
								if (ok)
									self.restoreDraft();
							}
						);
					} else
						self.restoreDraft();
				}
			});

			// Enable/disable restoredraft button depending on if there is a draft stored or not
			ed.onNodeChange.add(function() {
				var controlManager = ed.controlManager;

				if (controlManager.get(RESTORE_DRAFT))
					controlManager.setDisabled(RESTORE_DRAFT, !self.hasDraft());
			});

			ed.onInit.add(function() {
				// Check if the user added the restore button, then setup auto storage logic
				if (ed.controlManager.get(RESTORE_DRAFT)) {
					// Setup storage engine
					self.setupStorage(ed);

					// Auto save contents each interval time
					setInterval(function() {
						self.storeDraft();
						ed.nodeChanged();
					}, settings.autosave_interval);
				}
			});

			/**
			 * This event gets fired when a draft is stored to local storage.
			 *
			 * @event onStoreDraft
			 * @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event.
			 * @param {Object} draft Draft object containing the HTML contents of the editor.
			 */
			self.onStoreDraft = new Dispatcher(self);

			/**
			 * This event gets fired when a draft is restored from local storage.
			 *
			 * @event onStoreDraft
			 * @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event.
			 * @param {Object} draft Draft object containing the HTML contents of the editor.
			 */
			self.onRestoreDraft = new Dispatcher(self);

			/**
			 * This event gets fired when a draft removed/expired.
			 *
			 * @event onRemoveDraft
			 * @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event.
			 * @param {Object} draft Draft object containing the HTML contents of the editor.
			 */
			self.onRemoveDraft = new Dispatcher(self);

			// Add ask before unload dialog only add one unload handler
			if (!unloadHandlerAdded) {
				window.onbeforeunload = tinymce.plugins.AutoSave._beforeUnloadHandler;
				unloadHandlerAdded = TRUE;
			}
		},

		/**
		 * Returns information about the plugin as a name/value array.
		 * The current keys are longname, author, authorurl, infourl and version.
		 *
		 * @method getInfo
		 * @return {Object} Name/value array containing information about the plugin.
		 */
		getInfo : function() {
			return {
				longname : 'Auto save',
				author : 'Moxiecode Systems AB',
				authorurl : 'http://tinymce.moxiecode.com',
				infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/autosave',
				version : tinymce.majorVersion + "." + tinymce.minorVersion
			};
		},

		/**
		 * Returns an expiration date UTC string.
		 *
		 * @method getExpDate
		 * @return {String} Expiration date UTC string.
		 */
		getExpDate : function() {
			return new Date(
				new Date().getTime() + this.editor.settings.autosave_retention
			).toUTCString();
		},

		/**
		 * This method will setup the storage engine. If the browser has support for it.
		 *
		 * @method setupStorage
		 */
		setupStorage : function(ed) {
			var self = this, testKey = PLUGIN_NAME + '_test', testVal = "OK";

			self.key = PLUGIN_NAME + ed.id;

			// Loop though each storage engine type until we find one that works
			tinymce.each([
				function() {
					// Try HTML5 Local Storage
					if (localStorage) {
						localStorage.setItem(testKey, testVal);

						if (localStorage.getItem(testKey) === testVal) {
							localStorage.removeItem(testKey);

							return localStorage;
						}
					}
				},

				function() {
					// Try HTML5 Session Storage
					if (sessionStorage) {
						sessionStorage.setItem(testKey, testVal);

						if (sessionStorage.getItem(testKey) === testVal) {
							sessionStorage.removeItem(testKey);

							return sessionStorage;
						}
					}
				},

				function() {
					// Try IE userData
					if (tinymce.isIE) {
						ed.getElement().style.behavior = "url('#default#userData')";

						// Fake localStorage on old IE
						return {
							autoExpires : TRUE,

							setItem : function(key, value) {
								var userDataElement = ed.getElement();

								userDataElement.setAttribute(key, value);
								userDataElement.expires = self.getExpDate();

								try {
									userDataElement.save("TinyMCE");
								} catch (e) {
									// Ignore, saving might fail if "Userdata Persistence" is disabled in IE
								}
							},

							getItem : function(key) {
								var userDataElement = ed.getElement();

								try {
									userDataElement.load("TinyMCE");
									return userDataElement.getAttribute(key);
								} catch (e) {
									// Ignore, loading might fail if "Userdata Persistence" is disabled in IE
									return null;
								}
							},

							removeItem : function(key) {
								ed.getElement().removeAttribute(key);
							}
						};
					}
				},
			], function(setup) {
				// Try executing each function to find a suitable storage engine
				try {
					self.storage = setup();

					if (self.storage)
						return false;
				} catch (e) {
					// Ignore
				}
			});
		},

		/**
		 * This method will store the current contents in the the storage engine.
		 *
		 * @method storeDraft
		 */
		storeDraft : function() {
			var self = this, storage = self.storage, editor = self.editor, expires, content;

			// Is the contents dirty
			if (storage) {
				// If there is no existing key and the contents hasn't been changed since
				// it's original value then there is no point in saving a draft
				if (!storage.getItem(self.key) && !editor.isDirty())
					return;

				// Store contents if the contents if longer than the minlength of characters
				content = editor.getContent({draft: true});
				if (content.length > editor.settings.autosave_minlength) {
					expires = self.getExpDate();

					// Store expiration date if needed IE userData has auto expire built in
					if (!self.storage.autoExpires)
						self.storage.setItem(self.key + "_expires", expires);

					self.storage.setItem(self.key, content);
					self.onStoreDraft.dispatch(self, {
						expires : expires,
						content : content
					});
				}
			}
		},

		/**
		 * This method will restore the contents from the storage engine back to the editor.
		 *
		 * @method restoreDraft
		 */
		restoreDraft : function() {
			var self = this, storage = self.storage;

			if (storage) {
				content = storage.getItem(self.key);

				if (content) {
					self.editor.setContent(content);
					self.onRestoreDraft.dispatch(self, {
						content : content
					});
				}
			}
		},

		/**
		 * This method will return true/false if there is a local storage draft available.
		 *
		 * @method hasDraft
		 * @return {boolean} true/false state if there is a local draft.
		 */
		hasDraft : function() {
			var self = this, storage = self.storage, expDate, exists;

			if (storage) {
				// Does the item exist at all
				exists = !!storage.getItem(self.key);
				if (exists) {
					// Storage needs autoexpire
					if (!self.storage.autoExpires) {
						expDate = new Date(storage.getItem(self.key + "_expires"));

						// Contents hasn't expired
						if (new Date().getTime() < expDate.getTime())
							return TRUE;

						// Remove it if it has
						self.removeDraft();
					} else
						return TRUE;
				}
			}

			return false;
		},

		/**
		 * Removes the currently stored draft.
		 *
		 * @method removeDraft
		 */
		removeDraft : function() {
			var self = this, storage = self.storage, key = self.key, content;

			if (storage) {
				// Get current contents and remove the existing draft
				content = storage.getItem(key);
				storage.removeItem(key);
				storage.removeItem(key + "_expires");

				// Dispatch remove event if we had any contents
				if (content) {
					self.onRemoveDraft.dispatch(self, {
						content : content
					});
				}
			}
		},

		"static" : {
			// Internal unload handler will be called before the page is unloaded
			_beforeUnloadHandler : function(e) {
				var msg;

				tinymce.each(tinyMCE.editors, function(ed) {
					// Store a draft for each editor instance
					if (ed.plugins.autosave)
						ed.plugins.autosave.storeDraft();

					// Never ask in fullscreen mode
					if (ed.getParam("fullscreen_is_enabled"))
						return;

					// Setup a return message if the editor is dirty
					if (!msg && ed.isDirty() && ed.getParam("autosave_ask_before_unload"))
						msg = ed.getLang("autosave.unload_msg");
				});

				return msg;
			}
		}
	});

	tinymce.PluginManager.add('autosave', tinymce.plugins.AutoSave);
})(tinymce);