2 YUI 3.13.0 (build 508226d)
3 Copyright 2013 Yahoo! Inc. All rights reserved.
4 Licensed under the BSD License.
5 http://yuilibrary.com/license/
8 YUI.add('editor-base', function (Y, NAME) {
12 * Base class for Editor. Handles the business logic of Editor, no GUI involved only utility methods and events.
14 * var editor = new Y.EditorBase({
17 * editor.render('#demo');
23 * @submodule editor-base
29 EditorBase = function() {
30 EditorBase.superclass.constructor.apply(this, arguments);
31 }, LAST_CHILD = ':last-child';
33 Y.extend(EditorBase, Y.Base, {
35 * Internal reference to the Y.ContentEditable instance
40 initializer: function() {
41 this.publish('nodeChange', {
44 defaultFn: this._defNodeChangeFn
47 //this.plug(Y.Plugin.EditorPara);
49 destructor: function() {
53 * Copy certain styles from one node instance to another (used for new paragraph creation mainly)
55 * @param {Node} from The Node instance to copy the styles from
56 * @param {Node} to The Node instance to copy the styles to
58 copyStyles: function(from, to) {
60 //Don't carry the A styles
63 var styles = ['color', 'fontSize', 'fontFamily', 'backgroundColor', 'fontStyle' ],
66 Y.each(styles, function(v) {
67 newStyles[v] = from.getStyle(v);
69 if (from.ancestor('b,strong')) {
70 newStyles.fontWeight = 'bold';
72 if (from.ancestor('u')) {
73 if (!newStyles.textDecoration) {
74 newStyles.textDecoration = 'underline';
77 to.setStyles(newStyles);
80 * Holder for the selection bookmark in IE.
81 * @property _lastBookmark
86 * Resolves the e.changedNode in the nodeChange event if it comes from the document. If
87 * the event came from the document, it will get the last child of the last child of the document
88 * and return that instead.
89 * @method _resolveChangedNode
90 * @param {Node} n The node to resolve
93 _resolveChangedNode: function(n) {
94 var inst = this.getInstance(), lc, lc2, found, root = this._getRoot(), sel;
96 if (n && n.compareTo(root)) {
97 sel = new inst.EditorSelection();
98 if (sel && sel.anchorNode) {
102 if (inst && n && n.test('html')) {
103 lc = root.one(LAST_CHILD);
106 lc2 = lc.one(LAST_CHILD);
121 lc = lc.get('parentNode');
130 //Fallback to make sure a node is attached to the event
136 * Resolves the ROOT editor element.
140 _getRoot: function() {
141 return this.getInstance().EditorSelection.ROOT;
144 * The default handler for the nodeChange event.
145 * @method _defNodeChangeFn
146 * @param {Event} e The event
149 _defNodeChangeFn: function(e) {
150 var startTime = (new Date()).getTime(),
151 inst = this.getInstance(), sel,
153 cmds = {}, family, fsize, classes = [],
154 fColor = '', bColor = '', bq,
156 root = this._getRoot();
160 sel = inst.config.doc.selection.createRange();
161 if (sel.getBookmark) {
162 this._lastBookmark = sel.getBookmark();
167 e.changedNode = this._resolveChangedNode(e.changedNode);
172 * This whole method needs to be fixed and made more dynamic.
173 * Maybe static functions for the e.changeType and an object bag
174 * to walk through and filter to pass off the event to before firing..
177 switch (e.changedType) {
179 if (!e.changedNode.test('li, li *') && !e.changedEvent.shiftKey) {
180 e.changedEvent.frameEvent.preventDefault();
182 this.execCommand('inserttext', '\t');
183 } else if (Y.UA.gecko) {
184 this.frame.exec._command('inserthtml', EditorBase.TABKEY);
185 } else if (Y.UA.ie) {
186 this.execCommand('inserthtml', EditorBase.TABKEY);
191 // Fixes #2531090 - Joins text node strings so they become one for bidi
192 if (Y.UA.webkit && e.changedNode) {
193 e.changedNode.set('innerHTML', e.changedNode.get('innerHTML'));
197 if (Y.UA.webkit && e.commands && (e.commands.indent || e.commands.outdent)) {
199 * When executing execCommand 'indent or 'outdent' Webkit applies
200 * a class to the BLOCKQUOTE that adds left/right margin to it
201 * This strips that style so it is just a normal BLOCKQUOTE
203 bq = root.all('.webkit-indent-blockquote, blockquote');
205 bq.setStyle('margin', '');
209 changed = this.getDomPath(e.changedNode, false);
216 Y.each(changed, function(el) {
217 var tag = el.tagName.toLowerCase(),
218 cmd = EditorBase.TAG2CMD[tag], s,
219 n, family2, cls, bColor2;
225 //Bold and Italic styles
226 s = el.currentStyle || el.style;
228 if ((''+s.fontWeight) === 'normal') {
231 if ((''+s.fontWeight) === 'bold') { //Cast this to a string
235 if (s.fontWeight > 400) {
239 if (s.fontStyle === 'italic') {
243 if (s.textDecoration.indexOf('underline') > -1) {
246 if (s.textDecoration.indexOf('line-through') > -1) {
247 cmds.strikethrough = 1;
251 if (n.getStyle('fontFamily')) {
252 family2 = n.getStyle('fontFamily').split(',')[0].toLowerCase();
257 family = family.replace(/'/g, '').replace(/"/g, '');
261 fsize = EditorBase.NORMALIZE_FONTSIZE(n);
264 cls = el.className.split(' ');
265 Y.each(cls, function(v) {
266 if (v !== '' && (v.substr(0, 4) !== 'yui_')) {
271 fColor = EditorBase.FILTER_RGB(n.getStyle('color'));
272 bColor2 = EditorBase.FILTER_RGB(s.backgroundColor);
273 if (bColor2 !== 'transparent') {
274 if (bColor2 !== '') {
286 e.dompath = inst.all(changed);
287 e.classNames = classes;
290 //TODO Dont' like this, not dynamic enough..
292 e.fontFamily = family;
298 e.fontColor = fColor;
300 if (!e.backgroundColor) {
301 e.backgroundColor = bColor;
304 endTime = (new Date()).getTime();
307 * Walk the dom tree from this node up to body, returning a reversed array of parents.
309 * @param {Node} node The Node to start from
311 getDomPath: function(node, nodeList) {
312 var domPath = [], domNode, rootNode,
313 root = this._getRoot(),
314 inst = this.frame.getInstance();
316 domNode = inst.Node.getDOMNode(node);
317 rootNode = inst.Node.getDOMNode(root);
318 //return inst.all(domNode);
320 while (domNode !== null) {
322 if ((domNode === inst.config.doc.documentElement) || (domNode === inst.config.doc) || !domNode.tagName) {
327 if (!inst.DOM.inDoc(domNode)) {
332 //Check to see if we get el.nodeName and nodeType
333 if (domNode.nodeName && domNode.nodeType && (domNode.nodeType === 1)) {
334 domPath.push(domNode);
337 if (domNode === rootNode) {
342 domNode = domNode.parentNode;
346 while (node !== null) {
347 if (node.test('html') || node.test('doc') || !node.get('tagName')) {
355 //Check to see if we get el.nodeName and nodeType
356 if (node.get('nodeName') && node.get('nodeType') && (node.get('nodeType') == 1)) {
357 domPath.push(inst.Node.getDOMNode(node));
360 if (node.test('body')) {
365 node = node.get('parentNode');
369 if (domPath.length === 0) {
370 domPath[0] = inst.config.doc.body;
374 return inst.all(domPath.reverse());
376 return domPath.reverse();
381 * After frame ready, bind mousedown & keyup listeners
382 * @method _afterFrameReady
385 _afterFrameReady: function() {
386 var inst = this.frame.getInstance();
388 this.frame.on('dom:mouseup', Y.bind(this._onFrameMouseUp, this));
389 this.frame.on('dom:mousedown', Y.bind(this._onFrameMouseDown, this));
390 this.frame.on('dom:keydown', Y.bind(this._onFrameKeyDown, this));
393 this.frame.on('dom:activate', Y.bind(this._onFrameActivate, this));
394 this.frame.on('dom:beforedeactivate', Y.bind(this._beforeFrameDeactivate, this));
396 this.frame.on('dom:keyup', Y.bind(this._onFrameKeyUp, this));
397 this.frame.on('dom:keypress', Y.bind(this._onFrameKeyPress, this));
398 this.frame.on('dom:paste', Y.bind(this._onPaste, this));
400 inst.EditorSelection.filter();
404 * Caches the current cursor position in IE.
405 * @method _beforeFrameDeactivate
408 _beforeFrameDeactivate: function(e) {
409 if (e.frameTarget.test('html')) { //Means it came from a scrollbar
412 var inst = this.getInstance(),
413 sel = inst.config.doc.selection.createRange();
415 if (sel.compareEndPoints && !sel.compareEndPoints('StartToEnd', sel)) {
416 sel.pasteHTML('<var id="yui-ie-cursor">');
420 * Moves the cached selection bookmark back so IE can place the cursor in the right place.
421 * @method _onFrameActivate
424 _onFrameActivate: function(e) {
425 if (e.frameTarget.test('html')) { //Means it came from a scrollbar
428 var inst = this.getInstance(),
429 sel = new inst.EditorSelection(),
430 range = sel.createRange(),
431 root = this._getRoot(),
432 cur = root.all('#yui-ie-cursor');
435 cur.each(function(n) {
437 if (range.moveToElementText) {
439 range.moveToElementText(n._node);
440 var moved = range.move('character', -1);
441 if (moved === -1) { //Only move up if we actually moved back.
442 range.move('character', 1);
453 * Fires nodeChange event
457 _onPaste: function(e) {
458 this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'paste', changedEvent: e.frameEvent });
461 * Fires nodeChange event
462 * @method _onFrameMouseUp
465 _onFrameMouseUp: function(e) {
466 this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'mouseup', changedEvent: e.frameEvent });
469 * Fires nodeChange event
470 * @method _onFrameMouseDown
473 _onFrameMouseDown: function(e) {
474 this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'mousedown', changedEvent: e.frameEvent });
477 * Caches a copy of the selection for key events. Only creating the selection on keydown
478 * @property _currentSelection
481 _currentSelection: null,
483 * Holds the timer for selection clearing
484 * @property _currentSelectionTimer
487 _currentSelectionTimer: null,
489 * Flag to determine if we can clear the selection or not.
490 * @property _currentSelectionClear
493 _currentSelectionClear: null,
495 * Fires nodeChange event
496 * @method _onFrameKeyDown
499 _onFrameKeyDown: function(e) {
501 if (!this._currentSelection) {
502 if (this._currentSelectionTimer) {
503 this._currentSelectionTimer.cancel();
505 this._currentSelectionTimer = Y.later(850, this, function() {
506 this._currentSelectionClear = true;
509 inst = this.frame.getInstance();
510 sel = new inst.EditorSelection(e);
512 this._currentSelection = sel;
514 sel = this._currentSelection;
517 inst = this.frame.getInstance();
518 sel = new inst.EditorSelection();
520 this._currentSelection = sel;
522 if (sel && sel.anchorNode) {
523 this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keydown', changedEvent: e.frameEvent });
524 if (EditorBase.NC_KEYS[e.keyCode]) {
525 this.fire('nodeChange', {
526 changedNode: sel.anchorNode,
527 changedType: EditorBase.NC_KEYS[e.keyCode],
528 changedEvent: e.frameEvent
530 this.fire('nodeChange', {
531 changedNode: sel.anchorNode,
532 changedType: EditorBase.NC_KEYS[e.keyCode] + '-down',
533 changedEvent: e.frameEvent
539 * Fires nodeChange event
540 * @method _onFrameKeyPress
543 _onFrameKeyPress: function(e) {
544 var sel = this._currentSelection;
546 if (sel && sel.anchorNode) {
547 this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keypress', changedEvent: e.frameEvent });
548 if (EditorBase.NC_KEYS[e.keyCode]) {
549 this.fire('nodeChange', {
550 changedNode: sel.anchorNode,
551 changedType: EditorBase.NC_KEYS[e.keyCode] + '-press',
552 changedEvent: e.frameEvent
558 * Fires nodeChange event for keyup on specific keys
559 * @method _onFrameKeyUp
562 _onFrameKeyUp: function(e) {
563 var inst = this.frame.getInstance(),
564 sel = new inst.EditorSelection(e);
566 if (sel && sel.anchorNode) {
567 this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keyup', selection: sel, changedEvent: e.frameEvent });
568 if (EditorBase.NC_KEYS[e.keyCode]) {
569 this.fire('nodeChange', {
570 changedNode: sel.anchorNode,
571 changedType: EditorBase.NC_KEYS[e.keyCode] + '-up',
573 changedEvent: e.frameEvent
577 if (this._currentSelectionClear) {
578 this._currentSelectionClear = this._currentSelection = null;
582 * Validates linkedcss property
584 * @method _validateLinkedCSS
587 _validateLinkedCSS: function(value) {
588 return Lang.isString(value) || Lang.isArray(value);
591 * Pass through to the frame.execCommand method
592 * @method execCommand
593 * @param {String} cmd The command to pass: inserthtml, insertimage, bold
594 * @param {String} val The optional value of the command: Helvetica
595 * @return {Node/NodeList} The Node or Nodelist affected by the command. Only returns on override commands, not browser defined commands.
597 execCommand: function(cmd, val) {
598 var ret = this.frame.execCommand(cmd, val),
599 inst = this.frame.getInstance(),
600 sel = new inst.EditorSelection(), cmds = {},
601 e = { changedNode: sel.anchorNode, changedType: 'execcommand', nodes: ret };
608 e.backgroundColor = val;
621 this.fire('nodeChange', e);
626 * Get the YUI instance of the frame
627 * @method getInstance
628 * @return {YUI} The YUI instance bound to the frame.
630 getInstance: function() {
631 return this.frame.getInstance();
634 * Renders the Y.ContentEditable to the passed node.
636 * @param {Selector/HTMLElement/Node} node The node to append the Editor to
637 * @return {EditorBase}
640 render: function(node) {
641 var frame = this.frame;
644 this.plug(Y.Plugin.Frame, {
646 title: EditorBase.STRINGS.title,
648 dir: this.get('dir'),
649 extracss: this.get('extracss'),
650 linkedcss: this.get('linkedcss'),
651 defaultblock: this.get('defaultblock')
657 if (!frame.hasPlugin('exec')) {
658 frame.plug(Y.Plugin.ExecCommand);
661 frame.after('ready', Y.bind(this._afterFrameReady, this));
663 frame.addTarget(this);
665 frame.set('content', this.get('content'));
672 * Focus the contentWindow of the iframe
674 * @param {Function} fn Callback function to execute after focus happens
675 * @return {EditorBase}
678 focus: function(fn) {
679 this.frame.focus(fn);
683 * Handles the showing of the Editor instance. Currently only handles the iframe
685 * @return {EditorBase}
693 * Handles the hiding of the Editor instance. Currently only handles the iframe
695 * @return {EditorBase}
703 * (Un)Filters the content of the Editor, cleaning YUI related code. //TODO better filtering
705 * @return {String} The filtered content of the Editor
707 getContent: function() {
708 var html = '', inst = this.getInstance();
709 if (inst && inst.EditorSelection) {
710 html = inst.EditorSelection.unfilter();
712 //Removing the _yuid from the objects in IE
713 html = html.replace(/ _yuid="([^>]*)"/g, '');
719 * @method NORMALIZE_FONTSIZE
720 * @description Pulls the fontSize from a node, then checks for string values (x-large, x-small)
721 * and converts them to pixel sizes. If the parsed size is different from the original, it calls
722 * node.setStyle to update the node with a pixel size for normalization.
724 NORMALIZE_FONTSIZE: function(n) {
725 var size = n.getStyle('fontSize'), oSize = size;
728 case '-webkit-xxx-large':
750 if (oSize !== size) {
751 n.setStyle('fontSize', size);
758 * @description The HTML markup to use for the tabkey
760 TABKEY: '<span class="tab"> </span>',
764 * @param String css The CSS string containing rgb(#,#,#);
765 * @description Converts an RGB color string to a hex color, example: rgb(0, 255, 0) converts to #00ff00
768 FILTER_RGB: function(css) {
769 if (css.toLowerCase().indexOf('rgb') !== -1) {
770 var exp = new RegExp("(.*?)rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)(.*?)", "gi"),
771 rgb = css.replace(exp, "$1,$2,$3,$4,$5").split(','),
774 if (rgb.length === 5) {
775 r = parseInt(rgb[1], 10).toString(16);
776 g = parseInt(rgb[2], 10).toString(16);
777 b = parseInt(rgb[3], 10).toString(16);
779 r = r.length === 1 ? '0' + r : r;
780 g = g.length === 1 ? '0' + g : g;
781 b = b.length === 1 ? '0' + b : b;
783 css = "#" + r + g + b;
791 * @description A hash table of tags to their execcomand's
799 'sup': 'superscript',
801 'img': 'insertimage',
803 'ul' : 'insertunorderedlist',
804 'ol' : 'insertorderedlist'
807 * Hash table of keys to fire a nodeChange event for.
828 * The default modules to use inside the Frame
833 USE: ['node', 'selector-css3', 'editor-selection', 'stylesheet'],
835 * The Class Name: editorBase
841 * Editor Strings. By default contains only the `title` property for the
842 * Title of frame document (default "Rich Text Editor").
848 title: 'Rich Text Editor'
852 * The content to load into the Editor Frame
856 validator: Lang.isString,
857 value: '<br class="yui-cursor">',
858 setter: function(str) {
859 if (str.substr(0, 1) === "\n") {
863 str = '<br class="yui-cursor">';
867 str = '<br class="yui-cursor">';
870 return this.frame.set('content', str);
873 return this.frame.get('content');
877 * The value of the dir attribute on the HTML element of the frame. Default: ltr
881 validator: Lang.isString,
886 * @attribute linkedcss
887 * @description An array of url's to external linked style sheets
891 validator: '_validateLinkedCSS',
893 setter: function(css) {
895 this.frame.set('linkedcss', css);
901 * @attribute extracss
902 * @description A string of CSS to add to the Head of the Editor
906 validator: Lang.isString,
908 setter: function(css) {
910 this.frame.set('extracss', css);
916 * @attribute defaultblock
917 * @description The default tag to use for block level items, defaults to: p
921 validator: Lang.isString,
927 Y.EditorBase = EditorBase;
931 * @description Fired from several mouse/key/paste event points.
932 * @param {Event.Facade} event An Event Facade object with the following specific properties added:
934 * <dt>changedEvent</dt><dd>The event that caused the nodeChange</dd>
935 * <dt>changedNode</dt><dd>The node that was interacted with</dd>
936 * <dt>changedType</dt><dd>The type of change: mousedown, mouseup, right, left, backspace, tab, enter, etc..</dd>
937 * <dt>commands</dt><dd>The list of execCommands that belong to this change and the dompath that's associated with the changedNode</dd>
938 * <dt>classNames</dt><dd>An array of classNames that are applied to the changedNode and all of it's parents</dd>
939 * <dt>dompath</dt><dd>A sorted array of node instances that make up the DOM path from the changedNode to body.</dd>
940 * <dt>backgroundColor</dt><dd>The cascaded backgroundColor of the changedNode</dd>
941 * <dt>fontColor</dt><dd>The cascaded fontColor of the changedNode</dd>
942 * <dt>fontFamily</dt><dd>The cascaded fontFamily of the changedNode</dd>
943 * <dt>fontSize</dt><dd>The cascaded fontSize of the changedNode</dd>
945 * @type {Event.Custom}
950 * @description Fired after the frame is ready.
951 * @param {Event.Facade} event An Event Facade object.
952 * @type {Event.Custom}
959 }, '3.13.0', {"requires": ["base", "frame", "node", "exec-command", "editor-selection"]});