use strict"; module.exports = function(grunt)

download use strict"; module.exports = function(grunt)

If you can't read please download the document

Transcript of use strict"; module.exports = function(grunt)

neditor-master/.editorconfig

root = true

# Unix-style newlines with a newline ending every file[*]end_of_line = lfinsert_final_newline = truecharset = utf-8

[*.{html,js,css,scss,xml}]indent_style = spaceindent_size = 4trim_trailing_whitespace = true

[*.yml]indent_style = spaceindent_size = 2

neditor-master/.gitignore

################ folder ################.idealogjsp/uploadphp/uploadnet/uploadasp/uploadnode/upload

################ fixed file ################*.pptx*.doc*.docx*.xml

################### Eclipse#################

*.pydevproject.project.metadatabin/tmp/*.tmp*.bak*.swp*~.niblocal.properties.classpath.settings/.loadpath

# External tool builders.externalToolBuilders/

# Locally stored "Eclipse launch configurations"*.launch

# CDT-specific.cproject

# PDT-specific.buildpath

################### Visual Studio#################

## Ignore Visual Studio temporary files, build results, and## files generated by popular Visual Studio add-ons.

# User-specific files*.suo*.user*.sln.docstates

# Build results[Dd]ebug/[Rr]elease/*_i.c*_p.c*.ilk*.meta*.obj*.pch*.pdb*.pgc*.pgd*.rsp*.sbr*.tlb*.tli*.tlh*.tmp*.vspscc.builds*.dotCover

## TODO: If you have NuGet Package Restore enabled, uncomment this#packages/

# Visual C++ cache filesipch/*.aps*.ncb*.opensdf*.sdf

# Visual Studio profiler*.psess*.vsp

# ReSharper is a .NET coding add-in_ReSharper*

# Installshield output folder[Ee]xpress

# DocProject is a documentation generator add-inDocProject/buildhelp/DocProject/Help/*.HxTDocProject/Help/*.HxCDocProject/Help/*.hhcDocProject/Help/*.hhkDocProject/Help/*.hhpDocProject/Help/Html2DocProject/Help/html

# Click-Once directorypublish

# Others[Bb]in[Oo]bjsqlTestResults*.CacheClientBinstylecop.*~$**.dbmdlGenerated_Code #added for RIA/Silverlight projects

# Backup & report files from converting an old project file to a newer# Visual Studio version. Backup files are not needed, because we have git ;-)_UpgradeReport_Files/Backup*/UpgradeLog*.XML

############## Windows############

# Windows image file cachesThumbs.db

# Folder config fileDesktop.ini

############### Python#############

*.py[co]

# Packages*.egg*.egg-infodisteggsparts# binvarsdistdevelop-eggs.installed.cfg

# Installer logspip-log.txt

# Unit test / coverage reports.coverage.tox

#Translations*.mo

#Mr Developer.mr.developer.cfg

# Mac crap.DS_Store/node_modules

neditor-master/.travis.yml

sudo: false

language: node_js

matrix: fast_finish: true include: - node_js: node env: FOR=php - node_js: node env: FOR=jsp - node_js: node env: FOR=net - node_js: node env: FOR=asp

before_install: - npm install grunt -g

install: - npm install - grunt neditor --server="$FOR" # - sh -c "if [ '$FOR' = 'php' ]; then grunt neditor; fi" #- sh -c "if [ '$FOR' = 'jsp' ]; then grunt neditor --server=jsp; fi" #- sh -c "if [ '$FOR' = 'net' ]; then grunt neditor --server=.net; fi" #- sh -c "if [ '$FOR' = 'asp' ]; then grunt neditor --server=asp; fi" - tar -cvf neditor.tar --exclude=.git dist - xz -z9 neditor.tar

script: - curl -T neditor.tar.xz http://v0.api.upyun.com/notadd/download/neditor/Nediotr-"FOR"-master.tar.xz -u "$UPYUN" -v #- sh -c "if [ '$FOR' = '.net' ]; then curl -T neditor.tar.xz http://v0.api.upyun.com/notadd/download/neditor/Nediotr-net-master.tar.xz -u "$UPYUN" -v; fi" #- sh -c "if [ '$FOR' = 'asp' ]; then curl -T neditor.tar.xz http://v0.api.upyun.com/notadd/download/neditor/Nediotr-asp-master.tar.xz -u "$UPYUN" -v; fi" #- sh -c "if [ '$FOR' = 'php' ]; then curl -T neditor.tar.xz http://v0.api.upyun.com/notadd/download/neditor/Nediotr-php-master.tar.xz -u "$UPYUN" -v; fi" #- sh -c "if [ '$FOR' = 'jsp' ]; then curl -T neditor.tar.xz http://v0.api.upyun.com/notadd/download/neditor/Nediotr-jsp-master.tar.xz -u "$UPYUN" -v; fi" notifications: webhooks: - https://hook.bearychat.com/=bwA22/travis/52fa443470377f35e5a3d068b8d2d5ca - https://hook.bearychat.com/=bwA7K/travis/3c04d191a6066d3e178ab8d93643e708

neditor-master/Gruntfile.js

"use strict";

module.exports = function(grunt) { var fs = require("fs"), Util = { jsBasePath: "_src/", parseBasePath: "_parse/", cssBasePath: "themes/notadd/_css/",

fetchScripts: function(readFile, basePath) { var sources = fs.readFileSync(readFile); sources = /\[([^\]]+\.js'[^\]]+)\]/.exec(sources); sources = sources[1] .replace(/\/\/.*\n/g, "\n") .replace(/'|"|\n|\t|\s/g, ""); sources = sources.split(","); sources.forEach(function(filepath, index) { sources[index] = basePath + filepath; });

return sources; },

fetchStyles: function() { var sources = fs.readFileSync(this.cssBasePath + "neditor.css"), filepath = null, pattern = /@import\s+([^;]+)*;/g, src = [];

while ((filepath = pattern.exec(sources))) { src.push(this.cssBasePath + filepath[1].replace(/'|"/g, "")); }

return src; } }, packageJson = grunt.file.readJSON("package.json"), server = grunt.option("server") || "php", encode = grunt.option("encode") || "utf8", disDir = "dist/", banner = "/*!\n * " + packageJson.name + "\n * version: " + packageJson.version + "\n * build: \n */\n\n";

//init (function() { server = typeof server === "string" ? server.toLowerCase() : "php"; encode = typeof encode === "string" ? encode.toLowerCase() : "utf8";

disDir = "dist/" + encode + "-" + server + "/"; })();

grunt.initConfig({ pkg: packageJson, concat: { js: { options: { banner: "/*!\n * " + packageJson.name + "\n * version: " + packageJson.version + "\n * build: \n */\n\n" + "(function(){\n\n", footer: "\n\n})();\n", process: function(src, s) { var filename = s.substr(s.indexOf("/") + 1); return ( "// " + filename + "\n" + src.replace("/_css/", "/css/") + "\n" ); } }, src: Util.fetchScripts("_examples/editor_api.js", Util.jsBasePath), dest: disDir + packageJson.name + ".all.js" }, parse: { options: { banner: "/*!\n * " + packageJson.name + " parse\n * version: " + packageJson.version + "\n * build: \n */\n\n" + "(function(){\n\n", footer: "\n\n})();\n" }, src: Util.fetchScripts("neditor.parse.js", Util.parseBasePath), dest: disDir + packageJson.name + ".parse.js" }, css: { src: Util.fetchStyles(), dest: disDir + "themes/notadd/css/neditor.css" } }, cssmin: { options: { banner: banner }, files: { expand: true, cwd: disDir + "themes/notadd/css/", src: ["*.css", "!*.min.css"], dest: disDir + "themes/notadd/css/", ext: ".min.css" } }, uglify: { dist: { options: { banner: "/*!\n * " + packageJson.name + "\n * version: " + packageJson.version + "\n * build: \n */" }, src: disDir + ".all.js", dest: disDir + ".all.min.js" }, parse: { options: { banner: "/*!\n * " + packageJson.name + " parse\n * version: " + packageJson.version + "\n * build: \n */" }, src: disDir + ".parse.js", dest: disDir + ".parse.min.js" } }, copy: { base: { files: [ { src: [ "*.html", "themes/iframe.css", "themes/notadd/dialogbase.css", "themes/notadd/images/**", "themes/notadd/fonts/**", "dialogs/**", "lang/**", "third-party/**" ], dest: disDir } ] }, demo: { files: [ { src: "_examples/completeDemo.html", dest: disDir + "index.html" } ] }, php: { expand: true, src: "php/**", dest: disDir }, asp: { expand: true, src: "asp/**", dest: disDir }, jsp: { expand: true, src: "jsp/**", dest: disDir }, net: { expand: true, src: "net/**", dest: disDir } }, transcoding: { options: { charset: encode }, src: [ disDir + "**/*.html", disDir + "**/*.js", disDir + "**/*.css", disDir + "**/*.json", disDir + "**/*.jsp", disDir + "**/*.asp" ] }, replace: { fileEncode: { src: [ disDir + "**/*.html", disDir + "dialogs/**/*.js", disDir + "**/*.css", disDir + "**/*.php", disDir + "**/*.jsp", disDir + "**/*.ashx", disDir + "**/*.asp" ], overwrite: true, replacements: [ { from: /utf-8/gi, to: "gbk" } ] }, demo: { src: disDir + "index.html", overwrite: true, replacements: [ { from: /\.\.\//gi, to: "" }, { from: "editor_api.js", to: packageJson.name + ".all.min.js" } ] }, gbkasp: { src: [disDir + "asp/*.asp"], overwrite: true, replacements: [ { from: /65001/gi, to: "936" } ] } }, clean: { build: { src: [ disDir + "jsp/src", disDir + "*/upload", disDir + ".DS_Store", disDir + "**/.DS_Store", disDir + ".git", disDir + "**/.git" ] } } });

grunt.loadNpmTasks("grunt-text-replace"); grunt.loadNpmTasks("grunt-contrib-concat"); grunt.loadNpmTasks("grunt-contrib-cssmin"); grunt.loadNpmTasks("grunt-contrib-uglify"); grunt.loadNpmTasks("grunt-contrib-copy"); grunt.loadNpmTasks("grunt-transcoding"); grunt.loadNpmTasks("grunt-contrib-clean");

grunt.registerTask("neditor", "UEditor build", function() { var tasks = [ "concat", "cssmin", "uglify", "copy:base", "copy:" + server, "copy:demo", "replace:demo", "clean" ];

if (encode === "gbk") { tasks.push("replace:fileEncode"); if (server === "asp") { tasks.push("replace:gbkasp"); } }

tasks.push("transcoding");

//config updateConfigFile();

grunt.task.run(tasks); });

function updateConfigFile() { var filename = "neditor.config.js", file = grunt.file.read(filename), path = server + "/", suffix = server === "net" ? ".ashx" : "." + server;

file = file.replace(/php\//ig, path).replace(/\.php/ig, suffix);

if (encode == "gbk") { file = file.replace(/utf-8/gi, "gbk"); }

//dist if (grunt.file.write(disDir + filename, file)) { grunt.log.writeln("config file update success"); } else { grunt.log.warn("config file update error"); } }};

neditor-master/ISSUE_TEMPLATE.md

****

**** UEditor `ISSUE`

**** `ISSUE` `ISSUE` `UEditor` Bugs `UEditor`

##

* `ISSUE` ****[](http://fex.baidu.com/neditor/)* `ISSUE` **Google*** `ISSUE` `ISSUE` **`ISSUE`** `ISSUE` `ISSUE`

* * *

** `ISSUE` `Pull Request` `Pull Request` `debug` **

### `UEditor`

neditor-master/LICENSE

The MIT License (MIT)

Copyright (c) 2013 neditor

Permission is hereby granted, free of charge, to any person obtaining a copy ofthis software and associated documentation files (the "Software"), to deal inthe Software without restriction, including without limitation the rights touse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies ofthe Software, and to permit persons to whom the Software is furnished to do so,subject to the following conditions:

The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESSFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS ORCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHERIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

neditor-master/README.md

##

* BUG

* php

* jsp

* asp

* .net

* BUG

### HTTPS

ueditor https https [CDN](https://console.upyun.com/register/?invite=r17EYO3BW) CDN```imgbaidu.b0.upaiyun.comtingapi.b0.upaiyun.com```Neditor Ueditor Ueditor

![image](https://www.notadd.com/src/neditor.webp)

Demo: https://demo.neditor.notadd.com/

## ##

* [PHP](https://www.notadd.com/download/neditor/Nediotr-php-master.tar.xz)* [JSP](https://www.notadd.com/download/neditor/Nediotr-jsp-master.tar.xz)* [.NET](https://www.notadd.com/download/neditor/Nediotr-net-master.tar.xz)* [ASP](https://www.notadd.com/download/neditor/Nediotr-asp-master.tar.xz)

Node ISSUES UPYUN

## ##

### Grunt ###

grunt-cli

```shellgit clone npm installgrunt neditor```

### index.html ###

dist/utf8-php , index.html

![](https://www.notadd.com/src/neditor-demo.webp)

###

Neditor PHP jsp.net

grunt server jsp

```bashgrunt neditor --server=jsp```

dist utf8-jsp

###

```javascriptvar ue = UE.getEditor('container', { autoHeight: false});```

neditor.config.js [](http://fex.baidu.com/ueditor/#start-config1.4 .md)

###

getContent setContent

```javascriptvar ue = UE.getContent();ue.ready(function(){ // ue.setContent('hello'); //html:

hello

var html = ue.getContent(); //: hello var txt = ue.getContentTxt();});```

Ueditor API[API ](http://ueditor.baidu.com/doc "ueditor API ")

##

Neditor [http://gitee.com/notadd/neditor](http://gitee.com/notadd/neditor "Neditor github ")

Neditor github [http://github.com/notadd/neditor](http://github.com/notadd/neditor "Neditor github ")

##

Ueditor [http://ueditor.baidu.com](http://ueditor.baidu.com "ueditor ")

Ueditor API [http://ueditor.baidu.com/doc](http://ueditor.baidu.com/doc "ueditor API ")

Ueditor github [http://github.com/fex-team/ueditor](http://github.com/fex-team/ueditor "ueditor github ")

##

Ueditor [http://fex.baidu.com/ueditor/](http://fex.baidu.com/ueditor/)

: IE8

## ##

QQ 321735506

[issue](http://github.com/notadd/neditor/issues)

[](https://bbs.notadd.com/category/13 "Neditor ")

##

[](https://git.oschina.net/notadd/notadd?donate=true) ## Notadd

https://github.com/notadd/notadd

neditor-master/_examples/addCustomizeButton.js

UE.registerUI('button',function(editor,uiName){ //command editor.registerCommand(uiName,{ execCommand:function(){ alert('execCommand:' + uiName) } });

//button var btn = new UE.ui.Button({ // name:uiName, // title:uiName, //iconicon cssRules :'background-position: -500px 0;', // onclick:function () { //, editor.execCommand(uiName); } });

// editor.addListener('selectionchange', function () { var state = editor.queryCommandState(uiName); if (state == -1) { btn.setDisabled(true); btn.setChecked(false); } else { btn.setDisabled(false); btn.setChecked(state); } });

//button,button return btn;}/*index ,editorId UI*/);

//UE.registerUI('myblockquote',function(editor,uiName){ editor.registerCommand(uiName,{ execCommand:function(){ this.execCommand('blockquote',{ "style":"border-left: 3px solid #E5E6E1; margin-left: 0px; padding-left: 5px; line-height:36px;" }); } });

var btn = new UE.ui.Button({ name:uiName, title:'', cssRules :"background-position: -220px 0;", onclick:function () { editor.execCommand(uiName); } });

editor.addListener('selectionchange', function () { console.log(this); var state = editor.queryCommandState('blockquote'); if (state == -1) { btn.setDisabled(true); btn.setChecked(false); } else { btn.setDisabled(false); btn.setChecked(state); } });

return btn;});

neditor-master/_examples/addCustomizeCombox.js

UE.registerUI('combox',function(editor,uiName){ //command,uiNamecommand editor.registerCommand(uiName,{ execCommand:function(cmdName,value){ //fontsize this.execCommand('fontsize',value + 'px') }, queryCommandValue:function(){ //fontsize return this.queryCommandValue('fontsize') } });

// var items = []; for(var i= 0,ci;ci=[10, 11, 12, 14, 16, 18, 20, 24, 36][i++];){ items.push({ // label:':' + ci + 'px', // value:ci, // renderLabelHtml:function () { // return '' + (this.label || '') + ''; } }); } // var combox = new UE.ui.Combox({ // editor:editor, // items:items, // onselect:function (t, index) { // editor.execCommand(uiName, this.items[index].value); }, // title:uiName, //combox initValue:uiName });

editor.addListener('selectionchange', function (type, causeByUi, uiReady) { if (!uiReady) { var state = editor.queryCommandState(uiName); if (state == -1) { combox.setDisabled(true); } else { combox.setDisabled(false); var value = editor.queryCommandValue(uiName); if(!value){ combox.setValue(uiName); return; } //ie value && (value = value.replace(/['"]/g, '').split(',')[0]); combox.setValue(value);

} }

}); return combox;},2/*index ,editorId UI*/);

neditor-master/_examples/addCustomizeDialog.js

UE.registerUI('dialog',function(editor,uiName){

//dialog var dialog = new UE.ui.Dialog({ //,addCustomizeDialog.js iframeUrl:'customizeDialogPage.html', // editor:editor, //dialog name:uiName, //dialog title:"",

//dialog cssRules:"width:600px;height:300px;",

//buttonsdialog buttons:[ { className:'edui-okbutton', label:'', onclick:function () { dialog.close(true); } }, { className:'edui-cancelbutton', label:'', onclick:function () { dialog.close(false); } } ]});

//addCustomizeButton.js var btn = new UE.ui.Button({ name:'dialogbutton' + uiName, title:'dialogbutton' + uiName, //iconicon cssRules :'background-position: -500px 0;', onclick:function () { //dialog dialog.render(); dialog.open(); } });

return btn;}/*index ,editorId UI*/);

neditor-master/_examples/charts.html

neditor-master/_examples/completeDemo.html

demo

html

300

neditor-master/_examples/customPluginDemo.html

UEditor

neditor-master/_examples/customToolbarDemo.html

UEditortoolbar

andale monoarialarial blackcomic sans ms

10pt11pt12pt14pt16pt18pt20pt22pt24pt36pt

neditor-master/_examples/customizeDialogPage.html

neditor-master/_examples/customizeToolbarUIDemo.html

demo

neditor-master/_examples/editor_api.js

/** * */(function (){ var paths = [ 'editor.js', 'core/browser.js', 'core/utils.js', 'core/EventBase.js', 'core/dtd.js', 'core/domUtils.js', 'core/Range.js', 'core/Selection.js', 'core/Editor.js', 'core/Editor.defaultoptions.js', 'core/loadconfig.js', 'core/ajax.js', 'core/filterword.js', 'core/node.js', 'core/htmlparser.js', 'core/filternode.js', 'core/plugin.js', 'core/keymap.js', 'core/localstorage.js', 'plugins/defaultfilter.js', 'plugins/inserthtml.js', 'plugins/autotypeset.js', 'plugins/autosubmit.js', 'plugins/background.js', 'plugins/image.js', 'plugins/justify.js', 'plugins/font.js', 'plugins/link.js', 'plugins/iframe.js', 'plugins/scrawl.js', 'plugins/removeformat.js', 'plugins/blockquote.js', 'plugins/convertcase.js', 'plugins/indent.js', 'plugins/print.js', 'plugins/preview.js', 'plugins/selectall.js', 'plugins/paragraph.js', 'plugins/directionality.js', 'plugins/horizontal.js', 'plugins/time.js', 'plugins/rowspacing.js', 'plugins/lineheight.js', 'plugins/insertcode.js', 'plugins/cleardoc.js', 'plugins/anchor.js', 'plugins/wordcount.js', 'plugins/pagebreak.js', 'plugins/wordimage.js', 'plugins/dragdrop.js', 'plugins/undo.js', 'plugins/copy.js', 'plugins/paste.js', 'plugins/puretxtpaste.js', 'plugins/list.js', 'plugins/source.js', 'plugins/enterkey.js', 'plugins/keystrokes.js', 'plugins/fiximgclick.js', 'plugins/autolink.js', 'plugins/autoheight.js', 'plugins/autofloat.js', 'plugins/video.js', 'plugins/table.core.js', 'plugins/table.cmds.js', 'plugins/table.action.js', 'plugins/table.sort.js', 'plugins/contextmenu.js', 'plugins/shortcutmenu.js', 'plugins/basestyle.js', 'plugins/elementpath.js', 'plugins/formatmatch.js', 'plugins/searchreplace.js', 'plugins/customstyle.js', 'plugins/catchremoteimage.js', 'plugins/snapscreen.js', 'plugins/insertparagraph.js', 'plugins/webapp.js', 'plugins/template.js', 'plugins/music.js', 'plugins/autoupload.js', 'plugins/autosave.js', 'plugins/charts.js', 'plugins/section.js', 'plugins/simpleupload.js', 'plugins/serverparam.js', 'plugins/insertfile.js', 'plugins/xssFilter.js', 'ui/ui.js', 'ui/uiutils.js', 'ui/uibase.js', 'ui/separator.js', 'ui/mask.js', 'ui/popup.js', 'ui/colorpicker.js', 'ui/tablepicker.js', 'ui/stateful.js', 'ui/button.js', 'ui/splitbutton.js', 'ui/colorbutton.js', 'ui/tablebutton.js', 'ui/autotypesetpicker.js', 'ui/autotypesetbutton.js', 'ui/cellalignpicker.js', 'ui/pastepicker.js', 'ui/toolbar.js', 'ui/menu.js', 'ui/combox.js', 'ui/dialog.js', 'ui/menubutton.js', 'ui/multiMenu.js', 'ui/shortcutmenu.js', 'ui/breakline.js', 'ui/message.js', 'ui/iconfont.js', 'adapter/editorui.js', 'adapter/editor.js', 'adapter/message.js', 'adapter/autosave.js'

], baseURL = '../_src/'; for (var i=0,pi;pi = paths[i++];) { document.write(''); }})();

neditor-master/_examples/filterRuleDemo.html

inlineiframe,style,script,embed

neditor-master/_examples/highlightDemo.html

UE.getEditor('myEditor');

neditor-master/_examples/index.html

UEditor

Toolbar

,

jquery

jquery

jqueryValidation

jqueryValidation

uparse.js

uparse.js

filterRules

demo

neditor-master/_examples/jqueryCompleteDemo.html

neditor-master/_examples/jqueryValidation.html

Ueditorjquery validation

neditor-master/_examples/multiDemo.html

UEditor

neditor-master/_examples/multiEditorWithOneInstance.html

UEditor

2

3

neditor-master/_examples/renderInTable.html

neditor-master/_examples/resetDemo.html

neditor-master/_examples/sectiondemo.html

demo

neditor-master/_examples/server/getContent.ashx

/** * Created by visual studio 2010 * User: xuheng * Date: 12-3-6 * Time: 21:23 * To get the value of editor and output the value . */using System;using System.Web;

public class getContent : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/html";

// string content = context.Server.HtmlEncode(context.Request.Form["myEditor"]);

// //-------------

// context.Response.Write(""); context.Response.Write(

"uParse('.content',{"+ "'rootPath': '../'"+ "})"+ "");

context.Response.Write("Content of First Editor: "); context.Response.Write("" + context.Server.HtmlDecode(content) + "");

} public bool IsReusable { get { return false; } }

}

neditor-master/_examples/server/getContent.asp

uParse('.content',{ 'rootPath': '../' })

neditor-master/_examples/server/getContent.jsp

uParse('.content',{ 'rootPath': '../' })

neditor-master/_examples/server/getContent.php

uParse('.content',{ 'rootPath': '../' })

" + "" + "" + // ".view{padding:0;word-wrap:break-word;cursor:text;height:90%;}\n" + // //font-familysafarifillchar "body{margin:8px;font-family:sans-serif;font-size:16px;}" + // "p{margin:5px 0;}" + (options.iframeCssUrl ? "" : "") + (options.initialStyle ? "" + options.initialStyle + "" : "") + "" + "" + "" + "setTimeout(function(){editor = window.parent.UE.instants['ueditorInstant" + me.uid + "'];editor._setup(document);},0);" + "var _tmpScript = document.getElementById('_initialScript');_tmpScript.parentNode.removeChild(_tmpScript);" + "" + (options.iframeJsUrl ? "" : "") + "";

container.appendChild( domUtils.createElement(document, "iframe", { id: "ueditor_" + me.uid, width: "100%", height: "100%", frameborder: "0", // // scrolling :'no', src: "javascript:void(function(){document.open();" + (options.customDomain && document.domain != location.hostname ? 'document.domain="' + document.domain + '";' : "") + 'document.write("' + html + '");document.close();}())' }) ); container.style.overflow = "hidden"; // setTimeout(function() { if (/%$/.test(options.initialFrameWidth)) { options.minFrameWidth = options.initialFrameWidth = container.offsetWidth; //ie // container.style.width = options.initialFrameWidth + 'px'; } if (/%$/.test(options.initialFrameHeight)) { options.minFrameHeight = options.initialFrameHeight = container.offsetHeight; container.style.height = options.initialFrameHeight + "px"; } }); } },

/** * * @method _setup * @private * @param { Element } doc Iframe */ _setup: function(doc) { var me = this, options = me.options; if (ie) { doc.body.disabled = true; doc.body.contentEditable = true; doc.body.disabled = false; } else { doc.body.contentEditable = true; } doc.body.spellcheck = false; me.document = doc; me.window = doc.defaultView || doc.parentWindow; me.iframe = me.window.frameElement; me.body = doc.body; me.selection = new dom.Selection(doc); //geckorange,isFocus var geckoSel; if (browser.gecko && (geckoSel = this.selection.getNative())) { geckoSel.removeAllRanges(); } this._initEvents(); //formtextarea for ( var form = this.iframe.parentNode; !domUtils.isBody(form); form = form.parentNode ) { if (form.tagName == "FORM") { me.form = form; if (me.options.autoSyncData) { domUtils.on(me.window, "blur", function() { setValue(form, me); }); } else { domUtils.on(form, "submit", function() { setValue(this, me); }); } break; } } if (options.initialContent) { if (options.autoClearinitialContent) { var oldExecCommand = me.execCommand; me.execCommand = function() { me.fireEvent("firstBeforeExecCommand"); return oldExecCommand.apply(me, arguments); }; this._setDefaultContent(options.initialContent); } else this.setContent(options.initialContent, false, true); }

//

if (domUtils.isEmptyNode(me.body)) { me.body.innerHTML = "

" + (browser.ie ? "" : "
") + "

"; } //focus, if (options.focus) { setTimeout(function() { me.focus(me.options.focusInEnd); //selectionchange; !me.options.autoClearinitialContent && me._selectionChange(); }, 0); } if (!me.container) { me.container = this.iframe.parentNode; } if (options.fullscreen && me.ui) { me.ui.setFullScreen(true); }

try { me.document.execCommand("2D-position", false, false); } catch (e) {} try { me.document.execCommand("enableInlineTableEditing", false, false); } catch (e) {} try { me.document.execCommand("enableObjectResizing", false, false); } catch (e) {}

// me._bindshortcutKeys(); me.isReady = 1; me.fireEvent("ready"); options.onready && options.onready.call(me); if (!browser.ie9below) { domUtils.on(me.window, ["blur", "focus"], function(e) { //chromealt+tab if (e.type == "blur") { me._bakRange = me.selection.getRange(); try { me._bakNativeRange = me.selection.getNative().getRangeAt(0); me.selection.getNative().removeAllRanges(); } catch (e) { me._bakNativeRange = null; } } else { try { me._bakRange && me._bakRange.select(); } catch (e) {} } }); } //trace:1518 ff3.6body if (browser.gecko && browser.version 8) { var headHtmlForIE9 = ""; utils.each(me.document.styleSheets, function(si) { headHtmlForIE9 += si.href ? '' : "" + si.cssText + ""; }); utils.each(me.document.getElementsByTagName("script"), function(si) { headHtmlForIE9 += si.outerHTML; }); } return ( "" + (me.options.charset ? '' : "") + (headHtmlForIE9 || me.document.getElementsByTagName("head")[0].innerHTML) + headHtml.join("\n") + "" + "" + me.getContent(null, null, true) + "" ); },

/** * * @method getPlainTxt * @return { String } * @example * ```javascript * //html:

1

2

* console.log(editor.getPlainTxt()); //:"1\n2\n * ``` */ getPlainTxt: function() { var reg = new RegExp(domUtils.fillChar, "g"), html = this.body.innerHTML.replace(/[\n\r]/g, ""); //ie\n html = html .replace(/]*>(|)/gi, "\n") .replace(//gi, "\n") .replace(//]+>/g, "") .replace(/(\n)?]+)>/g, function(a, b, c) { return dtd.$block[c] ? "\n" : b ? b : ""; }); //c2a0\u00a0 return html .replace(reg, "") .replace(/\u00a0/g, " ") .replace(//g, " "); },

/** * , * @method getContentTxt * @return { String } * @example * ```javascript * //html:

1

2

* console.log(editor.getPlainTxt()); //:"12 * ``` */ getContentTxt: function() { var reg = new RegExp(domUtils.fillChar, "g"); //c2a0\u00a0 return this.body[browser.ie ? "innerText" : "textContent"] .replace(reg, "") .replace(/\u00a0/g, " "); },

/** * html * @method setContent * @warning * @warning selectionchange * @param { String } html html * @example * ```javascript * editor.getContent('

test

'); * ``` */

/** * html * @method setContent * @warning * @warning selectionchange * @param { String } html html * @param { Boolean } isAppendTo true * @example * ```javascript * //

old text

* editor.setContent('

new text

', true); //

old text

new text

* ``` */ setContent: function(html, isAppendTo, notFireSelectionchange) { var me = this;

me.fireEvent("beforesetcontent", html); var root = UE.htmlparser(html); me.filterInputRule(root); html = root.toHtml();

me.body.innerHTML = (isAppendTo ? me.body.innerHTML : "") + html;

function isCdataDiv(node) { return node.tagName == "DIV" && node.getAttribute("cdata_tag"); } //inlinep if (me.options.enterTag == "p") { var child = this.body.firstChild, tmpNode; if ( !child || (child.nodeType == 1 && (dtd.$cdata[child.tagName] || isCdataDiv(child) || domUtils.isCustomeNode(child)) && child === this.body.lastChild) ) { this.body.innerHTML = "

" + (browser.ie ? "" : "
") + "

" + this.body.innerHTML; } else { var p = me.document.createElement("p"); while (child) { while ( child && (child.nodeType == 3 || (child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName])) ) { tmpNode = child.nextSibling; p.appendChild(child); child = tmpNode; } if (p.firstChild) { if (!child) { me.body.appendChild(p); break; } else { child.parentNode.insertBefore(p, child); p = me.document.createElement("p"); } } child = child.nextSibling; } } } me.fireEvent("aftersetcontent"); me.fireEvent("contentchange");

!notFireSelectionchange && me._selectionChange(); // me._bakRange = me._bakIERange = me._bakNativeRange = null; //trace:1742 setContentgecko var geckoSel; if (browser.gecko && (geckoSel = this.selection.getNative())) { geckoSel.removeAllRanges(); } if (me.options.autoSyncData) { me.form && setValue(me.form, me); } },

/** * focus * @method focus * @example * ```javascript * editor.focus() * ``` */

/** * toEndfocus * @method focus * @param { Boolean } toEnd focustoEndtruefocus * @example * ```javascript * editor.focus(true) * ``` */ focus: function(toEnd) { try { var me = this, rng = me.selection.getRange(); if (toEnd) { var node = me.body.lastChild; if (node && node.nodeType == 1 && !dtd.$empty[node.tagName]) { if (domUtils.isEmptyBlock(node)) { rng.setStartAtFirst(node); } else { rng.setStartAtLast(node); } rng.collapse(true); } rng.setCursor(true); } else { if ( !rng.collapsed && domUtils.isBody(rng.startContainer) && rng.startOffset == 0 ) { var node = me.body.firstChild; if (node && node.nodeType == 1 && !dtd.$empty[node.tagName]) { rng.setStartAtFirst(node).collapse(true); } }

rng.select(true); } this.fireEvent("focus selectionchange"); } catch (e) {} }, isFocus: function() { return this.selection.isFocus(); }, blur: function() { var sel = this.selection.getNative(); if (sel.empty && browser.ie) { var nativeRng = document.body.createTextRange(); nativeRng.moveToElementText(document.body); nativeRng.collapse(true); nativeRng.select(); sel.empty(); } else { sel.removeAllRanges(); }

//this.fireEvent('blur selectionchange'); }, /** * UE * @method _initEvents * @private */ _initEvents: function() { var me = this, doc = me.document, win = me.window; me._proxyDomEvent = utils.bind(me._proxyDomEvent, me); domUtils.on( doc, [ "click", "contextmenu", "mousedown", "keydown", "keyup", "keypress", "mouseup", "mouseover", "mouseout", "selectstart" ], me._proxyDomEvent ); domUtils.on(win, ["focus", "blur"], me._proxyDomEvent); domUtils.on(me.body, "drop", function(e) { //ff if (browser.gecko && e.stopPropagation) { e.stopPropagation(); } me.fireEvent("contentchange"); }); domUtils.on(doc, ["mouseup", "keydown"], function(evt) { //selectionchange if ( evt.type == "keydown" && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey) ) { return; } if (evt.button == 2) return; me._selectionChange(250, evt); }); }, /** * * @method _proxyDomEvent * @private * @return { * } fireEvent * @see UE.EventBase:fireEvent(String) */ _proxyDomEvent: function(evt) { if ( this.fireEvent("before" + evt.type.replace(/^on/, "").toLowerCase()) === false ) { return false; } if (this.fireEvent(evt.type.replace(/^on/, ""), evt) === false) { return false; } return this.fireEvent( "after" + evt.type.replace(/^on/, "").toLowerCase() ); }, /** * * @method _selectionChange * @private */ _selectionChange: function(delay, evt) { var me = this; //selectionchange focussourcesourcenotNeedUndo=1 // if ( !me.selection.isFocus() ){ // return; // }

var hackForMouseUp = false; var mouseX, mouseY; if (browser.ie && browser.version < 9 && evt && evt.type == "mouseup") { var range = this.selection.getRange(); if (!range.collapsed) { hackForMouseUp = true; mouseX = evt.clientX; mouseY = evt.clientY; } } clearTimeout(_selectionChangeTimer); _selectionChangeTimer = setTimeout(function() { if (!me.selection || !me.selection.getNative()) { return; } //IEbug: mouseuprangeselectiontypeNone. //IEmouseup var ieRange; if (hackForMouseUp && me.selection.getNative().type == "None") { ieRange = me.document.body.createTextRange(); try { ieRange.moveToPoint(mouseX, mouseY); } catch (ex) { ieRange = null; } } var bakGetIERange; if (ieRange) { bakGetIERange = me.selection.getIERange; me.selection.getIERange = function() { return ieRange; }; } me.selection.cache(); if (bakGetIERange) { me.selection.getIERange = bakGetIERange; } if (me.selection._cachedRange && me.selection._cachedStartElement) { me.fireEvent("beforeselectionchange"); // causeByUitrueselectionchange. me.fireEvent("selectionchange", !!evt); me.fireEvent("afterselectionchange"); me.selection.clear(); } }, delay || 50); },

/** * * @method _callCmdFn * @private * @param { String } fnName * @param { * } args * @return { * } */ _callCmdFn: function(fnName, args) { var cmdName = args[0].toLowerCase(), cmd, cmdFn; cmd = this.commands[cmdName] || UE.commands[cmdName]; cmdFn = cmd && cmd[fnName]; //querycommandstatecommand0 if ((!cmd || !cmdFn) && fnName == "queryCommandState") { return 0; } else if (cmdFn) { return cmdFn.apply(this, args); } },

/** * cmdName * @method execCommand * @param { String } cmdName * @remind * @return { * } * @example * ```javascript * editor.execCommand(cmdName); * ``` */ execCommand: function(cmdName) { cmdName = cmdName.toLowerCase(); var me = this; var result; var cmd = me.commands[cmdName] || UE.commands[cmdName]; if (!cmd || !cmd.execCommand) { return null; } if (!cmd.notNeedUndo && !me.__hasEnterExecCommand) { me.__hasEnterExecCommand = true; if (me.queryCommandState.apply(me, arguments) != -1) { me.fireEvent("saveScene"); me.fireEvent.apply( me, ["beforeexeccommand", cmdName].concat(arguments) ); result = this._callCmdFn("execCommand", arguments); //contentchange // (!cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange'); me.fireEvent.apply( me, ["afterexeccommand", cmdName].concat(arguments) ); me.fireEvent("saveScene"); } me.__hasEnterExecCommand = false; } else { result = this._callCmdFn("execCommand", arguments); !me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange && me.fireEvent("contentchange"); } !me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange && me._selectionChange(); return result; },

/** * command * @method queryCommandState * @param { String } cmdName * @remind * @return { Number } number (-1|0|1) * @example * ```javascript * editor.queryCommandState(cmdName) => (-1|0|1) * ``` * @see COMMAND.LIST */ queryCommandState: function(cmdName) { return this._callCmdFn("queryCommandState", arguments); },

/** * command * @method queryCommandValue * @param { String } cmdName * @remind * @remind * @return { * } * @grammar editor.queryCommandValue(cmdName) => {*} * @see COMMAND.LIST */ queryCommandValue: function(cmdName) { return this._callCmdFn("queryCommandValue", arguments); },

/** * * @method hasContents * @remind * table,ul,ol,dl,iframe,area,base,col,hr,img,embed,input,link,meta,param * @return { Boolean } truefalse * @example * ```javascript * editor.hasContents() * ``` */

/** * tagstrue * @method hasContents * @param { Array } tags * @return { Boolean } tagstagtruefalse * @example * ```javascript * editor.hasContents(['span']); * ``` */ hasContents: function(tags) { if (tags) { for (var i = 0, ci; (ci = tags[i++]); ) { if (this.document.getElementsByTagName(ci).length > 0) { return true; } } } if (!domUtils.isEmptyBlock(this.body)) { return true; } //, tags = ["div"]; for (i = 0; (ci = tags[i++]); ) { var nodes = domUtils.getElementsByTagName(this.document, ci); for (var n = 0, cn; (cn = nodes[n++]); ) { if (domUtils.isCustomeNode(cn)) { return true; } } } return false; },

/** * tab * @method reset * @remind reset * @example * ```javascript * editor.reset() * ``` */ reset: function() { this.fireEvent("reset"); },

/** * * @method setEnabled * @example * ```javascript * editor.setEnabled() * ``` */ setEnabled: function() { var me = this, range; if (me.body.contentEditable == "false") { me.body.contentEditable = true; range = me.selection.getRange(); // try { range.moveToBookmark(me.lastBk); delete me.lastBk; } catch (e) { range.setStartAtFirst(me.body).collapse(true); } range.select(true); if (me.bkqueryCommandState) { me.queryCommandState = me.bkqueryCommandState; delete me.bkqueryCommandState; } if (me.bkqueryCommandValue) { me.queryCommandValue = me.bkqueryCommandValue; delete me.bkqueryCommandValue; } me.fireEvent("selectionchange"); } }, enable: function() { return this.setEnabled(); },

/** * @method setDisabled */

/** ,except * @method setDisabled * @param { String } except * @remind disable * @example * ```javascript * editor.setDisabled('bold'); // * ``` */

/** ,except * @method setDisabled * @param { Array } except * @remind disable * @example * ```javascript * editor.setDisabled(['bold','insertimage']); // * ``` */ setDisabled: function(except) { var me = this; except = except ? (utils.isArray(except) ? except : [except]) : []; if (me.body.contentEditable == "true") { if (!me.lastBk) { me.lastBk = me.selection.getRange().createBookmark(true); } me.body.contentEditable = false; me.bkqueryCommandState = me.queryCommandState; me.bkqueryCommandValue = me.queryCommandValue; me.queryCommandState = function(type) { if (utils.indexOf(except, type) != -1) { return me.bkqueryCommandState.apply(me, arguments); } return -1; }; me.queryCommandValue = function(type) { if (utils.indexOf(except, type) != -1) { return me.bkqueryCommandValue.apply(me, arguments); } return null; }; me.fireEvent("selectionchange"); } }, disable: function(except) { return this.setDisabled(except); },

/** * * @method _setDefaultContent * @private * @param { String } cont */ _setDefaultContent: (function() { function clear() { var me = this; if (me.document.getElementById("initContent")) { me.body.innerHTML = "

" + (ie ? "" : "
") + "

"; me.removeListener("firstBeforeExecCommand focus", clear); setTimeout(function() { me.focus(); me._selectionChange(); }, 0); } }

return function(cont) { var me = this; me.body.innerHTML = '

' + cont + "

";

me.addListener("firstBeforeExecCommand focus", clear); }; })(),

/** * * @method setShow * @example * ```javascript * editor.setShow() * ``` */ setShow: function() { var me = this, range = me.selection.getRange(); if (me.container.style.display == "none") { // try { range.moveToBookmark(me.lastBk); delete me.lastBk; } catch (e) { range.setStartAtFirst(me.body).collapse(true); } //iefocus setTimeout(function() { range.select(true); }, 100); me.container.style.display = ""; } }, show: function() { return this.setShow(); }, /** * * @method setHide * @example * ```javascript * editor.setHide() * ``` */ setHide: function() { var me = this; if (!me.lastBk) { me.lastBk = me.selection.getRange().createBookmark(true); } me.container.style.display = "none"; }, hide: function() { return this.setHide(); },

/** * * @method getLang * @param { String } path lang * @return { Object | String } Json * @example * ```javascript * editor.getLang('contextMenu.delete'); //'' * ``` */ getLang: function(path) { var lang = UE.I18N[this.options.lang]; if (!lang) { throw Error("not import language file"); } path = (path || "").split("."); for (var i = 0, ci; (ci = path[i++]); ) { lang = lang[ci]; if (!lang) break; } return lang; },

/** * html * @method getContentLength * @return { Number } * @example * ```javascript * //html

132

* editor.getContentLength() //27 * ``` */ /** * * @method getContentLength * @param { Boolean } ingoneHtml true * @return { Number } hr/img/iframe1 * @example * ```javascript * //html

132

* editor.getContentLength() //3 * ``` */ getContentLength: function(ingoneHtml, tagNames) { var count = this.getContent(false, false, true).length; if (ingoneHtml) { tagNames = (tagNames || []).concat(["hr", "img", "iframe"]); count = this.getContentTxt().replace(/[\t\r\n]+/g, "").length; for (var i = 0, ci; (ci = tagNames[i++]); ) { count += this.document.getElementsByTagName(ci).length; } } return count; },

/** * * @method addInputRule * @param { Function } rule * @example * ```javascript * editor.addInputRule(function(root){ * $.each(root.getNodesByTagName('div'),function(i,node){ * node.tagName="p"; * }); * }); * ``` */ addInputRule: function(rule) { this.inputRules.push(rule); },

/** * * @method filterInputRule * @param { UE.uNode } root uNode * @remind editor.setContent'inserthtml' * @example * ```javascript * editor.filterInputRule(editor.body); * ``` * @see UE.Editor:addInputRule */ filterInputRule: function(root) { for (var i = 0, ci; (ci = this.inputRules[i++]); ) { ci.call(this, root); } },

/** * * @method addOutputRule * @param { Function } rule * @example * ```javascript * editor.addOutputRule(function(root){ * $.each(root.getNodesByTagName('p'),function(i,node){ * node.tagName="div"; * }); * }); * ``` */ addOutputRule: function(rule) { this.outputRules.push(rule); },

/** * * @method filterOutputRule * @remind editor.getContent * @param { UE.uNode } root uNode * @example * ```javascript * editor.filterOutputRule(editor.body); * ``` * @see UE.Editor:addOutputRule */ filterOutputRule: function(root) { for (var i = 0, ci; (ci = this.outputRules[i++]); ) { ci.call(this, root); } },

/** * action * @method getActionUrl * @remind serverUrl,imageUrlcontroller * @param { String } action action * @example * ```javascript * editor.getActionUrl('config'); // "/ueditor/php/controller.php?action=config" * editor.getActionUrl('image'); // "/ueditor/php/controller.php?action=uplaodimage" * editor.getActionUrl('scrawl'); // "/ueditor/php/controller.php?action=uplaodscrawl" * editor.getActionUrl('imageManager'); // "/ueditor/php/controller.php?action=listimage" * ``` */ getActionUrl: function(action) { var actionName = this.getOpt(action) || action, imageUrl = this.getOpt("imageUrl"), serverUrl = this.getOpt("serverUrl");

if (!serverUrl && imageUrl) { serverUrl = imageUrl.replace(/^(.*[\/]).+([\.].+)$/, "$1controller$2"); }

if (serverUrl) { serverUrl = serverUrl + (serverUrl.indexOf("?") == -1 ? "?" : "&") + "action=" + (actionName || ""); return utils.formatUrl(serverUrl); } else { return ""; } } }; utils.inherits(Editor, EventBase);})();

neditor-master/_src/core/EventBase.js

/** * UE * @file * @module UE * @class EventBase * @since 1.2.6.1 */

/** * UEditorUEditor * @unfile * @module UE */

/** * UEaddListener,removeListener,fireEvent * UEEditoruiuieditor * @unfile * @module UE * @class EventBase */

/** * EventBase * @constructor * @example * ```javascript * UE.EventBase.call(editor); * ``` */var EventBase = (UE.EventBase = function() {});

EventBase.prototype = { /** * * @method addListener * @param { String } types * @param { Function } fn * @waining true * @example * ```javascript * editor.addListener('selectionchange',function(){ * console.log(""); * }) * editor.addListener('beforegetcontent aftergetcontent',function(type){ * if(type == 'beforegetcontent'){ * //do something * }else{ * //do something * } * console.log(this.getContent) // this * }) * ``` * @see UE.EventBase:fireEvent(String) */ addListener: function(types, listener) { types = utils.trim(types).split(/\s+/); for (var i = 0, ti; (ti = types[i++]); ) { getListener(this, ti, true).push(listener); } },

on: function(types, listener) { return this.addListener(types, listener); }, off: function(types, listener) { return this.removeListener(types, listener); }, trigger: function() { return this.fireEvent.apply(this, arguments); }, /** * * @method removeListener * @param { String } types * @param { Function } fn * @example * ```javascript * //changeCallback * editor.removeListener("selectionchange",changeCallback); * ``` */ removeListener: function(types, listener) { types = utils.trim(types).split(/\s+/); for (var i = 0, ti; (ti = types[i++]); ) { utils.removeItem(getListener(this, ti) || [], listener); } },

/** * * @method fireEvent * @param { String } types * @remind addListener * @return { * } * @example * ```javascript * editor.fireEvent("selectionchange"); * ``` */

/** * * @method fireEvent * @param { String } types * @param { *... } options * @return { * } * @example * ```javascript * * editor.addListener( "selectionchange", function ( type, arg1, arg2 ) { * * console.log( arg1 + " " + arg2 ); * * } ); * * //selectionchange * //output: Hello World * editor.fireEvent("selectionchange", "Hello", "World"); * ``` */ fireEvent: function() { var types = arguments[0]; types = utils.trim(types).split(" "); for (var i = 0, ti; (ti = types[i++]); ) { var listeners = getListener(this, ti), r, t, k; if (listeners) { k = listeners.length; while (k--) { if (!listeners[k]) continue; t = listeners[k].apply(this, arguments); if (t === true) { return t; } if (t !== undefined) { r = t; } } } if ((t = this["on" + ti.toLowerCase()])) { r = t.apply(this, arguments); } } return r; }};/** * * @unfile * @module UE * @since 1.2.6.1 * @method getListener * @public * @param { Object } obj * @param { String } type * @param { Boolean } force truetype * @return { Array } */function getListener(obj, type, force) { var allListeners; type = type.toLowerCase(); return ( (allListeners = obj.__allListeners || (force && (obj.__allListeners = {}))) && (allListeners[type] || (force && (allListeners[type] = []))) );}

neditor-master/_src/core/Range.js

/** * Range * @file * @module UE.dom * @class Range * @since 1.2.6.1 */

/** * dom * @unfile * @module UE.dom */

/** * RangeUEditorRange * @unfile * @module UE.dom * @class Range */

;(function() { var guid = 0, fillChar = domUtils.fillChar, fillData;

/** * rangecollapse * @param {Range} range range */ function updateCollapse(range) { range.collapsed = range.startContainer && range.endContainer && range.startContainer === range.endContainer && range.startOffset == range.endOffset; }

function selectOneNode(rng) { return ( !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1 ); } function setEndPoint(toStart, node, offset, range) { //node if ( node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName]) ) { offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1); node = node.parentNode; } if (toStart) { range.startContainer = node; range.startOffset = offset; if (!range.endContainer) { range.collapse(true); } } else { range.endContainer = node; range.endOffset = offset; if (!range.startContainer) { range.collapse(false); } } updateCollapse(range); return range; }

function execContentsAction(range, action) { // //range.includeBookmark(); var start = range.startContainer, end = range.endContainer, startOffset = range.startOffset, endOffset = range.endOffset, doc = range.document, frag = doc.createDocumentFragment(), tmpStart, tmpEnd; if (start.nodeType == 1) { start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode(""))); } if (end.nodeType == 1) { end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode(""))); } if (start === end && start.nodeType == 3) { frag.appendChild( doc.createTextNode( start.substringData(startOffset, endOffset - startOffset) ) ); //is not clone if (action) { start.deleteData(startOffset, endOffset - startOffset); range.collapse(true); } return frag; } var current, currentLevel, clone = frag, startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true); for (var i = 0; startParents[i] == endParents[i]; ) { i++; } for (var j = i, si; (si = startParents[j]); j++) { current = si.nextSibling; if (si == start) { if (!tmpStart) { if (range.startContainer.nodeType == 3) { clone.appendChild( doc.createTextNode(start.nodeValue.slice(startOffset)) ); //is not clone if (action) { start.deleteData( startOffset, start.nodeValue.length - startOffset ); } } else { clone.appendChild(!action ? start.cloneNode(true) : start); } } } else { currentLevel = si.cloneNode(false); clone.appendChild(currentLevel); } while (current) { if (current === end || current === endParents[j]) { break; } si = current.nextSibling; clone.appendChild(!action ? current.cloneNode(true) : current); current = si; } clone = currentLevel; } clone = frag; if (!startParents[i]) { clone.appendChild(startParents[i - 1].cloneNode(false)); clone = clone.firstChild; } for (var j = i, ei; (ei = endParents[j]); j++) { current = ei.previousSibling; if (ei == end) { if (!tmpEnd && range.endContainer.nodeType == 3) { clone.appendChild( doc.createTextNode(end.substringData(0, endOffset)) ); //is not clone if (action) { end.deleteData(0, endOffset); } } } else { currentLevel = ei.cloneNode(false); clone.appendChild(currentLevel); } // if (j != i || !startParents[i]) { while (current) { if (current === start) { break; } ei = current.previousSibling; clone.insertBefore( !action ? current.cloneNode(true) : current, clone.firstChild ); current = ei; } } clone = currentLevel; } if (action) { range .setStartBefore( !endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i] ) .collapse(true); } tmpStart && domUtils.remove(tmpStart); tmpEnd && domUtils.remove(tmpEnd); return frag; }

/** * documentRange * @constructor * @param { Document } document */

/** * @property { Node } startContainer Range, */

/** * @property { Node } startOffset Range, * childNodes */

/** * @property { Node } endContainer Range, */

/** * @property { Node } endOffset Range, * childNodes */

/** * @property { Boolean } collapsed Range * @default true * @remind Range startContainer === endContainer && startOffset === endOffset */

/** * @property { Document } document RangeDocument * @remind rangedocument */ var Range = (dom.Range = function(document) { var me = this; me.startContainer = me.startOffset = me.endContainer = me.endOffset = null; me.document = document; me.collapsed = true; });

/** * fillData * @param doc * @param excludeNode */ function removeFillData(doc, excludeNode) { try { if (fillData && domUtils.inDoc(fillData, doc)) { if (!fillData.nodeValue.replace(fillCharReg, "").length) { var tmpNode = fillData.parentNode; domUtils.remove(fillData); while ( tmpNode && domUtils.isEmptyInlineElement(tmpNode) && //safaricontainsbug (browser.safari ? !( domUtils.getPosition(tmpNode, excludeNode) & domUtils.POSITION_CONTAINS ) : !tmpNode.contains(excludeNode)) ) { fillData = tmpNode.parentNode; domUtils.remove(tmpNode); tmpNode = fillData; } } else { fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, ""); } } } catch (e) {} }

/** * @param node * @param dir */ function mergeSibling(node, dir) { var tmpNode; node = node[dir]; while (node && domUtils.isFillChar(node)) { tmpNode = node[dir]; domUtils.remove(node); node = tmpNode; } }

Range.prototype = { /** * DocumentFragment * @method cloneContents * @return { DocumentFragment | NULL } null cloneDocumentFragment * @example * ```html * * * xx[xxx]x * * * //range * var fragment = range.cloneContents(), * node = document.createElement("div"); * * node.appendChild( fragment ); * * //output: xxx * console.log( node.innerHTML ); * * * * ``` */ cloneContents: function() { return this.collapsed ? null : execContentsAction(this, 0); },

/** * * @method deleteContents * @remind Range * @return { UE.dom.Range } Range * @example * ```html * * * xx[xxx]x * * * //range * range.deleteContents(); * * // * //output: xx|x * console.log( document.body.innerHTML ); * * // range * //output: B * console.log( range.startContainer.tagName ); * //output: 2 * console.log( range.startOffset ); * //output: B * console.log( range.endContainer.tagName ); * //output: 2 * console.log( range.endOffset ); * //output: true * console.log( range.collapsed ); * * * * ``` */ deleteContents: function() { var txt; if (!this.collapsed) { execContentsAction(this, 1); } if (browser.webkit) { txt = this.startContainer; if (txt.nodeType == 3 && !txt.nodeValue.length) { this.setStartBefore(txt).collapse(true); domUtils.remove(txt); } } return this; },

/** * DocumentFragment * @method extractContents * @remind * @warning dom * @return { DocumentFragment } DocumentFragment * @example * ```html * * * xx[xxx]x * * * //range * var fragment = range.extractContents(), * node = document.createElement( "div" ); * * node.appendChild( fragment ); * * // * * //output: xx|x * console.log( document.body.innerHTML ); * //output: xxx * console.log( node.innerHTML ); * * // range * //output: B * console.log( range.startContainer.tagName ); * //output: 2 * console.log( range.startOffset ); * //output: B * console.log( range.endContainer.tagName ); * //output: 2 * console.log( range.endOffset ); * //output: true * console.log( range.collapsed ); * * * */ extractContents: function() { return this.collapsed ? null : execContentsAction(this, 2); },

/** * Range * @method setStart * @remind offsetoffset * offsetoffset * @remind * * * @param { Node } node * @param { int } offset * @return { UE.dom.Range } range * @example * ```html * * xxxxxxxxxxxxx[xxx] * * * * // * range.setStart( document.getElementsByTagName("i")[0], 1 ); * * // * //xxxx[xxxxxxxxxxxx] * * * ``` * @example * ```html * * xxx[xx]x * * * * // * range.setStart( document.getElementsByTagName("img")[0], 3 ); * * // * //xxx[xx]x * * * ``` */ setStart: function(node, offset) { return setEndPoint(true, node, offset, this); },

/** * Range * @method setEnd * @param { Node } node * @param { int } offset * @see UE.dom.Range:setStart(Node,int) * @return { UE.dom.Range } range */ setEnd: function(node, offset) { return setEndPoint(false, node, offset, this); },

/** * Rangenode * @method setStartAfter * @remind range +1 * @param { Node } node * @return { UE.dom.Range } range * @example * ```html * * xxxxxxx[xxxx] * * * * // * range.setStartAfter( document.getElementsByTagName("i")[0] ); * * // * //xxxxx[xxxxxx] * * * ``` */ setStartAfter: function(node) { return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1); },

/** * Rangenode * @method setStartBefore * @remind range * @param { Node } node * @see UE.dom.Range:setStartAfter(Node) * @return { UE.dom.Range } range */ setStartBefore: function(node) { return this.setStart(node.parentNode, domUtils.getNodeIndex(node)); },

/** * Rangenode * @method setEndAfter * @remind range +1 * @param { Node } node * @see UE.dom.Range:setStartAfter(Node) * @return { UE.dom.Range } range * @example * ```html * * [xxxxxxx]xxxx * * * * // * range.setStartAfter( document.getElementsByTagName("span")[0] ); * * // * //[xxxxxxxx]xxx * * * ``` */ setEndAfter: function(node) { return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1); },

/** * Rangenode * @method setEndBefore * @remind range * @param { Node } node * @see UE.dom.Range:setEndAfter(Node) * @return { UE.dom.Range } range */ setEndBefore: function(node) { return this.setEnd(node.parentNode, domUtils.getNodeIndex(node)); },

/** * Rangenode * @method setStartAtFirst * @remind 0 * @remind * @param { Node } node * @see UE.dom.Range:setStartBefore(Node) * @return { UE.dom.Range } range * @example * ```html * * xxxxx[xx]xxxx * * * * // * range.setStartAtFirst( document.getElementsByTagName("i")[0] ); * * // * //xx[xxxxx]xxxx * * * ``` */ setStartAtFirst: function(node) { return this.setStart(node, 0); },

/** * Rangenode * @method setStartAtLast * @remind * @remind * @param { Node } node * @see UE.dom.Range:setStartAtFirst(Node) * @return { UE.dom.Range } range */ setStartAtLast: function(node) { return this.setStart( node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length ); },

/** * Rangenode * @method setEndAtFirst * @param { Node } node * @remind 0 * @remind node * @see UE.dom.Range:setStartAtFirst(Node) * @return { UE.dom.Range } range */ setEndAtFirst: function(node) { return this.setEnd(node, 0); },

/** * Rangenode * @method setEndAtLast * @param { Node } node * @remind * @remind node * @see UE.dom.Range:setStartAtFirst(Node) * @return { UE.dom.Range } range */ setEndAtLast: function(node) { return this.setEnd( node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length ); },

/** * * @method selectNode * @remind startOffset * endOffsetstartOffset+1 * @param { Node } node * @return { UE.dom.Range } rangerange * @example * ```html * * xxxxx[xx]xxxx * * * * // * range.selectNode( document.getElementsByTagName("i")[0] ); * * // * //xx[xxx]xxxxxx * * * ``` */ selectNode: function(node) { return this.setStartBefore(node).setEndAfter(node); },

/** * * @method selectNodeContents * @remind startOffset0 * endOffset * @param { Node } node range * @return { UE.dom.Range } range range * @example * ```html * * xxxxx[xx]xxxx * * * * // * range.selectNode( document.getElementsByTagName("b")[0] ); * * // * //[xxxxxxxxxxx] * * * ``` */ selectNodeContents: function(node) { return this.setStart(node, 0).setEndAtLast(node); },

/** * cloneRange * @method cloneRange * @remind rangerange clonerange * @return { UE.dom.Range } range */ cloneRange: function() { var me = this; return new Range(me.document) .setStart(me.startContainer, me.startOffset) .setEnd(me.endContainer, me.endOffset); },

/** * * @method collapse * @return { UE.dom.Range } range * @example * ```html * * xxxxx[xx]xxxx * * * * // * range.collapse(); * * // * //| * //xxxxxxx|xxxx * * * ``` */

/** * toStart * toStarttrue * @method collapse * @param { Boolean } toStart * @return { UE.dom.Range } rangerange * @see UE.dom.Range:collapse() * @example * ```html * * xxxxx[xx]xxxx * * * * // * range.collapse( true ); * * // * //| * //xxxxx|xxxxxx * * * ``` */ collapse: function(toStart) { var me = this; if (toStart) { me.endContainer = me.startContainer; me.endOffset = me.startOffset; } else { me.startContainer = me.endContainer; me.startOffset = me.endOffset; } me.collapsed = true; return me; },

/** * range"" * @method shrinkBoundary * @return { UE.dom.Range } range * @example * ```html * xxxx[xxxxx] => xxxx[xxxxx] * ``` * * @example * ```html * * x[xx]xxx * * * * // * range.shrinkBoundary(); * * // * //x[xx]xxx * * ``` * * @example * ```html * [xxxxxxxxxxx] => [xxxxxxxxxxx] * ``` */

/** * range"" * ignoreEndtrue * @method shrinkBoundary * @param { Boolean } ignoreEnd * @return { UE.dom.Range } range * @see UE.dom.domUtils.Range:shrinkBoundary() */ shrinkBoundary: function(ignoreEnd) { var me = this, child, collapsed = me.collapsed; function check(node) { return ( node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName] ); } while ( me.startContainer.nodeType == 1 && //element (child = me.startContainer.childNodes[me.startOffset]) && //element check(child) ) { me.setStart(child, 0); } if (collapsed) { return me.collapse(true); } if (!ignoreEnd) { while ( me.endContainer.nodeType == 1 && //element me.endOffset > 0 && // endOffset=0endOffst-1childNodes[endOffset] (child = me.endContainer.childNodes[me.endOffset - 1]) && //element check(child) ) { me.setEnd(child, child.childNodes.length); } } return me; },

/** * * @method getCommonAncestor * @remind range * @return { Node } range * @example * ```html * // * xxxx[xxx]xxxxxx * * * var node = range.getCommonAncestor(); * * // b * // B * console.log(node.tagName); * * * ``` */

/** * includeSelf * startContainerendContainer includeSelf * true * @method getCommonAncestor * @param { Boolean } includeSelf range * @return { Node } range * @see UE.dom.Range:getCommonAncestor() * @example * ```html * * * * xxxxxxxxx[xxx]xxxxxxxx * * * * var node = range.getCommonAncestor( false ); * * //BI * //output: B * console.log( node.tagName ); * * * * * ``` */

/** * includeSelf * startContainerendContainer includeSelf * true * ignoreTextNode * @method getCommonAncestor * @param { Boolean } includeSelf range * @param { Boolean } ignoreTextNode * @return { Node } range * @see UE.dom.Range:getCommonAncestor() * @see UE.dom.Range:getCommonAncestor(Boolean) * @example * ```html * * * * xxxxxxxx[x]xxxxxxxxxxx * * * * var node = range.getCommonAncestor( true, false ); * * //output: SPAN * console.log( node.tagName ); * * * * * ``` */ getCommonAncestor: function(includeSelf, ignoreTextNode) { var me = this, start = me.startContainer, end = me.endContainer; if (start === end) { if (includeSelf && selectOneNode(this)) { start = start.childNodes[me.startOffset]; if (start.nodeType == 1) return start; } // return ignoreTextNode && start.nodeType == 3 ? start.parentNode : start; } return domUtils.getCommonAncestor(start, end); },

/** * Range, * @method trimBoundary * @remind * @return { UE.dom.Range } range * @example * ```html * * // * xxx[xxxxx]xxx * * * // * // * range.trimBoundary(); * * // i * //xxx[xxxxx]xxx * * ``` */

/** * Range, * ignoreEnd * @method trimBoundary * @param { Boolean } ignoreEnd * @return { UE.dom.Range } range * @example * ```html * * // * xxx[xxxxx]xxx * * * // * // * range.trimBoundary( true ); * * // i * // * //xxx[xxxxx]xxx * * ``` */ trimBoundary: function(ignoreEnd) { this.txtToElmBoundary(); var start = this.startContainer, offset = this.startOffset, collapsed = this.collapsed, end = this.endContainer; if (start.nodeType == 3) { if (offset == 0) { this.setStartBefore(start); } else { if (offset >= start.nodeValue.length) { this.setStartAfter(start); } else { var textNode = domUtils.split(start, offset); // if (start === end) { this.setEnd(textNode, this.endOffset - offset); } else if (start.parentNode === end) { this.endOffset += 1; } this.setStartBefore(textNode); } } if (collapsed) { return this.collapse(true); } } if (!ignoreEnd) { offset = this.endOffset; end = this.endContainer; if (end.nodeType == 3) { if (offset == 0) { this.setEndBefore(end); } else { offset < end.nodeValue.length && domUtils.split(end, offset); this.setEndAfter(end); } } } return this; },

/** * , * @method txtToElmBoundary * @remind dom * @return { UE.dom.Range } range */

/** * , * ignoreCollapsed * @method txtToElmBoundary * @param { Boolean } ignoreCollapsed true * * @return { UE.dom.Range } range */ txtToElmBoundary: function(ignoreCollapsed) { function adjust(r, c) { var container = r[c + "Container"], offset = r[c + "Offset"]; if (container.nodeType == 3) { if (!offset) { r[ "set" + c.replace(/(\w)/, function(a) { return a.toUpperCase(); }) + "Before" ](container); } else if (offset >= container.nodeValue.length) { r[ "set" + c.replace(/(\w)/, function(a) { return a.toUpperCase(); }) + "After" ](container); } } }

if (ignoreCollapsed || !this.collapsed) { adjust(this, "start"); adjust(this, "end"); } return this; },

/** * range * @method insertNode * @param { Node } node * @remind DocumentFragment * @return { UE.dom.Range } range */ insertNode: function(node) { var first = node, length = 1; if (node.nodeType == 11) { first = node.firstChild; length = node.childNodes.length; } this.trimBoundary(true); var start = this.startContainer, offset = this.startOffset; var nextNode = start.childNodes[offset]; if (nextNode) { start.insertBefore(node, nextNode); } else { start.appendChild(node); } if (first.parentNode === this.endContainer) { this.endOffset = this.endOffset + length; } return this.setStartBefore(first); },

/** * * @method setCursor * @return { UE.dom.Range } range * @see UE.dom.Range:collapse() */

/** * toEnd * @method setCursor * @param { Boolean } toEnd true * * @return { UE.dom.Range } range * @see UE.dom.Range:collapse(Boolean) */ setCursor: function(toEnd, noFillData) { return this.collapse(!toEnd).select(noFillData); },

/** * rangerangedom * @method createBookmark * @param { Boolean } serialize IDtrue * ID * @return { Object } key start => ID * end => ID id => true * ID */ createBookmark: function(serialize, same) { var endNode, startNode = this.document.createElement("span"); startNode.style.cssText = "display:none;line-height:0px;"; startNode.appendChild(this.document.createTextNode("\u200D")); startNode.id = "_baidu_bookmark_start_" + (same ? "" : guid++);

if (!this.collapsed) { endNode = startNode.cloneNode(true); endNode.id = "_baidu_bookmark_end_" + (same ? "" : guid++); } this.insertNode(startNode); if (endNode) { this.collapse().insertNode(endNode).setEndBefore(endNode); } this.setStartAfter(startNode); return { start: serialize ? startNode.id : startNode, end: endNode ? (serialize ? endNode.id : endNode) : null, id: serialize }; },

/** * range * @method moveToBookmark * @param { BookMark } bookmark createBookmark * @return { UE.dom.Range } range * @see UE.dom.Range:createBookmark(Boolean) */ moveToBookmark: function(bookmark) { var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start, end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end; this.setStartBefore(start); domUtils.remove(start); if (end) { this.setEndBefore(end); domUtils.remove(end); } else { this.collapse(true); } return this; },

/** * range"" * @method enlarge * @remind * @return { UE.dom.Range } range */

/** * range"" toBlock * block * @method enlarge * @param { Boolean } toBlock block * @return { UE.dom.Range } range */ enlarge: function(toBlock, stopFn) { var isBody = domUtils.isBody, pre, node, tmp = this.document.createTextNode(""); if (toBlock) { node = this.startContainer; if (node.nodeType == 1) { if (node.childNodes[this.startOffset]) { pre = node = node.childNodes[this.startOffset]; } else { node.appendChild(tmp); pre = node = tmp; } } else { pre = node; } while (1) { if (domUtils.isBlockElm(node)) { node = pre; while ((pre = node.previousSibling) && !domUtils.isBlockE