1
/* YUI 3.9.1 (build 5852) Copyright 2013 Yahoo! Inc. http://yuilibrary.com/license/ */
2
YUI.add('editor-base', function (Y, NAME) {
6
* Base class for Editor. Handles the business logic of Editor, no GUI involved only utility methods and events.
8
* var editor = new Y.EditorBase({
11
* editor.render('#demo');
17
* @submodule editor-base
21
var EditorBase = function() {
22
EditorBase.superclass.constructor.apply(this, arguments);
23
}, LAST_CHILD = ':last-child', BODY = 'body';
25
Y.extend(EditorBase, Y.Base, {
27
* Internal reference to the Y.Frame instance
31
initializer: function() {
32
var frame = new Y.Frame({
34
title: EditorBase.STRINGS.title,
37
extracss: this.get('extracss'),
38
linkedcss: this.get('linkedcss'),
39
defaultblock: this.get('defaultblock'),
41
}).plug(Y.Plugin.ExecCommand);
44
frame.after('ready', Y.bind(this._afterFrameReady, this));
45
frame.addTarget(this);
49
this.publish('nodeChange', {
52
defaultFn: this._defNodeChangeFn
55
//this.plug(Y.Plugin.EditorPara);
57
destructor: function() {
63
* Copy certain styles from one node instance to another (used for new paragraph creation mainly)
65
* @param {Node} from The Node instance to copy the styles from
66
* @param {Node} to The Node instance to copy the styles to
68
copyStyles: function(from, to) {
70
//Don't carry the A styles
73
var styles = ['color', 'fontSize', 'fontFamily', 'backgroundColor', 'fontStyle' ],
76
Y.each(styles, function(v) {
77
newStyles[v] = from.getStyle(v);
79
if (from.ancestor('b,strong')) {
80
newStyles.fontWeight = 'bold';
82
if (from.ancestor('u')) {
83
if (!newStyles.textDecoration) {
84
newStyles.textDecoration = 'underline';
87
to.setStyles(newStyles);
90
* Holder for the selection bookmark in IE.
91
* @property _lastBookmark
96
* Resolves the e.changedNode in the nodeChange event if it comes from the document. If
97
* the event came from the document, it will get the last child of the last child of the document
98
* and return that instead.
99
* @method _resolveChangedNode
100
* @param {Node} n The node to resolve
103
_resolveChangedNode: function(n) {
104
var inst = this.getInstance(), lc, lc2, found, sel;
105
if (n && n.test(BODY)) {
106
sel = new inst.EditorSelection();
107
if (sel && sel.anchorNode) {
111
if (inst && n && n.test('html')) {
112
lc = inst.one(BODY).one(LAST_CHILD);
115
lc2 = lc.one(LAST_CHILD);
130
lc = lc.get('parentNode');
139
//Fallback to make sure a node is attached to the event
145
* The default handler for the nodeChange event.
146
* @method _defNodeChangeFn
147
* @param {Event} e The event
150
_defNodeChangeFn: function(e) {
151
var startTime = (new Date()).getTime(),
152
inst = this.getInstance(), sel,
154
cmds = {}, family, fsize, classes = [],
155
fColor = '', bColor = '', bq,
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();
181
Y.log('Overriding TAB key to insert HTML: HALTING', 'info', 'editor');
183
this.execCommand('inserttext', '\t');
184
} else if (Y.UA.gecko) {
185
this.frame.exec._command('inserthtml', EditorBase.TABKEY);
186
} else if (Y.UA.ie) {
187
this.execCommand('inserthtml', EditorBase.TABKEY);
192
// Fixes #2531090 - Joins text node strings so they become one for bidi
193
if (Y.UA.webkit && e.changedNode) {
194
e.changedNode.set('innerHTML', e.changedNode.get('innerHTML'));
198
if (Y.UA.webkit && e.commands && (e.commands.indent || e.commands.outdent)) {
200
* When executing execCommand 'indent or 'outdent' Webkit applies
201
* a class to the BLOCKQUOTE that adds left/right margin to it
202
* This strips that style so it is just a normal BLOCKQUOTE
204
bq = inst.all('.webkit-indent-blockquote, blockquote');
206
bq.setStyle('margin', '');
210
changed = this.getDomPath(e.changedNode, false);
217
Y.each(changed, function(el) {
218
var tag = el.tagName.toLowerCase(),
219
cmd = EditorBase.TAG2CMD[tag], s,
220
n, family2, cls, bColor2;
226
//Bold and Italic styles
227
s = el.currentStyle || el.style;
229
if ((''+s.fontWeight) === 'normal') {
232
if ((''+s.fontWeight) === 'bold') { //Cast this to a string
236
if (s.fontWeight > 400) {
240
if (s.fontStyle === 'italic') {
244
if (s.textDecoration.indexOf('underline') > -1) {
247
if (s.textDecoration.indexOf('line-through') > -1) {
248
cmds.strikethrough = 1;
252
if (n.getStyle('fontFamily')) {
253
family2 = n.getStyle('fontFamily').split(',')[0].toLowerCase();
258
family = family.replace(/'/g, '').replace(/"/g, '');
262
fsize = EditorBase.NORMALIZE_FONTSIZE(n);
265
cls = el.className.split(' ');
266
Y.each(cls, function(v) {
267
if (v !== '' && (v.substr(0, 4) !== 'yui_')) {
272
fColor = EditorBase.FILTER_RGB(n.getStyle('color'));
273
bColor2 = EditorBase.FILTER_RGB(s.backgroundColor);
274
if (bColor2 !== 'transparent') {
275
if (bColor2 !== '') {
287
e.dompath = inst.all(changed);
288
e.classNames = classes;
291
//TODO Dont' like this, not dynamic enough..
293
e.fontFamily = family;
299
e.fontColor = fColor;
301
if (!e.backgroundColor) {
302
e.backgroundColor = bColor;
305
endTime = (new Date()).getTime();
306
Y.log('_defNodeChangeTimer 2: ' + (endTime - startTime) + 'ms', 'info', 'selection');
309
* Walk the dom tree from this node up to body, returning a reversed array of parents.
311
* @param {Node} node The Node to start from
313
getDomPath: function(node, nodeList) {
314
var domPath = [], domNode,
315
inst = this.frame.getInstance();
317
domNode = inst.Node.getDOMNode(node);
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 === inst.config.doc.body) {
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
cur = inst.all('#yui-ie-cursor');
434
cur.each(function(n) {
436
if (range.moveToElementText) {
438
range.moveToElementText(n._node);
439
var moved = range.move('character', -1);
440
if (moved === -1) { //Only move up if we actually moved back.
441
range.move('character', 1);
452
* Fires nodeChange event
456
_onPaste: function(e) {
457
this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'paste', changedEvent: e.frameEvent });
460
* Fires nodeChange event
461
* @method _onFrameMouseUp
464
_onFrameMouseUp: function(e) {
465
this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'mouseup', changedEvent: e.frameEvent });
468
* Fires nodeChange event
469
* @method _onFrameMouseDown
472
_onFrameMouseDown: function(e) {
473
this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'mousedown', changedEvent: e.frameEvent });
476
* Caches a copy of the selection for key events. Only creating the selection on keydown
477
* @property _currentSelection
480
_currentSelection: null,
482
* Holds the timer for selection clearing
483
* @property _currentSelectionTimer
486
_currentSelectionTimer: null,
488
* Flag to determine if we can clear the selection or not.
489
* @property _currentSelectionClear
492
_currentSelectionClear: null,
494
* Fires nodeChange event
495
* @method _onFrameKeyDown
498
_onFrameKeyDown: function(e) {
500
if (!this._currentSelection) {
501
if (this._currentSelectionTimer) {
502
this._currentSelectionTimer.cancel();
504
this._currentSelectionTimer = Y.later(850, this, function() {
505
this._currentSelectionClear = true;
508
inst = this.frame.getInstance();
509
sel = new inst.EditorSelection(e);
511
this._currentSelection = sel;
513
sel = this._currentSelection;
516
inst = this.frame.getInstance();
517
sel = new inst.EditorSelection();
519
this._currentSelection = sel;
521
if (sel && sel.anchorNode) {
522
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keydown', changedEvent: e.frameEvent });
523
if (EditorBase.NC_KEYS[e.keyCode]) {
524
this.fire('nodeChange', {
525
changedNode: sel.anchorNode,
526
changedType: EditorBase.NC_KEYS[e.keyCode],
527
changedEvent: e.frameEvent
529
this.fire('nodeChange', {
530
changedNode: sel.anchorNode,
531
changedType: EditorBase.NC_KEYS[e.keyCode] + '-down',
532
changedEvent: e.frameEvent
538
* Fires nodeChange event
539
* @method _onFrameKeyPress
542
_onFrameKeyPress: function(e) {
543
var sel = this._currentSelection;
545
if (sel && sel.anchorNode) {
546
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keypress', changedEvent: e.frameEvent });
547
if (EditorBase.NC_KEYS[e.keyCode]) {
548
this.fire('nodeChange', {
549
changedNode: sel.anchorNode,
550
changedType: EditorBase.NC_KEYS[e.keyCode] + '-press',
551
changedEvent: e.frameEvent
557
* Fires nodeChange event for keyup on specific keys
558
* @method _onFrameKeyUp
561
_onFrameKeyUp: function(e) {
562
var inst = this.frame.getInstance(),
563
sel = new inst.EditorSelection(e);
565
if (sel && sel.anchorNode) {
566
this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keyup', selection: sel, changedEvent: e.frameEvent });
567
if (EditorBase.NC_KEYS[e.keyCode]) {
568
this.fire('nodeChange', {
569
changedNode: sel.anchorNode,
570
changedType: EditorBase.NC_KEYS[e.keyCode] + '-up',
572
changedEvent: e.frameEvent
576
if (this._currentSelectionClear) {
577
this._currentSelectionClear = this._currentSelection = null;
581
* Pass through to the frame.execCommand method
582
* @method execCommand
583
* @param {String} cmd The command to pass: inserthtml, insertimage, bold
584
* @param {String} val The optional value of the command: Helvetica
585
* @return {Node/NodeList} The Node or Nodelist affected by the command. Only returns on override commands, not browser defined commands.
587
execCommand: function(cmd, val) {
588
var ret = this.frame.execCommand(cmd, val),
589
inst = this.frame.getInstance(),
590
sel = new inst.EditorSelection(), cmds = {},
591
e = { changedNode: sel.anchorNode, changedType: 'execcommand', nodes: ret };
598
e.backgroundColor = val;
611
this.fire('nodeChange', e);
616
* Get the YUI instance of the frame
617
* @method getInstance
618
* @return {YUI} The YUI instance bound to the frame.
620
getInstance: function() {
621
return this.frame.getInstance();
624
* Renders the Y.Frame to the passed node.
626
* @param {Selector/HTMLElement/Node} node The node to append the Editor to
627
* @return {EditorBase}
630
render: function(node) {
631
this.frame.set('content', this.get('content'));
632
this.frame.render(node);
636
* Focus the contentWindow of the iframe
638
* @param {Function} fn Callback function to execute after focus happens
639
* @return {EditorBase}
642
focus: function(fn) {
643
this.frame.focus(fn);
647
* Handles the showing of the Editor instance. Currently only handles the iframe
649
* @return {EditorBase}
657
* Handles the hiding of the Editor instance. Currently only handles the iframe
659
* @return {EditorBase}
667
* (Un)Filters the content of the Editor, cleaning YUI related code. //TODO better filtering
669
* @return {String} The filtered content of the Editor
671
getContent: function() {
672
var html = '', inst = this.getInstance();
673
if (inst && inst.EditorSelection) {
674
html = inst.EditorSelection.unfilter();
676
//Removing the _yuid from the objects in IE
677
html = html.replace(/ _yuid="([^>]*)"/g, '');
683
* @method NORMALIZE_FONTSIZE
684
* @description Pulls the fontSize from a node, then checks for string values (x-large, x-small)
685
* and converts them to pixel sizes. If the parsed size is different from the original, it calls
686
* node.setStyle to update the node with a pixel size for normalization.
688
NORMALIZE_FONTSIZE: function(n) {
689
var size = n.getStyle('fontSize'), oSize = size;
692
case '-webkit-xxx-large':
714
if (oSize !== size) {
715
n.setStyle('fontSize', size);
722
* @description The HTML markup to use for the tabkey
724
TABKEY: '<span class="tab"> </span>',
728
* @param String css The CSS string containing rgb(#,#,#);
729
* @description Converts an RGB color string to a hex color, example: rgb(0, 255, 0) converts to #00ff00
732
FILTER_RGB: function(css) {
733
if (css.toLowerCase().indexOf('rgb') !== -1) {
734
var exp = new RegExp("(.*?)rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)(.*?)", "gi"),
735
rgb = css.replace(exp, "$1,$2,$3,$4,$5").split(','),
738
if (rgb.length === 5) {
739
r = parseInt(rgb[1], 10).toString(16);
740
g = parseInt(rgb[2], 10).toString(16);
741
b = parseInt(rgb[3], 10).toString(16);
743
r = r.length === 1 ? '0' + r : r;
744
g = g.length === 1 ? '0' + g : g;
745
b = b.length === 1 ? '0' + b : b;
747
css = "#" + r + g + b;
755
* @description A hash table of tags to their execcomand's
763
'sup': 'superscript',
765
'img': 'insertimage',
767
'ul' : 'insertunorderedlist',
768
'ol' : 'insertorderedlist'
771
* Hash table of keys to fire a nodeChange event for.
792
* The default modules to use inside the Frame
797
USE: ['node', 'selector-css3', 'editor-selection', 'stylesheet'],
799
* The Class Name: editorBase
805
* Editor Strings. By default contains only the `title` property for the
806
* Title of frame document (default "Rich Text Editor").
812
title: 'Rich Text Editor'
816
* The content to load into the Editor Frame
820
value: '<br class="yui-cursor">',
821
setter: function(str) {
822
if (str.substr(0, 1) === "\n") {
823
Y.log('Stripping first carriage return from content before injecting', 'warn', 'editor');
827
str = '<br class="yui-cursor">';
831
str = '<br class="yui-cursor">';
834
return this.frame.set('content', str);
837
return this.frame.get('content');
841
* The value of the dir attribute on the HTML element of the frame. Default: ltr
849
* @attribute linkedcss
850
* @description An array of url's to external linked style sheets
855
setter: function(css) {
857
this.frame.set('linkedcss', css);
863
* @attribute extracss
864
* @description A string of CSS to add to the Head of the Editor
869
setter: function(css) {
871
this.frame.set('extracss', css);
877
* @attribute defaultblock
878
* @description The default tag to use for block level items, defaults to: p
887
Y.EditorBase = EditorBase;
891
* @description Fired from several mouse/key/paste event points.
892
* @param {Event.Facade} event An Event Facade object with the following specific properties added:
894
* <dt>changedEvent</dt><dd>The event that caused the nodeChange</dd>
895
* <dt>changedNode</dt><dd>The node that was interacted with</dd>
896
* <dt>changedType</dt><dd>The type of change: mousedown, mouseup, right, left, backspace, tab, enter, etc..</dd>
897
* <dt>commands</dt><dd>The list of execCommands that belong to this change and the dompath that's associated with the changedNode</dd>
898
* <dt>classNames</dt><dd>An array of classNames that are applied to the changedNode and all of it's parents</dd>
899
* <dt>dompath</dt><dd>A sorted array of node instances that make up the DOM path from the changedNode to body.</dd>
900
* <dt>backgroundColor</dt><dd>The cascaded backgroundColor of the changedNode</dd>
901
* <dt>fontColor</dt><dd>The cascaded fontColor of the changedNode</dd>
902
* <dt>fontFamily</dt><dd>The cascaded fontFamily of the changedNode</dd>
903
* <dt>fontSize</dt><dd>The cascaded fontSize of the changedNode</dd>
905
* @type {Event.Custom}
910
* @description Fired after the frame is ready.
911
* @param {Event.Facade} event An Event Facade object.
912
* @type {Event.Custom}
919
}, '3.9.1', {"requires": ["base", "frame", "node", "exec-command", "editor-selection"]});