3
Copyright 2011 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 (inst && n && n.test('html')) {
111
lc = inst.one(BODY).one(LAST_CHILD);
114
lc2 = lc.one(LAST_CHILD);
129
lc = lc.get('parentNode');
138
//Fallback to make sure a node is attached to the event
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
var inst = this.getInstance(), sel, cur,
152
btag = inst.Selection.DEFAULT_BLOCK_TAG;
156
sel = inst.config.doc.selection.createRange();
157
if (sel.getBookmark) {
158
this._lastBookmark = sel.getBookmark();
163
e.changedNode = this._resolveChangedNode(e.changedNode);
167
* This whole method needs to be fixed and made more dynamic.
168
* Maybe static functions for the e.changeType and an object bag
169
* to walk through and filter to pass off the event to before firing..
172
switch (e.changedType) {
175
if (!EditorBase.NC_KEYS[e.changedEvent.keyCode] && !e.changedEvent.shiftKey && !e.changedEvent.ctrlKey && (e.changedEvent.keyCode !== 13)) {
176
//inst.later(100, inst, inst.Selection.cleanCursor);
181
if (!e.changedNode.test('li, li *') && !e.changedEvent.shiftKey) {
182
e.changedEvent.frameEvent.preventDefault();
184
this.execCommand('inserttext', '\t');
185
} else if (Y.UA.gecko) {
186
this.frame.exec._command('inserthtml', EditorBase.TABKEY);
187
} else if (Y.UA.ie) {
188
this.execCommand('inserthtml', EditorBase.TABKEY);
193
// Fixes #2531090 - Joins text node strings so they become one for bidi
194
if (Y.UA.webkit && e.changedNode) {
195
e.changedNode.set('innerHTML', e.changedNode.get('innerHTML'));
199
if (Y.UA.webkit && e.commands && (e.commands.indent || e.commands.outdent)) {
201
* When executing execCommand 'indent or 'outdent' Webkit applies
202
* a class to the BLOCKQUOTE that adds left/right margin to it
203
* This strips that style so it is just a normal BLOCKQUOTE
205
var bq = inst.all('.webkit-indent-blockquote');
207
bq.setStyle('margin', '');
211
var changed = this.getDomPath(e.changedNode, false),
212
cmds = {}, family, fsize, classes = [],
213
fColor = '', bColor = '';
221
Y.each(changed, function(el) {
222
var tag = el.tagName.toLowerCase(),
223
cmd = EditorBase.TAG2CMD[tag];
229
//Bold and Italic styles
230
var s = el.currentStyle || el.style;
232
if ((''+s.fontWeight) == 'normal') {
235
if ((''+s.fontWeight) == 'bold') { //Cast this to a string
239
if (s.fontWeight > 400) {
243
if (s.fontStyle == 'italic') {
247
if (s.textDecoration == 'underline') {
250
if (s.textDecoration == 'line-through') {
251
cmds.strikethrough = 1;
254
var n = inst.one(el);
255
if (n.getStyle('fontFamily')) {
256
var family2 = n.getStyle('fontFamily').split(',')[0].toLowerCase();
261
family = family.replace(/'/g, '').replace(/"/g, '');
265
fsize = EditorBase.NORMALIZE_FONTSIZE(n);
268
var cls = el.className.split(' ');
270
Y.each(cls, function(v) {
271
if (v !== '' && (v.substr(0, 4) !== 'yui_')) {
276
fColor = EditorBase.FILTER_RGB(n.getStyle('color'));
277
var bColor2 = EditorBase.FILTER_RGB(s.backgroundColor);
278
if (bColor2 !== 'transparent') {
279
if (bColor2 !== '') {
291
e.dompath = inst.all(changed);
292
e.classNames = classes;
295
//TODO Dont' like this, not dynamic enough..
297
e.fontFamily = family;
303
e.fontColor = fColor;
305
if (!e.backgroundColor) {
306
e.backgroundColor = bColor;
309
var endTime = (new Date()).getTime();
312
* Walk the dom tree from this node up to body, returning a reversed array of parents.
314
* @param {Node} node The Node to start from
316
getDomPath: function(node, nodeList) {
317
var domPath = [], domNode,
318
inst = this.frame.getInstance();
320
domNode = inst.Node.getDOMNode(node);
321
//return inst.all(domNode);
323
while (domNode !== null) {
325
if ((domNode === inst.config.doc.documentElement) || (domNode === inst.config.doc) || !domNode.tagName) {
330
if (!inst.DOM.inDoc(domNode)) {
335
//Check to see if we get el.nodeName and nodeType
336
if (domNode.nodeName && domNode.nodeType && (domNode.nodeType == 1)) {
337
domPath.push(domNode);
340
if (domNode == inst.config.doc.body) {
345
domNode = domNode.parentNode;
349
while (node !== null) {
350
if (node.test('html') || node.test('doc') || !node.get('tagName')) {
358
//Check to see if we get el.nodeName and nodeType
359
if (node.get('nodeName') && node.get('nodeType') && (node.get('nodeType') == 1)) {
360
domPath.push(inst.Node.getDOMNode(node));
363
if (node.test('body')) {
368
node = node.get('parentNode');
372
if (domPath.length === 0) {
373
domPath[0] = inst.config.doc.body;
377
return inst.all(domPath.reverse());
379
return domPath.reverse();
384
* After frame ready, bind mousedown & keyup listeners
385
* @method _afterFrameReady
388
_afterFrameReady: function() {
389
var inst = this.frame.getInstance();
391
this.frame.on('dom:mouseup', Y.bind(this._onFrameMouseUp, this));
392
this.frame.on('dom:mousedown', Y.bind(this._onFrameMouseDown, this));
393
this.frame.on('dom:keydown', Y.bind(this._onFrameKeyDown, this));
396
this.frame.on('dom:activate', Y.bind(this._onFrameActivate, this));
397
this.frame.on('dom:beforedeactivate', Y.bind(this._beforeFrameDeactivate, this));
399
this.frame.on('dom:keyup', Y.bind(this._onFrameKeyUp, this));
400
this.frame.on('dom:keypress', Y.bind(this._onFrameKeyPress, this));
401
this.frame.on('dom:paste', Y.bind(this._onPaste, this));
403
inst.Selection.filter();
407
* Caches the current cursor position in IE.
408
* @method _beforeFrameDeactivate
411
_beforeFrameDeactivate: function(e) {
412
if (e.frameTarget.test('html')) { //Means it came from a scrollbar
415
var inst = this.getInstance(),
416
sel = inst.config.doc.selection.createRange();
418
if (sel.compareEndPoints && !sel.compareEndPoints('StartToEnd', sel)) {
419
sel.pasteHTML('<var id="yui-ie-cursor">');
423
* Moves the cached selection bookmark back so IE can place the cursor in the right place.
424
* @method _onFrameActivate
427
_onFrameActivate: function(e) {
428
if (e.frameTarget.test('html')) { //Means it came from a scrollbar
431
var inst = this.getInstance(),
432
sel = new inst.Selection(),
433
range = sel.createRange(),
434
cur = inst.all('#yui-ie-cursor');
437
cur.each(function(n) {
439
if (range.moveToElementText) {
441
range.moveToElementText(n._node);
442
var moved = range.move('character', -1);
443
if (moved === -1) { //Only move up if we actually moved back.
444
range.move('character', 1);
455
* Fires nodeChange event
459
_onPaste: function(e) {
460
this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'paste', changedEvent: e.frameEvent });
463
* Fires nodeChange event
464
* @method _onFrameMouseUp
467
_onFrameMouseUp: function(e) {
468
this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'mouseup', changedEvent: e.frameEvent });
471
* Fires nodeChange event
472
* @method _onFrameMouseDown
475
_onFrameMouseDown: function(e) {
476
this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'mousedown', changedEvent: e.frameEvent });
479
* Caches a copy of the selection for key events. Only creating the selection on keydown
480
* @property _currentSelection
483
_currentSelection: null,
485
* Holds the timer for selection clearing
486
* @property _currentSelectionTimer
489
_currentSelectionTimer: null,
491
* Flag to determine if we can clear the selection or not.
492
* @property _currentSelectionClear
495
_currentSelectionClear: null,
497
* Fires nodeChange event
498
* @method _onFrameKeyDown
501
_onFrameKeyDown: function(e) {
503
if (!this._currentSelection) {
504
if (this._currentSelectionTimer) {
505
this._currentSelectionTimer.cancel();
507
this._currentSelectionTimer = Y.later(850, this, function() {
508
this._currentSelectionClear = true;
511
inst = this.frame.getInstance();
512
sel = new inst.Selection(e);
514
this._currentSelection = sel;
516
sel = this._currentSelection;
519
inst = this.frame.getInstance();
520
sel = new inst.Selection();
522
this._currentSelection = sel;
524
if (sel && sel.anchorNode) {
525
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keydown', changedEvent: e.frameEvent });
526
if (EditorBase.NC_KEYS[e.keyCode]) {
527
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode], changedEvent: e.frameEvent });
528
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode] + '-down', changedEvent: e.frameEvent });
533
* Fires nodeChange event
534
* @method _onFrameKeyPress
537
_onFrameKeyPress: function(e) {
538
var sel = this._currentSelection;
540
if (sel && sel.anchorNode) {
541
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keypress', changedEvent: e.frameEvent });
542
if (EditorBase.NC_KEYS[e.keyCode]) {
543
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode] + '-press', changedEvent: e.frameEvent });
548
* Fires nodeChange event for keyup on specific keys
549
* @method _onFrameKeyUp
552
_onFrameKeyUp: function(e) {
553
var inst = this.frame.getInstance(),
554
sel = new inst.Selection(e);
556
if (sel && sel.anchorNode) {
557
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keyup', selection: sel, changedEvent: e.frameEvent });
558
if (EditorBase.NC_KEYS[e.keyCode]) {
559
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode] + '-up', selection: sel, changedEvent: e.frameEvent });
562
if (this._currentSelectionClear) {
563
this._currentSelectionClear = this._currentSelection = null;
567
* Pass through to the frame.execCommand method
568
* @method execCommand
569
* @param {String} cmd The command to pass: inserthtml, insertimage, bold
570
* @param {String} val The optional value of the command: Helvetica
571
* @return {Node/NodeList} The Node or Nodelist affected by the command. Only returns on override commands, not browser defined commands.
573
execCommand: function(cmd, val) {
574
var ret = this.frame.execCommand(cmd, val),
575
inst = this.frame.getInstance(),
576
sel = new inst.Selection(), cmds = {},
577
e = { changedNode: sel.anchorNode, changedType: 'execcommand', nodes: ret };
584
e.backgroundColor = val;
597
this.fire('nodeChange', e);
602
* Get the YUI instance of the frame
603
* @method getInstance
604
* @return {YUI} The YUI instance bound to the frame.
606
getInstance: function() {
607
return this.frame.getInstance();
610
* Renders the Y.Frame to the passed node.
612
* @param {Selector/HTMLElement/Node} node The node to append the Editor to
613
* @return {EditorBase}
616
render: function(node) {
617
this.frame.set('content', this.get('content'));
618
this.frame.render(node);
622
* Focus the contentWindow of the iframe
624
* @param {Function} fn Callback function to execute after focus happens
625
* @return {EditorBase}
628
focus: function(fn) {
629
this.frame.focus(fn);
633
* Handles the showing of the Editor instance. Currently only handles the iframe
635
* @return {EditorBase}
643
* Handles the hiding of the Editor instance. Currently only handles the iframe
645
* @return {EditorBase}
653
* (Un)Filters the content of the Editor, cleaning YUI related code. //TODO better filtering
655
* @return {String} The filtered content of the Editor
657
getContent: function() {
658
var html = '', inst = this.getInstance();
659
if (inst && inst.Selection) {
660
html = inst.Selection.unfilter();
662
//Removing the _yuid from the objects in IE
663
html = html.replace(/ _yuid="([^>]*)"/g, '');
669
* @method NORMALIZE_FONTSIZE
670
* @description Pulls the fontSize from a node, then checks for string values (x-large, x-small)
671
* and converts them to pixel sizes. If the parsed size is different from the original, it calls
672
* node.setStyle to update the node with a pixel size for normalization.
674
NORMALIZE_FONTSIZE: function(n) {
675
var size = n.getStyle('fontSize'), oSize = size;
678
case '-webkit-xxx-large':
700
if (oSize !== size) {
701
n.setStyle('fontSize', size);
708
* @description The HTML markup to use for the tabkey
710
TABKEY: '<span class="tab"> </span>',
714
* @param String css The CSS string containing rgb(#,#,#);
715
* @description Converts an RGB color string to a hex color, example: rgb(0, 255, 0) converts to #00ff00
718
FILTER_RGB: function(css) {
719
if (css.toLowerCase().indexOf('rgb') != -1) {
720
var exp = new RegExp("(.*?)rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)(.*?)", "gi");
721
var rgb = css.replace(exp, "$1,$2,$3,$4,$5").split(',');
723
if (rgb.length == 5) {
724
var r = parseInt(rgb[1], 10).toString(16);
725
var g = parseInt(rgb[2], 10).toString(16);
726
var b = parseInt(rgb[3], 10).toString(16);
728
r = r.length == 1 ? '0' + r : r;
729
g = g.length == 1 ? '0' + g : g;
730
b = b.length == 1 ? '0' + b : b;
732
css = "#" + r + g + b;
740
* @description A hash table of tags to their execcomand's
748
'sup': 'superscript',
750
'img': 'insertimage',
752
'ul' : 'insertunorderedlist',
753
'ol' : 'insertorderedlist'
756
* Hash table of keys to fire a nodeChange event for.
777
* The default modules to use inside the Frame
782
USE: ['substitute', 'node', 'selector-css3', 'selection', 'stylesheet'],
784
* The Class Name: editorBase
790
* Editor Strings. By default contains only the `title` property for the
791
* Title of frame document (default "Rich Text Editor").
797
title: 'Rich Text Editor'
801
* The content to load into the Editor Frame
805
value: '<br class="yui-cursor">',
806
setter: function(str) {
807
if (str.substr(0, 1) === "\n") {
811
str = '<br class="yui-cursor">';
815
str = '<br class="yui-cursor">';
818
return this.frame.set('content', str);
821
return this.frame.get('content');
825
* The value of the dir attribute on the HTML element of the frame. Default: ltr
833
* @attribute linkedcss
834
* @description An array of url's to external linked style sheets
839
setter: function(css) {
841
this.frame.set('linkedcss', css);
847
* @attribute extracss
848
* @description A string of CSS to add to the Head of the Editor
853
setter: function(css) {
855
this.frame.set('extracss', css);
861
* @attribute defaultblock
862
* @description The default tag to use for block level items, defaults to: p
871
Y.EditorBase = EditorBase;
875
* @description Fired from several mouse/key/paste event points.
876
* @param {Event.Facade} event An Event Facade object with the following specific properties added:
878
* <dt>changedEvent</dt><dd>The event that caused the nodeChange</dd>
879
* <dt>changedNode</dt><dd>The node that was interacted with</dd>
880
* <dt>changedType</dt><dd>The type of change: mousedown, mouseup, right, left, backspace, tab, enter, etc..</dd>
881
* <dt>commands</dt><dd>The list of execCommands that belong to this change and the dompath that's associated with the changedNode</dd>
882
* <dt>classNames</dt><dd>An array of classNames that are applied to the changedNode and all of it's parents</dd>
883
* <dt>dompath</dt><dd>A sorted array of node instances that make up the DOM path from the changedNode to body.</dd>
884
* <dt>backgroundColor</dt><dd>The cascaded backgroundColor of the changedNode</dd>
885
* <dt>fontColor</dt><dd>The cascaded fontColor of the changedNode</dd>
886
* <dt>fontFamily</dt><dd>The cascaded fontFamily of the changedNode</dd>
887
* <dt>fontSize</dt><dd>The cascaded fontSize of the changedNode</dd>
889
* @type {Event.Custom}
894
* @description Fired after the frame is ready.
895
* @param {Event.Facade} event An Event Facade object.
896
* @type {Event.Custom}
903
}, '3.4.1' ,{skinnable:false, requires:['base', 'frame', 'node', 'exec-command', 'selection']});