PageRenderTime 147ms CodeModel.GetById 60ms app.highlight 55ms RepoModel.GetById 26ms app.codeStats 0ms

/static/scripts/tiny_mce/plugins/safari/editor_plugin_src.js

http://n23.googlecode.com/
JavaScript | 460 lines | 292 code | 97 blank | 71 comment | 79 complexity | 60b5be3b6f6076e766a41ceb37805709 MD5 | raw file
  1/**
  2 * $Id: editor_plugin_src.js 264 2007-04-26 20:53:09Z spocke $
  3 *
  4 * @author Moxiecode
  5 * @copyright Copyright Š 2004-2008, Moxiecode Systems AB, All rights reserved.
  6 */
  7
  8(function() {
  9	var Event = tinymce.dom.Event, grep = tinymce.grep, each = tinymce.each, inArray = tinymce.inArray, isOldWebKit = tinymce.isOldWebKit;
 10
 11	tinymce.create('tinymce.plugins.Safari', {
 12		init : function(ed) {
 13			var t = this, dom;
 14
 15			// Ignore on non webkit
 16			if (!tinymce.isWebKit)
 17				return;
 18
 19			t.editor = ed;
 20			t.webKitFontSizes = ['x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', '-webkit-xxx-large'];
 21			t.namedFontSizes = ['xx-small', 'x-small','small','medium','large','x-large', 'xx-large'];
 22
 23			// Safari will crash if the build in createlink command is used
 24/*			ed.addCommand('CreateLink', function(u, v) {
 25				ed.execCommand("mceInsertContent", false, '<a href="' + dom.encode(v) + '">' + ed.selection.getContent() + '</a>');
 26			});*/
 27
 28			ed.onPaste.add(function(ed, e) {
 29				function removeStyles(e) {
 30					e = e.target;
 31
 32					if (e.nodeType == 1) {
 33						e.style.cssText = '';
 34
 35						each(ed.dom.select('*', e), function(e) {
 36							e.style.cssText = '';
 37						});
 38					}
 39				};
 40
 41				Event.add(ed.getDoc(), 'DOMNodeInserted', removeStyles);
 42
 43				window.setTimeout(function() {
 44					Event.remove(ed.getDoc(), 'DOMNodeInserted', removeStyles);
 45				}, 0);
 46			});
 47
 48			ed.onKeyUp.add(function(ed, e) {
 49				var h, b;
 50
 51				// If backspace or delete key
 52				if (e.keyCode == 46 || e.keyCode == 8) {
 53					b = ed.getBody();
 54					h = b.innerHTML;
 55
 56					// If there is no text content or images or hr elements then remove everything
 57					if (b.childNodes.length == 1 && !/<(img|hr)/.test(h) && tinymce.trim(h.replace(/<[^>]+>/g, '')).length == 0)
 58						ed.setContent('', {format : 'raw'});
 59				}
 60			});
 61
 62			// Workaround for FormatBlock bug, http://bugs.webkit.org/show_bug.cgi?id=16004
 63			ed.addCommand('FormatBlock', function(u, v) {
 64				var dom = ed.dom, e = dom.getParent(ed.selection.getNode(), dom.isBlock);
 65
 66				if (e)
 67					dom.replace(dom.create(v), e, 1);
 68				else
 69					ed.getDoc().execCommand("FormatBlock", false, v);
 70			});
 71
 72			// Workaround for InsertHTML bug, http://bugs.webkit.org/show_bug.cgi?id=16382
 73			ed.addCommand('mceInsertContent', function(u, v) {
 74				ed.getDoc().execCommand("InsertText", false, 'mce_marker');
 75				ed.getBody().innerHTML = ed.getBody().innerHTML.replace(/mce_marker/g, v + '<span id="_mce_tmp">XX</span>');
 76				ed.selection.select(ed.dom.get('_mce_tmp'));
 77				ed.getDoc().execCommand("Delete", false, ' ');
 78			});
 79
 80			// Workaround for missing shift+enter support, http://bugs.webkit.org/show_bug.cgi?id=16973
 81			ed.onKeyPress.add(function(ed, e) {
 82				if (e.keyCode == 13 && (e.shiftKey || ed.settings.force_br_newlines && ed.selection.getNode().nodeName != 'LI')) {
 83					t._insertBR(ed);
 84					Event.cancel(e);
 85				}
 86			});
 87
 88			// Safari returns incorrect values
 89			ed.addQueryValueHandler('FontSize', function(u, v) {
 90				var e, v;
 91
 92				// Check for the real font size at the start of selection
 93				if ((e = ed.dom.getParent(ed.selection.getStart(), 'span')) && (v = e.style.fontSize))
 94					return tinymce.inArray(t.namedFontSizes, v) + 1;
 95
 96				// Check for the real font size at the end of selection
 97				if ((e = ed.dom.getParent(ed.selection.getEnd(), 'span')) && (v = e.style.fontSize))
 98					return tinymce.inArray(t.namedFontSizes, v) + 1;
 99
100				// Return default value it's better than nothing right!
101				return ed.getDoc().queryCommandValue('FontSize');
102			});
103
104			// Safari returns incorrect values
105			ed.addQueryValueHandler('FontName', function(u, v) {
106				var e, v;
107
108				// Check for the real font name at the start of selection
109				if ((e = ed.dom.getParent(ed.selection.getStart(), 'span')) && (v = e.style.fontFamily))
110					return v.replace(/, /g, ',');
111
112				// Check for the real font name at the end of selection
113				if ((e = ed.dom.getParent(ed.selection.getEnd(), 'span')) && (v = e.style.fontFamily))
114					return v.replace(/, /g, ',');
115
116				// Return default value it's better than nothing right!
117				return ed.getDoc().queryCommandValue('FontName');
118			});
119
120			// Workaround for bug, http://bugs.webkit.org/show_bug.cgi?id=12250
121			ed.onClick.add(function(ed, e) {
122				e = e.target;
123
124				if (e.nodeName == 'IMG') {
125					t.selElm = e;
126					ed.selection.select(e);
127				} else
128					t.selElm = null;
129			});
130
131/*			ed.onBeforeExecCommand.add(function(ed, c, b) {
132				var r = t.bookmarkRng;
133
134				// Restore selection
135				if (r) {
136					ed.selection.setRng(r);
137					t.bookmarkRng = null;
138					//console.debug('restore', r.startContainer, r.startOffset, r.endContainer, r.endOffset);
139				}
140			});*/
141
142			ed.onInit.add(function() {
143				t._fixWebKitSpans();
144
145/*				ed.windowManager.onOpen.add(function() {
146					var r = ed.selection.getRng();
147
148					// Store selection if valid
149					if (r.startContainer != ed.getDoc()) {
150						t.bookmarkRng = r.cloneRange();
151						//console.debug('store', r.startContainer, r.startOffset, r.endContainer, r.endOffset);
152					}
153				});
154
155				ed.windowManager.onClose.add(function() {
156					t.bookmarkRng = null;
157				});*/
158
159				if (isOldWebKit)
160					t._patchSafari2x(ed);
161			});
162
163			ed.onSetContent.add(function() {
164				dom = ed.dom;
165
166				// Convert strong,b,em,u,strike to spans
167				each(['strong','b','em','u','strike','sub','sup','a'], function(v) {
168					each(grep(dom.select(v)).reverse(), function(n) {
169						var nn = n.nodeName.toLowerCase(), st;
170
171						// Convert anchors into images
172						if (nn == 'a') {
173							if (n.name)
174								dom.replace(dom.create('img', {mce_name : 'a', name : n.name, 'class' : 'mceItemAnchor'}), n);
175
176							return;
177						}
178
179						switch (nn) {
180							case 'b':
181							case 'strong':
182								if (nn == 'b')
183									nn = 'strong';
184
185								st = 'font-weight: bold;';
186								break;
187
188							case 'em':
189								st = 'font-style: italic;';
190								break;
191
192							case 'u':
193								st = 'text-decoration: underline;';
194								break;
195
196							case 'sub':
197								st = 'vertical-align: sub;';
198								break;
199
200							case 'sup':
201								st = 'vertical-align: super;';
202								break;
203
204							case 'strike':
205								st = 'text-decoration: line-through;';
206								break;
207						}
208
209						dom.replace(dom.create('span', {mce_name : nn, style : st, 'class' : 'Apple-style-span'}), n, 1);
210					});
211				});
212			});
213
214			ed.onPreProcess.add(function(ed, o) {
215				dom = ed.dom;
216
217				each(grep(o.node.getElementsByTagName('span')).reverse(), function(n) {
218					var v, bg;
219
220					if (o.get) {
221						if (dom.hasClass(n, 'Apple-style-span')) {
222							bg = n.style.backgroundColor;
223
224							switch (dom.getAttrib(n, 'mce_name')) {
225								case 'font':
226									if (!ed.settings.convert_fonts_to_spans)
227										dom.setAttrib(n, 'style', '');
228									break;
229
230								case 'strong':
231								case 'em':
232								case 'sub':
233								case 'sup':
234									dom.setAttrib(n, 'style', '');
235									break;
236
237								case 'strike':
238								case 'u':
239									if (!ed.settings.inline_styles)
240										dom.setAttrib(n, 'style', '');
241									else
242										dom.setAttrib(n, 'mce_name', '');
243
244									break;
245
246								default:
247									if (!ed.settings.inline_styles)
248										dom.setAttrib(n, 'style', '');
249							}
250
251
252							if (bg)
253								n.style.backgroundColor = bg;
254						}
255					}
256
257					if (dom.hasClass(n, 'mceItemRemoved'))
258						dom.remove(n, 1);
259				});
260			});
261
262			ed.onPostProcess.add(function(ed, o) {
263				// Safari adds BR at end of all block elements
264				o.content = o.content.replace(/<br \/><\/(h[1-6]|div|p|address|pre)>/g, '</$1>');
265
266				// Safari adds id="undefined" to HR elements
267				o.content = o.content.replace(/ id=\"undefined\"/g, '');
268			});
269		},
270
271		getInfo : function() {
272			return {
273				longname : 'Safari compatibility',
274				author : 'Moxiecode Systems AB',
275				authorurl : 'http://tinymce.moxiecode.com',
276				infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/safari',
277				version : tinymce.majorVersion + "." + tinymce.minorVersion
278			};
279		},
280
281		// Internal methods
282
283		_fixWebKitSpans : function() {
284			var t = this, ed = t.editor;
285
286			if (!isOldWebKit) {
287				// Use mutator events on new WebKit
288				Event.add(ed.getDoc(), 'DOMNodeInserted', function(e) {
289					e = e.target;
290
291					if (e && e.nodeType == 1)
292						t._fixAppleSpan(e);
293				});
294			} else {
295				// Do post command processing in old WebKit since the browser crashes on Mutator events :(
296				ed.onExecCommand.add(function() {
297					each(ed.dom.select('span'), function(n) {
298						t._fixAppleSpan(n);
299					});
300
301					ed.nodeChanged();
302				});
303			}
304		},
305
306		_fixAppleSpan : function(e) {
307			var ed = this.editor, dom = ed.dom, fz = this.webKitFontSizes, fzn = this.namedFontSizes, s = ed.settings, st, p;
308
309			if (dom.getAttrib(e, 'mce_fixed'))
310				return;
311
312			// Handle Apple style spans
313			if (e.nodeName == 'SPAN' && e.className == 'Apple-style-span') {
314				st = e.style;
315
316				if (!s.convert_fonts_to_spans) {
317					if (st.fontSize) {
318						dom.setAttrib(e, 'mce_name', 'font');
319						dom.setAttrib(e, 'size', inArray(fz, st.fontSize) + 1);
320					}
321
322					if (st.fontFamily) {
323						dom.setAttrib(e, 'mce_name', 'font');
324						dom.setAttrib(e, 'face', st.fontFamily);
325					}
326
327					if (st.color) {
328						dom.setAttrib(e, 'mce_name', 'font');
329						dom.setAttrib(e, 'color', dom.toHex(st.color));
330					}
331
332					if (st.backgroundColor) {
333						dom.setAttrib(e, 'mce_name', 'font');
334						dom.setStyle(e, 'background-color', st.backgroundColor);
335					}
336				} else {
337					if (st.fontSize)
338						dom.setStyle(e, 'fontSize', fzn[inArray(fz, st.fontSize)]);
339				}
340
341				if (st.fontWeight == 'bold')
342					dom.setAttrib(e, 'mce_name', 'strong');
343
344				if (st.fontStyle == 'italic')
345					dom.setAttrib(e, 'mce_name', 'em');
346
347				if (st.textDecoration == 'underline')
348					dom.setAttrib(e, 'mce_name', 'u');
349
350				if (st.textDecoration == 'line-through')
351					dom.setAttrib(e, 'mce_name', 'strike');
352
353				if (st.verticalAlign == 'super')
354					dom.setAttrib(e, 'mce_name', 'sup');
355
356				if (st.verticalAlign == 'sub')
357					dom.setAttrib(e, 'mce_name', 'sub');
358
359				dom.setAttrib(e, 'mce_fixed', '1');
360			}
361		},
362
363		_patchSafari2x : function(ed) {
364			var t = this, setContent, getNode, dom = ed.dom, lr;
365
366			// Inline dialogs
367			if (ed.windowManager.onBeforeOpen) {
368				ed.windowManager.onBeforeOpen.add(function() {
369					r = ed.selection.getRng();
370				});
371			}
372
373			// Fake select on 2.x
374			ed.selection.select = function(n) {
375				this.getSel().setBaseAndExtent(n, 0, n, 1);
376			};
377
378			getNode = ed.selection.getNode;
379			ed.selection.getNode = function() {
380				return t.selElm || getNode.call(this);
381			};
382
383			// Fake range on Safari 2.x
384			ed.selection.getRng = function() {
385				var t = this, s = t.getSel(), d = ed.getDoc(), r, rb, ra, di;
386
387				// Fake range on Safari 2.x
388				if (s.anchorNode) {
389					r = d.createRange();
390
391					try {
392						// Setup before range
393						rb = d.createRange();
394						rb.setStart(s.anchorNode, s.anchorOffset);
395						rb.collapse(1);
396
397						// Setup after range
398						ra = d.createRange();
399						ra.setStart(s.focusNode, s.focusOffset);
400						ra.collapse(1);
401
402						// Setup start/end points by comparing locations
403						di = rb.compareBoundaryPoints(rb.START_TO_END, ra) < 0;
404						r.setStart(di ? s.anchorNode : s.focusNode, di ? s.anchorOffset : s.focusOffset);
405						r.setEnd(di ? s.focusNode : s.anchorNode, di ? s.focusOffset : s.anchorOffset);
406
407						lr = r;
408					} catch (ex) {
409						// Sometimes fails, at least we tried to do it by the book. I hope Safari 2.x will go disappear soooon!!!
410					}
411				}
412
413				return r || lr;
414			};
415
416			// Fix setContent so it works
417			setContent = ed.selection.setContent;
418			ed.selection.setContent = function(h, s) {
419				var r = this.getRng(), b;
420
421				try {
422					setContent.call(this, h, s);
423				} catch (ex) {
424					// Workaround for Safari 2.x
425					b = dom.create('body');
426					b.innerHTML = h;
427
428					each(b.childNodes, function(n) {
429						r.insertNode(n.cloneNode(true));
430					});
431				}
432			};
433		},
434
435		_insertBR : function(ed) {
436			var dom = ed.dom, s = ed.selection, r = s.getRng(), br;
437
438			// Insert BR element
439			r.insertNode(br = dom.create('br'));
440
441			// Place caret after BR
442			r.setStartAfter(br);
443			r.setEndAfter(br);
444			s.setRng(r);
445
446			// Could not place caret after BR then insert an nbsp entity and move the caret
447			if (s.getSel().focusNode == br.previousSibling) {
448				s.select(dom.insertAfter(dom.doc.createTextNode('\u00a0'), br));
449				s.collapse(1);
450			}
451
452			// Scroll to new position, scrollIntoView can't be used due to bug: http://bugs.webkit.org/show_bug.cgi?id=16117
453			ed.getWin().scrollTo(0, dom.getPos(s.getRng().startContainer).y);
454		}
455	});
456
457	// Register plugin
458	tinymce.PluginManager.add('safari', tinymce.plugins.Safari);
459})();
460