3
Copyright 2012 Yahoo! Inc. All rights reserved.
4
Licensed under the BSD License.
5
http://yuilibrary.com/license/
7
YUI.add('editor-base', function(Y) {
11
* Base class for Editor. Handles the business logic of Editor, no GUI involved only utility methods and events.
13
* var editor = new Y.EditorBase({
16
* editor.render('#demo');
22
* @submodule editor-base
26
var EditorBase = function() {
27
EditorBase.superclass.constructor.apply(this, arguments);
28
}, LAST_CHILD = ':last-child', BODY = 'body';
30
Y.extend(EditorBase, Y.Base, {
32
* Internal reference to the Y.Frame instance
36
initializer: function() {
37
var frame = new Y.Frame({
39
title: EditorBase.STRINGS.title,
42
extracss: this.get('extracss'),
43
linkedcss: this.get('linkedcss'),
44
defaultblock: this.get('defaultblock'),
46
}).plug(Y.Plugin.ExecCommand);
49
frame.after('ready', Y.bind(this._afterFrameReady, this));
50
frame.addTarget(this);
54
this.publish('nodeChange', {
57
defaultFn: this._defNodeChangeFn
60
//this.plug(Y.Plugin.EditorPara);
62
destructor: function() {
68
* Copy certain styles from one node instance to another (used for new paragraph creation mainly)
70
* @param {Node} from The Node instance to copy the styles from
71
* @param {Node} to The Node instance to copy the styles to
73
copyStyles: function(from, to) {
75
//Don't carry the A styles
78
var styles = ['color', 'fontSize', 'fontFamily', 'backgroundColor', 'fontStyle' ],
81
Y.each(styles, function(v) {
82
newStyles[v] = from.getStyle(v);
84
if (from.ancestor('b,strong')) {
85
newStyles.fontWeight = 'bold';
87
if (from.ancestor('u')) {
88
if (!newStyles.textDecoration) {
89
newStyles.textDecoration = 'underline';
92
to.setStyles(newStyles);
95
* Holder for the selection bookmark in IE.
96
* @property _lastBookmark
101
* Resolves the e.changedNode in the nodeChange event if it comes from the document. If
102
* the event came from the document, it will get the last child of the last child of the document
103
* and return that instead.
104
* @method _resolveChangedNode
105
* @param {Node} n The node to resolve
108
_resolveChangedNode: function(n) {
109
var inst = this.getInstance(), lc, lc2, found;
110
if (n && n.test(BODY)) {
111
var sel = new inst.EditorSelection();
112
if (sel && sel.anchorNode) {
116
if (inst && n && n.test('html')) {
117
lc = inst.one(BODY).one(LAST_CHILD);
120
lc2 = lc.one(LAST_CHILD);
135
lc = lc.get('parentNode');
144
//Fallback to make sure a node is attached to the event
150
* The default handler for the nodeChange event.
151
* @method _defNodeChangeFn
152
* @param {Event} e The event
155
_defNodeChangeFn: function(e) {
156
var startTime = (new Date()).getTime();
157
//Y.log('Default nodeChange function: ' + e.changedType, 'info', 'editor');
158
var inst = this.getInstance(), sel, cur,
159
btag = inst.EditorSelection.DEFAULT_BLOCK_TAG;
163
sel = inst.config.doc.selection.createRange();
164
if (sel.getBookmark) {
165
this._lastBookmark = sel.getBookmark();
170
e.changedNode = this._resolveChangedNode(e.changedNode);
175
* This whole method needs to be fixed and made more dynamic.
176
* Maybe static functions for the e.changeType and an object bag
177
* to walk through and filter to pass off the event to before firing..
180
switch (e.changedType) {
183
if (!EditorBase.NC_KEYS[e.changedEvent.keyCode] && !e.changedEvent.shiftKey && !e.changedEvent.ctrlKey && (e.changedEvent.keyCode !== 13)) {
184
//inst.later(100, inst, inst.EditorSelection.cleanCursor);
189
if (!e.changedNode.test('li, li *') && !e.changedEvent.shiftKey) {
190
e.changedEvent.frameEvent.preventDefault();
191
Y.log('Overriding TAB key to insert HTML: HALTING', 'info', 'editor');
193
this.execCommand('inserttext', '\t');
194
} else if (Y.UA.gecko) {
195
this.frame.exec._command('inserthtml', EditorBase.TABKEY);
196
} else if (Y.UA.ie) {
197
this.execCommand('inserthtml', EditorBase.TABKEY);
202
// Fixes #2531090 - Joins text node strings so they become one for bidi
203
if (Y.UA.webkit && e.changedNode) {
204
e.changedNode.set('innerHTML', e.changedNode.get('innerHTML'));
208
if (Y.UA.webkit && e.commands && (e.commands.indent || e.commands.outdent)) {
210
* When executing execCommand 'indent or 'outdent' Webkit applies
211
* a class to the BLOCKQUOTE that adds left/right margin to it
212
* This strips that style so it is just a normal BLOCKQUOTE
214
var bq = inst.all('.webkit-indent-blockquote');
216
bq.setStyle('margin', '');
220
var changed = this.getDomPath(e.changedNode, false),
221
cmds = {}, family, fsize, classes = [],
222
fColor = '', bColor = '';
230
Y.each(changed, function(el) {
231
var tag = el.tagName.toLowerCase(),
232
cmd = EditorBase.TAG2CMD[tag];
238
//Bold and Italic styles
239
var s = el.currentStyle || el.style;
241
if ((''+s.fontWeight) == 'normal') {
244
if ((''+s.fontWeight) == 'bold') { //Cast this to a string
248
if (s.fontWeight > 400) {
252
if (s.fontStyle == 'italic') {
256
if (s.textDecoration == 'underline') {
259
if (s.textDecoration == 'line-through') {
260
cmds.strikethrough = 1;
263
var n = inst.one(el);
264
if (n.getStyle('fontFamily')) {
265
var family2 = n.getStyle('fontFamily').split(',')[0].toLowerCase();
270
family = family.replace(/'/g, '').replace(/"/g, '');
274
fsize = EditorBase.NORMALIZE_FONTSIZE(n);
277
var cls = el.className.split(' ');
279
Y.each(cls, function(v) {
280
if (v !== '' && (v.substr(0, 4) !== 'yui_')) {
285
fColor = EditorBase.FILTER_RGB(n.getStyle('color'));
286
var bColor2 = EditorBase.FILTER_RGB(s.backgroundColor);
287
if (bColor2 !== 'transparent') {
288
if (bColor2 !== '') {
300
e.dompath = inst.all(changed);
301
e.classNames = classes;
304
//TODO Dont' like this, not dynamic enough..
306
e.fontFamily = family;
312
e.fontColor = fColor;
314
if (!e.backgroundColor) {
315
e.backgroundColor = bColor;
318
var endTime = (new Date()).getTime();
319
Y.log('_defNodeChangeTimer 2: ' + (endTime - startTime) + 'ms', 'info', 'selection');
322
* Walk the dom tree from this node up to body, returning a reversed array of parents.
324
* @param {Node} node The Node to start from
326
getDomPath: function(node, nodeList) {
327
var domPath = [], domNode,
328
inst = this.frame.getInstance();
330
domNode = inst.Node.getDOMNode(node);
331
//return inst.all(domNode);
333
while (domNode !== null) {
335
if ((domNode === inst.config.doc.documentElement) || (domNode === inst.config.doc) || !domNode.tagName) {
340
if (!inst.DOM.inDoc(domNode)) {
345
//Check to see if we get el.nodeName and nodeType
346
if (domNode.nodeName && domNode.nodeType && (domNode.nodeType == 1)) {
347
domPath.push(domNode);
350
if (domNode == inst.config.doc.body) {
355
domNode = domNode.parentNode;
359
while (node !== null) {
360
if (node.test('html') || node.test('doc') || !node.get('tagName')) {
368
//Check to see if we get el.nodeName and nodeType
369
if (node.get('nodeName') && node.get('nodeType') && (node.get('nodeType') == 1)) {
370
domPath.push(inst.Node.getDOMNode(node));
373
if (node.test('body')) {
378
node = node.get('parentNode');
382
if (domPath.length === 0) {
383
domPath[0] = inst.config.doc.body;
387
return inst.all(domPath.reverse());
389
return domPath.reverse();
394
* After frame ready, bind mousedown & keyup listeners
395
* @method _afterFrameReady
398
_afterFrameReady: function() {
399
var inst = this.frame.getInstance();
401
this.frame.on('dom:mouseup', Y.bind(this._onFrameMouseUp, this));
402
this.frame.on('dom:mousedown', Y.bind(this._onFrameMouseDown, this));
403
this.frame.on('dom:keydown', Y.bind(this._onFrameKeyDown, this));
406
this.frame.on('dom:activate', Y.bind(this._onFrameActivate, this));
407
this.frame.on('dom:beforedeactivate', Y.bind(this._beforeFrameDeactivate, this));
409
this.frame.on('dom:keyup', Y.bind(this._onFrameKeyUp, this));
410
this.frame.on('dom:keypress', Y.bind(this._onFrameKeyPress, this));
411
this.frame.on('dom:paste', Y.bind(this._onPaste, this));
413
inst.EditorSelection.filter();
417
* Caches the current cursor position in IE.
418
* @method _beforeFrameDeactivate
421
_beforeFrameDeactivate: function(e) {
422
if (e.frameTarget.test('html')) { //Means it came from a scrollbar
425
var inst = this.getInstance(),
426
sel = inst.config.doc.selection.createRange();
428
if (sel.compareEndPoints && !sel.compareEndPoints('StartToEnd', sel)) {
429
sel.pasteHTML('<var id="yui-ie-cursor">');
433
* Moves the cached selection bookmark back so IE can place the cursor in the right place.
434
* @method _onFrameActivate
437
_onFrameActivate: function(e) {
438
if (e.frameTarget.test('html')) { //Means it came from a scrollbar
441
var inst = this.getInstance(),
442
sel = new inst.EditorSelection(),
443
range = sel.createRange(),
444
cur = inst.all('#yui-ie-cursor');
447
cur.each(function(n) {
449
if (range.moveToElementText) {
451
range.moveToElementText(n._node);
452
var moved = range.move('character', -1);
453
if (moved === -1) { //Only move up if we actually moved back.
454
range.move('character', 1);
465
* Fires nodeChange event
469
_onPaste: function(e) {
470
this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'paste', changedEvent: e.frameEvent });
473
* Fires nodeChange event
474
* @method _onFrameMouseUp
477
_onFrameMouseUp: function(e) {
478
this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'mouseup', changedEvent: e.frameEvent });
481
* Fires nodeChange event
482
* @method _onFrameMouseDown
485
_onFrameMouseDown: function(e) {
486
this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'mousedown', changedEvent: e.frameEvent });
489
* Caches a copy of the selection for key events. Only creating the selection on keydown
490
* @property _currentSelection
493
_currentSelection: null,
495
* Holds the timer for selection clearing
496
* @property _currentSelectionTimer
499
_currentSelectionTimer: null,
501
* Flag to determine if we can clear the selection or not.
502
* @property _currentSelectionClear
505
_currentSelectionClear: null,
507
* Fires nodeChange event
508
* @method _onFrameKeyDown
511
_onFrameKeyDown: function(e) {
513
if (!this._currentSelection) {
514
if (this._currentSelectionTimer) {
515
this._currentSelectionTimer.cancel();
517
this._currentSelectionTimer = Y.later(850, this, function() {
518
this._currentSelectionClear = true;
521
inst = this.frame.getInstance();
522
sel = new inst.EditorSelection(e);
524
this._currentSelection = sel;
526
sel = this._currentSelection;
529
inst = this.frame.getInstance();
530
sel = new inst.EditorSelection();
532
this._currentSelection = sel;
534
if (sel && sel.anchorNode) {
535
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keydown', changedEvent: e.frameEvent });
536
if (EditorBase.NC_KEYS[e.keyCode]) {
537
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode], changedEvent: e.frameEvent });
538
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode] + '-down', changedEvent: e.frameEvent });
543
* Fires nodeChange event
544
* @method _onFrameKeyPress
547
_onFrameKeyPress: function(e) {
548
var sel = this._currentSelection;
550
if (sel && sel.anchorNode) {
551
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keypress', changedEvent: e.frameEvent });
552
if (EditorBase.NC_KEYS[e.keyCode]) {
553
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode] + '-press', 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', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode] + '-up', selection: sel, changedEvent: e.frameEvent });
572
if (this._currentSelectionClear) {
573
this._currentSelectionClear = this._currentSelection = null;
577
* Pass through to the frame.execCommand method
578
* @method execCommand
579
* @param {String} cmd The command to pass: inserthtml, insertimage, bold
580
* @param {String} val The optional value of the command: Helvetica
581
* @return {Node/NodeList} The Node or Nodelist affected by the command. Only returns on override commands, not browser defined commands.
583
execCommand: function(cmd, val) {
584
var ret = this.frame.execCommand(cmd, val),
585
inst = this.frame.getInstance(),
586
sel = new inst.EditorSelection(), cmds = {},
587
e = { changedNode: sel.anchorNode, changedType: 'execcommand', nodes: ret };
594
e.backgroundColor = val;
607
this.fire('nodeChange', e);
612
* Get the YUI instance of the frame
613
* @method getInstance
614
* @return {YUI} The YUI instance bound to the frame.
616
getInstance: function() {
617
return this.frame.getInstance();
620
* Renders the Y.Frame to the passed node.
622
* @param {Selector/HTMLElement/Node} node The node to append the Editor to
623
* @return {EditorBase}
626
render: function(node) {
627
this.frame.set('content', this.get('content'));
628
this.frame.render(node);
632
* Focus the contentWindow of the iframe
634
* @param {Function} fn Callback function to execute after focus happens
635
* @return {EditorBase}
638
focus: function(fn) {
639
this.frame.focus(fn);
643
* Handles the showing of the Editor instance. Currently only handles the iframe
645
* @return {EditorBase}
653
* Handles the hiding of the Editor instance. Currently only handles the iframe
655
* @return {EditorBase}
663
* (Un)Filters the content of the Editor, cleaning YUI related code. //TODO better filtering
665
* @return {String} The filtered content of the Editor
667
getContent: function() {
668
var html = '', inst = this.getInstance();
669
if (inst && inst.EditorSelection) {
670
html = inst.EditorSelection.unfilter();
672
//Removing the _yuid from the objects in IE
673
html = html.replace(/ _yuid="([^>]*)"/g, '');
679
* @method NORMALIZE_FONTSIZE
680
* @description Pulls the fontSize from a node, then checks for string values (x-large, x-small)
681
* and converts them to pixel sizes. If the parsed size is different from the original, it calls
682
* node.setStyle to update the node with a pixel size for normalization.
684
NORMALIZE_FONTSIZE: function(n) {
685
var size = n.getStyle('fontSize'), oSize = size;
688
case '-webkit-xxx-large':
710
if (oSize !== size) {
711
n.setStyle('fontSize', size);
718
* @description The HTML markup to use for the tabkey
720
TABKEY: '<span class="tab"> </span>',
724
* @param String css The CSS string containing rgb(#,#,#);
725
* @description Converts an RGB color string to a hex color, example: rgb(0, 255, 0) converts to #00ff00
728
FILTER_RGB: function(css) {
729
if (css.toLowerCase().indexOf('rgb') != -1) {
730
var exp = new RegExp("(.*?)rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)(.*?)", "gi");
731
var rgb = css.replace(exp, "$1,$2,$3,$4,$5").split(',');
733
if (rgb.length == 5) {
734
var r = parseInt(rgb[1], 10).toString(16);
735
var g = parseInt(rgb[2], 10).toString(16);
736
var b = parseInt(rgb[3], 10).toString(16);
738
r = r.length == 1 ? '0' + r : r;
739
g = g.length == 1 ? '0' + g : g;
740
b = b.length == 1 ? '0' + b : b;
742
css = "#" + r + g + b;
750
* @description A hash table of tags to their execcomand's
758
'sup': 'superscript',
760
'img': 'insertimage',
762
'ul' : 'insertunorderedlist',
763
'ol' : 'insertorderedlist'
766
* Hash table of keys to fire a nodeChange event for.
787
* The default modules to use inside the Frame
792
USE: ['substitute', 'node', 'selector-css3', 'editor-selection', 'stylesheet'],
794
* The Class Name: editorBase
800
* Editor Strings. By default contains only the `title` property for the
801
* Title of frame document (default "Rich Text Editor").
807
title: 'Rich Text Editor'
811
* The content to load into the Editor Frame
815
value: '<br class="yui-cursor">',
816
setter: function(str) {
817
if (str.substr(0, 1) === "\n") {
818
Y.log('Stripping first carriage return from content before injecting', 'warn', 'editor');
822
str = '<br class="yui-cursor">';
826
str = '<br class="yui-cursor">';
829
return this.frame.set('content', str);
832
return this.frame.get('content');
836
* The value of the dir attribute on the HTML element of the frame. Default: ltr
844
* @attribute linkedcss
845
* @description An array of url's to external linked style sheets
850
setter: function(css) {
852
this.frame.set('linkedcss', css);
858
* @attribute extracss
859
* @description A string of CSS to add to the Head of the Editor
864
setter: function(css) {
866
this.frame.set('extracss', css);
872
* @attribute defaultblock
873
* @description The default tag to use for block level items, defaults to: p
882
Y.EditorBase = EditorBase;
886
* @description Fired from several mouse/key/paste event points.
887
* @param {Event.Facade} event An Event Facade object with the following specific properties added:
889
* <dt>changedEvent</dt><dd>The event that caused the nodeChange</dd>
890
* <dt>changedNode</dt><dd>The node that was interacted with</dd>
891
* <dt>changedType</dt><dd>The type of change: mousedown, mouseup, right, left, backspace, tab, enter, etc..</dd>
892
* <dt>commands</dt><dd>The list of execCommands that belong to this change and the dompath that's associated with the changedNode</dd>
893
* <dt>classNames</dt><dd>An array of classNames that are applied to the changedNode and all of it's parents</dd>
894
* <dt>dompath</dt><dd>A sorted array of node instances that make up the DOM path from the changedNode to body.</dd>
895
* <dt>backgroundColor</dt><dd>The cascaded backgroundColor of the changedNode</dd>
896
* <dt>fontColor</dt><dd>The cascaded fontColor of the changedNode</dd>
897
* <dt>fontFamily</dt><dd>The cascaded fontFamily of the changedNode</dd>
898
* <dt>fontSize</dt><dd>The cascaded fontSize of the changedNode</dd>
900
* @type {Event.Custom}
905
* @description Fired after the frame is ready.
906
* @param {Event.Facade} event An Event Facade object.
907
* @type {Event.Custom}
914
}, '3.5.1' ,{skinnable:false, requires:['base', 'frame', 'node', 'exec-command', 'editor-selection']});