2
YUI 3.10.3 (build 2fb5187)
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
27
var EditorBase = function() {
28
EditorBase.superclass.constructor.apply(this, arguments);
29
}, LAST_CHILD = ':last-child', BODY = 'body';
31
Y.extend(EditorBase, Y.Base, {
33
* Internal reference to the Y.Frame instance
37
initializer: function() {
38
var frame = new Y.Frame({
40
title: EditorBase.STRINGS.title,
43
extracss: this.get('extracss'),
44
linkedcss: this.get('linkedcss'),
45
defaultblock: this.get('defaultblock'),
47
}).plug(Y.Plugin.ExecCommand);
50
frame.after('ready', Y.bind(this._afterFrameReady, this));
51
frame.addTarget(this);
55
this.publish('nodeChange', {
58
defaultFn: this._defNodeChangeFn
61
//this.plug(Y.Plugin.EditorPara);
63
destructor: function() {
69
* Copy certain styles from one node instance to another (used for new paragraph creation mainly)
71
* @param {Node} from The Node instance to copy the styles from
72
* @param {Node} to The Node instance to copy the styles to
74
copyStyles: function(from, to) {
76
//Don't carry the A styles
79
var styles = ['color', 'fontSize', 'fontFamily', 'backgroundColor', 'fontStyle' ],
82
Y.each(styles, function(v) {
83
newStyles[v] = from.getStyle(v);
85
if (from.ancestor('b,strong')) {
86
newStyles.fontWeight = 'bold';
88
if (from.ancestor('u')) {
89
if (!newStyles.textDecoration) {
90
newStyles.textDecoration = 'underline';
93
to.setStyles(newStyles);
96
* Holder for the selection bookmark in IE.
97
* @property _lastBookmark
102
* Resolves the e.changedNode in the nodeChange event if it comes from the document. If
103
* the event came from the document, it will get the last child of the last child of the document
104
* and return that instead.
105
* @method _resolveChangedNode
106
* @param {Node} n The node to resolve
109
_resolveChangedNode: function(n) {
110
var inst = this.getInstance(), lc, lc2, found, sel;
111
if (n && n.test(BODY)) {
112
sel = new inst.EditorSelection();
113
if (sel && sel.anchorNode) {
117
if (inst && n && n.test('html')) {
118
lc = inst.one(BODY).one(LAST_CHILD);
121
lc2 = lc.one(LAST_CHILD);
136
lc = lc.get('parentNode');
145
//Fallback to make sure a node is attached to the event
151
* The default handler for the nodeChange event.
152
* @method _defNodeChangeFn
153
* @param {Event} e The event
156
_defNodeChangeFn: function(e) {
157
var startTime = (new Date()).getTime(),
158
inst = this.getInstance(), sel,
160
cmds = {}, family, fsize, classes = [],
161
fColor = '', bColor = '', bq,
166
sel = inst.config.doc.selection.createRange();
167
if (sel.getBookmark) {
168
this._lastBookmark = sel.getBookmark();
173
e.changedNode = this._resolveChangedNode(e.changedNode);
178
* This whole method needs to be fixed and made more dynamic.
179
* Maybe static functions for the e.changeType and an object bag
180
* to walk through and filter to pass off the event to before firing..
183
switch (e.changedType) {
185
if (!e.changedNode.test('li, li *') && !e.changedEvent.shiftKey) {
186
e.changedEvent.frameEvent.preventDefault();
187
Y.log('Overriding TAB key to insert HTML: HALTING', 'info', 'editor');
189
this.execCommand('inserttext', '\t');
190
} else if (Y.UA.gecko) {
191
this.frame.exec._command('inserthtml', EditorBase.TABKEY);
192
} else if (Y.UA.ie) {
193
this.execCommand('inserthtml', EditorBase.TABKEY);
198
// Fixes #2531090 - Joins text node strings so they become one for bidi
199
if (Y.UA.webkit && e.changedNode) {
200
e.changedNode.set('innerHTML', e.changedNode.get('innerHTML'));
204
if (Y.UA.webkit && e.commands && (e.commands.indent || e.commands.outdent)) {
206
* When executing execCommand 'indent or 'outdent' Webkit applies
207
* a class to the BLOCKQUOTE that adds left/right margin to it
208
* This strips that style so it is just a normal BLOCKQUOTE
210
bq = inst.all('.webkit-indent-blockquote, blockquote');
212
bq.setStyle('margin', '');
216
changed = this.getDomPath(e.changedNode, false);
223
Y.each(changed, function(el) {
224
var tag = el.tagName.toLowerCase(),
225
cmd = EditorBase.TAG2CMD[tag], s,
226
n, family2, cls, bColor2;
232
//Bold and Italic styles
233
s = el.currentStyle || el.style;
235
if ((''+s.fontWeight) === 'normal') {
238
if ((''+s.fontWeight) === 'bold') { //Cast this to a string
242
if (s.fontWeight > 400) {
246
if (s.fontStyle === 'italic') {
250
if (s.textDecoration.indexOf('underline') > -1) {
253
if (s.textDecoration.indexOf('line-through') > -1) {
254
cmds.strikethrough = 1;
258
if (n.getStyle('fontFamily')) {
259
family2 = n.getStyle('fontFamily').split(',')[0].toLowerCase();
264
family = family.replace(/'/g, '').replace(/"/g, '');
268
fsize = EditorBase.NORMALIZE_FONTSIZE(n);
271
cls = el.className.split(' ');
272
Y.each(cls, function(v) {
273
if (v !== '' && (v.substr(0, 4) !== 'yui_')) {
278
fColor = EditorBase.FILTER_RGB(n.getStyle('color'));
279
bColor2 = EditorBase.FILTER_RGB(s.backgroundColor);
280
if (bColor2 !== 'transparent') {
281
if (bColor2 !== '') {
293
e.dompath = inst.all(changed);
294
e.classNames = classes;
297
//TODO Dont' like this, not dynamic enough..
299
e.fontFamily = family;
305
e.fontColor = fColor;
307
if (!e.backgroundColor) {
308
e.backgroundColor = bColor;
311
endTime = (new Date()).getTime();
312
Y.log('_defNodeChangeTimer 2: ' + (endTime - startTime) + 'ms', 'info', 'selection');
315
* Walk the dom tree from this node up to body, returning a reversed array of parents.
317
* @param {Node} node The Node to start from
319
getDomPath: function(node, nodeList) {
320
var domPath = [], domNode,
321
inst = this.frame.getInstance();
323
domNode = inst.Node.getDOMNode(node);
324
//return inst.all(domNode);
326
while (domNode !== null) {
328
if ((domNode === inst.config.doc.documentElement) || (domNode === inst.config.doc) || !domNode.tagName) {
333
if (!inst.DOM.inDoc(domNode)) {
338
//Check to see if we get el.nodeName and nodeType
339
if (domNode.nodeName && domNode.nodeType && (domNode.nodeType === 1)) {
340
domPath.push(domNode);
343
if (domNode === inst.config.doc.body) {
348
domNode = domNode.parentNode;
352
while (node !== null) {
353
if (node.test('html') || node.test('doc') || !node.get('tagName')) {
361
//Check to see if we get el.nodeName and nodeType
362
if (node.get('nodeName') && node.get('nodeType') && (node.get('nodeType') == 1)) {
363
domPath.push(inst.Node.getDOMNode(node));
366
if (node.test('body')) {
371
node = node.get('parentNode');
375
if (domPath.length === 0) {
376
domPath[0] = inst.config.doc.body;
380
return inst.all(domPath.reverse());
382
return domPath.reverse();
387
* After frame ready, bind mousedown & keyup listeners
388
* @method _afterFrameReady
391
_afterFrameReady: function() {
392
var inst = this.frame.getInstance();
394
this.frame.on('dom:mouseup', Y.bind(this._onFrameMouseUp, this));
395
this.frame.on('dom:mousedown', Y.bind(this._onFrameMouseDown, this));
396
this.frame.on('dom:keydown', Y.bind(this._onFrameKeyDown, this));
399
this.frame.on('dom:activate', Y.bind(this._onFrameActivate, this));
400
this.frame.on('dom:beforedeactivate', Y.bind(this._beforeFrameDeactivate, this));
402
this.frame.on('dom:keyup', Y.bind(this._onFrameKeyUp, this));
403
this.frame.on('dom:keypress', Y.bind(this._onFrameKeyPress, this));
404
this.frame.on('dom:paste', Y.bind(this._onPaste, this));
406
inst.EditorSelection.filter();
410
* Caches the current cursor position in IE.
411
* @method _beforeFrameDeactivate
414
_beforeFrameDeactivate: function(e) {
415
if (e.frameTarget.test('html')) { //Means it came from a scrollbar
418
var inst = this.getInstance(),
419
sel = inst.config.doc.selection.createRange();
421
if (sel.compareEndPoints && !sel.compareEndPoints('StartToEnd', sel)) {
422
sel.pasteHTML('<var id="yui-ie-cursor">');
426
* Moves the cached selection bookmark back so IE can place the cursor in the right place.
427
* @method _onFrameActivate
430
_onFrameActivate: function(e) {
431
if (e.frameTarget.test('html')) { //Means it came from a scrollbar
434
var inst = this.getInstance(),
435
sel = new inst.EditorSelection(),
436
range = sel.createRange(),
437
cur = inst.all('#yui-ie-cursor');
440
cur.each(function(n) {
442
if (range.moveToElementText) {
444
range.moveToElementText(n._node);
445
var moved = range.move('character', -1);
446
if (moved === -1) { //Only move up if we actually moved back.
447
range.move('character', 1);
458
* Fires nodeChange event
462
_onPaste: function(e) {
463
this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'paste', changedEvent: e.frameEvent });
466
* Fires nodeChange event
467
* @method _onFrameMouseUp
470
_onFrameMouseUp: function(e) {
471
this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'mouseup', changedEvent: e.frameEvent });
474
* Fires nodeChange event
475
* @method _onFrameMouseDown
478
_onFrameMouseDown: function(e) {
479
this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'mousedown', changedEvent: e.frameEvent });
482
* Caches a copy of the selection for key events. Only creating the selection on keydown
483
* @property _currentSelection
486
_currentSelection: null,
488
* Holds the timer for selection clearing
489
* @property _currentSelectionTimer
492
_currentSelectionTimer: null,
494
* Flag to determine if we can clear the selection or not.
495
* @property _currentSelectionClear
498
_currentSelectionClear: null,
500
* Fires nodeChange event
501
* @method _onFrameKeyDown
504
_onFrameKeyDown: function(e) {
506
if (!this._currentSelection) {
507
if (this._currentSelectionTimer) {
508
this._currentSelectionTimer.cancel();
510
this._currentSelectionTimer = Y.later(850, this, function() {
511
this._currentSelectionClear = true;
514
inst = this.frame.getInstance();
515
sel = new inst.EditorSelection(e);
517
this._currentSelection = sel;
519
sel = this._currentSelection;
522
inst = this.frame.getInstance();
523
sel = new inst.EditorSelection();
525
this._currentSelection = sel;
527
if (sel && sel.anchorNode) {
528
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keydown', changedEvent: e.frameEvent });
529
if (EditorBase.NC_KEYS[e.keyCode]) {
530
this.fire('nodeChange', {
531
changedNode: sel.anchorNode,
532
changedType: EditorBase.NC_KEYS[e.keyCode],
533
changedEvent: e.frameEvent
535
this.fire('nodeChange', {
536
changedNode: sel.anchorNode,
537
changedType: EditorBase.NC_KEYS[e.keyCode] + '-down',
538
changedEvent: e.frameEvent
544
* Fires nodeChange event
545
* @method _onFrameKeyPress
548
_onFrameKeyPress: function(e) {
549
var sel = this._currentSelection;
551
if (sel && sel.anchorNode) {
552
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keypress', changedEvent: e.frameEvent });
553
if (EditorBase.NC_KEYS[e.keyCode]) {
554
this.fire('nodeChange', {
555
changedNode: sel.anchorNode,
556
changedType: EditorBase.NC_KEYS[e.keyCode] + '-press',
557
changedEvent: e.frameEvent
563
* Fires nodeChange event for keyup on specific keys
564
* @method _onFrameKeyUp
567
_onFrameKeyUp: function(e) {
568
var inst = this.frame.getInstance(),
569
sel = new inst.EditorSelection(e);
571
if (sel && sel.anchorNode) {
572
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keyup', selection: sel, changedEvent: e.frameEvent });
573
if (EditorBase.NC_KEYS[e.keyCode]) {
574
this.fire('nodeChange', {
575
changedNode: sel.anchorNode,
576
changedType: EditorBase.NC_KEYS[e.keyCode] + '-up',
578
changedEvent: e.frameEvent
582
if (this._currentSelectionClear) {
583
this._currentSelectionClear = this._currentSelection = null;
587
* Pass through to the frame.execCommand method
588
* @method execCommand
589
* @param {String} cmd The command to pass: inserthtml, insertimage, bold
590
* @param {String} val The optional value of the command: Helvetica
591
* @return {Node/NodeList} The Node or Nodelist affected by the command. Only returns on override commands, not browser defined commands.
593
execCommand: function(cmd, val) {
594
var ret = this.frame.execCommand(cmd, val),
595
inst = this.frame.getInstance(),
596
sel = new inst.EditorSelection(), cmds = {},
597
e = { changedNode: sel.anchorNode, changedType: 'execcommand', nodes: ret };
604
e.backgroundColor = val;
617
this.fire('nodeChange', e);
622
* Get the YUI instance of the frame
623
* @method getInstance
624
* @return {YUI} The YUI instance bound to the frame.
626
getInstance: function() {
627
return this.frame.getInstance();
630
* Renders the Y.Frame to the passed node.
632
* @param {Selector/HTMLElement/Node} node The node to append the Editor to
633
* @return {EditorBase}
636
render: function(node) {
637
this.frame.set('content', this.get('content'));
638
this.frame.render(node);
642
* Focus the contentWindow of the iframe
644
* @param {Function} fn Callback function to execute after focus happens
645
* @return {EditorBase}
648
focus: function(fn) {
649
this.frame.focus(fn);
653
* Handles the showing of the Editor instance. Currently only handles the iframe
655
* @return {EditorBase}
663
* Handles the hiding of the Editor instance. Currently only handles the iframe
665
* @return {EditorBase}
673
* (Un)Filters the content of the Editor, cleaning YUI related code. //TODO better filtering
675
* @return {String} The filtered content of the Editor
677
getContent: function() {
678
var html = '', inst = this.getInstance();
679
if (inst && inst.EditorSelection) {
680
html = inst.EditorSelection.unfilter();
682
//Removing the _yuid from the objects in IE
683
html = html.replace(/ _yuid="([^>]*)"/g, '');
689
* @method NORMALIZE_FONTSIZE
690
* @description Pulls the fontSize from a node, then checks for string values (x-large, x-small)
691
* and converts them to pixel sizes. If the parsed size is different from the original, it calls
692
* node.setStyle to update the node with a pixel size for normalization.
694
NORMALIZE_FONTSIZE: function(n) {
695
var size = n.getStyle('fontSize'), oSize = size;
698
case '-webkit-xxx-large':
720
if (oSize !== size) {
721
n.setStyle('fontSize', size);
728
* @description The HTML markup to use for the tabkey
730
TABKEY: '<span class="tab"> </span>',
734
* @param String css The CSS string containing rgb(#,#,#);
735
* @description Converts an RGB color string to a hex color, example: rgb(0, 255, 0) converts to #00ff00
738
FILTER_RGB: function(css) {
739
if (css.toLowerCase().indexOf('rgb') !== -1) {
740
var exp = new RegExp("(.*?)rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)(.*?)", "gi"),
741
rgb = css.replace(exp, "$1,$2,$3,$4,$5").split(','),
744
if (rgb.length === 5) {
745
r = parseInt(rgb[1], 10).toString(16);
746
g = parseInt(rgb[2], 10).toString(16);
747
b = parseInt(rgb[3], 10).toString(16);
749
r = r.length === 1 ? '0' + r : r;
750
g = g.length === 1 ? '0' + g : g;
751
b = b.length === 1 ? '0' + b : b;
753
css = "#" + r + g + b;
761
* @description A hash table of tags to their execcomand's
769
'sup': 'superscript',
771
'img': 'insertimage',
773
'ul' : 'insertunorderedlist',
774
'ol' : 'insertorderedlist'
777
* Hash table of keys to fire a nodeChange event for.
798
* The default modules to use inside the Frame
803
USE: ['node', 'selector-css3', 'editor-selection', 'stylesheet'],
805
* The Class Name: editorBase
811
* Editor Strings. By default contains only the `title` property for the
812
* Title of frame document (default "Rich Text Editor").
818
title: 'Rich Text Editor'
822
* The content to load into the Editor Frame
826
value: '<br class="yui-cursor">',
827
setter: function(str) {
828
if (str.substr(0, 1) === "\n") {
829
Y.log('Stripping first carriage return from content before injecting', 'warn', 'editor');
833
str = '<br class="yui-cursor">';
837
str = '<br class="yui-cursor">';
840
return this.frame.set('content', str);
843
return this.frame.get('content');
847
* The value of the dir attribute on the HTML element of the frame. Default: ltr
855
* @attribute linkedcss
856
* @description An array of url's to external linked style sheets
861
setter: function(css) {
863
this.frame.set('linkedcss', css);
869
* @attribute extracss
870
* @description A string of CSS to add to the Head of the Editor
875
setter: function(css) {
877
this.frame.set('extracss', css);
883
* @attribute defaultblock
884
* @description The default tag to use for block level items, defaults to: p
893
Y.EditorBase = EditorBase;
897
* @description Fired from several mouse/key/paste event points.
898
* @param {Event.Facade} event An Event Facade object with the following specific properties added:
900
* <dt>changedEvent</dt><dd>The event that caused the nodeChange</dd>
901
* <dt>changedNode</dt><dd>The node that was interacted with</dd>
902
* <dt>changedType</dt><dd>The type of change: mousedown, mouseup, right, left, backspace, tab, enter, etc..</dd>
903
* <dt>commands</dt><dd>The list of execCommands that belong to this change and the dompath that's associated with the changedNode</dd>
904
* <dt>classNames</dt><dd>An array of classNames that are applied to the changedNode and all of it's parents</dd>
905
* <dt>dompath</dt><dd>A sorted array of node instances that make up the DOM path from the changedNode to body.</dd>
906
* <dt>backgroundColor</dt><dd>The cascaded backgroundColor of the changedNode</dd>
907
* <dt>fontColor</dt><dd>The cascaded fontColor of the changedNode</dd>
908
* <dt>fontFamily</dt><dd>The cascaded fontFamily of the changedNode</dd>
909
* <dt>fontSize</dt><dd>The cascaded fontSize of the changedNode</dd>
911
* @type {Event.Custom}
916
* @description Fired after the frame is ready.
917
* @param {Event.Facade} event An Event Facade object.
918
* @type {Event.Custom}
925
}, '3.10.3', {"requires": ["base", "frame", "node", "exec-command", "editor-selection"]});