aboutsummaryrefslogtreecommitdiffstats
path: root/library/tinymce/jscripts/tiny_mce/plugins/noneditable/editor_plugin_src.js
blob: c87d241bd45a12759ef60179f87c9c9dcdc4ee06 (plain) (blame)
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
432
433
434
435
436
437
438
/**
 * 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
 */

(function() {
	var TreeWalker = tinymce.dom.TreeWalker;
	var externalName = 'contenteditable', internalName = 'data-mce-' + externalName;
	var VK = tinymce.VK;

	function handleContentEditableSelection(ed) {
		var dom = ed.dom, selection = ed.selection, invisibleChar, caretContainerId = 'mce_noneditablecaret';

		// Setup invisible character use zero width space on Gecko since it doesn't change the height of the container
		invisibleChar = tinymce.isGecko ? '\u200B' : '\uFEFF';

		// Returns the content editable state of a node "true/false" or null
		function getContentEditable(node) {
			var contentEditable;

			// Ignore non elements
			if (node.nodeType === 1) {
				// Check for fake content editable
				contentEditable = node.getAttribute(internalName);
				if (contentEditable && contentEditable !== "inherit") {
					return contentEditable;
				}

				// Check for real content editable
				contentEditable = node.contentEditable;
				if (contentEditable !== "inherit") {
					return contentEditable;
				}
			}

			return null;
		};

		// Returns the noneditable parent or null if there is a editable before it or if it wasn't found
		function getNonEditableParent(node) {
			var state;

			while (node) {
				state = getContentEditable(node);
				if (state) {
					return state  === "false" ? node : null;
				}

				node = node.parentNode;
			}
		};

		// Get caret container parent for the specified node
		function getParentCaretContainer(node) {
			while (node) {
				if (node.id === caretContainerId) {
					return node;
				}

				node = node.parentNode;
			}
		};

		// Finds the first text node in the specified node
		function findFirstTextNode(node) {
			var walker;

			if (node) {
				walker = new TreeWalker(node, node);

				for (node = walker.current(); node; node = walker.next()) {
					if (node.nodeType === 3) {
						return node;
					}
				}
			}
		};

		// Insert caret container before/after target or expand selection to include block
		function insertCaretContainerOrExpandToBlock(target, before) {
			var caretContainer, rng;

			// Select block
			if (getContentEditable(target) === "false") {
				if (dom.isBlock(target)) {
					selection.select(target);
					return;
				}
			}

			rng = dom.createRng();

			if (getContentEditable(target) === "true") {
				if (!target.firstChild) {
					target.appendChild(ed.getDoc().createTextNode('\u00a0'));
				}

				target = target.firstChild;
				before = true;
			}

			//caretContainer = dom.create('span', {id: caretContainerId, 'data-mce-bogus': true, style:'border: 1px solid red'}, invisibleChar);
			caretContainer = dom.create('span', {id: caretContainerId, 'data-mce-bogus': true}, invisibleChar);

			if (before) {
				target.parentNode.insertBefore(caretContainer, target);
			} else {
				dom.insertAfter(caretContainer, target);
			}

			rng.setStart(caretContainer.firstChild, 1);
			rng.collapse(true);
			selection.setRng(rng);

			return caretContainer;
		};

		// Removes any caret container except the one we might be in
		function removeCaretContainer(caretContainer) {
			var child, currentCaretContainer, lastContainer;

			if (caretContainer) {
					rng = selection.getRng(true);
					rng.setStartBefore(caretContainer);
					rng.setEndBefore(caretContainer);

					child = findFirstTextNode(caretContainer);
					if (child && child.nodeValue.charAt(0) == invisibleChar) {
						child = child.deleteData(0, 1);
					}

					dom.remove(caretContainer, true);

					selection.setRng(rng);
			} else {
				currentCaretContainer = getParentCaretContainer(selection.getStart());
				while ((caretContainer = dom.get(caretContainerId)) && caretContainer !== lastContainer) {
					if (currentCaretContainer !== caretContainer) {
						child = findFirstTextNode(caretContainer);
						if (child && child.nodeValue.charAt(0) == invisibleChar) {
							child = child.deleteData(0, 1);
						}

						dom.remove(caretContainer, true);
					}

					lastContainer = caretContainer;
				}
			}
		};

		// Modifies the selection to include contentEditable false elements or insert caret containers
		function moveSelection() {
			var nonEditableStart, nonEditableEnd, isCollapsed, rng, element;

			// Checks if there is any contents to the left/right side of caret returns the noneditable element or any editable element if it finds one inside
			function hasSideContent(element, left) {
				var container, offset, walker, node, len;

				container = rng.startContainer;
				offset = rng.startOffset;

				// If endpoint is in middle of text node then expand to beginning/end of element
				if (container.nodeType == 3) {
					len = container.nodeValue.length;
					if ((offset > 0 && offset < len) || (left ? offset == len : offset == 0)) {
						return;
					}
				} else {
					// Can we resolve the node by index
					if (offset < container.childNodes.length) {
						// Browser represents caret position as the offset at the start of an element. When moving right
						// this is the element we are moving into so we consider our container to be child node at offset-1
						var pos = !left && offset > 0 ? offset-1 : offset;
						container = container.childNodes[pos];
						if (container.hasChildNodes()) {
							container = container.firstChild;
						}
					} else {
						// If not then the caret is at the last position in it's container and the caret container should be inserted after the noneditable element
						return !left ? element : null;
					}
				}

				// Walk left/right to look for contents
				walker = new TreeWalker(container, element);
				while (node = walker[left ? 'prev' : 'next']()) {
					if (node.nodeType === 3 && node.nodeValue.length > 0) {
						return;
					} else if (getContentEditable(node) === "true") {
						// Found contentEditable=true element return this one to we can move the caret inside it
						return node;
					}
				}

				return element;
			};

			// Remove any existing caret containers
			removeCaretContainer();

			// Get noneditable start/end elements
			isCollapsed = selection.isCollapsed();
			nonEditableStart = getNonEditableParent(selection.getStart());
			nonEditableEnd = getNonEditableParent(selection.getEnd());

			// Is any fo the range endpoints noneditable
			if (nonEditableStart || nonEditableEnd) {
				rng = selection.getRng(true);

				// If it's a caret selection then look left/right to see if we need to move the caret out side or expand
				if (isCollapsed) {
					nonEditableStart = nonEditableStart || nonEditableEnd;
					var start = selection.getStart();
					if (element = hasSideContent(nonEditableStart, true)) {
						// We have no contents to the left of the caret then insert a caret container before the noneditable element
						insertCaretContainerOrExpandToBlock(element, true);
					} else if (element = hasSideContent(nonEditableStart, false)) {
						// We have no contents to the right of the caret then insert a caret container after the noneditable element
						insertCaretContainerOrExpandToBlock(element, false);
					} else {
						// We are in the middle of a noneditable so expand to select it
						selection.select(nonEditableStart);
					}
				} else {
					rng = selection.getRng(true);

					// Expand selection to include start non editable element
					if (nonEditableStart) {
						rng.setStartBefore(nonEditableStart);
					}

					// Expand selection to include end non editable element
					if (nonEditableEnd) {
						rng.setEndAfter(nonEditableEnd);
					}

					selection.setRng(rng);
				}
			}
		};

		function handleKey(ed, e) {
			var keyCode = e.keyCode, nonEditableParent, caretContainer, startElement, endElement;

			function getNonEmptyTextNodeSibling(node, prev) {
				while (node = node[prev ? 'previousSibling' : 'nextSibling']) {
					if (node.nodeType !== 3 || node.nodeValue.length > 0) {
						return node;
					}
				}
			};

			function positionCaretOnElement(element, start) {
				selection.select(element);
				selection.collapse(start);
			}

			startElement = selection.getStart()
			endElement = selection.getEnd();

			// Disable all key presses in contentEditable=false except delete or backspace
			nonEditableParent = getNonEditableParent(startElement) || getNonEditableParent(endElement);
			if (nonEditableParent && (keyCode < 112 || keyCode > 124) && keyCode != VK.DELETE && keyCode != VK.BACKSPACE) {
				e.preventDefault();

				// Arrow left/right select the element and collapse left/right
				if (keyCode == VK.LEFT || keyCode == VK.RIGHT) {
					var left = keyCode == VK.LEFT;
					// If a block element find previous or next element to position the caret
					if (ed.dom.isBlock(nonEditableParent)) {
						var targetElement = left ? nonEditableParent.previousSibling : nonEditableParent.nextSibling;
						var walker = new TreeWalker(targetElement, targetElement);
						var caretElement = left ? walker.prev() : walker.next();
						positionCaretOnElement(caretElement, !left);
					} else {
						positionCaretOnElement(nonEditableParent, left);
					}
				}
			} else {
				// Is arrow left/right, backspace or delete
				if (keyCode == VK.LEFT || keyCode == VK.RIGHT || keyCode == VK.BACKSPACE || keyCode == VK.DELETE) {
					caretContainer = getParentCaretContainer(startElement);
					if (caretContainer) {
						// Arrow left or backspace
						if (keyCode == VK.LEFT || keyCode == VK.BACKSPACE) {
							nonEditableParent = getNonEmptyTextNodeSibling(caretContainer, true);

							if (nonEditableParent && getContentEditable(nonEditableParent) === "false") {
								e.preventDefault();

								if (keyCode == VK.LEFT) {
									positionCaretOnElement(nonEditableParent, true);
								} else {
									dom.remove(nonEditableParent);
								}
							} else {
								removeCaretContainer(caretContainer);
							}
						}

						// Arrow right or delete
						if (keyCode == VK.RIGHT || keyCode == VK.DELETE) {
							nonEditableParent = getNonEmptyTextNodeSibling(caretContainer);

							if (nonEditableParent && getContentEditable(nonEditableParent) === "false") {
								e.preventDefault();

								if (keyCode == VK.RIGHT) {
									positionCaretOnElement(nonEditableParent, false);
								} else {
									dom.remove(nonEditableParent);
								}
							} else {
								removeCaretContainer(caretContainer);
							}
						}
					}
				}
			}
		};

		ed.onMouseDown.addToTop(function(ed, e){
			// prevent collapsing selection to caret when clicking in a non-editable section
			var node = ed.selection.getNode();
			if (getContentEditable(node) === "false" && node == e.target) {
				e.preventDefault();
			}
		});
		ed.onMouseUp.addToTop(moveSelection);
		ed.onKeyDown.addToTop(handleKey);
		ed.onKeyUp.addToTop(moveSelection);
	};

	tinymce.create('tinymce.plugins.NonEditablePlugin', {
		init : function(ed, url) {
			var editClass, nonEditClass, nonEditableRegExps;

			editClass = " " + tinymce.trim(ed.getParam("noneditable_editable_class", "mceEditable")) + " ";
			nonEditClass = " " + tinymce.trim(ed.getParam("noneditable_noneditable_class", "mceNonEditable")) + " ";

			// Setup noneditable regexps array
			nonEditableRegExps = ed.getParam("noneditable_regexp");
			if (nonEditableRegExps && !nonEditableRegExps.length) {
				nonEditableRegExps = [nonEditableRegExps];
			}

			ed.onPreInit.add(function() {
				handleContentEditableSelection(ed);

				if (nonEditableRegExps) {
					ed.onBeforeSetContent.add(function(ed, args) {
						var i = nonEditableRegExps.length, content = args.content, cls = tinymce.trim(nonEditClass);

						// Don't replace the variables when raw is used for example on undo/redo
						if (args.format == "raw") {
							return;
						}

						while (i--) {
							content = content.replace(nonEditableRegExps[i], function() {
								var args = arguments;

								return '<span class="' + cls + '" data-mce-content="' + ed.dom.encode(args[0]) + '">' + ed.dom.encode(typeof(args[1]) === "string" ? args[1] : args[0]) + '</span>';
							});
						}

						args.content = content;
					});
				}
				
				// Apply contentEditable true/false on elements with the noneditable/editable classes
				ed.parser.addAttributeFilter('class', function(nodes) {
					var i = nodes.length, className, node;

					while (i--) {
						node = nodes[i];
						className = " " + node.attr("class") + " ";

						if (className.indexOf(editClass) !== -1) {
							node.attr(internalName, "true");
						} else if (className.indexOf(nonEditClass) !== -1) {
							node.attr(internalName, "false");
						}
					}
				});

				// Remove internal name
				ed.serializer.addAttributeFilter(internalName, function(nodes, name) {
					var i = nodes.length, node;

					while (i--) {
						node = nodes[i];

						if (nonEditableRegExps && node.attr('data-mce-content')) {
							node.name = "#text";
							node.type = 3;
							node.raw = true;
							node.value = node.attr('data-mce-content');
						} else {
							node.attr(externalName, null);
							node.attr(internalName, null);
						}
					}
				});

				// Convert external name into internal name
				ed.parser.addAttributeFilter(externalName, function(nodes, name) {
					var i = nodes.length, node;

					while (i--) {
						node = nodes[i];
						node.attr(internalName, node.attr(externalName));
						node.attr(externalName, null);
					}
				});
			});
		},

		getInfo : function() {
			return {
				longname : 'Non editable elements',
				author : 'Moxiecode Systems AB',
				authorurl : 'http://tinymce.moxiecode.com',
				infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/noneditable',
				version : tinymce.majorVersion + "." + tinymce.minorVersion
			};
		}
	});

	// Register plugin
	tinymce.PluginManager.add('noneditable', tinymce.plugins.NonEditablePlugin);
})();