You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

29659 lines
1.2 MiB

  1. /*!
  2. * UEditor
  3. * version: ueditor
  4. * build: Fri Sep 28 2018 15:50:42 GMT+0800 (China Standard Time)
  5. */
  6. // import $ from 'jquery'
  7. (function () {
  8. // editor.js
  9. UEDITOR_CONFIG = window.UEDITOR_CONFIG || {};
  10. var baidu = window.baidu || {};
  11. window.baidu = baidu;
  12. window.UE = baidu.editor = window.UE || {};
  13. UE.plugins = {};
  14. UE.commands = {};
  15. UE.instants = {};
  16. UE.I18N = {};
  17. UE._customizeUI = {};
  18. UE.version = "1.4.3";
  19. var dom = UE.dom = {};
  20. // core/browser.js
  21. /**
  22. * 浏览器判断模块
  23. * @file
  24. * @module UE.browser
  25. * @since 1.2.6.1
  26. */
  27. /**
  28. * 提供浏览器检测的模块
  29. * @unfile
  30. * @module UE.browser
  31. */
  32. var browser = UE.browser = function () {
  33. var agent = navigator.userAgent.toLowerCase(),
  34. opera = window.opera,
  35. browser = {
  36. /**
  37. * @property {boolean} ie 检测当前浏览器是否为IE
  38. * @example
  39. * ```javascript
  40. * if ( UE.browser.ie ) {
  41. * console.log( '当前浏览器是IE' );
  42. * }
  43. * ```
  44. */
  45. ie: /(msie\s|trident.*rv:)([\w.]+)/.test(agent),
  46. /**
  47. * @property {boolean} opera 检测当前浏览器是否为Opera
  48. * @example
  49. * ```javascript
  50. * if ( UE.browser.opera ) {
  51. * console.log( '当前浏览器是Opera' );
  52. * }
  53. * ```
  54. */
  55. opera: (!!opera && opera.version),
  56. /**
  57. * @property {boolean} webkit 检测当前浏览器是否是webkit内核的浏览器
  58. * @example
  59. * ```javascript
  60. * if ( UE.browser.webkit ) {
  61. * console.log( '当前浏览器是webkit内核浏览器' );
  62. * }
  63. * ```
  64. */
  65. webkit: (agent.indexOf(' applewebkit/') > -1),
  66. /**
  67. * @property {boolean} mac 检测当前浏览器是否是运行在mac平台下
  68. * @example
  69. * ```javascript
  70. * if ( UE.browser.mac ) {
  71. * console.log( '当前浏览器运行在mac平台下' );
  72. * }
  73. * ```
  74. */
  75. mac: (agent.indexOf('macintosh') > -1),
  76. /**
  77. * @property {boolean} quirks 检测当前浏览器是否处于“怪异模式”下
  78. * @example
  79. * ```javascript
  80. * if ( UE.browser.quirks ) {
  81. * console.log( '当前浏览器运行处于“怪异模式”' );
  82. * }
  83. * ```
  84. */
  85. quirks: (document.compatMode == 'BackCompat')
  86. };
  87. /**
  88. * @property {boolean} gecko 检测当前浏览器内核是否是gecko内核
  89. * @example
  90. * ```javascript
  91. * if ( UE.browser.gecko ) {
  92. * console.log( '当前浏览器内核是gecko内核' );
  93. * }
  94. * ```
  95. */
  96. browser.gecko = (navigator.product == 'Gecko' && !browser.webkit && !browser.opera && !browser.ie);
  97. var version = 0;
  98. // Internet Explorer 6.0+
  99. if (browser.ie) {
  100. var v1 = agent.match(/(?:msie\s([\w.]+))/);
  101. var v2 = agent.match(/(?:trident.*rv:([\w.]+))/);
  102. if (v1 && v2 && v1[1] && v2[1]) {
  103. version = Math.max(v1[1] * 1, v2[1] * 1);
  104. } else if (v1 && v1[1]) {
  105. version = v1[1] * 1;
  106. } else if (v2 && v2[1]) {
  107. version = v2[1] * 1;
  108. } else {
  109. version = 0;
  110. }
  111. browser.ie11Compat = document.documentMode == 11;
  112. /**
  113. * @property { boolean } ie9Compat 检测浏览器模式是否为 IE9 兼容模式
  114. * @warning 如果浏览器不是IE, 则该值为undefined
  115. * @example
  116. * ```javascript
  117. * if ( UE.browser.ie9Compat ) {
  118. * console.log( '当前浏览器运行在IE9兼容模式下' );
  119. * }
  120. * ```
  121. */
  122. browser.ie9Compat = document.documentMode == 9;
  123. /**
  124. * @property { boolean } ie8 检测浏览器是否是IE8浏览器
  125. * @warning 如果浏览器不是IE, 则该值为undefined
  126. * @example
  127. * ```javascript
  128. * if ( UE.browser.ie8 ) {
  129. * console.log( '当前浏览器是IE8浏览器' );
  130. * }
  131. * ```
  132. */
  133. browser.ie8 = !!document.documentMode;
  134. /**
  135. * @property { boolean } ie8Compat 检测浏览器模式是否为 IE8 兼容模式
  136. * @warning 如果浏览器不是IE, 则该值为undefined
  137. * @example
  138. * ```javascript
  139. * if ( UE.browser.ie8Compat ) {
  140. * console.log( '当前浏览器运行在IE8兼容模式下' );
  141. * }
  142. * ```
  143. */
  144. browser.ie8Compat = document.documentMode == 8;
  145. /**
  146. * @property { boolean } ie7Compat 检测浏览器模式是否为 IE7 兼容模式
  147. * @warning 如果浏览器不是IE, 则该值为undefined
  148. * @example
  149. * ```javascript
  150. * if ( UE.browser.ie7Compat ) {
  151. * console.log( '当前浏览器运行在IE7兼容模式下' );
  152. * }
  153. * ```
  154. */
  155. browser.ie7Compat = ((version == 7 && !document.documentMode)
  156. || document.documentMode == 7);
  157. /**
  158. * @property { boolean } ie6Compat 检测浏览器模式是否为 IE6 模式 或者怪异模式
  159. * @warning 如果浏览器不是IE, 则该值为undefined
  160. * @example
  161. * ```javascript
  162. * if ( UE.browser.ie6Compat ) {
  163. * console.log( '当前浏览器运行在IE6模式或者怪异模式下' );
  164. * }
  165. * ```
  166. */
  167. browser.ie6Compat = (version < 7 || browser.quirks);
  168. browser.ie9above = version > 8;
  169. browser.ie9below = version < 9;
  170. browser.ie11above = version > 10;
  171. browser.ie11below = version < 11;
  172. }
  173. // Gecko.
  174. if (browser.gecko) {
  175. var geckoRelease = agent.match(/rv:([\d\.]+)/);
  176. if (geckoRelease) {
  177. geckoRelease = geckoRelease[1].split('.');
  178. version = geckoRelease[0] * 10000 + (geckoRelease[1] || 0) * 100 + (geckoRelease[2] || 0) * 1;
  179. }
  180. }
  181. /**
  182. * @property { Number } chrome 检测当前浏览器是否为Chrome, 如果是,则返回Chrome的大版本号
  183. * @warning 如果浏览器不是chrome, 则该值为undefined
  184. * @example
  185. * ```javascript
  186. * if ( UE.browser.chrome ) {
  187. * console.log( '当前浏览器是Chrome' );
  188. * }
  189. * ```
  190. */
  191. if (/chrome\/(\d+\.\d)/i.test(agent)) {
  192. browser.chrome = + RegExp['\x241'];
  193. }
  194. /**
  195. * @property { Number } safari 检测当前浏览器是否为Safari, 如果是,则返回Safari的大版本号
  196. * @warning 如果浏览器不是safari, 则该值为undefined
  197. * @example
  198. * ```javascript
  199. * if ( UE.browser.safari ) {
  200. * console.log( '当前浏览器是Safari' );
  201. * }
  202. * ```
  203. */
  204. if (/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(agent) && !/chrome/i.test(agent)) {
  205. browser.safari = + (RegExp['\x241'] || RegExp['\x242']);
  206. }
  207. // Opera 9.50+
  208. if (browser.opera)
  209. version = parseFloat(opera.version());
  210. // WebKit 522+ (Safari 3+)
  211. if (browser.webkit)
  212. version = parseFloat(agent.match(/ applewebkit\/(\d+)/)[1]);
  213. /**
  214. * @property { Number } version 检测当前浏览器版本号
  215. * @remind
  216. * <ul>
  217. * <li>IE系列返回值为5,6,7,8,9,10等</li>
  218. * <li>gecko系列会返回10900,158900等</li>
  219. * <li>webkit系列会返回其build号 (如 522等)</li>
  220. * </ul>
  221. * @example
  222. * ```javascript
  223. * console.log( '当前浏览器版本号是: ' + UE.browser.version );
  224. * ```
  225. */
  226. browser.version = version;
  227. /**
  228. * @property { boolean } isCompatible 检测当前浏览器是否能够与UEditor良好兼容
  229. * @example
  230. * ```javascript
  231. * if ( UE.browser.isCompatible ) {
  232. * console.log( '浏览器与UEditor能够良好兼容' );
  233. * }
  234. * ```
  235. */
  236. browser.isCompatible =
  237. !browser.mobile && (
  238. (browser.ie && version >= 6) ||
  239. (browser.gecko && version >= 10801) ||
  240. (browser.opera && version >= 9.5) ||
  241. (browser.air && version >= 1) ||
  242. (browser.webkit && version >= 522) ||
  243. false);
  244. return browser;
  245. }();
  246. //快捷方式
  247. var ie = browser.ie,
  248. webkit = browser.webkit,
  249. gecko = browser.gecko,
  250. opera = browser.opera;
  251. // core/utils.js
  252. /**
  253. * 工具函数包
  254. * @file
  255. * @module UE.utils
  256. * @since 1.2.6.1
  257. */
  258. /**
  259. * UEditor封装使用的静态工具函数
  260. * @module UE.utils
  261. * @unfile
  262. */
  263. var utils = UE.utils = {
  264. /**
  265. * 用给定的迭代器遍历对象
  266. * @method each
  267. * @param { Object } obj 需要遍历的对象
  268. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  269. * @example
  270. * ```javascript
  271. * var demoObj = {
  272. * key1: 1,
  273. * key2: 2
  274. * };
  275. *
  276. * //output: key1: 1, key2: 2
  277. * UE.utils.each( demoObj, funciton ( value, key ) {
  278. *
  279. * console.log( key + ":" + value );
  280. *
  281. * } );
  282. * ```
  283. */
  284. /**
  285. * 用给定的迭代器遍历数组或类数组对象
  286. * @method each
  287. * @param { Array } array 需要遍历的数组或者类数组
  288. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  289. * @example
  290. * ```javascript
  291. * var divs = document.getElmentByTagNames( "div" );
  292. *
  293. * //output: 0: DIV, 1: DIV ...
  294. * UE.utils.each( divs, funciton ( value, key ) {
  295. *
  296. * console.log( key + ":" + value.tagName );
  297. *
  298. * } );
  299. * ```
  300. */
  301. each: function (obj, iterator, context) {
  302. if (obj == null) return;
  303. if (obj.length === +obj.length) {
  304. for (var i = 0, l = obj.length; i < l; i++) {
  305. if (iterator.call(context, obj[i], i, obj) === false)
  306. return false;
  307. }
  308. } else {
  309. for (var key in obj) {
  310. if (obj.hasOwnProperty(key)) {
  311. if (iterator.call(context, obj[key], key, obj) === false)
  312. return false;
  313. }
  314. }
  315. }
  316. },
  317. /**
  318. * 以给定对象作为原型创建一个新对象
  319. * @method makeInstance
  320. * @param { Object } protoObject 该对象将作为新创建对象的原型
  321. * @return { Object } 新的对象, 该对象的原型是给定的protoObject对象
  322. * @example
  323. * ```javascript
  324. *
  325. * var protoObject = { sayHello: function () { console.log('Hello UEditor!'); } };
  326. *
  327. * var newObject = UE.utils.makeInstance( protoObject );
  328. * //output: Hello UEditor!
  329. * newObject.sayHello();
  330. * ```
  331. */
  332. makeInstance: function (obj) {
  333. var noop = new Function();
  334. noop.prototype = obj;
  335. obj = new noop;
  336. noop.prototype = null;
  337. return obj;
  338. },
  339. /**
  340. * 将source对象中的属性扩展到target对象上
  341. * @method extend
  342. * @remind 该方法将强制把source对象上的属性复制到target对象上
  343. * @see UE.utils.extend(Object,Object,Boolean)
  344. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  345. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  346. * @return { Object } 返回target对象
  347. * @example
  348. * ```javascript
  349. *
  350. * var target = { name: 'target', sex: 1 },
  351. * source = { name: 'source', age: 17 };
  352. *
  353. * UE.utils.extend( target, source );
  354. *
  355. * //output: { name: 'source', sex: 1, age: 17 }
  356. * console.log( target );
  357. *
  358. * ```
  359. */
  360. /**
  361. * 将source对象中的属性扩展到target对象上, 根据指定的isKeepTarget值决定是否保留目标对象中与
  362. * 源对象属性名相同的属性值。
  363. * @method extend
  364. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  365. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  366. * @param { Boolean } isKeepTarget 是否保留目标对象中与源对象中属性名相同的属性
  367. * @return { Object } 返回target对象
  368. * @example
  369. * ```javascript
  370. *
  371. * var target = { name: 'target', sex: 1 },
  372. * source = { name: 'source', age: 17 };
  373. *
  374. * UE.utils.extend( target, source, true );
  375. *
  376. * //output: { name: 'target', sex: 1, age: 17 }
  377. * console.log( target );
  378. *
  379. * ```
  380. */
  381. extend: function (t, s, b) {
  382. if (s) {
  383. for (var k in s) {
  384. if (!b || !t.hasOwnProperty(k)) {
  385. t[k] = s[k];
  386. }
  387. }
  388. }
  389. return t;
  390. },
  391. /**
  392. * 将给定的多个对象的属性复制到目标对象target上
  393. * @method extend2
  394. * @remind 该方法将强制把源对象上的属性复制到target对象上
  395. * @remind 该方法支持两个及以上的参数, 从第二个参数开始, 其属性都会被复制到第一个参数上。 如果遇到同名的属性,
  396. * 将会覆盖掉之前的值。
  397. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  398. * @param { Object... } source 源对象, 支持多个对象, 该对象的属性会被附加到target对象上
  399. * @return { Object } 返回target对象
  400. * @example
  401. * ```javascript
  402. *
  403. * var target = {},
  404. * source1 = { name: 'source', age: 17 },
  405. * source2 = { title: 'dev' };
  406. *
  407. * UE.utils.extend2( target, source1, source2 );
  408. *
  409. * //output: { name: 'source', age: 17, title: 'dev' }
  410. * console.log( target );
  411. *
  412. * ```
  413. */
  414. extend2: function (t) {
  415. var a = arguments;
  416. for (var i = 1; i < a.length; i++) {
  417. var x = a[i];
  418. for (var k in x) {
  419. if (!t.hasOwnProperty(k)) {
  420. t[k] = x[k];
  421. }
  422. }
  423. }
  424. return t;
  425. },
  426. /**
  427. * 模拟继承机制, 使得subClass继承自superClass
  428. * @method inherits
  429. * @param { Object } subClass 子类对象
  430. * @param { Object } superClass 超类对象
  431. * @warning 该方法只能让subClass继承超类的原型, subClass对象自身的属性和方法不会被继承
  432. * @return { Object } 继承superClass后的子类对象
  433. * @example
  434. * ```javascript
  435. * function SuperClass(){
  436. * this.name = "小李";
  437. * }
  438. *
  439. * SuperClass.prototype = {
  440. * hello:function(str){
  441. * console.log(this.name + str);
  442. * }
  443. * }
  444. *
  445. * function SubClass(){
  446. * this.name = "小张";
  447. * }
  448. *
  449. * UE.utils.inherits(SubClass,SuperClass);
  450. *
  451. * var sub = new SubClass();
  452. * //output: '小张早上好!
  453. * sub.hello("早上好!");
  454. * ```
  455. */
  456. inherits: function (subClass, superClass) {
  457. var oldP = subClass.prototype,
  458. newP = utils.makeInstance(superClass.prototype);
  459. utils.extend(newP, oldP, true);
  460. subClass.prototype = newP;
  461. return (newP.constructor = subClass);
  462. },
  463. /**
  464. * 用指定的context对象作为函数fn的上下文
  465. * @method bind
  466. * @param { Function } fn 需要绑定上下文的函数对象
  467. * @param { Object } content 函数fn新的上下文对象
  468. * @return { Function } 一个新的函数, 该函数作为原始函数fn的代理, 将完成fn的上下文调换工作。
  469. * @example
  470. * ```javascript
  471. *
  472. * var name = 'window',
  473. * newTest = null;
  474. *
  475. * function test () {
  476. * console.log( this.name );
  477. * }
  478. *
  479. * newTest = UE.utils.bind( test, { name: 'object' } );
  480. *
  481. * //output: object
  482. * newTest();
  483. *
  484. * //output: window
  485. * test();
  486. *
  487. * ```
  488. */
  489. bind: function (fn, context) {
  490. return function () {
  491. return fn.apply(context, arguments);
  492. };
  493. },
  494. /**
  495. * 创建延迟指定时间后执行的函数fn
  496. * @method defer
  497. * @param { Function } fn 需要延迟执行的函数对象
  498. * @param { int } delay 延迟的时间, 单位是毫秒
  499. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  500. * 而不能保证刚好到达延迟时间时执行。
  501. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  502. * @example
  503. * ```javascript
  504. * var start = 0;
  505. *
  506. * function test(){
  507. * console.log( new Date() - start );
  508. * }
  509. *
  510. * var testDefer = UE.utils.defer( test, 1000 );
  511. * //
  512. * start = new Date();
  513. * //output: (大约在1000毫秒之后输出) 1000
  514. * testDefer();
  515. * ```
  516. */
  517. /**
  518. * 创建延迟指定时间后执行的函数fn, 如果在延迟时间内再次执行该方法, 将会根据指定的exclusion的值,
  519. * 决定是否取消前一次函数的执行, 如果exclusion的值为true, 则取消执行,反之,将继续执行前一个方法。
  520. * @method defer
  521. * @param { Function } fn 需要延迟执行的函数对象
  522. * @param { int } delay 延迟的时间, 单位是毫秒
  523. * @param { Boolean } exclusion 如果在延迟时间内再次执行该函数,该值将决定是否取消执行前一次函数的执行,
  524. * 值为true表示取消执行, 反之则将在执行前一次函数之后才执行本次函数调用。
  525. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  526. * 而不能保证刚好到达延迟时间时执行。
  527. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  528. * @example
  529. * ```javascript
  530. *
  531. * function test(){
  532. * console.log(1);
  533. * }
  534. *
  535. * var testDefer = UE.utils.defer( test, 1000, true );
  536. *
  537. * //output: (两次调用仅有一次输出) 1
  538. * testDefer();
  539. * testDefer();
  540. * ```
  541. */
  542. defer: function (fn, delay, exclusion) {
  543. var timerID;
  544. return function () {
  545. if (exclusion) {
  546. clearTimeout(timerID);
  547. }
  548. timerID = setTimeout(fn, delay);
  549. };
  550. },
  551. /**
  552. * 获取元素item在数组array中首次出现的位置, 如果未找到item, 则返回-1
  553. * @method indexOf
  554. * @remind 该方法的匹配过程使用的是恒等“===”
  555. * @param { Array } array 需要查找的数组对象
  556. * @param { * } item 需要在目标数组中查找的值
  557. * @return { int } 返回item在目标数组array中首次出现的位置, 如果在数组中未找到item, 则返回-1
  558. * @example
  559. * ```javascript
  560. * var item = 1,
  561. * arr = [ 3, 4, 6, 8, 1, 1, 2 ];
  562. *
  563. * //output: 4
  564. * console.log( UE.utils.indexOf( arr, item ) );
  565. * ```
  566. */
  567. /**
  568. * 获取元素item数组array中首次出现的位置, 如果未找到item, 则返回-1。通过start的值可以指定搜索的起始位置。
  569. * @method indexOf
  570. * @remind 该方法的匹配过程使用的是恒等“===”
  571. * @param { Array } array 需要查找的数组对象
  572. * @param { * } item 需要在目标数组中查找的值
  573. * @param { int } start 搜索的起始位置
  574. * @return { int } 返回item在目标数组array中的start位置之后首次出现的位置, 如果在数组中未找到item, 则返回-1
  575. * @example
  576. * ```javascript
  577. * var item = 1,
  578. * arr = [ 3, 4, 6, 8, 1, 2, 8, 3, 2, 1, 1, 4 ];
  579. *
  580. * //output: 9
  581. * console.log( UE.utils.indexOf( arr, item, 5 ) );
  582. * ```
  583. */
  584. indexOf: function (array, item, start) {
  585. var index = -1;
  586. start = this.isNumber(start) ? start : 0;
  587. this.each(array, function (v, i) {
  588. if (i >= start && v === item) {
  589. index = i;
  590. return false;
  591. }
  592. });
  593. return index;
  594. },
  595. /**
  596. * 移除数组array中所有的元素item
  597. * @method removeItem
  598. * @param { Array } array 要移除元素的目标数组
  599. * @param { * } item 将要被移除的元素
  600. * @remind 该方法的匹配过程使用的是恒等“===”
  601. * @example
  602. * ```javascript
  603. * var arr = [ 4, 5, 7, 1, 3, 4, 6 ];
  604. *
  605. * UE.utils.removeItem( arr, 4 );
  606. * //output: [ 5, 7, 1, 3, 6 ]
  607. * console.log( arr );
  608. *
  609. * ```
  610. */
  611. removeItem: function (array, item) {
  612. for (var i = 0, l = array.length; i < l; i++) {
  613. if (array[i] === item) {
  614. array.splice(i, 1);
  615. i--;
  616. }
  617. }
  618. },
  619. /**
  620. * 删除字符串str的首尾空格
  621. * @method trim
  622. * @param { String } str 需要删除首尾空格的字符串
  623. * @return { String } 删除了首尾的空格后的字符串
  624. * @example
  625. * ```javascript
  626. *
  627. * var str = " UEdtior ";
  628. *
  629. * //output: 9
  630. * console.log( str.length );
  631. *
  632. * //output: 7
  633. * console.log( UE.utils.trim( " UEdtior " ).length );
  634. *
  635. * //output: 9
  636. * console.log( str.length );
  637. *
  638. * ```
  639. */
  640. trim: function (str) {
  641. return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, '');
  642. },
  643. /**
  644. * 将字符串str以','分隔成数组后,将该数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  645. * @method listToMap
  646. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  647. * @param { String } str 该字符串将被以','分割为数组, 然后进行转化
  648. * @return { Object } 转化之后的hash对象
  649. * @example
  650. * ```javascript
  651. *
  652. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  653. * console.log( UE.utils.listToMap( 'UEdtior,Hello' ) );
  654. *
  655. * ```
  656. */
  657. /**
  658. * 将字符串数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  659. * @method listToMap
  660. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  661. * @param { Array } arr 字符串数组
  662. * @return { Object } 转化之后的hash对象
  663. * @example
  664. * ```javascript
  665. *
  666. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  667. * console.log( UE.utils.listToMap( [ 'UEdtior', 'Hello' ] ) );
  668. *
  669. * ```
  670. */
  671. listToMap: function (list) {
  672. if (!list) return {};
  673. list = utils.isArray(list) ? list : list.split(',');
  674. for (var i = 0, ci, obj = {}; ci = list[i++];) {
  675. obj[ci.toUpperCase()] = obj[ci] = 1;
  676. }
  677. return obj;
  678. },
  679. /**
  680. * 将str中的html符号转义,将转义“',&,<,",>”五个字符
  681. * @method unhtml
  682. * @param { String } str 需要转义的字符串
  683. * @return { String } 转义后的字符串
  684. * @example
  685. * ```javascript
  686. * var html = '<body>&</body>';
  687. *
  688. * //output: &lt;body&gt;&amp;&lt;/body&gt;
  689. * console.log( UE.utils.unhtml( html ) );
  690. *
  691. * ```
  692. */
  693. unhtml: function (str, reg) {
  694. return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp|#\d+);)?/g, function (a, b) {
  695. if (b) {
  696. return a;
  697. } else {
  698. return {
  699. '<': '&lt;',
  700. '&': '&amp;',
  701. '"': '&quot;',
  702. '>': '&gt;',
  703. "'": '&#39;'
  704. }[a]
  705. }
  706. }) : '';
  707. },
  708. /**
  709. * 将url中的html字符转义, 仅转义 ', ", <, > 四个字符
  710. * @param { String } str 需要转义的字符串
  711. * @param { RegExp } reg 自定义的正则
  712. * @return { String } 转义后的字符串
  713. */
  714. unhtmlForUrl: function (str, reg) {
  715. return str ? str.replace(reg || /[<">']/g, function (a) {
  716. return {
  717. '<': '&lt;',
  718. '&': '&amp;',
  719. '"': '&quot;',
  720. '>': '&gt;',
  721. "'": '&#39;'
  722. }[a]
  723. }) : '';
  724. },
  725. /**
  726. * 将str中的转义字符还原成html字符
  727. * @see UE.utils.unhtml(String);
  728. * @method html
  729. * @param { String } str 需要逆转义的字符串
  730. * @return { String } 逆转义后的字符串
  731. * @example
  732. * ```javascript
  733. *
  734. * var str = '&lt;body&gt;&amp;&lt;/body&gt;';
  735. *
  736. * //output: <body>&</body>
  737. * console.log( UE.utils.html( str ) );
  738. *
  739. * ```
  740. */
  741. html: function (str) {
  742. return str ? str.replace(/&((g|l|quo)t|amp|#39|nbsp);/g, function (m) {
  743. return {
  744. '&lt;': '<',
  745. '&amp;': '&',
  746. '&quot;': '"',
  747. '&gt;': '>',
  748. '&#39;': "'",
  749. '&nbsp;': ' '
  750. }[m]
  751. }) : '';
  752. },
  753. /**
  754. * 将css样式转换为驼峰的形式
  755. * @method cssStyleToDomStyle
  756. * @param { String } cssName 需要转换的css样式名
  757. * @return { String } 转换成驼峰形式后的css样式名
  758. * @example
  759. * ```javascript
  760. *
  761. * var str = 'border-top';
  762. *
  763. * //output: borderTop
  764. * console.log( UE.utils.cssStyleToDomStyle( str ) );
  765. *
  766. * ```
  767. */
  768. cssStyleToDomStyle: function () {
  769. var test = document.createElement('div').style,
  770. cache = {
  771. 'float': test.cssFloat != undefined ? 'cssFloat' : test.styleFloat != undefined ? 'styleFloat' : 'float'
  772. };
  773. return function (cssName) {
  774. return cache[cssName] || (cache[cssName] = cssName.toLowerCase().replace(/-./g, function (match) {
  775. return match.charAt(1).toUpperCase();
  776. }));
  777. };
  778. }(),
  779. /**
  780. * 动态加载文件到doc中
  781. * @method loadFile
  782. * @param { DomDocument } document 需要加载资源文件的文档对象
  783. * @param { Object } options 加载资源文件的属性集合, 取值请参考代码示例
  784. * @example
  785. * ```javascript
  786. *
  787. * UE.utils.loadFile( document, {
  788. * src:"test.js",
  789. * tag:"script",
  790. * type:"text/javascript",
  791. * defer:"defer"
  792. * } );
  793. *
  794. * ```
  795. */
  796. /**
  797. * 动态加载文件到doc中,加载成功后执行的回调函数fn
  798. * @method loadFile
  799. * @param { DomDocument } document 需要加载资源文件的文档对象
  800. * @param { Object } options 加载资源文件的属性集合, 该集合支持的值是script标签和style标签支持的所有属性。
  801. * @param { Function } fn 资源文件加载成功之后执行的回调
  802. * @warning 对于在同一个文档中多次加载同一URL的文件, 该方法会在第一次加载之后缓存该请求,
  803. * 在此之后的所有同一URL的请求, 将会直接触发回调。
  804. * @example
  805. * ```javascript
  806. *
  807. * UE.utils.loadFile( document, {
  808. * src:"test.js",
  809. * tag:"script",
  810. * type:"text/javascript",
  811. * defer:"defer"
  812. * }, function () {
  813. * console.log('加载成功');
  814. * } );
  815. *
  816. * ```
  817. */
  818. loadFile: function () {
  819. var tmpList = [];
  820. function getItem(doc, obj) {
  821. try {
  822. for (var i = 0, ci; ci = tmpList[i++];) {
  823. if (ci.doc === doc && ci.url == (obj.src || obj.href)) {
  824. return ci;
  825. }
  826. }
  827. } catch (e) {
  828. return null;
  829. }
  830. }
  831. return function (doc, obj, fn) {
  832. var item = getItem(doc, obj);
  833. if (item) {
  834. if (item.ready) {
  835. fn && fn();
  836. } else {
  837. item.funs.push(fn)
  838. }
  839. return;
  840. }
  841. tmpList.push({
  842. doc: doc,
  843. url: obj.src || obj.href,
  844. funs: [fn]
  845. });
  846. if (!doc.body) {
  847. var html = [];
  848. for (var p in obj) {
  849. if (p == 'tag') continue;
  850. html.push(p + '="' + obj[p] + '"')
  851. }
  852. doc.write('<' + obj.tag + ' ' + html.join(' ') + ' ></' + obj.tag + '>');
  853. return;
  854. }
  855. if (obj.id && doc.getElementById(obj.id)) {
  856. return;
  857. }
  858. var element = doc.createElement(obj.tag);
  859. delete obj.tag;
  860. for (var p in obj) {
  861. element.setAttribute(p, obj[p]);
  862. }
  863. element.onload = element.onreadystatechange = function () {
  864. if (!this.readyState || /loaded|complete/.test(this.readyState)) {
  865. item = getItem(doc, obj);
  866. if (item.funs.length > 0) {
  867. item.ready = 1;
  868. for (var fi; fi = item.funs.pop();) {
  869. fi();
  870. }
  871. }
  872. element.onload = element.onreadystatechange = null;
  873. }
  874. };
  875. element.onerror = function () {
  876. throw Error('The load ' + (obj.href || obj.src) + ' fails,check the url settings of file ueditor.config.js ')
  877. };
  878. doc.getElementsByTagName("head")[0].appendChild(element);
  879. }
  880. }(),
  881. /**
  882. * 判断obj对象是否为空
  883. * @method isEmptyObject
  884. * @param { * } obj 需要判断的对象
  885. * @remind 如果判断的对象是NULL, 将直接返回true, 如果是数组且为空, 返回true, 如果是字符串, 且字符串为空,
  886. * 返回true, 如果是普通对象, 且该对象没有任何实例属性, 返回true
  887. * @return { Boolean } 对象是否为空
  888. * @example
  889. * ```javascript
  890. *
  891. * //output: true
  892. * console.log( UE.utils.isEmptyObject( {} ) );
  893. *
  894. * //output: true
  895. * console.log( UE.utils.isEmptyObject( [] ) );
  896. *
  897. * //output: true
  898. * console.log( UE.utils.isEmptyObject( "" ) );
  899. *
  900. * //output: false
  901. * console.log( UE.utils.isEmptyObject( { key: 1 } ) );
  902. *
  903. * //output: false
  904. * console.log( UE.utils.isEmptyObject( [1] ) );
  905. *
  906. * //output: false
  907. * console.log( UE.utils.isEmptyObject( "1" ) );
  908. *
  909. * ```
  910. */
  911. isEmptyObject: function (obj) {
  912. if (obj == null) return true;
  913. if (this.isArray(obj) || this.isString(obj)) return obj.length === 0;
  914. for (var key in obj) if (obj.hasOwnProperty(key)) return false;
  915. return true;
  916. },
  917. /**
  918. * 把rgb格式的颜色值转换成16进制格式
  919. * @method fixColor
  920. * @param { String } rgb格式的颜色值
  921. * @param { String }
  922. * @example
  923. * rgb(255,255,255) => "#ffffff"
  924. */
  925. fixColor: function (name, value) {
  926. if (/color/i.test(name) && /rgba?/.test(value)) {
  927. var array = value.split(",");
  928. if (array.length > 3)
  929. return "";
  930. value = "#";
  931. for (var i = 0, color; color = array[i++];) {
  932. color = parseInt(color.replace(/[^\d]/gi, ''), 10).toString(16);
  933. value += color.length == 1 ? "0" + color : color;
  934. }
  935. value = value.toUpperCase();
  936. }
  937. return value;
  938. },
  939. /**
  940. * 只针对border,padding,margin做了处理,因为性能问题
  941. * @public
  942. * @function
  943. * @param {String} val style字符串
  944. */
  945. optCss: function (val) {
  946. var padding, margin, border;
  947. val = val.replace(/(padding|margin|border)\-([^:]+):([^;]+);?/gi, function (str, key, name, val) {
  948. if (val.split(' ').length == 1) {
  949. switch (key) {
  950. case 'padding':
  951. !padding && (padding = {});
  952. padding[name] = val;
  953. return '';
  954. case 'margin':
  955. !margin && (margin = {});
  956. margin[name] = val;
  957. return '';
  958. case 'border':
  959. return val == 'initial' ? '' : str;
  960. }
  961. }
  962. return str;
  963. });
  964. function opt(obj, name) {
  965. if (!obj) {
  966. return '';
  967. }
  968. var t = obj.top, b = obj.bottom, l = obj.left, r = obj.right, val = '';
  969. if (!t || !l || !b || !r) {
  970. for (var p in obj) {
  971. val += ';' + name + '-' + p + ':' + obj[p] + ';';
  972. }
  973. } else {
  974. val += ';' + name + ':' +
  975. (t == b && b == l && l == r ? t :
  976. t == b && l == r ? (t + ' ' + l) :
  977. l == r ? (t + ' ' + l + ' ' + b) : (t + ' ' + r + ' ' + b + ' ' + l)) + ';'
  978. }
  979. return val;
  980. }
  981. val += opt(padding, 'padding') + opt(margin, 'margin');
  982. return val.replace(/^[ \n\r\t;]*|[ \n\r\t]*$/, '').replace(/;([ \n\r\t]+)|\1;/g, ';')
  983. .replace(/(&((l|g)t|quot|#39))?;{2,}/g, function (a, b) {
  984. return b ? b + ";;" : ';'
  985. });
  986. },
  987. /**
  988. * 克隆对象
  989. * @method clone
  990. * @param { Object } source 源对象
  991. * @return { Object } source的一个副本
  992. */
  993. /**
  994. * 深度克隆对象,将source的属性克隆到target对象, 会覆盖target重名的属性。
  995. * @method clone
  996. * @param { Object } source 源对象
  997. * @param { Object } target 目标对象
  998. * @return { Object } 附加了source对象所有属性的target对象
  999. */
  1000. clone: function (source, target) {
  1001. var tmp;
  1002. target = target || {};
  1003. for (var i in source) {
  1004. if (source.hasOwnProperty(i)) {
  1005. tmp = source[i];
  1006. if (typeof tmp == 'object') {
  1007. target[i] = utils.isArray(tmp) ? [] : {};
  1008. utils.clone(source[i], target[i])
  1009. } else {
  1010. target[i] = tmp;
  1011. }
  1012. }
  1013. }
  1014. return target;
  1015. },
  1016. /**
  1017. * 把cm/pt为单位的值转换为px为单位的值
  1018. * @method transUnitToPx
  1019. * @param { String } 待转换的带单位的字符串
  1020. * @return { String } 转换为px为计量单位的值的字符串
  1021. * @example
  1022. * ```javascript
  1023. *
  1024. * //output: 500px
  1025. * console.log( UE.utils.transUnitToPx( '20cm' ) );
  1026. *
  1027. * //output: 27px
  1028. * console.log( UE.utils.transUnitToPx( '20pt' ) );
  1029. *
  1030. * ```
  1031. */
  1032. transUnitToPx: function (val) {
  1033. if (!/(pt|cm)/.test(val)) {
  1034. return val
  1035. }
  1036. var unit;
  1037. val.replace(/([\d.]+)(\w+)/, function (str, v, u) {
  1038. val = v;
  1039. unit = u;
  1040. });
  1041. switch (unit) {
  1042. case 'cm':
  1043. val = parseFloat(val) * 25;
  1044. break;
  1045. case 'pt':
  1046. val = Math.round(parseFloat(val) * 96 / 72);
  1047. }
  1048. return val + (val ? 'px' : '');
  1049. },
  1050. /**
  1051. * 在dom树ready之后执行给定的回调函数
  1052. * @method domReady
  1053. * @remind 如果在执行该方法的时候, dom树已经ready, 那么回调函数将立刻执行
  1054. * @param { Function } fn dom树ready之后的回调函数
  1055. * @example
  1056. * ```javascript
  1057. *
  1058. * UE.utils.domReady( function () {
  1059. *
  1060. * console.log('123');
  1061. *
  1062. * } );
  1063. *
  1064. * ```
  1065. */
  1066. domReady: function () {
  1067. var fnArr = [];
  1068. function doReady(doc) {
  1069. //确保onready只执行一次
  1070. doc.isReady = true;
  1071. for (var ci; ci = fnArr.pop(); ci()) {
  1072. }
  1073. }
  1074. return function (onready, win) {
  1075. win = win || window;
  1076. var doc = win.document;
  1077. onready && fnArr.push(onready);
  1078. if (doc.readyState === "complete") {
  1079. doReady(doc);
  1080. } else {
  1081. doc.isReady && doReady(doc);
  1082. if (browser.ie && browser.version != 11) {
  1083. (function () {
  1084. if (doc.isReady) return;
  1085. try {
  1086. doc.documentElement.doScroll("left");
  1087. } catch (error) {
  1088. setTimeout(arguments.callee, 0);
  1089. return;
  1090. }
  1091. doReady(doc);
  1092. })();
  1093. win.attachEvent('onload', function () {
  1094. doReady(doc)
  1095. });
  1096. } else {
  1097. doc.addEventListener("DOMContentLoaded", function () {
  1098. doc.removeEventListener("DOMContentLoaded", arguments.callee, false);
  1099. doReady(doc);
  1100. }, false);
  1101. win.addEventListener('load', function () {
  1102. doReady(doc)
  1103. }, false);
  1104. }
  1105. }
  1106. }
  1107. }(),
  1108. /**
  1109. * 动态添加css样式
  1110. * @method cssRule
  1111. * @param { String } 节点名称
  1112. * @grammar UE.utils.cssRule('添加的样式的节点名称',['样式','放到哪个document上'])
  1113. * @grammar UE.utils.cssRule('body','body{background:#ccc}') => null //给body添加背景颜色
  1114. * @grammar UE.utils.cssRule('body') =>样式的字符串 //取得key值为body的样式的内容,如果没有找到key值先关的样式将返回空,例如刚才那个背景颜色,将返回 body{background:#ccc}
  1115. * @grammar UE.utils.cssRule('body',document) => 返回指定key的样式,并且指定是哪个document
  1116. * @grammar UE.utils.cssRule('body','') =>null //清空给定的key值的背景颜色
  1117. */
  1118. cssRule: browser.ie && browser.version != 11 ? function (key, style, doc) {
  1119. var indexList, index;
  1120. if (style === undefined || style && style.nodeType && style.nodeType == 9) {
  1121. //获取样式
  1122. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1123. indexList = doc.indexList || (doc.indexList = {});
  1124. index = indexList[key];
  1125. if (index !== undefined) {
  1126. return doc.styleSheets[index].cssText
  1127. }
  1128. return undefined;
  1129. }
  1130. doc = doc || document;
  1131. indexList = doc.indexList || (doc.indexList = {});
  1132. index = indexList[key];
  1133. //清除样式
  1134. if (style === '') {
  1135. if (index !== undefined) {
  1136. doc.styleSheets[index].cssText = '';
  1137. delete indexList[key];
  1138. return true
  1139. }
  1140. return false;
  1141. }
  1142. //添加样式
  1143. if (index !== undefined) {
  1144. sheetStyle = doc.styleSheets[index];
  1145. } else {
  1146. sheetStyle = doc.createStyleSheet('', index = doc.styleSheets.length);
  1147. indexList[key] = index;
  1148. }
  1149. sheetStyle.cssText = style;
  1150. } : function (key, style, doc) {
  1151. var head, node;
  1152. if (style === undefined || style && style.nodeType && style.nodeType == 9) {
  1153. //获取样式
  1154. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1155. node = doc.getElementById(key);
  1156. return node ? node.innerHTML : undefined;
  1157. }
  1158. doc = doc || document;
  1159. node = doc.getElementById(key);
  1160. //清除样式
  1161. if (style === '') {
  1162. if (node) {
  1163. node.parentNode.removeChild(node);
  1164. return true
  1165. }
  1166. return false;
  1167. }
  1168. //添加样式
  1169. if (node) {
  1170. node.innerHTML = style;
  1171. } else {
  1172. node = doc.createElement('style');
  1173. node.id = key;
  1174. node.innerHTML = style;
  1175. doc.getElementsByTagName('head')[0].appendChild(node);
  1176. }
  1177. },
  1178. sort: function (array, compareFn) {
  1179. compareFn = compareFn || function (item1, item2) { return item1.localeCompare(item2); };
  1180. for (var i = 0, len = array.length; i < len; i++) {
  1181. for (var j = i, length = array.length; j < length; j++) {
  1182. if (compareFn(array[i], array[j]) > 0) {
  1183. var t = array[i];
  1184. array[i] = array[j];
  1185. array[j] = t;
  1186. }
  1187. }
  1188. }
  1189. return array;
  1190. },
  1191. serializeParam: function (json) {
  1192. var strArr = [];
  1193. for (var i in json) {
  1194. //忽略默认的几个参数
  1195. if (i == "method" || i == "timeout" || i == "async") continue;
  1196. //传递过来的对象和函数不在提交之列
  1197. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  1198. strArr.push(encodeURIComponent(i) + "=" + encodeURIComponent(json[i]));
  1199. } else if (utils.isArray(json[i])) {
  1200. //支持传数组内容
  1201. for (var j = 0; j < json[i].length; j++) {
  1202. strArr.push(encodeURIComponent(i) + "[]=" + encodeURIComponent(json[i][j]));
  1203. }
  1204. }
  1205. }
  1206. return strArr.join("&");
  1207. },
  1208. formatUrl: function (url) {
  1209. var u = url.replace(/&&/g, '&');
  1210. u = u.replace(/\?&/g, '?');
  1211. u = u.replace(/&$/g, '');
  1212. u = u.replace(/&#/g, '#');
  1213. u = u.replace(/&+/g, '&');
  1214. return u;
  1215. },
  1216. isCrossDomainUrl: function (url) {
  1217. var a = document.createElement('a');
  1218. a.href = url;
  1219. if (browser.ie) {
  1220. a.href = a.href;
  1221. }
  1222. return !(a.protocol == location.protocol && a.hostname == location.hostname &&
  1223. (a.port == location.port || (a.port == '80' && location.port == '') || (a.port == '' && location.port == '80')));
  1224. },
  1225. clearEmptyAttrs: function (obj) {
  1226. for (var p in obj) {
  1227. if (obj[p] === '') {
  1228. delete obj[p]
  1229. }
  1230. }
  1231. return obj;
  1232. },
  1233. str2json: function (s) {
  1234. if (!utils.isString(s)) return null;
  1235. if (window.JSON) {
  1236. return JSON.parse(s);
  1237. } else {
  1238. return (new Function("return " + utils.trim(s || '')))();
  1239. }
  1240. },
  1241. json2str: (function () {
  1242. if (window.JSON) {
  1243. return JSON.stringify;
  1244. } else {
  1245. var escapeMap = {
  1246. "\b": '\\b',
  1247. "\t": '\\t',
  1248. "\n": '\\n',
  1249. "\f": '\\f',
  1250. "\r": '\\r',
  1251. '"': '\\"',
  1252. "\\": '\\\\'
  1253. };
  1254. function encodeString(source) {
  1255. if (/["\\\x00-\x1f]/.test(source)) {
  1256. source = source.replace(
  1257. /["\\\x00-\x1f]/g,
  1258. function (match) {
  1259. var c = escapeMap[match];
  1260. if (c) {
  1261. return c;
  1262. }
  1263. c = match.charCodeAt();
  1264. return "\\u00"
  1265. + Math.floor(c / 16).toString(16)
  1266. + (c % 16).toString(16);
  1267. });
  1268. }
  1269. return '"' + source + '"';
  1270. }
  1271. function encodeArray(source) {
  1272. var result = ["["],
  1273. l = source.length,
  1274. preComma, i, item;
  1275. for (i = 0; i < l; i++) {
  1276. item = source[i];
  1277. switch (typeof item) {
  1278. case "undefined":
  1279. case "function":
  1280. case "unknown":
  1281. break;
  1282. default:
  1283. if (preComma) {
  1284. result.push(',');
  1285. }
  1286. result.push(utils.json2str(item));
  1287. preComma = 1;
  1288. }
  1289. }
  1290. result.push("]");
  1291. return result.join("");
  1292. }
  1293. function pad(source) {
  1294. return source < 10 ? '0' + source : source;
  1295. }
  1296. function encodeDate(source) {
  1297. return '"' + source.getFullYear() + "-"
  1298. + pad(source.getMonth() + 1) + "-"
  1299. + pad(source.getDate()) + "T"
  1300. + pad(source.getHours()) + ":"
  1301. + pad(source.getMinutes()) + ":"
  1302. + pad(source.getSeconds()) + '"';
  1303. }
  1304. return function (value) {
  1305. switch (typeof value) {
  1306. case 'undefined':
  1307. return 'undefined';
  1308. case 'number':
  1309. return isFinite(value) ? String(value) : "null";
  1310. case 'string':
  1311. return encodeString(value);
  1312. case 'boolean':
  1313. return String(value);
  1314. default:
  1315. if (value === null) {
  1316. return 'null';
  1317. } else if (utils.isArray(value)) {
  1318. return encodeArray(value);
  1319. } else if (utils.isDate(value)) {
  1320. return encodeDate(value);
  1321. } else {
  1322. var result = ['{'],
  1323. encode = utils.json2str,
  1324. preComma,
  1325. item;
  1326. for (var key in value) {
  1327. if (Object.prototype.hasOwnProperty.call(value, key)) {
  1328. item = value[key];
  1329. switch (typeof item) {
  1330. case 'undefined':
  1331. case 'unknown':
  1332. case 'function':
  1333. break;
  1334. default:
  1335. if (preComma) {
  1336. result.push(',');
  1337. }
  1338. preComma = 1;
  1339. result.push(encode(key) + ':' + encode(item));
  1340. }
  1341. }
  1342. }
  1343. result.push('}');
  1344. return result.join('');
  1345. }
  1346. }
  1347. };
  1348. }
  1349. })()
  1350. };
  1351. /**
  1352. * 判断给定的对象是否是字符串
  1353. * @method isString
  1354. * @param { * } object 需要判断的对象
  1355. * @return { Boolean } 给定的对象是否是字符串
  1356. */
  1357. /**
  1358. * 判断给定的对象是否是数组
  1359. * @method isArray
  1360. * @param { * } object 需要判断的对象
  1361. * @return { Boolean } 给定的对象是否是数组
  1362. */
  1363. /**
  1364. * 判断给定的对象是否是一个Function
  1365. * @method isFunction
  1366. * @param { * } object 需要判断的对象
  1367. * @return { Boolean } 给定的对象是否是Function
  1368. */
  1369. /**
  1370. * 判断给定的对象是否是Number
  1371. * @method isNumber
  1372. * @param { * } object 需要判断的对象
  1373. * @return { Boolean } 给定的对象是否是Number
  1374. */
  1375. /**
  1376. * 判断给定的对象是否是一个正则表达式
  1377. * @method isRegExp
  1378. * @param { * } object 需要判断的对象
  1379. * @return { Boolean } 给定的对象是否是正则表达式
  1380. */
  1381. /**
  1382. * 判断给定的对象是否是一个普通对象
  1383. * @method isObject
  1384. * @param { * } object 需要判断的对象
  1385. * @return { Boolean } 给定的对象是否是普通对象
  1386. */
  1387. utils.each(['String', 'Function', 'Array', 'Number', 'RegExp', 'Object', 'Date'], function (v) {
  1388. UE.utils['is' + v] = function (obj) {
  1389. return Object.prototype.toString.apply(obj) == '[object ' + v + ']';
  1390. }
  1391. });
  1392. // core/EventBase.js
  1393. /**
  1394. * UE采用的事件基类
  1395. * @file
  1396. * @module UE
  1397. * @class EventBase
  1398. * @since 1.2.6.1
  1399. */
  1400. /**
  1401. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  1402. * @unfile
  1403. * @module UE
  1404. */
  1405. /**
  1406. * UE采用的事件基类,继承此类的对应类将获取addListener,removeListener,fireEvent方法。
  1407. * 在UE中,Editor以及所有ui实例都继承了该类,故可以在对应的ui对象以及editor对象上使用上述方法。
  1408. * @unfile
  1409. * @module UE
  1410. * @class EventBase
  1411. */
  1412. /**
  1413. * 通过此构造器,子类可以继承EventBase获取事件监听的方法
  1414. * @constructor
  1415. * @example
  1416. * ```javascript
  1417. * UE.EventBase.call(editor);
  1418. * ```
  1419. */
  1420. var EventBase = UE.EventBase = function () { };
  1421. EventBase.prototype = {
  1422. /**
  1423. * 注册事件监听器
  1424. * @method addListener
  1425. * @param { String } types 监听的事件名称,同时监听多个事件使用空格分隔
  1426. * @param { Function } fn 监听的事件被触发时,会执行该回调函数
  1427. * @waining 事件被触发时,监听的函数假如返回的值恒等于true,回调函数的队列中后面的函数将不执行
  1428. * @example
  1429. * ```javascript
  1430. * editor.addListener('selectionchange',function(){
  1431. * console.log("选区已经变化!");
  1432. * })
  1433. * editor.addListener('beforegetcontent aftergetcontent',function(type){
  1434. * if(type == 'beforegetcontent'){
  1435. * //do something
  1436. * }else{
  1437. * //do something
  1438. * }
  1439. * console.log(this.getContent) // this是注册的事件的编辑器实例
  1440. * })
  1441. * ```
  1442. * @see UE.EventBase:fireEvent(String)
  1443. */
  1444. addListener: function (types, listener) {
  1445. types = utils.trim(types).split(/\s+/);
  1446. for (var i = 0, ti; ti = types[i++];) {
  1447. getListener(this, ti, true).push(listener);
  1448. }
  1449. },
  1450. on: function (types, listener) {
  1451. return this.addListener(types, listener);
  1452. },
  1453. off: function (types, listener) {
  1454. return this.removeListener(types, listener)
  1455. },
  1456. trigger: function () {
  1457. return this.fireEvent.apply(this, arguments);
  1458. },
  1459. /**
  1460. * 移除事件监听器
  1461. * @method removeListener
  1462. * @param { String } types 移除的事件名称,同时移除多个事件使用空格分隔
  1463. * @param { Function } fn 移除监听事件的函数引用
  1464. * @example
  1465. * ```javascript
  1466. * //changeCallback为方法体
  1467. * editor.removeListener("selectionchange",changeCallback);
  1468. * ```
  1469. */
  1470. removeListener: function (types, listener) {
  1471. types = utils.trim(types).split(/\s+/);
  1472. for (var i = 0, ti; ti = types[i++];) {
  1473. utils.removeItem(getListener(this, ti) || [], listener);
  1474. }
  1475. },
  1476. /**
  1477. * 触发事件
  1478. * @method fireEvent
  1479. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1480. * @remind 该方法会触发addListener
  1481. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1482. * @example
  1483. * ```javascript
  1484. * editor.fireEvent("selectionchange");
  1485. * ```
  1486. */
  1487. /**
  1488. * 触发事件
  1489. * @method fireEvent
  1490. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1491. * @param { *... } options 可选参数,可以传入一个或多个参数,会传给事件触发的回调函数
  1492. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1493. * @example
  1494. * ```javascript
  1495. *
  1496. * editor.addListener( "selectionchange", function ( type, arg1, arg2 ) {
  1497. *
  1498. * console.log( arg1 + " " + arg2 );
  1499. *
  1500. * } );
  1501. *
  1502. * //触发selectionchange事件, 会执行上面的事件监听器
  1503. * //output: Hello World
  1504. * editor.fireEvent("selectionchange", "Hello", "World");
  1505. * ```
  1506. */
  1507. fireEvent: function () {
  1508. var types = arguments[0];
  1509. types = utils.trim(types).split(' ');
  1510. for (var i = 0, ti; ti = types[i++];) {
  1511. var listeners = getListener(this, ti),
  1512. r, t, k;
  1513. if (listeners) {
  1514. k = listeners.length;
  1515. while (k--) {
  1516. if (!listeners[k]) continue;
  1517. t = listeners[k].apply(this, arguments);
  1518. if (t === true) {
  1519. return t;
  1520. }
  1521. if (t !== undefined) {
  1522. r = t;
  1523. }
  1524. }
  1525. }
  1526. if (t = this['on' + ti.toLowerCase()]) {
  1527. r = t.apply(this, arguments);
  1528. }
  1529. }
  1530. return r;
  1531. }
  1532. };
  1533. /**
  1534. * 获得对象所拥有监听类型的所有监听器
  1535. * @unfile
  1536. * @module UE
  1537. * @since 1.2.6.1
  1538. * @method getListener
  1539. * @public
  1540. * @param { Object } obj 查询监听器的对象
  1541. * @param { String } type 事件类型
  1542. * @param { Boolean } force 为true且当前所有type类型的侦听器不存在时,创建一个空监听器数组
  1543. * @return { Array } 监听器数组
  1544. */
  1545. function getListener(obj, type, force) {
  1546. var allListeners;
  1547. type = type.toLowerCase();
  1548. return ((allListeners = (obj.__allListeners || force && (obj.__allListeners = {})))
  1549. && (allListeners[type] || force && (allListeners[type] = [])));
  1550. }
  1551. // core/dtd.js
  1552. ///import editor.js
  1553. ///import core/dom/dom.js
  1554. ///import core/utils.js
  1555. /**
  1556. * dtd html语义化的体现类
  1557. * @constructor
  1558. * @namespace dtd
  1559. */
  1560. var dtd = dom.dtd = (function () {
  1561. function _(s) {
  1562. for (var k in s) {
  1563. s[k.toUpperCase()] = s[k];
  1564. }
  1565. return s;
  1566. }
  1567. var X = utils.extend2;
  1568. var A = _({ isindex: 1, fieldset: 1 }),
  1569. B = _({ input: 1, button: 1, select: 1, textarea: 1, label: 1 }),
  1570. C = X(_({ a: 1 }), B),
  1571. D = X({ iframe: 1 }, C),
  1572. E = _({ hr: 1, ul: 1, menu: 1, div: 1, blockquote: 1, noscript: 1, table: 1, center: 1, address: 1, dir: 1, pre: 1, h5: 1, dl: 1, h4: 1, noframes: 1, h6: 1, ol: 1, h1: 1, h3: 1, h2: 1 }),
  1573. F = _({ ins: 1, del: 1, script: 1, style: 1 }),
  1574. G = X(_({ b: 1, acronym: 1, bdo: 1, 'var': 1, '#': 1, abbr: 1, code: 1, br: 1, i: 1, cite: 1, kbd: 1, u: 1, strike: 1, s: 1, tt: 1, strong: 1, q: 1, samp: 1, em: 1, dfn: 1, span: 1 }), F),
  1575. H = X(_({ sub: 1, img: 1, embed: 1, object: 1, sup: 1, basefont: 1, map: 1, applet: 1, font: 1, big: 1, small: 1 }), G),
  1576. I = X(_({ p: 1 }), H),
  1577. J = X(_({ iframe: 1 }), H, B),
  1578. K = _({ img: 1, embed: 1, noscript: 1, br: 1, kbd: 1, center: 1, button: 1, basefont: 1, h5: 1, h4: 1, samp: 1, h6: 1, ol: 1, h1: 1, h3: 1, h2: 1, form: 1, font: 1, '#': 1, select: 1, menu: 1, ins: 1, abbr: 1, label: 1, code: 1, table: 1, script: 1, cite: 1, input: 1, iframe: 1, strong: 1, textarea: 1, noframes: 1, big: 1, small: 1, span: 1, hr: 1, sub: 1, bdo: 1, 'var': 1, div: 1, object: 1, sup: 1, strike: 1, dir: 1, map: 1, dl: 1, applet: 1, del: 1, isindex: 1, fieldset: 1, ul: 1, b: 1, acronym: 1, a: 1, blockquote: 1, i: 1, u: 1, s: 1, tt: 1, address: 1, q: 1, pre: 1, p: 1, em: 1, dfn: 1 }),
  1579. L = X(_({ a: 0 }), J),//a不能被切开,所以把他
  1580. M = _({ tr: 1 }),
  1581. N = _({ '#': 1 }),
  1582. O = X(_({ param: 1 }), K),
  1583. P = X(_({ form: 1 }), A, D, E, I),
  1584. Q = _({ li: 1, ol: 1, ul: 1 }),
  1585. R = _({ style: 1, script: 1 }),
  1586. S = _({ base: 1, link: 1, meta: 1, title: 1 }),
  1587. T = X(S, R),
  1588. U = _({ head: 1, body: 1 }),
  1589. V = _({ html: 1 });
  1590. var block = _({ address: 1, blockquote: 1, center: 1, dir: 1, div: 1, dl: 1, fieldset: 1, form: 1, h1: 1, h2: 1, h3: 1, h4: 1, h5: 1, h6: 1, hr: 1, isindex: 1, menu: 1, noframes: 1, ol: 1, p: 1, pre: 1, table: 1, ul: 1 }),
  1591. empty = _({ area: 1, base: 1, basefont: 1, br: 1, col: 1, command: 1, dialog: 1, embed: 1, hr: 1, img: 1, input: 1, isindex: 1, keygen: 1, link: 1, meta: 1, param: 1, source: 1, track: 1, wbr: 1 });
  1592. return _({
  1593. // $ 表示自定的属性
  1594. // body外的元素列表.
  1595. $nonBodyContent: X(V, U, S),
  1596. //块结构元素列表
  1597. $block: block,
  1598. //内联元素列表
  1599. $inline: L,
  1600. $inlineWithA: X(_({ a: 1 }), L),
  1601. $body: X(_({ script: 1, style: 1 }), block),
  1602. $cdata: _({ script: 1, style: 1 }),
  1603. //自闭和元素
  1604. $empty: empty,
  1605. //不是自闭合,但不能让range选中里边
  1606. $nonChild: _({ iframe: 1, textarea: 1 }),
  1607. //列表元素列表
  1608. $listItem: _({ dd: 1, dt: 1, li: 1 }),
  1609. //列表根元素列表
  1610. $list: _({ ul: 1, ol: 1, dl: 1 }),
  1611. //不能认为是空的元素
  1612. $isNotEmpty: _({ table: 1, ul: 1, ol: 1, dl: 1, iframe: 1, area: 1, base: 1, col: 1, hr: 1, img: 1, embed: 1, input: 1, link: 1, meta: 1, param: 1, h1: 1, h2: 1, h3: 1, h4: 1, h5: 1, h6: 1 }),
  1613. //如果没有子节点就可以删除的元素列表,像span,a
  1614. $removeEmpty: _({ a: 1, abbr: 1, acronym: 1, address: 1, b: 1, bdo: 1, big: 1, cite: 1, code: 1, del: 1, dfn: 1, em: 1, font: 1, i: 1, ins: 1, label: 1, kbd: 1, q: 1, s: 1, samp: 1, small: 1, span: 1, strike: 1, strong: 1, sub: 1, sup: 1, tt: 1, u: 1, 'var': 1 }),
  1615. $removeEmptyBlock: _({ 'p': 1, 'div': 1 }),
  1616. //在table元素里的元素列表
  1617. $tableContent: _({ caption: 1, col: 1, colgroup: 1, tbody: 1, td: 1, tfoot: 1, th: 1, thead: 1, tr: 1, table: 1 }),
  1618. //不转换的标签
  1619. $notTransContent: _({ pre: 1, script: 1, style: 1, textarea: 1 }),
  1620. html: U,
  1621. head: T,
  1622. style: N,
  1623. script: N,
  1624. body: P,
  1625. base: {},
  1626. link: {},
  1627. meta: {},
  1628. title: N,
  1629. col: {},
  1630. tr: _({ td: 1, th: 1 }),
  1631. img: {},
  1632. embed: {},
  1633. colgroup: _({ thead: 1, col: 1, tbody: 1, tr: 1, tfoot: 1 }),
  1634. noscript: P,
  1635. td: P,
  1636. br: {},
  1637. th: P,
  1638. center: P,
  1639. kbd: L,
  1640. button: X(I, E),
  1641. basefont: {},
  1642. h5: L,
  1643. h4: L,
  1644. samp: L,
  1645. h6: L,
  1646. ol: Q,
  1647. h1: L,
  1648. h3: L,
  1649. option: N,
  1650. h2: L,
  1651. form: X(A, D, E, I),
  1652. select: _({ optgroup: 1, option: 1 }),
  1653. font: L,
  1654. ins: L,
  1655. menu: Q,
  1656. abbr: L,
  1657. label: L,
  1658. table: _({ thead: 1, col: 1, tbody: 1, tr: 1, colgroup: 1, caption: 1, tfoot: 1 }),
  1659. code: L,
  1660. tfoot: M,
  1661. cite: L,
  1662. li: P,
  1663. input: {},
  1664. iframe: P,
  1665. strong: L,
  1666. textarea: N,
  1667. noframes: P,
  1668. big: L,
  1669. small: L,
  1670. //trace:
  1671. span: _({ '#': 1, br: 1, b: 1, strong: 1, u: 1, i: 1, em: 1, sub: 1, sup: 1, strike: 1, span: 1 }),
  1672. hr: L,
  1673. dt: L,
  1674. sub: L,
  1675. optgroup: _({ option: 1 }),
  1676. param: {},
  1677. bdo: L,
  1678. 'var': L,
  1679. div: P,
  1680. object: O,
  1681. sup: L,
  1682. dd: P,
  1683. strike: L,
  1684. area: {},
  1685. dir: Q,
  1686. map: X(_({ area: 1, form: 1, p: 1 }), A, F, E),
  1687. applet: O,
  1688. dl: _({ dt: 1, dd: 1 }),
  1689. del: L,
  1690. isindex: {},
  1691. fieldset: X(_({ legend: 1 }), K),
  1692. thead: M,
  1693. ul: Q,
  1694. acronym: L,
  1695. b: L,
  1696. a: X(_({ a: 1 }), J),
  1697. blockquote: X(_({ td: 1, tr: 1, tbody: 1, li: 1 }), P),
  1698. caption: L,
  1699. i: L,
  1700. u: L,
  1701. tbody: M,
  1702. s: L,
  1703. address: X(D, I),
  1704. tt: L,
  1705. legend: L,
  1706. q: L,
  1707. pre: X(G, C),
  1708. p: X(_({ 'a': 1 }), L),
  1709. em: L,
  1710. dfn: L
  1711. });
  1712. })();
  1713. // core/domUtils.js
  1714. /**
  1715. * Dom操作工具包
  1716. * @file
  1717. * @module UE.dom.domUtils
  1718. * @since 1.2.6.1
  1719. */
  1720. /**
  1721. * Dom操作工具包
  1722. * @unfile
  1723. * @module UE.dom.domUtils
  1724. */
  1725. function getDomNode(node, start, ltr, startFromChild, fn, guard) {
  1726. var tmpNode = startFromChild && node[start],
  1727. parent;
  1728. !tmpNode && (tmpNode = node[ltr]);
  1729. while (!tmpNode && (parent = (parent || node).parentNode)) {
  1730. if (parent.tagName == 'BODY' || guard && !guard(parent)) {
  1731. return null;
  1732. }
  1733. tmpNode = parent[ltr];
  1734. }
  1735. if (tmpNode && fn && !fn(tmpNode)) {
  1736. return getDomNode(tmpNode, start, ltr, false, fn);
  1737. }
  1738. return tmpNode;
  1739. }
  1740. var attrFix = ie && browser.version < 9 ? {
  1741. tabindex: "tabIndex",
  1742. readonly: "readOnly",
  1743. "for": "htmlFor",
  1744. "class": "className",
  1745. maxlength: "maxLength",
  1746. cellspacing: "cellSpacing",
  1747. cellpadding: "cellPadding",
  1748. rowspan: "rowSpan",
  1749. colspan: "colSpan",
  1750. usemap: "useMap",
  1751. frameborder: "frameBorder"
  1752. } : {
  1753. tabindex: "tabIndex",
  1754. readonly: "readOnly"
  1755. },
  1756. styleBlock = utils.listToMap([
  1757. '-webkit-box', '-moz-box', 'block',
  1758. 'list-item', 'table', 'table-row-group',
  1759. 'table-header-group', 'table-footer-group',
  1760. 'table-row', 'table-column-group', 'table-column',
  1761. 'table-cell', 'table-caption'
  1762. ]);
  1763. var domUtils = dom.domUtils = {
  1764. //节点常量
  1765. NODE_ELEMENT: 1,
  1766. NODE_DOCUMENT: 9,
  1767. NODE_TEXT: 3,
  1768. NODE_COMMENT: 8,
  1769. NODE_DOCUMENT_FRAGMENT: 11,
  1770. //位置关系
  1771. POSITION_IDENTICAL: 0,
  1772. POSITION_DISCONNECTED: 1,
  1773. POSITION_FOLLOWING: 2,
  1774. POSITION_PRECEDING: 4,
  1775. POSITION_IS_CONTAINED: 8,
  1776. POSITION_CONTAINS: 16,
  1777. //ie6使用其他的会有一段空白出现
  1778. fillChar: ie && browser.version == '6' ? '\ufeff' : '\u200B',
  1779. //-------------------------Node部分--------------------------------
  1780. keys: {
  1781. /*Backspace*/ 8: 1, /*Delete*/ 46: 1,
  1782. /*Shift*/ 16: 1, /*Ctrl*/ 17: 1, /*Alt*/ 18: 1,
  1783. 37: 1, 38: 1, 39: 1, 40: 1,
  1784. 13: 1 /*enter*/
  1785. },
  1786. /**
  1787. * 获取节点A相对于节点B的位置关系
  1788. * @method getPosition
  1789. * @param { Node } nodeA 需要查询位置关系的节点A
  1790. * @param { Node } nodeB 需要查询位置关系的节点B
  1791. * @return { Number } 节点A与节点B的关系
  1792. * @example
  1793. * ```javascript
  1794. * //output: 20
  1795. * var position = UE.dom.domUtils.getPosition( document.documentElement, document.body );
  1796. *
  1797. * switch ( position ) {
  1798. *
  1799. * //0
  1800. * case UE.dom.domUtils.POSITION_IDENTICAL:
  1801. * console.log('元素相同');
  1802. * break;
  1803. * //1
  1804. * case UE.dom.domUtils.POSITION_DISCONNECTED:
  1805. * console.log('两个节点在不同的文档中');
  1806. * break;
  1807. * //2
  1808. * case UE.dom.domUtils.POSITION_FOLLOWING:
  1809. * console.log('节点A在节点B之后');
  1810. * break;
  1811. * //4
  1812. * case UE.dom.domUtils.POSITION_PRECEDING;
  1813. * console.log('节点A在节点B之前');
  1814. * break;
  1815. * //8
  1816. * case UE.dom.domUtils.POSITION_IS_CONTAINED:
  1817. * console.log('节点A被节点B包含');
  1818. * break;
  1819. * case 10:
  1820. * console.log('节点A被节点B包含且节点A在节点B之后');
  1821. * break;
  1822. * //16
  1823. * case UE.dom.domUtils.POSITION_CONTAINS:
  1824. * console.log('节点A包含节点B');
  1825. * break;
  1826. * case 20:
  1827. * console.log('节点A包含节点B且节点A在节点B之前');
  1828. * break;
  1829. *
  1830. * }
  1831. * ```
  1832. */
  1833. getPosition: function (nodeA, nodeB) {
  1834. // 如果两个节点是同一个节点
  1835. if (nodeA === nodeB) {
  1836. // domUtils.POSITION_IDENTICAL
  1837. return 0;
  1838. }
  1839. var node,
  1840. parentsA = [nodeA],
  1841. parentsB = [nodeB];
  1842. node = nodeA;
  1843. while (node = node.parentNode) {
  1844. // 如果nodeB是nodeA的祖先节点
  1845. if (node === nodeB) {
  1846. // domUtils.POSITION_IS_CONTAINED + domUtils.POSITION_FOLLOWING
  1847. return 10;
  1848. }
  1849. parentsA.push(node);
  1850. }
  1851. node = nodeB;
  1852. while (node = node.parentNode) {
  1853. // 如果nodeA是nodeB的祖先节点
  1854. if (node === nodeA) {
  1855. // domUtils.POSITION_CONTAINS + domUtils.POSITION_PRECEDING
  1856. return 20;
  1857. }
  1858. parentsB.push(node);
  1859. }
  1860. parentsA.reverse();
  1861. parentsB.reverse();
  1862. if (parentsA[0] !== parentsB[0]) {
  1863. // domUtils.POSITION_DISCONNECTED
  1864. return 1;
  1865. }
  1866. var i = -1;
  1867. while (i++, parentsA[i] === parentsB[i]) {
  1868. }
  1869. nodeA = parentsA[i];
  1870. nodeB = parentsB[i];
  1871. while (nodeA = nodeA.nextSibling) {
  1872. if (nodeA === nodeB) {
  1873. // domUtils.POSITION_PRECEDING
  1874. return 4
  1875. }
  1876. }
  1877. // domUtils.POSITION_FOLLOWING
  1878. return 2;
  1879. },
  1880. /**
  1881. * 检测节点node在父节点中的索引位置
  1882. * @method getNodeIndex
  1883. * @param { Node } node 需要检测的节点对象
  1884. * @return { Number } 该节点在父节点中的位置
  1885. * @see UE.dom.domUtils.getNodeIndex(Node,Boolean)
  1886. */
  1887. /**
  1888. * 检测节点node在父节点中的索引位置, 根据给定的mergeTextNode参数决定是否要合并多个连续的文本节点为一个节点
  1889. * @method getNodeIndex
  1890. * @param { Node } node 需要检测的节点对象
  1891. * @param { Boolean } mergeTextNode 是否合并多个连续的文本节点为一个节点
  1892. * @return { Number } 该节点在父节点中的位置
  1893. * @example
  1894. * ```javascript
  1895. *
  1896. * var node = document.createElement("div");
  1897. *
  1898. * node.appendChild( document.createTextNode( "hello" ) );
  1899. * node.appendChild( document.createTextNode( "world" ) );
  1900. * node.appendChild( node = document.createElement( "div" ) );
  1901. *
  1902. * //output: 2
  1903. * console.log( UE.dom.domUtils.getNodeIndex( node ) );
  1904. *
  1905. * //output: 1
  1906. * console.log( UE.dom.domUtils.getNodeIndex( node, true ) );
  1907. *
  1908. * ```
  1909. */
  1910. getNodeIndex: function (node, ignoreTextNode) {
  1911. var preNode = node,
  1912. i = 0;
  1913. while (preNode = preNode.previousSibling) {
  1914. if (ignoreTextNode && preNode.nodeType == 3) {
  1915. if (preNode.nodeType != preNode.nextSibling.nodeType) {
  1916. i++;
  1917. }
  1918. continue;
  1919. }
  1920. i++;
  1921. }
  1922. return i;
  1923. },
  1924. /**
  1925. * 检测节点node是否在给定的document对象上
  1926. * @method inDoc
  1927. * @param { Node } node 需要检测的节点对象
  1928. * @param { DomDocument } doc 需要检测的document对象
  1929. * @return { Boolean } 该节点node是否在给定的document的dom树上
  1930. * @example
  1931. * ```javascript
  1932. *
  1933. * var node = document.createElement("div");
  1934. *
  1935. * //output: false
  1936. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1937. *
  1938. * document.body.appendChild( node );
  1939. *
  1940. * //output: true
  1941. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1942. *
  1943. * ```
  1944. */
  1945. inDoc: function (node, doc) {
  1946. return domUtils.getPosition(node, doc) == 10;
  1947. },
  1948. /**
  1949. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1950. * 查找的起点是给定node节点的父节点。
  1951. * @method findParent
  1952. * @param { Node } node 需要查找的节点
  1953. * @param { Function } filterFn 自定义的过滤方法。
  1954. * @warning 查找的终点是到body节点为止
  1955. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1956. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1957. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1958. * @example
  1959. * ```javascript
  1960. * var filterNode = UE.dom.domUtils.findParent( document.body.firstChild, function ( node ) {
  1961. *
  1962. * //由于查找的终点是body节点, 所以永远也不会匹配当前过滤器的条件, 即这里永远会返回false
  1963. * return node.tagName === "HTML";
  1964. *
  1965. * } );
  1966. *
  1967. * //output: true
  1968. * console.log( filterNode === null );
  1969. * ```
  1970. */
  1971. /**
  1972. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1973. * 如果includeSelf的值为true,则查找的起点是给定的节点node, 否则, 起点是node的父节点
  1974. * @method findParent
  1975. * @param { Node } node 需要查找的节点
  1976. * @param { Function } filterFn 自定义的过滤方法。
  1977. * @param { Boolean } includeSelf 查找过程是否包含自身
  1978. * @warning 查找的终点是到body节点为止
  1979. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1980. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1981. * @remind 如果includeSelf为true, 则过滤器第一次执行时的参数会是节点本身。
  1982. * 反之, 过滤器第一次执行时的参数将是该节点的父节点。
  1983. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1984. * @example
  1985. * ```html
  1986. * <body>
  1987. *
  1988. * <div id="test">
  1989. * </div>
  1990. *
  1991. * <script type="text/javascript">
  1992. *
  1993. * //output: DIV, BODY
  1994. * var filterNode = UE.dom.domUtils.findParent( document.getElementById( "test" ), function ( node ) {
  1995. *
  1996. * console.log( node.tagName );
  1997. * return false;
  1998. *
  1999. * }, true );
  2000. *
  2001. * </script>
  2002. * </body>
  2003. * ```
  2004. */
  2005. findParent: function (node, filterFn, includeSelf) {
  2006. if (node && !domUtils.isBody(node)) {
  2007. node = includeSelf ? node : node.parentNode;
  2008. while (node) {
  2009. if (!filterFn || filterFn(node) || domUtils.isBody(node)) {
  2010. return filterFn && !filterFn(node) && domUtils.isBody(node) ? null : node;
  2011. }
  2012. node = node.parentNode;
  2013. }
  2014. }
  2015. return null;
  2016. },
  2017. /**
  2018. * 查找node的节点名为tagName的第一个祖先节点, 查找的起点是node节点的父节点。
  2019. * @method findParentByTagName
  2020. * @param { Node } node 需要查找的节点对象
  2021. * @param { Array } tagNames 需要查找的父节点的名称数组
  2022. * @warning 查找的终点是到body节点为止
  2023. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  2024. * @example
  2025. * ```javascript
  2026. * var node = UE.dom.domUtils.findParentByTagName( document.getElementsByTagName("div")[0], [ "BODY" ] );
  2027. * //output: BODY
  2028. * console.log( node.tagName );
  2029. * ```
  2030. */
  2031. /**
  2032. * 查找node的节点名为tagName的祖先节点, 如果includeSelf的值为true,则查找的起点是给定的节点node,
  2033. * 否则, 起点是node的父节点。
  2034. * @method findParentByTagName
  2035. * @param { Node } node 需要查找的节点对象
  2036. * @param { Array } tagNames 需要查找的父节点的名称数组
  2037. * @param { Boolean } includeSelf 查找过程是否包含node节点自身
  2038. * @warning 查找的终点是到body节点为止
  2039. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  2040. * @example
  2041. * ```javascript
  2042. * var queryTarget = document.getElementsByTagName("div")[0];
  2043. * var node = UE.dom.domUtils.findParentByTagName( queryTarget, [ "DIV" ], true );
  2044. * //output: true
  2045. * console.log( queryTarget === node );
  2046. * ```
  2047. */
  2048. findParentByTagName: function (node, tagNames, includeSelf, excludeFn) {
  2049. tagNames = utils.listToMap(utils.isArray(tagNames) ? tagNames : [tagNames]);
  2050. return domUtils.findParent(node, function (node) {
  2051. return tagNames[node.tagName] && !(excludeFn && excludeFn(node));
  2052. }, includeSelf);
  2053. },
  2054. /**
  2055. * 查找节点node的祖先节点集合, 查找的起点是给定节点的父节点,结果集中不包含给定的节点。
  2056. * @method findParents
  2057. * @param { Node } node 需要查找的节点对象
  2058. * @return { Array } 给定节点的祖先节点数组
  2059. * @grammar UE.dom.domUtils.findParents(node) => Array //返回一个祖先节点数组集合,不包含自身
  2060. * @grammar UE.dom.domUtils.findParents(node,includeSelf) => Array //返回一个祖先节点数组集合,includeSelf指定是否包含自身
  2061. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn) => Array //返回一个祖先节点数组集合,filterFn指定过滤条件,返回true的node将被选取
  2062. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn,closerFirst) => Array //返回一个祖先节点数组集合,closerFirst为true的话,node的直接父亲节点是数组的第0个
  2063. */
  2064. /**
  2065. * 查找节点node的祖先节点集合, 如果includeSelf的值为true,
  2066. * 则返回的结果集中允许出现当前给定的节点, 否则, 该节点不会出现在其结果集中。
  2067. * @method findParents
  2068. * @param { Node } node 需要查找的节点对象
  2069. * @param { Boolean } includeSelf 查找的结果中是否允许包含当前查找的节点对象
  2070. * @return { Array } 给定节点的祖先节点数组
  2071. */
  2072. findParents: function (node, includeSelf, filterFn, closerFirst) {
  2073. var parents = includeSelf && (filterFn && filterFn(node) || !filterFn) ? [node] : [];
  2074. while (node = domUtils.findParent(node, filterFn)) {
  2075. parents.push(node);
  2076. }
  2077. return closerFirst ? parents : parents.reverse();
  2078. },
  2079. /**
  2080. * 在节点node后面插入新节点newNode
  2081. * @method insertAfter
  2082. * @param { Node } node 目标节点
  2083. * @param { Node } newNode 新插入的节点, 该节点将置于目标节点之后
  2084. * @return { Node } 新插入的节点
  2085. */
  2086. insertAfter: function (node, newNode) {
  2087. return node.nextSibling ? node.parentNode.insertBefore(newNode, node.nextSibling) :
  2088. node.parentNode.appendChild(newNode);
  2089. },
  2090. /**
  2091. * 删除节点node及其下属的所有节点
  2092. * @method remove
  2093. * @param { Node } node 需要删除的节点对象
  2094. * @return { Node } 返回刚删除的节点对象
  2095. * @example
  2096. * ```html
  2097. * <div id="test">
  2098. * <div id="child">你好</div>
  2099. * </div>
  2100. * <script>
  2101. * UE.dom.domUtils.remove( document.body, false );
  2102. * //output: false
  2103. * console.log( document.getElementById( "child" ) !== null );
  2104. * </script>
  2105. * ```
  2106. */
  2107. /**
  2108. * 删除节点node,并根据keepChildren的值决定是否保留子节点
  2109. * @method remove
  2110. * @param { Node } node 需要删除的节点对象
  2111. * @param { Boolean } keepChildren 是否需要保留子节点
  2112. * @return { Node } 返回刚删除的节点对象
  2113. * @example
  2114. * ```html
  2115. * <div id="test">
  2116. * <div id="child">你好</div>
  2117. * </div>
  2118. * <script>
  2119. * UE.dom.domUtils.remove( document.body, true );
  2120. * //output: true
  2121. * console.log( document.getElementById( "child" ) !== null );
  2122. * </script>
  2123. * ```
  2124. */
  2125. remove: function (node, keepChildren) {
  2126. var parent = node.parentNode,
  2127. child;
  2128. if (parent) {
  2129. if (keepChildren && node.hasChildNodes()) {
  2130. while (child = node.firstChild) {
  2131. parent.insertBefore(child, node);
  2132. }
  2133. }
  2134. parent.removeChild(node);
  2135. }
  2136. return node;
  2137. },
  2138. /**
  2139. * 取得node节点的下一个兄弟节点, 如果该节点其后没有兄弟节点, 则递归查找其父节点之后的第一个兄弟节点,
  2140. * 直到找到满足条件的节点或者递归到BODY节点之后才会结束。
  2141. * @method getNextDomNode
  2142. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  2143. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  2144. * @example
  2145. * ```html
  2146. * <body>
  2147. * <div id="test">
  2148. * <span></span>
  2149. * </div>
  2150. * <i>xxx</i>
  2151. * </body>
  2152. * <script>
  2153. *
  2154. * //output: i节点
  2155. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  2156. *
  2157. * </script>
  2158. * ```
  2159. * @example
  2160. * ```html
  2161. * <body>
  2162. * <div>
  2163. * <span></span>
  2164. * <i id="test">xxx</i>
  2165. * </div>
  2166. * <b>xxx</b>
  2167. * </body>
  2168. * <script>
  2169. *
  2170. * //由于id为test的i节点之后没有兄弟节点, 则查找其父节点(div)后面的兄弟节点
  2171. * //output: b节点
  2172. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  2173. *
  2174. * </script>
  2175. * ```
  2176. */
  2177. /**
  2178. * 取得node节点的下一个兄弟节点, 如果startFromChild的值为ture,则先获取其子节点,
  2179. * 如果有子节点则直接返回第一个子节点;如果没有子节点或者startFromChild的值为false,
  2180. * 则执行<a href="#UE.dom.domUtils.getNextDomNode(Node)">getNextDomNode(Node node)</a>的查找过程。
  2181. * @method getNextDomNode
  2182. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  2183. * @param { Boolean } startFromChild 查找过程是否从其子节点开始
  2184. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  2185. * @see UE.dom.domUtils.getNextDomNode(Node)
  2186. */
  2187. getNextDomNode: function (node, startFromChild, filterFn, guard) {
  2188. return getDomNode(node, 'firstChild', 'nextSibling', startFromChild, filterFn, guard);
  2189. },
  2190. getPreDomNode: function (node, startFromChild, filterFn, guard) {
  2191. return getDomNode(node, 'lastChild', 'previousSibling', startFromChild, filterFn, guard);
  2192. },
  2193. /**
  2194. * 检测节点node是否属是UEditor定义的bookmark节点
  2195. * @method isBookmarkNode
  2196. * @private
  2197. * @param { Node } node 需要检测的节点对象
  2198. * @return { Boolean } 是否是bookmark节点
  2199. * @example
  2200. * ```html
  2201. * <span id="_baidu_bookmark_1"></span>
  2202. * <script>
  2203. * var bookmarkNode = document.getElementById("_baidu_bookmark_1");
  2204. * //output: true
  2205. * console.log( UE.dom.domUtils.isBookmarkNode( bookmarkNode ) );
  2206. * </script>
  2207. * ```
  2208. */
  2209. isBookmarkNode: function (node) {
  2210. return node.nodeType == 1 && node.id && /^_baidu_bookmark_/i.test(node.id);
  2211. },
  2212. /**
  2213. * 获取节点node所属的window对象
  2214. * @method getWindow
  2215. * @param { Node } node 节点对象
  2216. * @return { Window } 当前节点所属的window对象
  2217. * @example
  2218. * ```javascript
  2219. * //output: true
  2220. * console.log( UE.dom.domUtils.getWindow( document.body ) === window );
  2221. * ```
  2222. */
  2223. getWindow: function (node) {
  2224. var doc = node.ownerDocument || node;
  2225. return doc.defaultView || doc.parentWindow;
  2226. },
  2227. /**
  2228. * 获取离nodeA与nodeB最近的公共的祖先节点
  2229. * @method getCommonAncestor
  2230. * @param { Node } nodeA 第一个节点
  2231. * @param { Node } nodeB 第二个节点
  2232. * @remind 如果给定的两个节点是同一个节点, 将直接返回该节点。
  2233. * @return { Node | NULL } 如果未找到公共节点, 返回NULL, 否则返回最近的公共祖先节点。
  2234. * @example
  2235. * ```javascript
  2236. * var commonAncestor = UE.dom.domUtils.getCommonAncestor( document.body, document.body.firstChild );
  2237. * //output: true
  2238. * console.log( commonAncestor.tagName.toLowerCase() === 'body' );
  2239. * ```
  2240. */
  2241. getCommonAncestor: function (nodeA, nodeB) {
  2242. if (nodeA === nodeB)
  2243. return nodeA;
  2244. var parentsA = [nodeA], parentsB = [nodeB], parent = nodeA, i = -1;
  2245. while (parent = parent.parentNode) {
  2246. if (parent === nodeB) {
  2247. return parent;
  2248. }
  2249. parentsA.push(parent);
  2250. }
  2251. parent = nodeB;
  2252. while (parent = parent.parentNode) {
  2253. if (parent === nodeA)
  2254. return parent;
  2255. parentsB.push(parent);
  2256. }
  2257. parentsA.reverse();
  2258. parentsB.reverse();
  2259. while (i++, parentsA[i] === parentsB[i]) {
  2260. }
  2261. return i == 0 ? null : parentsA[i - 1];
  2262. },
  2263. /**
  2264. * 清除node节点左右连续为空的兄弟inline节点
  2265. * @method clearEmptySibling
  2266. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2267. * 则这些兄弟节点将被删除
  2268. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext) //ignoreNext指定是否忽略右边空节点
  2269. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext,ignorePre) //ignorePre指定是否忽略左边空节点
  2270. * @example
  2271. * ```html
  2272. * <body>
  2273. * <div></div>
  2274. * <span id="test"></span>
  2275. * <i></i>
  2276. * <b></b>
  2277. * <em>xxx</em>
  2278. * <span></span>
  2279. * </body>
  2280. * <script>
  2281. *
  2282. * UE.dom.domUtils.clearEmptySibling( document.getElementById( "test" ) );
  2283. *
  2284. * //output: <div></div><span id="test"></span><em>xxx</em><span></span>
  2285. * console.log( document.body.innerHTML );
  2286. *
  2287. * </script>
  2288. * ```
  2289. */
  2290. /**
  2291. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2292. * 则忽略对右边兄弟节点的操作。
  2293. * @method clearEmptySibling
  2294. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2295. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2296. * 则这些兄弟节点将被删除
  2297. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2298. */
  2299. /**
  2300. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2301. * 则忽略对右边兄弟节点的操作, 如果ignorePre的值为true,则忽略对左边兄弟节点的操作。
  2302. * @method clearEmptySibling
  2303. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2304. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2305. * @param { Boolean } ignorePre 是否忽略忽略对左边的兄弟节点的操作
  2306. * 则这些兄弟节点将被删除
  2307. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2308. */
  2309. clearEmptySibling: function (node, ignoreNext, ignorePre) {
  2310. function clear(next, dir) {
  2311. var tmpNode;
  2312. while (next && !domUtils.isBookmarkNode(next) && (domUtils.isEmptyInlineElement(next)
  2313. //这里不能把空格算进来会吧空格干掉,出现文字间的空格丢掉了
  2314. || !new RegExp('[^\t\n\r' + domUtils.fillChar + ']').test(next.nodeValue))) {
  2315. tmpNode = next[dir];
  2316. domUtils.remove(next);
  2317. next = tmpNode;
  2318. }
  2319. }
  2320. !ignoreNext && clear(node.nextSibling, 'nextSibling');
  2321. !ignorePre && clear(node.previousSibling, 'previousSibling');
  2322. },
  2323. /**
  2324. * 将一个文本节点textNode拆分成两个文本节点,offset指定拆分位置
  2325. * @method split
  2326. * @param { Node } textNode 需要拆分的文本节点对象
  2327. * @param { int } offset 需要拆分的位置, 位置计算从0开始
  2328. * @return { Node } 拆分后形成的新节点
  2329. * @example
  2330. * ```html
  2331. * <div id="test">abcdef</div>
  2332. * <script>
  2333. * var newNode = UE.dom.domUtils.split( document.getElementById( "test" ).firstChild, 3 );
  2334. * //output: def
  2335. * console.log( newNode.nodeValue );
  2336. * </script>
  2337. * ```
  2338. */
  2339. split: function (node, offset) {
  2340. var doc = node.ownerDocument;
  2341. if (browser.ie && offset == node.nodeValue.length) {
  2342. var next = doc.createTextNode('');
  2343. return domUtils.insertAfter(node, next);
  2344. }
  2345. var retval = node.splitText(offset);
  2346. //ie8下splitText不会跟新childNodes,我们手动触发他的更新
  2347. if (browser.ie8) {
  2348. var tmpNode = doc.createTextNode('');
  2349. domUtils.insertAfter(retval, tmpNode);
  2350. domUtils.remove(tmpNode);
  2351. }
  2352. return retval;
  2353. },
  2354. /**
  2355. * 检测文本节点textNode是否为空节点(包括空格、换行、占位符等字符)
  2356. * @method isWhitespace
  2357. * @param { Node } node 需要检测的节点对象
  2358. * @return { Boolean } 检测的节点是否为空
  2359. * @example
  2360. * ```html
  2361. * <div id="test">
  2362. *
  2363. * </div>
  2364. * <script>
  2365. * //output: true
  2366. * console.log( UE.dom.domUtils.isWhitespace( document.getElementById("test").firstChild ) );
  2367. * </script>
  2368. * ```
  2369. */
  2370. isWhitespace: function (node) {
  2371. return !new RegExp('[^ \t\n\r' + domUtils.fillChar + ']').test(node.nodeValue);
  2372. },
  2373. /**
  2374. * 获取元素element相对于viewport的位置坐标
  2375. * @method getXY
  2376. * @param { Node } element 需要计算位置的节点对象
  2377. * @return { Object } 返回形如{x:left,y:top}的一个key-value映射对象, 其中键x代表水平偏移距离,
  2378. * y代表垂直偏移距离。
  2379. *
  2380. * @example
  2381. * ```javascript
  2382. * var location = UE.dom.domUtils.getXY( document.getElementById("test") );
  2383. * //output: test的坐标为: 12, 24
  2384. * console.log( 'test的坐标为: ', location.x, ',', location.y );
  2385. * ```
  2386. */
  2387. getXY: function (element) {
  2388. var x = 0, y = 0;
  2389. while (element.offsetParent) {
  2390. y += element.offsetTop;
  2391. x += element.offsetLeft;
  2392. element = element.offsetParent;
  2393. }
  2394. return { 'x': x, 'y': y };
  2395. },
  2396. /**
  2397. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2398. * @method on
  2399. * @param { Node } element 需要绑定事件的节点对象
  2400. * @param { String } type 绑定的事件类型
  2401. * @param { Function } handler 事件处理器
  2402. * @example
  2403. * ```javascript
  2404. * UE.dom.domUtils.on(document.body,"click",function(e){
  2405. * //e为事件对象,this为被点击元素对戏那个
  2406. * });
  2407. * ```
  2408. */
  2409. /**
  2410. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2411. * @method on
  2412. * @param { Node } element 需要绑定事件的节点对象
  2413. * @param { Array } type 绑定的事件类型数组
  2414. * @param { Function } handler 事件处理器
  2415. * @example
  2416. * ```javascript
  2417. * UE.dom.domUtils.on(document.body,["click","mousedown"],function(evt){
  2418. * //evt为事件对象,this为被点击元素对象
  2419. * });
  2420. * ```
  2421. */
  2422. on: function (element, type, handler) {
  2423. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2424. k = types.length;
  2425. if (k) while (k--) {
  2426. type = types[k];
  2427. if (element.addEventListener) {
  2428. element.addEventListener(type, handler, false);
  2429. } else {
  2430. if (!handler._d) {
  2431. handler._d = {
  2432. els: []
  2433. };
  2434. }
  2435. var key = type + handler.toString(), index = utils.indexOf(handler._d.els, element);
  2436. if (!handler._d[key] || index == -1) {
  2437. if (index == -1) {
  2438. handler._d.els.push(element);
  2439. }
  2440. if (!handler._d[key]) {
  2441. handler._d[key] = function (evt) {
  2442. return handler.call(evt.srcElement, evt || window.event);
  2443. };
  2444. }
  2445. element.attachEvent('on' + type, handler._d[key]);
  2446. }
  2447. }
  2448. }
  2449. element = null;
  2450. },
  2451. /**
  2452. * 解除DOM事件绑定
  2453. * @method un
  2454. * @param { Node } element 需要解除事件绑定的节点对象
  2455. * @param { String } type 需要接触绑定的事件类型
  2456. * @param { Function } handler 对应的事件处理器
  2457. * @example
  2458. * ```javascript
  2459. * UE.dom.domUtils.un(document.body,"click",function(evt){
  2460. * //evt为事件对象,this为被点击元素对象
  2461. * });
  2462. * ```
  2463. */
  2464. /**
  2465. * 解除DOM事件绑定
  2466. * @method un
  2467. * @param { Node } element 需要解除事件绑定的节点对象
  2468. * @param { Array } type 需要接触绑定的事件类型数组
  2469. * @param { Function } handler 对应的事件处理器
  2470. * @example
  2471. * ```javascript
  2472. * UE.dom.domUtils.un(document.body, ["click","mousedown"],function(evt){
  2473. * //evt为事件对象,this为被点击元素对象
  2474. * });
  2475. * ```
  2476. */
  2477. un: function (element, type, handler) {
  2478. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2479. k = types.length;
  2480. if (k) while (k--) {
  2481. type = types[k];
  2482. if (element.removeEventListener) {
  2483. element.removeEventListener(type, handler, false);
  2484. } else {
  2485. var key = type + handler.toString();
  2486. try {
  2487. element.detachEvent('on' + type, handler._d ? handler._d[key] : handler);
  2488. } catch (e) { }
  2489. if (handler._d && handler._d[key]) {
  2490. var index = utils.indexOf(handler._d.els, element);
  2491. if (index != -1) {
  2492. handler._d.els.splice(index, 1);
  2493. }
  2494. handler._d.els.length == 0 && delete handler._d[key];
  2495. }
  2496. }
  2497. }
  2498. },
  2499. /**
  2500. * 比较节点nodeA与节点nodeB是否具有相同的标签名、属性名以及属性值
  2501. * @method isSameElement
  2502. * @param { Node } nodeA 需要比较的节点
  2503. * @param { Node } nodeB 需要比较的节点
  2504. * @return { Boolean } 两个节点是否具有相同的标签名、属性名以及属性值
  2505. * @example
  2506. * ```html
  2507. * <span style="font-size:12px">ssss</span>
  2508. * <span style="font-size:12px">bbbbb</span>
  2509. * <span style="font-size:13px">ssss</span>
  2510. * <span style="font-size:14px">bbbbb</span>
  2511. *
  2512. * <script>
  2513. *
  2514. * var nodes = document.getElementsByTagName( "span" );
  2515. *
  2516. * //output: true
  2517. * console.log( UE.dom.domUtils.isSameElement( nodes[0], nodes[1] ) );
  2518. *
  2519. * //output: false
  2520. * console.log( UE.dom.domUtils.isSameElement( nodes[2], nodes[3] ) );
  2521. *
  2522. * </script>
  2523. * ```
  2524. */
  2525. isSameElement: function (nodeA, nodeB) {
  2526. if (nodeA.tagName != nodeB.tagName) {
  2527. return false;
  2528. }
  2529. var thisAttrs = nodeA.attributes,
  2530. otherAttrs = nodeB.attributes;
  2531. if (!ie && thisAttrs.length != otherAttrs.length) {
  2532. return false;
  2533. }
  2534. var attrA, attrB, al = 0, bl = 0;
  2535. for (var i = 0; attrA = thisAttrs[i++];) {
  2536. if (attrA.nodeName == 'style') {
  2537. if (attrA.specified) {
  2538. al++;
  2539. }
  2540. if (domUtils.isSameStyle(nodeA, nodeB)) {
  2541. continue;
  2542. } else {
  2543. return false;
  2544. }
  2545. }
  2546. if (ie) {
  2547. if (attrA.specified) {
  2548. al++;
  2549. attrB = otherAttrs.getNamedItem(attrA.nodeName);
  2550. } else {
  2551. continue;
  2552. }
  2553. } else {
  2554. attrB = nodeB.attributes[attrA.nodeName];
  2555. }
  2556. if (!attrB.specified || attrA.nodeValue != attrB.nodeValue) {
  2557. return false;
  2558. }
  2559. }
  2560. // 有可能attrB的属性包含了attrA的属性之外还有自己的属性
  2561. if (ie) {
  2562. for (i = 0; attrB = otherAttrs[i++];) {
  2563. if (attrB.specified) {
  2564. bl++;
  2565. }
  2566. }
  2567. if (al != bl) {
  2568. return false;
  2569. }
  2570. }
  2571. return true;
  2572. },
  2573. /**
  2574. * 判断节点nodeA与节点nodeB的元素的style属性是否一致
  2575. * @method isSameStyle
  2576. * @param { Node } nodeA 需要比较的节点
  2577. * @param { Node } nodeB 需要比较的节点
  2578. * @return { Boolean } 两个节点是否具有相同的style属性值
  2579. * @example
  2580. * ```html
  2581. * <span style="font-size:12px">ssss</span>
  2582. * <span style="font-size:12px">bbbbb</span>
  2583. * <span style="font-size:13px">ssss</span>
  2584. * <span style="font-size:14px">bbbbb</span>
  2585. *
  2586. * <script>
  2587. *
  2588. * var nodes = document.getElementsByTagName( "span" );
  2589. *
  2590. * //output: true
  2591. * console.log( UE.dom.domUtils.isSameStyle( nodes[0], nodes[1] ) );
  2592. *
  2593. * //output: false
  2594. * console.log( UE.dom.domUtils.isSameStyle( nodes[2], nodes[3] ) );
  2595. *
  2596. * </script>
  2597. * ```
  2598. */
  2599. isSameStyle: function (nodeA, nodeB) {
  2600. var styleA = nodeA.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':'),
  2601. styleB = nodeB.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':');
  2602. if (browser.opera) {
  2603. styleA = nodeA.style;
  2604. styleB = nodeB.style;
  2605. if (styleA.length != styleB.length)
  2606. return false;
  2607. for (var p in styleA) {
  2608. if (/^(\d+|csstext)$/i.test(p)) {
  2609. continue;
  2610. }
  2611. if (styleA[p] != styleB[p]) {
  2612. return false;
  2613. }
  2614. }
  2615. return true;
  2616. }
  2617. if (!styleA || !styleB) {
  2618. return styleA == styleB;
  2619. }
  2620. styleA = styleA.split(';');
  2621. styleB = styleB.split(';');
  2622. if (styleA.length != styleB.length) {
  2623. return false;
  2624. }
  2625. for (var i = 0, ci; ci = styleA[i++];) {
  2626. if (utils.indexOf(styleB, ci) == -1) {
  2627. return false;
  2628. }
  2629. }
  2630. return true;
  2631. },
  2632. /**
  2633. * 检查节点node是否为block元素
  2634. * @method isBlockElm
  2635. * @param { Node } node 需要检测的节点对象
  2636. * @return { Boolean } 是否是block元素节点
  2637. * @warning 该方法的判断规则如下: 如果该元素原本是block元素, 则不论该元素当前的css样式是什么都会返回true;
  2638. * 否则,检测该元素的css样式, 如果该元素当前是block元素, 则返回true。 其余情况下都返回false。
  2639. * @example
  2640. * ```html
  2641. * <span id="test1" style="display: block"></span>
  2642. * <span id="test2"></span>
  2643. * <div id="test3" style="display: inline"></div>
  2644. *
  2645. * <script>
  2646. *
  2647. * //output: true
  2648. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test1") ) );
  2649. *
  2650. * //output: false
  2651. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test2") ) );
  2652. *
  2653. * //output: true
  2654. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test3") ) );
  2655. *
  2656. * </script>
  2657. * ```
  2658. */
  2659. isBlockElm: function (node) {
  2660. return node.nodeType == 1 && (dtd.$block[node.tagName] || styleBlock[domUtils.getComputedStyle(node, 'display')]) && !dtd.$nonChild[node.tagName];
  2661. },
  2662. /**
  2663. * 检测node节点是否为body节点
  2664. * @method isBody
  2665. * @param { Element } node 需要检测的dom元素
  2666. * @return { Boolean } 给定的元素是否是body元素
  2667. * @example
  2668. * ```javascript
  2669. * //output: true
  2670. * console.log( UE.dom.domUtils.isBody( document.body ) );
  2671. * ```
  2672. */
  2673. isBody: function (node) {
  2674. return node && node.nodeType == 1 && node.tagName.toLowerCase() == 'body';
  2675. },
  2676. /**
  2677. * 以node节点为分界,将该节点的指定祖先节点parent拆分成两个独立的节点,
  2678. * 拆分形成的两个节点之间是node节点
  2679. * @method breakParent
  2680. * @param { Node } node 作为分界的节点对象
  2681. * @param { Node } parent 该节点必须是node节点的祖先节点, 且是block节点。
  2682. * @return { Node } 给定的node分界节点
  2683. * @example
  2684. * ```javascript
  2685. *
  2686. * var node = document.createElement("span"),
  2687. * wrapNode = document.createElement( "div" ),
  2688. * parent = document.createElement("p");
  2689. *
  2690. * parent.appendChild( node );
  2691. * wrapNode.appendChild( parent );
  2692. *
  2693. * //拆分前
  2694. * //output: <p><span></span></p>
  2695. * console.log( wrapNode.innerHTML );
  2696. *
  2697. *
  2698. * UE.dom.domUtils.breakParent( node, parent );
  2699. * //拆分后
  2700. * //output: <p></p><span></span><p></p>
  2701. * console.log( wrapNode.innerHTML );
  2702. *
  2703. * ```
  2704. */
  2705. breakParent: function (node, parent) {
  2706. var tmpNode,
  2707. parentClone = node,
  2708. clone = node,
  2709. leftNodes,
  2710. rightNodes;
  2711. do {
  2712. parentClone = parentClone.parentNode;
  2713. if (leftNodes) {
  2714. tmpNode = parentClone.cloneNode(false);
  2715. tmpNode.appendChild(leftNodes);
  2716. leftNodes = tmpNode;
  2717. tmpNode = parentClone.cloneNode(false);
  2718. tmpNode.appendChild(rightNodes);
  2719. rightNodes = tmpNode;
  2720. } else {
  2721. leftNodes = parentClone.cloneNode(false);
  2722. rightNodes = leftNodes.cloneNode(false);
  2723. }
  2724. while (tmpNode = clone.previousSibling) {
  2725. leftNodes.insertBefore(tmpNode, leftNodes.firstChild);
  2726. }
  2727. while (tmpNode = clone.nextSibling) {
  2728. rightNodes.appendChild(tmpNode);
  2729. }
  2730. clone = parentClone;
  2731. } while (parent !== parentClone);
  2732. tmpNode = parent.parentNode;
  2733. tmpNode.insertBefore(leftNodes, parent);
  2734. tmpNode.insertBefore(rightNodes, parent);
  2735. tmpNode.insertBefore(node, rightNodes);
  2736. domUtils.remove(parent);
  2737. return node;
  2738. },
  2739. /**
  2740. * 检查节点node是否是空inline节点
  2741. * @method isEmptyInlineElement
  2742. * @param { Node } node 需要检测的节点对象
  2743. * @return { Number } 如果给定的节点是空的inline节点, 则返回1, 否则返回0。
  2744. * @example
  2745. * ```html
  2746. * <b><i></i></b> => 1
  2747. * <b><i></i><u></u></b> => 1
  2748. * <b></b> => 1
  2749. * <b>xx<i></i></b> => 0
  2750. * ```
  2751. */
  2752. isEmptyInlineElement: function (node) {
  2753. if (node.nodeType != 1 || !dtd.$removeEmpty[node.tagName]) {
  2754. return 0;
  2755. }
  2756. node = node.firstChild;
  2757. while (node) {
  2758. //如果是创建的bookmark就跳过
  2759. if (domUtils.isBookmarkNode(node)) {
  2760. return 0;
  2761. }
  2762. if (node.nodeType == 1 && !domUtils.isEmptyInlineElement(node) ||
  2763. node.nodeType == 3 && !domUtils.isWhitespace(node)
  2764. ) {
  2765. return 0;
  2766. }
  2767. node = node.nextSibling;
  2768. }
  2769. return 1;
  2770. },
  2771. /**
  2772. * 删除node节点下首尾两端的空白文本子节点
  2773. * @method trimWhiteTextNode
  2774. * @param { Element } node 需要执行删除操作的元素对象
  2775. * @example
  2776. * ```javascript
  2777. * var node = document.createElement("div");
  2778. *
  2779. * node.appendChild( document.createTextNode( "" ) );
  2780. *
  2781. * node.appendChild( document.createElement("div") );
  2782. *
  2783. * node.appendChild( document.createTextNode( "" ) );
  2784. *
  2785. * //3
  2786. * console.log( node.childNodes.length );
  2787. *
  2788. * UE.dom.domUtils.trimWhiteTextNode( node );
  2789. *
  2790. * //1
  2791. * console.log( node.childNodes.length );
  2792. * ```
  2793. */
  2794. trimWhiteTextNode: function (node) {
  2795. function remove(dir) {
  2796. var child;
  2797. while ((child = node[dir]) && child.nodeType == 3 && domUtils.isWhitespace(child)) {
  2798. node.removeChild(child);
  2799. }
  2800. }
  2801. remove('firstChild');
  2802. remove('lastChild');
  2803. },
  2804. /**
  2805. * 合并node节点下相同的子节点
  2806. * @name mergeChild
  2807. * @desc
  2808. * UE.dom.domUtils.mergeChild(node,tagName) //tagName要合并的子节点的标签
  2809. * @example
  2810. * <p><span style="font-size:12px;">xx<span style="font-size:12px;">aa</span>xx</span></p>
  2811. * ==> UE.dom.domUtils.mergeChild(node,'span')
  2812. * <p><span style="font-size:12px;">xxaaxx</span></p>
  2813. */
  2814. mergeChild: function (node, tagName, attrs) {
  2815. var list = domUtils.getElementsByTagName(node, node.tagName.toLowerCase());
  2816. for (var i = 0, ci; ci = list[i++];) {
  2817. if (!ci.parentNode || domUtils.isBookmarkNode(ci)) {
  2818. continue;
  2819. }
  2820. //span单独处理
  2821. if (ci.tagName.toLowerCase() == 'span') {
  2822. if (node === ci.parentNode) {
  2823. domUtils.trimWhiteTextNode(node);
  2824. if (node.childNodes.length == 1) {
  2825. node.style.cssText = ci.style.cssText + ";" + node.style.cssText;
  2826. domUtils.remove(ci, true);
  2827. continue;
  2828. }
  2829. }
  2830. ci.style.cssText = node.style.cssText + ';' + ci.style.cssText;
  2831. if (attrs) {
  2832. var style = attrs.style;
  2833. if (style) {
  2834. style = style.split(';');
  2835. for (var j = 0, s; s = style[j++];) {
  2836. ci.style[utils.cssStyleToDomStyle(s.split(':')[0])] = s.split(':')[1];
  2837. }
  2838. }
  2839. }
  2840. if (domUtils.isSameStyle(ci, node)) {
  2841. domUtils.remove(ci, true);
  2842. }
  2843. continue;
  2844. }
  2845. if (domUtils.isSameElement(node, ci)) {
  2846. domUtils.remove(ci, true);
  2847. }
  2848. }
  2849. },
  2850. /**
  2851. * 原生方法getElementsByTagName的封装
  2852. * @method getElementsByTagName
  2853. * @param { Node } node 目标节点对象
  2854. * @param { String } tagName 需要查找的节点的tagName, 多个tagName以空格分割
  2855. * @return { Array } 符合条件的节点集合
  2856. */
  2857. getElementsByTagName: function (node, name, filter) {
  2858. if (filter && utils.isString(filter)) {
  2859. var className = filter;
  2860. filter = function (node) { return domUtils.hasClass(node, className) }
  2861. }
  2862. name = utils.trim(name).replace(/[ ]{2,}/g, ' ').split(' ');
  2863. var arr = [];
  2864. for (var n = 0, ni; ni = name[n++];) {
  2865. var list = node.getElementsByTagName(ni);
  2866. for (var i = 0, ci; ci = list[i++];) {
  2867. if (!filter || filter(ci))
  2868. arr.push(ci);
  2869. }
  2870. }
  2871. return arr;
  2872. },
  2873. /**
  2874. * 将节点node提取到父节点上
  2875. * @method mergeToParent
  2876. * @param { Element } node 需要提取的元素对象
  2877. * @example
  2878. * ```html
  2879. * <div id="parent">
  2880. * <div id="sub">
  2881. * <span id="child"></span>
  2882. * </div>
  2883. * </div>
  2884. *
  2885. * <script>
  2886. *
  2887. * var child = document.getElementById( "child" );
  2888. *
  2889. * //output: sub
  2890. * console.log( child.parentNode.id );
  2891. *
  2892. * UE.dom.domUtils.mergeToParent( child );
  2893. *
  2894. * //output: parent
  2895. * console.log( child.parentNode.id );
  2896. *
  2897. * </script>
  2898. * ```
  2899. */
  2900. mergeToParent: function (node) {
  2901. var parent = node.parentNode;
  2902. while (parent && dtd.$removeEmpty[parent.tagName]) {
  2903. if (parent.tagName == node.tagName || parent.tagName == 'A') {//针对a标签单独处理
  2904. domUtils.trimWhiteTextNode(parent);
  2905. //span需要特殊处理 不处理这样的情况 <span stlye="color:#fff">xxx<span style="color:#ccc">xxx</span>xxx</span>
  2906. if (parent.tagName == 'SPAN' && !domUtils.isSameStyle(parent, node)
  2907. || (parent.tagName == 'A' && node.tagName == 'SPAN')) {
  2908. if (parent.childNodes.length > 1 || parent !== node.parentNode) {
  2909. node.style.cssText = parent.style.cssText + ";" + node.style.cssText;
  2910. parent = parent.parentNode;
  2911. continue;
  2912. } else {
  2913. parent.style.cssText += ";" + node.style.cssText;
  2914. //trace:952 a标签要保持下划线
  2915. if (parent.tagName == 'A') {
  2916. parent.style.textDecoration = 'underline';
  2917. }
  2918. }
  2919. }
  2920. if (parent.tagName != 'A') {
  2921. parent === node.parentNode && domUtils.remove(node, true);
  2922. break;
  2923. }
  2924. }
  2925. parent = parent.parentNode;
  2926. }
  2927. },
  2928. /**
  2929. * 合并节点node的左右兄弟节点
  2930. * @method mergeSibling
  2931. * @param { Element } node 需要合并的目标节点
  2932. * @example
  2933. * ```html
  2934. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2935. *
  2936. * <script>
  2937. * var demoNode = document.getElementById("test");
  2938. * UE.dom.domUtils.mergeSibling( demoNode );
  2939. * //output: xxxxoooxxxx
  2940. * console.log( demoNode.innerHTML );
  2941. * </script>
  2942. * ```
  2943. */
  2944. /**
  2945. * 合并节点node的左右兄弟节点, 可以根据给定的条件选择是否忽略合并左节点。
  2946. * @method mergeSibling
  2947. * @param { Element } node 需要合并的目标节点
  2948. * @param { Boolean } ignorePre 是否忽略合并左节点
  2949. * @example
  2950. * ```html
  2951. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2952. *
  2953. * <script>
  2954. * var demoNode = document.getElementById("test");
  2955. * UE.dom.domUtils.mergeSibling( demoNode, true );
  2956. * //output: oooxxxx
  2957. * console.log( demoNode.innerHTML );
  2958. * </script>
  2959. * ```
  2960. */
  2961. /**
  2962. * 合并节点node的左右兄弟节点,可以根据给定的条件选择是否忽略合并左右节点。
  2963. * @method mergeSibling
  2964. * @param { Element } node 需要合并的目标节点
  2965. * @param { Boolean } ignorePre 是否忽略合并左节点
  2966. * @param { Boolean } ignoreNext 是否忽略合并右节点
  2967. * @remind 如果同时忽略左右节点, 则该操作什么也不会做
  2968. * @example
  2969. * ```html
  2970. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2971. *
  2972. * <script>
  2973. * var demoNode = document.getElementById("test");
  2974. * UE.dom.domUtils.mergeSibling( demoNode, false, true );
  2975. * //output: xxxxooo
  2976. * console.log( demoNode.innerHTML );
  2977. * </script>
  2978. * ```
  2979. */
  2980. mergeSibling: function (node, ignorePre, ignoreNext) {
  2981. function merge(rtl, start, node) {
  2982. var next;
  2983. if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1 && domUtils.isSameElement(node, next)) {
  2984. while (next.firstChild) {
  2985. if (start == 'firstChild') {
  2986. node.insertBefore(next.lastChild, node.firstChild);
  2987. } else {
  2988. node.appendChild(next.firstChild);
  2989. }
  2990. }
  2991. domUtils.remove(next);
  2992. }
  2993. }
  2994. !ignorePre && merge('previousSibling', 'firstChild', node);
  2995. !ignoreNext && merge('nextSibling', 'lastChild', node);
  2996. },
  2997. /**
  2998. * 设置节点node及其子节点不会被选中
  2999. * @method unSelectable
  3000. * @param { Element } node 需要执行操作的dom元素
  3001. * @remind 执行该操作后的节点, 将不能被鼠标选中
  3002. * @example
  3003. * ```javascript
  3004. * UE.dom.domUtils.unSelectable( document.body );
  3005. * ```
  3006. */
  3007. unSelectable: ie && browser.ie9below || browser.opera ? function (node) {
  3008. //for ie9
  3009. node.onselectstart = function () {
  3010. return false;
  3011. };
  3012. node.onclick = node.onkeyup = node.onkeydown = function () {
  3013. return false;
  3014. };
  3015. node.unselectable = 'on';
  3016. node.setAttribute("unselectable", "on");
  3017. for (var i = 0, ci; ci = node.all[i++];) {
  3018. switch (ci.tagName.toLowerCase()) {
  3019. case 'iframe':
  3020. case 'textarea':
  3021. case 'input':
  3022. case 'select':
  3023. break;
  3024. default:
  3025. ci.unselectable = 'on';
  3026. node.setAttribute("unselectable", "on");
  3027. }
  3028. }
  3029. } : function (node) {
  3030. node.style.MozUserSelect =
  3031. node.style.webkitUserSelect =
  3032. node.style.msUserSelect =
  3033. node.style.KhtmlUserSelect = 'none';
  3034. },
  3035. /**
  3036. * 删除节点node上的指定属性名称的属性
  3037. * @method removeAttributes
  3038. * @param { Node } node 需要删除属性的节点对象
  3039. * @param { String } attrNames 可以是空格隔开的多个属性名称,该操作将会依次删除相应的属性
  3040. * @example
  3041. * ```html
  3042. * <div id="wrap">
  3043. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  3044. * </div>
  3045. *
  3046. * <script>
  3047. *
  3048. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), "id name" );
  3049. *
  3050. * //output: <span style="font-size:14px;">xxxxx</span>
  3051. * console.log( document.getElementById("wrap").innerHTML );
  3052. *
  3053. * </script>
  3054. * ```
  3055. */
  3056. /**
  3057. * 删除节点node上的指定属性名称的属性
  3058. * @method removeAttributes
  3059. * @param { Node } node 需要删除属性的节点对象
  3060. * @param { Array } attrNames 需要删除的属性名数组
  3061. * @example
  3062. * ```html
  3063. * <div id="wrap">
  3064. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  3065. * </div>
  3066. *
  3067. * <script>
  3068. *
  3069. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), ["id", "name"] );
  3070. *
  3071. * //output: <span style="font-size:14px;">xxxxx</span>
  3072. * console.log( document.getElementById("wrap").innerHTML );
  3073. *
  3074. * </script>
  3075. * ```
  3076. */
  3077. removeAttributes: function (node, attrNames) {
  3078. attrNames = utils.isArray(attrNames) ? attrNames : utils.trim(attrNames).replace(/[ ]{2,}/g, ' ').split(' ');
  3079. for (var i = 0, ci; ci = attrNames[i++];) {
  3080. ci = attrFix[ci] || ci;
  3081. switch (ci) {
  3082. case 'className':
  3083. node[ci] = '';
  3084. break;
  3085. case 'style':
  3086. node.style.cssText = '';
  3087. var val = node.getAttributeNode('style');
  3088. !browser.ie && val && node.removeAttributeNode(val);
  3089. }
  3090. node.removeAttribute(ci);
  3091. }
  3092. },
  3093. /**
  3094. * 在doc下创建一个标签名为tag,属性为attrs的元素
  3095. * @method createElement
  3096. * @param { DomDocument } doc 新创建的元素属于该document节点创建
  3097. * @param { String } tagName 需要创建的元素的标签名
  3098. * @param { Object } attrs 新创建的元素的属性key-value集合
  3099. * @return { Element } 新创建的元素对象
  3100. * @example
  3101. * ```javascript
  3102. * var ele = UE.dom.domUtils.createElement( document, 'div', {
  3103. * id: 'test'
  3104. * } );
  3105. *
  3106. * //output: DIV
  3107. * console.log( ele.tagName );
  3108. *
  3109. * //output: test
  3110. * console.log( ele.id );
  3111. *
  3112. * ```
  3113. */
  3114. createElement: function (doc, tag, attrs) {
  3115. return domUtils.setAttributes(doc.createElement(tag), attrs)
  3116. },
  3117. /**
  3118. * 为节点node添加属性attrs,attrs为属性键值对
  3119. * @method setAttributes
  3120. * @param { Element } node 需要设置属性的元素对象
  3121. * @param { Object } attrs 需要设置的属性名-值对
  3122. * @return { Element } 设置属性的元素对象
  3123. * @example
  3124. * ```html
  3125. * <span id="test"></span>
  3126. *
  3127. * <script>
  3128. *
  3129. * var testNode = UE.dom.domUtils.setAttributes( document.getElementById( "test" ), {
  3130. * id: 'demo'
  3131. * } );
  3132. *
  3133. * //output: demo
  3134. * console.log( testNode.id );
  3135. *
  3136. * </script>
  3137. *
  3138. */
  3139. setAttributes: function (node, attrs) {
  3140. for (var attr in attrs) {
  3141. if (attrs.hasOwnProperty(attr)) {
  3142. var value = attrs[attr];
  3143. switch (attr) {
  3144. case 'class':
  3145. //ie下要这样赋值,setAttribute不起作用
  3146. node.className = value;
  3147. break;
  3148. case 'style':
  3149. node.style.cssText = node.style.cssText + ";" + value;
  3150. break;
  3151. case 'innerHTML':
  3152. node[attr] = value;
  3153. break;
  3154. case 'value':
  3155. node.value = value;
  3156. break;
  3157. default:
  3158. node.setAttribute(attrFix[attr] || attr, value);
  3159. }
  3160. }
  3161. }
  3162. return node;
  3163. },
  3164. /**
  3165. * 获取元素element经过计算后的样式值
  3166. * @method getComputedStyle
  3167. * @param { Element } element 需要获取样式的元素对象
  3168. * @param { String } styleName 需要获取的样式名
  3169. * @return { String } 获取到的样式值
  3170. * @example
  3171. * ```html
  3172. * <style type="text/css">
  3173. * #test {
  3174. * font-size: 15px;
  3175. * }
  3176. * </style>
  3177. *
  3178. * <span id="test"></span>
  3179. *
  3180. * <script>
  3181. * //output: 15px
  3182. * console.log( UE.dom.domUtils.getComputedStyle( document.getElementById( "test" ), 'font-size' ) );
  3183. * </script>
  3184. * ```
  3185. */
  3186. getComputedStyle: function (element, styleName) {
  3187. //一下的属性单独处理
  3188. var pros = 'width height top left';
  3189. if (pros.indexOf(styleName) > -1) {
  3190. return element['offset' + styleName.replace(/^\w/, function (s) { return s.toUpperCase() })] + 'px';
  3191. }
  3192. //忽略文本节点
  3193. if (element.nodeType == 3) {
  3194. element = element.parentNode;
  3195. }
  3196. //ie下font-size若body下定义了font-size,则从currentStyle里会取到这个font-size. 取不到实际值,故此修改.
  3197. if (browser.ie && browser.version < 9 && styleName == 'font-size' && !element.style.fontSize &&
  3198. !dtd.$empty[element.tagName] && !dtd.$nonChild[element.tagName]) {
  3199. var span = element.ownerDocument.createElement('span');
  3200. span.style.cssText = 'padding:0;border:0;font-family:simsun;';
  3201. span.innerHTML = '.';
  3202. element.appendChild(span);
  3203. var result = span.offsetHeight;
  3204. element.removeChild(span);
  3205. span = null;
  3206. return result + 'px';
  3207. }
  3208. try {
  3209. var value = domUtils.getStyle(element, styleName) ||
  3210. (window.getComputedStyle ? domUtils.getWindow(element).getComputedStyle(element, '').getPropertyValue(styleName) :
  3211. (element.currentStyle || element.style)[utils.cssStyleToDomStyle(styleName)]);
  3212. } catch (e) {
  3213. return "";
  3214. }
  3215. return utils.transUnitToPx(utils.fixColor(styleName, value));
  3216. },
  3217. /**
  3218. * 删除元素element指定的className
  3219. * @method removeClasses
  3220. * @param { Element } ele 需要删除class的元素节点
  3221. * @param { String } classNames 需要删除的className, 多个className之间以空格分开
  3222. * @example
  3223. * ```html
  3224. * <span id="test" class="test1 test2 test3">xxx</span>
  3225. *
  3226. * <script>
  3227. *
  3228. * var testNode = document.getElementById( "test" );
  3229. * UE.dom.domUtils.removeClasses( testNode, "test1 test2" );
  3230. *
  3231. * //output: test3
  3232. * console.log( testNode.className );
  3233. *
  3234. * </script>
  3235. * ```
  3236. */
  3237. /**
  3238. * 删除元素element指定的className
  3239. * @method removeClasses
  3240. * @param { Element } ele 需要删除class的元素节点
  3241. * @param { Array } classNames 需要删除的className数组
  3242. * @example
  3243. * ```html
  3244. * <span id="test" class="test1 test2 test3">xxx</span>
  3245. *
  3246. * <script>
  3247. *
  3248. * var testNode = document.getElementById( "test" );
  3249. * UE.dom.domUtils.removeClasses( testNode, ["test1", "test2"] );
  3250. *
  3251. * //output: test3
  3252. * console.log( testNode.className );
  3253. *
  3254. * </script>
  3255. * ```
  3256. */
  3257. removeClasses: function (elm, classNames) {
  3258. classNames = utils.isArray(classNames) ? classNames :
  3259. utils.trim(classNames).replace(/[ ]{2,}/g, ' ').split(' ');
  3260. for (var i = 0, ci, cls = elm.className; ci = classNames[i++];) {
  3261. cls = cls.replace(new RegExp('\\b' + ci + '\\b'), '')
  3262. }
  3263. cls = utils.trim(cls).replace(/[ ]{2,}/g, ' ');
  3264. if (cls) {
  3265. elm.className = cls;
  3266. } else {
  3267. domUtils.removeAttributes(elm, ['class']);
  3268. }
  3269. },
  3270. /**
  3271. * 给元素element添加className
  3272. * @method addClass
  3273. * @param { Node } ele 需要增加className的元素
  3274. * @param { String } classNames 需要添加的className, 多个className之间以空格分割
  3275. * @remind 相同的类名不会被重复添加
  3276. * @example
  3277. * ```html
  3278. * <span id="test" class="cls1 cls2"></span>
  3279. *
  3280. * <script>
  3281. * var testNode = document.getElementById("test");
  3282. *
  3283. * UE.dom.domUtils.addClass( testNode, "cls2 cls3 cls4" );
  3284. *
  3285. * //output: cl1 cls2 cls3 cls4
  3286. * console.log( testNode.className );
  3287. *
  3288. * <script>
  3289. * ```
  3290. */
  3291. /**
  3292. * 给元素element添加className
  3293. * @method addClass
  3294. * @param { Node } ele 需要增加className的元素
  3295. * @param { Array } classNames 需要添加的className的数组
  3296. * @remind 相同的类名不会被重复添加
  3297. * @example
  3298. * ```html
  3299. * <span id="test" class="cls1 cls2"></span>
  3300. *
  3301. * <script>
  3302. * var testNode = document.getElementById("test");
  3303. *
  3304. * UE.dom.domUtils.addClass( testNode, ["cls2", "cls3", "cls4"] );
  3305. *
  3306. * //output: cl1 cls2 cls3 cls4
  3307. * console.log( testNode.className );
  3308. *
  3309. * <script>
  3310. * ```
  3311. */
  3312. addClass: function (elm, classNames) {
  3313. if (!elm) return;
  3314. classNames = utils.trim(classNames).replace(/[ ]{2,}/g, ' ').split(' ');
  3315. for (var i = 0, ci, cls = elm.className; ci = classNames[i++];) {
  3316. if (!new RegExp('\\b' + ci + '\\b').test(cls)) {
  3317. cls += ' ' + ci;
  3318. }
  3319. }
  3320. elm.className = utils.trim(cls);
  3321. },
  3322. /**
  3323. * 判断元素element是否包含给定的样式类名className
  3324. * @method hasClass
  3325. * @param { Node } ele 需要检测的元素
  3326. * @param { String } classNames 需要检测的className, 多个className之间用空格分割
  3327. * @return { Boolean } 元素是否包含所有给定的className
  3328. * @example
  3329. * ```html
  3330. * <span id="test1" class="cls1 cls2"></span>
  3331. *
  3332. * <script>
  3333. * var test1 = document.getElementById("test1");
  3334. *
  3335. * //output: false
  3336. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1 cls3" ) );
  3337. *
  3338. * //output: true
  3339. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1" ) );
  3340. * </script>
  3341. * ```
  3342. */
  3343. /**
  3344. * 判断元素element是否包含给定的样式类名className
  3345. * @method hasClass
  3346. * @param { Node } ele 需要检测的元素
  3347. * @param { Array } classNames 需要检测的className数组
  3348. * @return { Boolean } 元素是否包含所有给定的className
  3349. * @example
  3350. * ```html
  3351. * <span id="test1" class="cls1 cls2"></span>
  3352. *
  3353. * <script>
  3354. * var test1 = document.getElementById("test1");
  3355. *
  3356. * //output: false
  3357. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1", "cls3" ] ) );
  3358. *
  3359. * //output: true
  3360. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1" ]) );
  3361. * </script>
  3362. * ```
  3363. */
  3364. hasClass: function (element, className) {
  3365. if (utils.isRegExp(className)) {
  3366. return className.test(element.className)
  3367. }
  3368. className = utils.trim(className).replace(/[ ]{2,}/g, ' ').split(' ');
  3369. for (var i = 0, ci, cls = element.className; ci = className[i++];) {
  3370. if (!new RegExp('\\b' + ci + '\\b', 'i').test(cls)) {
  3371. return false;
  3372. }
  3373. }
  3374. return i - 1 == className.length;
  3375. },
  3376. /**
  3377. * 阻止事件默认行为
  3378. * @method preventDefault
  3379. * @param { Event } evt 需要阻止默认行为的事件对象
  3380. * @example
  3381. * ```javascript
  3382. * UE.dom.domUtils.preventDefault( evt );
  3383. * ```
  3384. */
  3385. preventDefault: function (evt) {
  3386. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  3387. },
  3388. /**
  3389. * 删除元素element指定的样式
  3390. * @method removeStyle
  3391. * @param { Element } element 需要删除样式的元素
  3392. * @param { String } styleName 需要删除的样式名
  3393. * @example
  3394. * ```html
  3395. * <span id="test" style="color: red; background: blue;"></span>
  3396. *
  3397. * <script>
  3398. *
  3399. * var testNode = document.getElementById("test");
  3400. *
  3401. * UE.dom.domUtils.removeStyle( testNode, 'color' );
  3402. *
  3403. * //output: background: blue;
  3404. * console.log( testNode.style.cssText );
  3405. *
  3406. * </script>
  3407. * ```
  3408. */
  3409. removeStyle: function (element, name) {
  3410. if (browser.ie) {
  3411. //针对color先单独处理一下
  3412. if (name == 'color') {
  3413. name = '(^|;)' + name;
  3414. }
  3415. element.style.cssText = element.style.cssText.replace(new RegExp(name + '[^:]*:[^;]+;?', 'ig'), '')
  3416. } else {
  3417. if (element.style.removeProperty) {
  3418. element.style.removeProperty(name);
  3419. } else {
  3420. element.style.removeAttribute(utils.cssStyleToDomStyle(name));
  3421. }
  3422. }
  3423. if (!element.style.cssText) {
  3424. domUtils.removeAttributes(element, ['style']);
  3425. }
  3426. },
  3427. /**
  3428. * 获取元素element的style属性的指定值
  3429. * @method getStyle
  3430. * @param { Element } element 需要获取属性值的元素
  3431. * @param { String } styleName 需要获取的style的名称
  3432. * @warning 该方法仅获取元素style属性中所标明的值
  3433. * @return { String } 该元素包含指定的style属性值
  3434. * @example
  3435. * ```html
  3436. * <div id="test" style="color: red;"></div>
  3437. *
  3438. * <script>
  3439. *
  3440. * var testNode = document.getElementById( "test" );
  3441. *
  3442. * //output: red
  3443. * console.log( UE.dom.domUtils.getStyle( testNode, "color" ) );
  3444. *
  3445. * //output: ""
  3446. * console.log( UE.dom.domUtils.getStyle( testNode, "background" ) );
  3447. *
  3448. * </script>
  3449. * ```
  3450. */
  3451. getStyle: function (element, name) {
  3452. var value = element.style[utils.cssStyleToDomStyle(name)];
  3453. return utils.fixColor(name, value);
  3454. },
  3455. /**
  3456. * 为元素element设置样式属性值
  3457. * @method setStyle
  3458. * @param { Element } element 需要设置样式的元素
  3459. * @param { String } styleName 样式名
  3460. * @param { String } styleValue 样式值
  3461. * @example
  3462. * ```html
  3463. * <div id="test"></div>
  3464. *
  3465. * <script>
  3466. *
  3467. * var testNode = document.getElementById( "test" );
  3468. *
  3469. * //output: ""
  3470. * console.log( testNode.style.color );
  3471. *
  3472. * UE.dom.domUtils.setStyle( testNode, 'color', 'red' );
  3473. * //output: "red"
  3474. * console.log( testNode.style.color );
  3475. *
  3476. * </script>
  3477. * ```
  3478. */
  3479. setStyle: function (element, name, value) {
  3480. element.style[utils.cssStyleToDomStyle(name)] = value;
  3481. if (!utils.trim(element.style.cssText)) {
  3482. this.removeAttributes(element, 'style')
  3483. }
  3484. },
  3485. /**
  3486. * 为元素element设置多个样式属性值
  3487. * @method setStyles
  3488. * @param { Element } element 需要设置样式的元素
  3489. * @param { Object } styles 样式名值对
  3490. * @example
  3491. * ```html
  3492. * <div id="test"></div>
  3493. *
  3494. * <script>
  3495. *
  3496. * var testNode = document.getElementById( "test" );
  3497. *
  3498. * //output: ""
  3499. * console.log( testNode.style.color );
  3500. *
  3501. * UE.dom.domUtils.setStyles( testNode, {
  3502. * 'color': 'red'
  3503. * } );
  3504. * //output: "red"
  3505. * console.log( testNode.style.color );
  3506. *
  3507. * </script>
  3508. * ```
  3509. */
  3510. setStyles: function (element, styles) {
  3511. for (var name in styles) {
  3512. if (styles.hasOwnProperty(name)) {
  3513. domUtils.setStyle(element, name, styles[name]);
  3514. }
  3515. }
  3516. },
  3517. /**
  3518. * 删除_moz_dirty属性
  3519. * @private
  3520. * @method removeDirtyAttr
  3521. */
  3522. removeDirtyAttr: function (node) {
  3523. for (var i = 0, ci, nodes = node.getElementsByTagName('*'); ci = nodes[i++];) {
  3524. ci.removeAttribute('_moz_dirty');
  3525. }
  3526. node.removeAttribute('_moz_dirty');
  3527. },
  3528. /**
  3529. * 获取子节点的数量
  3530. * @method getChildCount
  3531. * @param { Element } node 需要检测的元素
  3532. * @return { Number } 给定的node元素的子节点数量
  3533. * @example
  3534. * ```html
  3535. * <div id="test">
  3536. * <span></span>
  3537. * </div>
  3538. *
  3539. * <script>
  3540. *
  3541. * //output: 3
  3542. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test") ) );
  3543. *
  3544. * </script>
  3545. * ```
  3546. */
  3547. /**
  3548. * 根据给定的过滤规则, 获取符合条件的子节点的数量
  3549. * @method getChildCount
  3550. * @param { Element } node 需要检测的元素
  3551. * @param { Function } fn 过滤器, 要求对符合条件的子节点返回true, 反之则要求返回false
  3552. * @return { Number } 符合过滤条件的node元素的子节点数量
  3553. * @example
  3554. * ```html
  3555. * <div id="test">
  3556. * <span></span>
  3557. * </div>
  3558. *
  3559. * <script>
  3560. *
  3561. * //output: 1
  3562. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test"), function ( node ) {
  3563. *
  3564. * return node.nodeType === 1;
  3565. *
  3566. * } ) );
  3567. *
  3568. * </script>
  3569. * ```
  3570. */
  3571. getChildCount: function (node, fn) {
  3572. var count = 0, first = node.firstChild;
  3573. fn = fn || function () {
  3574. return 1;
  3575. };
  3576. while (first) {
  3577. if (fn(first)) {
  3578. count++;
  3579. }
  3580. first = first.nextSibling;
  3581. }
  3582. return count;
  3583. },
  3584. /**
  3585. * 判断给定节点是否为空节点
  3586. * @method isEmptyNode
  3587. * @param { Node } node 需要检测的节点对象
  3588. * @return { Boolean } 节点是否为空
  3589. * @example
  3590. * ```javascript
  3591. * UE.dom.domUtils.isEmptyNode( document.body );
  3592. * ```
  3593. */
  3594. isEmptyNode: function (node) {
  3595. return !node.firstChild || domUtils.getChildCount(node, function (node) {
  3596. return !domUtils.isBr(node) && !domUtils.isBookmarkNode(node) && !domUtils.isWhitespace(node)
  3597. }) == 0
  3598. },
  3599. clearSelectedArr: function (nodes) {
  3600. var node;
  3601. while (node = nodes.pop()) {
  3602. domUtils.removeAttributes(node, ['class']);
  3603. }
  3604. },
  3605. /**
  3606. * 将显示区域滚动到指定节点的位置
  3607. * @method scrollToView
  3608. * @param {Node} node 节点
  3609. * @param {window} win window对象
  3610. * @param {Number} offsetTop 距离上方的偏移量
  3611. */
  3612. scrollToView: function (node, win, offsetTop) {
  3613. var getViewPaneSize = function () {
  3614. var doc = win.document,
  3615. mode = doc.compatMode == 'CSS1Compat';
  3616. return {
  3617. width: (mode ? doc.documentElement.clientWidth : doc.body.clientWidth) || 0,
  3618. height: (mode ? doc.documentElement.clientHeight : doc.body.clientHeight) || 0
  3619. };
  3620. },
  3621. getScrollPosition = function (win) {
  3622. if ('pageXOffset' in win) {
  3623. return {
  3624. x: win.pageXOffset || 0,
  3625. y: win.pageYOffset || 0
  3626. };
  3627. }
  3628. else {
  3629. var doc = win.document;
  3630. return {
  3631. x: doc.documentElement.scrollLeft || doc.body.scrollLeft || 0,
  3632. y: doc.documentElement.scrollTop || doc.body.scrollTop || 0
  3633. };
  3634. }
  3635. };
  3636. var winHeight = getViewPaneSize().height, offset = winHeight * -1 + offsetTop;
  3637. offset += (node.offsetHeight || 0);
  3638. var elementPosition = domUtils.getXY(node);
  3639. offset += elementPosition.y;
  3640. var currentScroll = getScrollPosition(win).y;
  3641. // offset += 50;
  3642. if (offset > currentScroll || offset < currentScroll - winHeight) {
  3643. win.scrollTo(0, offset + (offset < 0 ? -20 : 20));
  3644. }
  3645. },
  3646. /**
  3647. * 判断给定节点是否为br
  3648. * @method isBr
  3649. * @param { Node } node 需要判断的节点对象
  3650. * @return { Boolean } 给定的节点是否是br节点
  3651. */
  3652. isBr: function (node) {
  3653. return node.nodeType == 1 && node.tagName == 'BR';
  3654. },
  3655. /**
  3656. * 判断给定的节点是否是一个“填充”节点
  3657. * @private
  3658. * @method isFillChar
  3659. * @param { Node } node 需要判断的节点
  3660. * @param { Boolean } isInStart 是否从节点内容的开始位置匹配
  3661. * @returns { Boolean } 节点是否是填充节点
  3662. */
  3663. isFillChar: function (node, isInStart) {
  3664. if (node.nodeType != 3)
  3665. return false;
  3666. var text = node.nodeValue;
  3667. if (isInStart) {
  3668. return new RegExp('^' + domUtils.fillChar).test(text)
  3669. }
  3670. return !text.replace(new RegExp(domUtils.fillChar, 'g'), '').length
  3671. },
  3672. isStartInblock: function (range) {
  3673. var tmpRange = range.cloneRange(),
  3674. flag = 0,
  3675. start = tmpRange.startContainer,
  3676. tmp;
  3677. if (start.nodeType == 1 && start.childNodes[tmpRange.startOffset]) {
  3678. start = start.childNodes[tmpRange.startOffset];
  3679. var pre = start.previousSibling;
  3680. while (pre && domUtils.isFillChar(pre)) {
  3681. start = pre;
  3682. pre = pre.previousSibling;
  3683. }
  3684. }
  3685. if (this.isFillChar(start, true) && tmpRange.startOffset == 1) {
  3686. tmpRange.setStartBefore(start);
  3687. start = tmpRange.startContainer;
  3688. }
  3689. while (start && domUtils.isFillChar(start)) {
  3690. tmp = start;
  3691. start = start.previousSibling
  3692. }
  3693. if (tmp) {
  3694. tmpRange.setStartBefore(tmp);
  3695. start = tmpRange.startContainer;
  3696. }
  3697. if (start.nodeType == 1 && domUtils.isEmptyNode(start) && tmpRange.startOffset == 1) {
  3698. tmpRange.setStart(start, 0).collapse(true);
  3699. }
  3700. while (!tmpRange.startOffset) {
  3701. start = tmpRange.startContainer;
  3702. if (domUtils.isBlockElm(start) || domUtils.isBody(start)) {
  3703. flag = 1;
  3704. break;
  3705. }
  3706. var pre = tmpRange.startContainer.previousSibling,
  3707. tmpNode;
  3708. if (!pre) {
  3709. tmpRange.setStartBefore(tmpRange.startContainer);
  3710. } else {
  3711. while (pre && domUtils.isFillChar(pre)) {
  3712. tmpNode = pre;
  3713. pre = pre.previousSibling;
  3714. }
  3715. if (tmpNode) {
  3716. tmpRange.setStartBefore(tmpNode);
  3717. } else {
  3718. tmpRange.setStartBefore(tmpRange.startContainer);
  3719. }
  3720. }
  3721. }
  3722. return flag && !domUtils.isBody(tmpRange.startContainer) ? 1 : 0;
  3723. },
  3724. /**
  3725. * 判断给定的元素是否是一个空元素
  3726. * @method isEmptyBlock
  3727. * @param { Element } node 需要判断的元素
  3728. * @return { Boolean } 是否是空元素
  3729. * @example
  3730. * ```html
  3731. * <div id="test"></div>
  3732. *
  3733. * <script>
  3734. * //output: true
  3735. * console.log( UE.dom.domUtils.isEmptyBlock( document.getElementById("test") ) );
  3736. * </script>
  3737. * ```
  3738. */
  3739. /**
  3740. * 根据指定的判断规则判断给定的元素是否是一个空元素
  3741. * @method isEmptyBlock
  3742. * @param { Element } node 需要判断的元素
  3743. * @param { RegExp } reg 对内容执行判断的正则表达式对象
  3744. * @return { Boolean } 是否是空元素
  3745. */
  3746. isEmptyBlock: function (node, reg) {
  3747. // HaoChuan9421
  3748. if (!node) {
  3749. return;
  3750. }
  3751. if (node.nodeType != 1)
  3752. return 0;
  3753. reg = reg || new RegExp('[ \xa0\t\r\n' + domUtils.fillChar + ']', 'g');
  3754. if (node[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').length > 0) {
  3755. return 0;
  3756. }
  3757. for (var n in dtd.$isNotEmpty) {
  3758. if (node.getElementsByTagName(n).length) {
  3759. return 0;
  3760. }
  3761. }
  3762. return 1;
  3763. },
  3764. /**
  3765. * 移动元素使得该元素的位置移动指定的偏移量的距离
  3766. * @method setViewportOffset
  3767. * @param { Element } element 需要设置偏移量的元素
  3768. * @param { Object } offset 偏移量, 形如{ left: 100, top: 50 }的一个键值对, 表示该元素将在
  3769. * 现有的位置上向水平方向偏移offset.left的距离, 在竖直方向上偏移
  3770. * offset.top的距离
  3771. * @example
  3772. * ```html
  3773. * <div id="test" style="top: 100px; left: 50px; position: absolute;"></div>
  3774. *
  3775. * <script>
  3776. *
  3777. * var testNode = document.getElementById("test");
  3778. *
  3779. * UE.dom.domUtils.setViewportOffset( testNode, {
  3780. * left: 200,
  3781. * top: 50
  3782. * } );
  3783. *
  3784. * //output: top: 300px; left: 100px; position: absolute;
  3785. * console.log( testNode.style.cssText );
  3786. *
  3787. * </script>
  3788. * ```
  3789. */
  3790. setViewportOffset: function (element, offset) {
  3791. var left = parseInt(element.style.left) | 0;
  3792. var top = parseInt(element.style.top) | 0;
  3793. var rect = element.getBoundingClientRect();
  3794. var offsetLeft = offset.left - rect.left;
  3795. var offsetTop = offset.top - rect.top;
  3796. if (offsetLeft) {
  3797. element.style.left = left + offsetLeft + 'px';
  3798. }
  3799. if (offsetTop) {
  3800. element.style.top = top + offsetTop + 'px';
  3801. }
  3802. },
  3803. /**
  3804. * 用“填充字符”填充节点
  3805. * @method fillNode
  3806. * @private
  3807. * @param { DomDocument } doc 填充的节点所在的docment对象
  3808. * @param { Node } node 需要填充的节点对象
  3809. * @example
  3810. * ```html
  3811. * <div id="test"></div>
  3812. *
  3813. * <script>
  3814. * var testNode = document.getElementById("test");
  3815. *
  3816. * //output: 0
  3817. * console.log( testNode.childNodes.length );
  3818. *
  3819. * UE.dom.domUtils.fillNode( document, testNode );
  3820. *
  3821. * //output: 1
  3822. * console.log( testNode.childNodes.length );
  3823. *
  3824. * </script>
  3825. * ```
  3826. */
  3827. fillNode: function (doc, node) {
  3828. var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br');
  3829. node.innerHTML = '';
  3830. node.appendChild(tmpNode);
  3831. },
  3832. /**
  3833. * 把节点src的所有子节点追加到另一个节点tag上去
  3834. * @method moveChild
  3835. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3836. * @param { Node } tag 目标节点, 从源节点移除的子节点将被追加到该节点下
  3837. * @example
  3838. * ```html
  3839. * <div id="test1">
  3840. * <span></span>
  3841. * </div>
  3842. * <div id="test2">
  3843. * <div></div>
  3844. * </div>
  3845. *
  3846. * <script>
  3847. *
  3848. * var test1 = document.getElementById("test1"),
  3849. * test2 = document.getElementById("test2");
  3850. *
  3851. * UE.dom.domUtils.moveChild( test1, test2 );
  3852. *
  3853. * //output: ""(空字符串)
  3854. * console.log( test1.innerHTML );
  3855. *
  3856. * //output: "<div></div><span></span>"
  3857. * console.log( test2.innerHTML );
  3858. *
  3859. * </script>
  3860. * ```
  3861. */
  3862. /**
  3863. * 把节点src的所有子节点移动到另一个节点tag上去, 可以通过dir参数控制附加的行为是“追加”还是“插入顶部”
  3864. * @method moveChild
  3865. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3866. * @param { Node } tag 目标节点, 从源节点移除的子节点将被附加到该节点下
  3867. * @param { Boolean } dir 附加方式, 如果为true, 则附加进去的节点将被放到目标节点的顶部, 反之,则放到末尾
  3868. * @example
  3869. * ```html
  3870. * <div id="test1">
  3871. * <span></span>
  3872. * </div>
  3873. * <div id="test2">
  3874. * <div></div>
  3875. * </div>
  3876. *
  3877. * <script>
  3878. *
  3879. * var test1 = document.getElementById("test1"),
  3880. * test2 = document.getElementById("test2");
  3881. *
  3882. * UE.dom.domUtils.moveChild( test1, test2, true );
  3883. *
  3884. * //output: ""(空字符串)
  3885. * console.log( test1.innerHTML );
  3886. *
  3887. * //output: "<span></span><div></div>"
  3888. * console.log( test2.innerHTML );
  3889. *
  3890. * </script>
  3891. * ```
  3892. */
  3893. moveChild: function (src, tag, dir) {
  3894. while (src.firstChild) {
  3895. if (dir && tag.firstChild) {
  3896. tag.insertBefore(src.lastChild, tag.firstChild);
  3897. } else {
  3898. tag.appendChild(src.firstChild);
  3899. }
  3900. }
  3901. },
  3902. /**
  3903. * 判断节点的标签上是否不存在任何属性
  3904. * @method hasNoAttributes
  3905. * @private
  3906. * @param { Node } node 需要检测的节点对象
  3907. * @return { Boolean } 节点是否不包含任何属性
  3908. * @example
  3909. * ```html
  3910. * <div id="test"><span>xxxx</span></div>
  3911. *
  3912. * <script>
  3913. *
  3914. * //output: false
  3915. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test") ) );
  3916. *
  3917. * //output: true
  3918. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test").firstChild ) );
  3919. *
  3920. * </script>
  3921. * ```
  3922. */
  3923. hasNoAttributes: function (node) {
  3924. return browser.ie ? /^<\w+\s*?>/.test(node.outerHTML) : node.attributes.length == 0;
  3925. },
  3926. /**
  3927. * 检测节点是否是UEditor所使用的辅助节点
  3928. * @method isCustomeNode
  3929. * @private
  3930. * @param { Node } node 需要检测的节点
  3931. * @remind 辅助节点是指编辑器要完成工作临时添加的节点, 在输出的时候将会从编辑器内移除, 不会影响最终的结果。
  3932. * @return { Boolean } 给定的节点是否是一个辅助节点
  3933. */
  3934. isCustomeNode: function (node) {
  3935. return node.nodeType == 1 && node.getAttribute('_ue_custom_node_');
  3936. },
  3937. /**
  3938. * 检测节点的标签是否是给定的标签
  3939. * @method isTagNode
  3940. * @param { Node } node 需要检测的节点对象
  3941. * @param { String } tagName 标签
  3942. * @return { Boolean } 节点的标签是否是给定的标签
  3943. * @example
  3944. * ```html
  3945. * <div id="test"></div>
  3946. *
  3947. * <script>
  3948. *
  3949. * //output: true
  3950. * console.log( UE.dom.domUtils.isTagNode( document.getElementById("test"), "div" ) );
  3951. *
  3952. * </script>
  3953. * ```
  3954. */
  3955. isTagNode: function (node, tagNames) {
  3956. return node.nodeType == 1 && new RegExp('\\b' + node.tagName + '\\b', 'i').test(tagNames)
  3957. },
  3958. /**
  3959. * 给定一个节点数组,在通过指定的过滤器过滤后, 获取其中满足过滤条件的第一个节点
  3960. * @method filterNodeList
  3961. * @param { Array } nodeList 需要过滤的节点数组
  3962. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3963. * @return { Node | NULL } 如果找到符合过滤条件的节点, 则返回该节点, 否则返回NULL
  3964. * @example
  3965. * ```javascript
  3966. * var divNodes = document.getElementsByTagName("div");
  3967. * divNodes = [].slice.call( divNodes, 0 );
  3968. *
  3969. * //output: null
  3970. * console.log( UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3971. * return node.tagName.toLowerCase() !== 'div';
  3972. * } ) );
  3973. * ```
  3974. */
  3975. /**
  3976. * 给定一个节点数组nodeList和一组标签名tagNames, 获取其中能够匹配标签名的节点集合中的第一个节点
  3977. * @method filterNodeList
  3978. * @param { Array } nodeList 需要过滤的节点数组
  3979. * @param { String } tagNames 需要匹配的标签名, 多个标签名之间用空格分割
  3980. * @return { Node | NULL } 如果找到标签名匹配的节点, 则返回该节点, 否则返回NULL
  3981. * @example
  3982. * ```javascript
  3983. * var divNodes = document.getElementsByTagName("div");
  3984. * divNodes = [].slice.call( divNodes, 0 );
  3985. *
  3986. * //output: null
  3987. * console.log( UE.dom.domUtils.filterNodeList( divNodes, 'a span' ) );
  3988. * ```
  3989. */
  3990. /**
  3991. * 给定一个节点数组,在通过指定的过滤器过滤后, 如果参数forAll为true, 则会返回所有满足过滤
  3992. * 条件的节点集合, 否则, 返回满足条件的节点集合中的第一个节点
  3993. * @method filterNodeList
  3994. * @param { Array } nodeList 需要过滤的节点数组
  3995. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3996. * @param { Boolean } forAll 是否返回整个节点数组, 如果该参数为false, 则返回节点集合中的第一个节点
  3997. * @return { Array | Node | NULL } 如果找到符合过滤条件的节点, 则根据参数forAll的值决定返回满足
  3998. * 过滤条件的节点数组或第一个节点, 否则返回NULL
  3999. * @example
  4000. * ```javascript
  4001. * var divNodes = document.getElementsByTagName("div");
  4002. * divNodes = [].slice.call( divNodes, 0 );
  4003. *
  4004. * //output: 3(假定有3个div)
  4005. * console.log( divNodes.length );
  4006. *
  4007. * var nodes = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  4008. * return node.tagName.toLowerCase() === 'div';
  4009. * }, true );
  4010. *
  4011. * //output: 3
  4012. * console.log( nodes.length );
  4013. *
  4014. * var node = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  4015. * return node.tagName.toLowerCase() === 'div';
  4016. * }, false );
  4017. *
  4018. * //output: div
  4019. * console.log( node.nodeName );
  4020. * ```
  4021. */
  4022. filterNodeList: function (nodelist, filter, forAll) {
  4023. var results = [];
  4024. if (!utils.isFunction(filter)) {
  4025. var str = filter;
  4026. filter = function (n) {
  4027. return utils.indexOf(utils.isArray(str) ? str : str.split(' '), n.tagName.toLowerCase()) != -1
  4028. };
  4029. }
  4030. utils.each(nodelist, function (n) {
  4031. filter(n) && results.push(n)
  4032. });
  4033. return results.length == 0 ? null : results.length == 1 || !forAll ? results[0] : results
  4034. },
  4035. /**
  4036. * 查询给定的range选区是否在给定的node节点内,且在该节点的最末尾
  4037. * @method isInNodeEndBoundary
  4038. * @param { UE.dom.Range } rng 需要判断的range对象, 该对象的startContainer不能为NULL
  4039. * @param node 需要检测的节点对象
  4040. * @return { Number } 如果给定的选取range对象是在node内部的最末端, 则返回1, 否则返回0
  4041. */
  4042. isInNodeEndBoundary: function (rng, node) {
  4043. var start = rng.startContainer;
  4044. if (start.nodeType == 3 && rng.startOffset != start.nodeValue.length) {
  4045. return 0;
  4046. }
  4047. if (start.nodeType == 1 && rng.startOffset != start.childNodes.length) {
  4048. return 0;
  4049. }
  4050. while (start !== node) {
  4051. if (start.nextSibling) {
  4052. return 0
  4053. };
  4054. start = start.parentNode;
  4055. }
  4056. return 1;
  4057. },
  4058. isBoundaryNode: function (node, dir) {
  4059. var tmp;
  4060. while (!domUtils.isBody(node)) {
  4061. tmp = node;
  4062. node = node.parentNode;
  4063. if (tmp !== node[dir]) {
  4064. return false;
  4065. }
  4066. }
  4067. return true;
  4068. },
  4069. fillHtml: browser.ie11below ? '&nbsp;' : '<br/>'
  4070. };
  4071. var fillCharReg = new RegExp(domUtils.fillChar, 'g');
  4072. // core/Range.js
  4073. /**
  4074. * Range封装
  4075. * @file
  4076. * @module UE.dom
  4077. * @class Range
  4078. * @since 1.2.6.1
  4079. */
  4080. /**
  4081. * dom操作封装
  4082. * @unfile
  4083. * @module UE.dom
  4084. */
  4085. /**
  4086. * Range实现类,本类是UEditor底层核心类,封装不同浏览器之间的Range操作。
  4087. * @unfile
  4088. * @module UE.dom
  4089. * @class Range
  4090. */
  4091. (function () {
  4092. var guid = 0,
  4093. fillChar = domUtils.fillChar,
  4094. fillData;
  4095. /**
  4096. * 更新range的collapse状态
  4097. * @param {Range} range range对象
  4098. */
  4099. function updateCollapse(range) {
  4100. range.collapsed =
  4101. range.startContainer && range.endContainer &&
  4102. range.startContainer === range.endContainer &&
  4103. range.startOffset == range.endOffset;
  4104. }
  4105. function selectOneNode(rng) {
  4106. return !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1
  4107. }
  4108. function setEndPoint(toStart, node, offset, range) {
  4109. //如果node是自闭合标签要处理
  4110. if (node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) {
  4111. offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1);
  4112. node = node.parentNode;
  4113. }
  4114. if (toStart) {
  4115. range.startContainer = node;
  4116. range.startOffset = offset;
  4117. if (!range.endContainer) {
  4118. range.collapse(true);
  4119. }
  4120. } else {
  4121. range.endContainer = node;
  4122. range.endOffset = offset;
  4123. if (!range.startContainer) {
  4124. range.collapse(false);
  4125. }
  4126. }
  4127. updateCollapse(range);
  4128. return range;
  4129. }
  4130. function execContentsAction(range, action) {
  4131. //调整边界
  4132. //range.includeBookmark();
  4133. var start = range.startContainer,
  4134. end = range.endContainer,
  4135. startOffset = range.startOffset,
  4136. endOffset = range.endOffset,
  4137. doc = range.document,
  4138. frag = doc.createDocumentFragment(),
  4139. tmpStart, tmpEnd;
  4140. if (start.nodeType == 1) {
  4141. start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode('')));
  4142. }
  4143. if (end.nodeType == 1) {
  4144. end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode('')));
  4145. }
  4146. if (start === end && start.nodeType == 3) {
  4147. frag.appendChild(doc.createTextNode(start.substringData(startOffset, endOffset - startOffset)));
  4148. //is not clone
  4149. if (action) {
  4150. start.deleteData(startOffset, endOffset - startOffset);
  4151. range.collapse(true);
  4152. }
  4153. return frag;
  4154. }
  4155. var current, currentLevel, clone = frag,
  4156. startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true);
  4157. for (var i = 0; startParents[i] == endParents[i];) {
  4158. i++;
  4159. }
  4160. for (var j = i, si; si = startParents[j]; j++) {
  4161. current = si.nextSibling;
  4162. if (si == start) {
  4163. if (!tmpStart) {
  4164. if (range.startContainer.nodeType == 3) {
  4165. clone.appendChild(doc.createTextNode(start.nodeValue.slice(startOffset)));
  4166. //is not clone
  4167. if (action) {
  4168. start.deleteData(startOffset, start.nodeValue.length - startOffset);
  4169. }
  4170. } else {
  4171. clone.appendChild(!action ? start.cloneNode(true) : start);
  4172. }
  4173. }
  4174. } else {
  4175. currentLevel = si.cloneNode(false);
  4176. clone.appendChild(currentLevel);
  4177. }
  4178. while (current) {
  4179. if (current === end || current === endParents[j]) {
  4180. break;
  4181. }
  4182. si = current.nextSibling;
  4183. clone.appendChild(!action ? current.cloneNode(true) : current);
  4184. current = si;
  4185. }
  4186. clone = currentLevel;
  4187. }
  4188. clone = frag;
  4189. if (!startParents[i]) {
  4190. clone.appendChild(startParents[i - 1].cloneNode(false));
  4191. clone = clone.firstChild;
  4192. }
  4193. for (var j = i, ei; ei = endParents[j]; j++) {
  4194. current = ei.previousSibling;
  4195. if (ei == end) {
  4196. if (!tmpEnd && range.endContainer.nodeType == 3) {
  4197. clone.appendChild(doc.createTextNode(end.substringData(0, endOffset)));
  4198. //is not clone
  4199. if (action) {
  4200. end.deleteData(0, endOffset);
  4201. }
  4202. }
  4203. } else {
  4204. currentLevel = ei.cloneNode(false);
  4205. clone.appendChild(currentLevel);
  4206. }
  4207. //如果两端同级,右边第一次已经被开始做了
  4208. if (j != i || !startParents[i]) {
  4209. while (current) {
  4210. if (current === start) {
  4211. break;
  4212. }
  4213. ei = current.previousSibling;
  4214. clone.insertBefore(!action ? current.cloneNode(true) : current, clone.firstChild);
  4215. current = ei;
  4216. }
  4217. }
  4218. clone = currentLevel;
  4219. }
  4220. if (action) {
  4221. range.setStartBefore(!endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i]).collapse(true);
  4222. }
  4223. tmpStart && domUtils.remove(tmpStart);
  4224. tmpEnd && domUtils.remove(tmpEnd);
  4225. return frag;
  4226. }
  4227. /**
  4228. * 创建一个跟document绑定的空的Range实例
  4229. * @constructor
  4230. * @param { Document } document 新建的选区所属的文档对象
  4231. */
  4232. /**
  4233. * @property { Node } startContainer 当前Range的开始边界的容器节点, 可以是一个元素节点或者是文本节点
  4234. */
  4235. /**
  4236. * @property { Node } startOffset 当前Range的开始边界容器节点的偏移量, 如果是元素节点,
  4237. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4238. */
  4239. /**
  4240. * @property { Node } endContainer 当前Range的结束边界的容器节点, 可以是一个元素节点或者是文本节点
  4241. */
  4242. /**
  4243. * @property { Node } endOffset 当前Range的结束边界容器节点的偏移量, 如果是元素节点,
  4244. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4245. */
  4246. /**
  4247. * @property { Boolean } collapsed 当前Range是否闭合
  4248. * @default true
  4249. * @remind Range是闭合的时候, startContainer === endContainer && startOffset === endOffset
  4250. */
  4251. /**
  4252. * @property { Document } document 当前Range所属的Document对象
  4253. * @remind 不同range的的document属性可以是不同的
  4254. */
  4255. var Range = dom.Range = function (document) {
  4256. var me = this;
  4257. me.startContainer =
  4258. me.startOffset =
  4259. me.endContainer =
  4260. me.endOffset = null;
  4261. me.document = document;
  4262. me.collapsed = true;
  4263. };
  4264. /**
  4265. * 删除fillData
  4266. * @param doc
  4267. * @param excludeNode
  4268. */
  4269. function removeFillData(doc, excludeNode) {
  4270. try {
  4271. if (fillData && domUtils.inDoc(fillData, doc)) {
  4272. if (!fillData.nodeValue.replace(fillCharReg, '').length) {
  4273. var tmpNode = fillData.parentNode;
  4274. domUtils.remove(fillData);
  4275. while (tmpNode && domUtils.isEmptyInlineElement(tmpNode) &&
  4276. //safari的contains有bug
  4277. (browser.safari ? !(domUtils.getPosition(tmpNode, excludeNode) & domUtils.POSITION_CONTAINS) : !tmpNode.contains(excludeNode))
  4278. ) {
  4279. fillData = tmpNode.parentNode;
  4280. domUtils.remove(tmpNode);
  4281. tmpNode = fillData;
  4282. }
  4283. } else {
  4284. fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, '');
  4285. }
  4286. }
  4287. } catch (e) {
  4288. }
  4289. }
  4290. /**
  4291. * @param node
  4292. * @param dir
  4293. */
  4294. function mergeSibling(node, dir) {
  4295. var tmpNode;
  4296. node = node[dir];
  4297. while (node && domUtils.isFillChar(node)) {
  4298. tmpNode = node[dir];
  4299. domUtils.remove(node);
  4300. node = tmpNode;
  4301. }
  4302. }
  4303. Range.prototype = {
  4304. /**
  4305. * 克隆选区的内容到一个DocumentFragment里
  4306. * @method cloneContents
  4307. * @return { DocumentFragment | NULL } 如果选区是闭合的将返回null, 否则, 返回包含所clone内容的DocumentFragment元素
  4308. * @example
  4309. * ```html
  4310. * <body>
  4311. * <!-- 中括号表示选区 -->
  4312. * <b>x<i>x[x</i>xx]x</b>
  4313. *
  4314. * <script>
  4315. * //range是已选中的选区
  4316. * var fragment = range.cloneContents(),
  4317. * node = document.createElement("div");
  4318. *
  4319. * node.appendChild( fragment );
  4320. *
  4321. * //output: <i>x</i>xx
  4322. * console.log( node.innerHTML );
  4323. *
  4324. * </script>
  4325. * </body>
  4326. * ```
  4327. */
  4328. cloneContents: function () {
  4329. return this.collapsed ? null : execContentsAction(this, 0);
  4330. },
  4331. /**
  4332. * 删除当前选区范围中的所有内容
  4333. * @method deleteContents
  4334. * @remind 执行完该操作后, 当前Range对象变成了闭合状态
  4335. * @return { UE.dom.Range } 当前操作的Range对象
  4336. * @example
  4337. * ```html
  4338. * <body>
  4339. * <!-- 中括号表示选区 -->
  4340. * <b>x<i>x[x</i>xx]x</b>
  4341. *
  4342. * <script>
  4343. * //range是已选中的选区
  4344. * range.deleteContents();
  4345. *
  4346. * //竖线表示闭合后的选区位置
  4347. * //output: <b>x<i>x</i>|x</b>
  4348. * console.log( document.body.innerHTML );
  4349. *
  4350. * //此时, range的各项属性为
  4351. * //output: B
  4352. * console.log( range.startContainer.tagName );
  4353. * //output: 2
  4354. * console.log( range.startOffset );
  4355. * //output: B
  4356. * console.log( range.endContainer.tagName );
  4357. * //output: 2
  4358. * console.log( range.endOffset );
  4359. * //output: true
  4360. * console.log( range.collapsed );
  4361. *
  4362. * </script>
  4363. * </body>
  4364. * ```
  4365. */
  4366. deleteContents: function () {
  4367. var txt;
  4368. if (!this.collapsed) {
  4369. execContentsAction(this, 1);
  4370. }
  4371. if (browser.webkit) {
  4372. txt = this.startContainer;
  4373. if (txt.nodeType == 3 && !txt.nodeValue.length) {
  4374. this.setStartBefore(txt).collapse(true);
  4375. domUtils.remove(txt);
  4376. }
  4377. }
  4378. return this;
  4379. },
  4380. /**
  4381. * 将当前选区的内容提取到一个DocumentFragment里
  4382. * @method extractContents
  4383. * @remind 执行该操作后, 选区将变成闭合状态
  4384. * @warning 执行该操作后, 原来选区所选中的内容将从dom树上剥离出来
  4385. * @return { DocumentFragment } 返回包含所提取内容的DocumentFragment对象
  4386. * @example
  4387. * ```html
  4388. * <body>
  4389. * <!-- 中括号表示选区 -->
  4390. * <b>x<i>x[x</i>xx]x</b>
  4391. *
  4392. * <script>
  4393. * //range是已选中的选区
  4394. * var fragment = range.extractContents(),
  4395. * node = document.createElement( "div" );
  4396. *
  4397. * node.appendChild( fragment );
  4398. *
  4399. * //竖线表示闭合后的选区位置
  4400. *
  4401. * //output: <b>x<i>x</i>|x</b>
  4402. * console.log( document.body.innerHTML );
  4403. * //output: <i>x</i>xx
  4404. * console.log( node.innerHTML );
  4405. *
  4406. * //此时, range的各项属性为
  4407. * //output: B
  4408. * console.log( range.startContainer.tagName );
  4409. * //output: 2
  4410. * console.log( range.startOffset );
  4411. * //output: B
  4412. * console.log( range.endContainer.tagName );
  4413. * //output: 2
  4414. * console.log( range.endOffset );
  4415. * //output: true
  4416. * console.log( range.collapsed );
  4417. *
  4418. * </script>
  4419. * </body>
  4420. */
  4421. extractContents: function () {
  4422. return this.collapsed ? null : execContentsAction(this, 2);
  4423. },
  4424. /**
  4425. * 设置Range的开始容器节点和偏移量
  4426. * @method setStart
  4427. * @remind 如果给定的节点是元素节点,那么offset指的是其子元素中索引为offset的元素,
  4428. * 如果是文本节点,那么offset指的是其文本内容的第offset个字符
  4429. * @remind 如果提供的容器节点是一个不能包含子元素的节点, 则该选区的开始容器将被设置
  4430. * 为该节点的父节点, 此时, 其距离开始容器的偏移量也变成了该节点在其父节点
  4431. * 中的索引
  4432. * @param { Node } node 将被设为当前选区开始边界容器的节点对象
  4433. * @param { int } offset 选区的开始位置偏移量
  4434. * @return { UE.dom.Range } 当前range对象
  4435. * @example
  4436. * ```html
  4437. * <!-- 选区 -->
  4438. * <b>xxx<i>x<span>xx</span>xx<em>xx</em>xxx</i>[xxx]</b>
  4439. *
  4440. * <script>
  4441. *
  4442. * //执行操作
  4443. * range.setStart( document.getElementsByTagName("i")[0], 1 );
  4444. *
  4445. * //此时, 选区变成了
  4446. * //<b>xxx<i>x[<span>xx</span>xx<em>xx</em>xxx</i>xxx]</b>
  4447. *
  4448. * </script>
  4449. * ```
  4450. * @example
  4451. * ```html
  4452. * <!-- 选区 -->
  4453. * <b>xxx<img>[xx]x</b>
  4454. *
  4455. * <script>
  4456. *
  4457. * //执行操作
  4458. * range.setStart( document.getElementsByTagName("img")[0], 3 );
  4459. *
  4460. * //此时, 选区变成了
  4461. * //<b>xxx[<img>xx]x</b>
  4462. *
  4463. * </script>
  4464. * ```
  4465. */
  4466. setStart: function (node, offset) {
  4467. return setEndPoint(true, node, offset, this);
  4468. },
  4469. /**
  4470. * 设置Range的结束容器和偏移量
  4471. * @method setEnd
  4472. * @param { Node } node 作为当前选区结束边界容器的节点对象
  4473. * @param { int } offset 结束边界的偏移量
  4474. * @see UE.dom.Range:setStart(Node,int)
  4475. * @return { UE.dom.Range } 当前range对象
  4476. */
  4477. setEnd: function (node, offset) {
  4478. return setEndPoint(false, node, offset, this);
  4479. },
  4480. /**
  4481. * 将Range开始位置设置到node节点之后
  4482. * @method setStartAfter
  4483. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引+1
  4484. * @param { Node } node 选区的开始边界将紧接着该节点之后
  4485. * @return { UE.dom.Range } 当前range对象
  4486. * @example
  4487. * ```html
  4488. * <!-- 选区示例 -->
  4489. * <b>xx<i>xxx</i><span>xx[x</span>xxx]</b>
  4490. *
  4491. * <script>
  4492. *
  4493. * //执行操作
  4494. * range.setStartAfter( document.getElementsByTagName("i")[0] );
  4495. *
  4496. * //结果选区
  4497. * //<b>xx<i>xxx</i>[<span>xxx</span>xxx]</b>
  4498. *
  4499. * </script>
  4500. * ```
  4501. */
  4502. setStartAfter: function (node) {
  4503. return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4504. },
  4505. /**
  4506. * 将Range开始位置设置到node节点之前
  4507. * @method setStartBefore
  4508. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引
  4509. * @param { Node } node 新的选区开始位置在该节点之前
  4510. * @see UE.dom.Range:setStartAfter(Node)
  4511. * @return { UE.dom.Range } 当前range对象
  4512. */
  4513. setStartBefore: function (node) {
  4514. return this.setStart(node.parentNode, domUtils.getNodeIndex(node));
  4515. },
  4516. /**
  4517. * 将Range结束位置设置到node节点之后
  4518. * @method setEndAfter
  4519. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引+1
  4520. * @param { Node } node 目标节点
  4521. * @see UE.dom.Range:setStartAfter(Node)
  4522. * @return { UE.dom.Range } 当前range对象
  4523. * @example
  4524. * ```html
  4525. * <!-- 选区示例 -->
  4526. * <b>[xx<i>xxx</i><span>xx]x</span>xxx</b>
  4527. *
  4528. * <script>
  4529. *
  4530. * //执行操作
  4531. * range.setStartAfter( document.getElementsByTagName("span")[0] );
  4532. *
  4533. * //结果选区
  4534. * //<b>[xx<i>xxx</i><span>xxx</span>]xxx</b>
  4535. *
  4536. * </script>
  4537. * ```
  4538. */
  4539. setEndAfter: function (node) {
  4540. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4541. },
  4542. /**
  4543. * 将Range结束位置设置到node节点之前
  4544. * @method setEndBefore
  4545. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引
  4546. * @param { Node } node 目标节点
  4547. * @see UE.dom.Range:setEndAfter(Node)
  4548. * @return { UE.dom.Range } 当前range对象
  4549. */
  4550. setEndBefore: function (node) {
  4551. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node));
  4552. },
  4553. /**
  4554. * 设置Range的开始位置到node节点内的第一个子节点之前
  4555. * @method setStartAtFirst
  4556. * @remind 选区的开始容器将变成给定的节点, 且偏移量为0
  4557. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4558. * @param { Node } node 目标节点
  4559. * @see UE.dom.Range:setStartBefore(Node)
  4560. * @return { UE.dom.Range } 当前range对象
  4561. * @example
  4562. * ```html
  4563. * <!-- 选区示例 -->
  4564. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4565. *
  4566. * <script>
  4567. *
  4568. * //执行操作
  4569. * range.setStartAtFirst( document.getElementsByTagName("i")[0] );
  4570. *
  4571. * //结果选区
  4572. * //<b>xx<i>[xxx</i><span>xx]x</span>xxx</b>
  4573. *
  4574. * </script>
  4575. * ```
  4576. */
  4577. setStartAtFirst: function (node) {
  4578. return this.setStart(node, 0);
  4579. },
  4580. /**
  4581. * 设置Range的开始位置到node节点内的最后一个节点之后
  4582. * @method setStartAtLast
  4583. * @remind 选区的开始容器将变成给定的节点, 且偏移量为该节点的子节点数
  4584. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4585. * @param { Node } node 目标节点
  4586. * @see UE.dom.Range:setStartAtFirst(Node)
  4587. * @return { UE.dom.Range } 当前range对象
  4588. */
  4589. setStartAtLast: function (node) {
  4590. return this.setStart(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4591. },
  4592. /**
  4593. * 设置Range的结束位置到node节点内的第一个节点之前
  4594. * @method setEndAtFirst
  4595. * @param { Node } node 目标节点
  4596. * @remind 选区的结束容器将变成给定的节点, 且偏移量为0
  4597. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4598. * @see UE.dom.Range:setStartAtFirst(Node)
  4599. * @return { UE.dom.Range } 当前range对象
  4600. */
  4601. setEndAtFirst: function (node) {
  4602. return this.setEnd(node, 0);
  4603. },
  4604. /**
  4605. * 设置Range的结束位置到node节点内的最后一个节点之后
  4606. * @method setEndAtLast
  4607. * @param { Node } node 目标节点
  4608. * @remind 选区的结束容器将变成给定的节点, 且偏移量为该节点的子节点数量
  4609. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4610. * @see UE.dom.Range:setStartAtFirst(Node)
  4611. * @return { UE.dom.Range } 当前range对象
  4612. */
  4613. setEndAtLast: function (node) {
  4614. return this.setEnd(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4615. },
  4616. /**
  4617. * 选中给定节点
  4618. * @method selectNode
  4619. * @remind 此时, 选区的开始容器和结束容器都是该节点的父节点, 其startOffset是该节点在父节点中的位置索引,
  4620. * 而endOffset为startOffset+1
  4621. * @param { Node } node 需要选中的节点
  4622. * @return { UE.dom.Range } 当前range对象,此时的range仅包含当前给定的节点对象
  4623. * @example
  4624. * ```html
  4625. * <!-- 选区示例 -->
  4626. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4627. *
  4628. * <script>
  4629. *
  4630. * //执行操作
  4631. * range.selectNode( document.getElementsByTagName("i")[0] );
  4632. *
  4633. * //结果选区
  4634. * //<b>xx[<i>xxx</i>]<span>xxx</span>xxx</b>
  4635. *
  4636. * </script>
  4637. * ```
  4638. */
  4639. selectNode: function (node) {
  4640. return this.setStartBefore(node).setEndAfter(node);
  4641. },
  4642. /**
  4643. * 选中给定节点内部的所有节点
  4644. * @method selectNodeContents
  4645. * @remind 此时, 选区的开始容器和结束容器都是该节点, 其startOffset为0,
  4646. * 而endOffset是该节点的子节点数。
  4647. * @param { Node } node 目标节点, 当前range将包含该节点内的所有节点
  4648. * @return { UE.dom.Range } 当前range对象, 此时range仅包含给定节点的所有子节点
  4649. * @example
  4650. * ```html
  4651. * <!-- 选区示例 -->
  4652. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4653. *
  4654. * <script>
  4655. *
  4656. * //执行操作
  4657. * range.selectNode( document.getElementsByTagName("b")[0] );
  4658. *
  4659. * //结果选区
  4660. * //<b>[xx<i>xxx</i><span>xxx</span>xxx]</b>
  4661. *
  4662. * </script>
  4663. * ```
  4664. */
  4665. selectNodeContents: function (node) {
  4666. return this.setStart(node, 0).setEndAtLast(node);
  4667. },
  4668. /**
  4669. * clone当前Range对象
  4670. * @method cloneRange
  4671. * @remind 返回的range是一个全新的range对象, 其内部所有属性与当前被clone的range相同。
  4672. * @return { UE.dom.Range } 当前range对象的一个副本
  4673. */
  4674. cloneRange: function () {
  4675. var me = this;
  4676. return new Range(me.document).setStart(me.startContainer, me.startOffset).setEnd(me.endContainer, me.endOffset);
  4677. },
  4678. /**
  4679. * 向当前选区的结束处闭合选区
  4680. * @method collapse
  4681. * @return { UE.dom.Range } 当前range对象
  4682. * @example
  4683. * ```html
  4684. * <!-- 选区示例 -->
  4685. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4686. *
  4687. * <script>
  4688. *
  4689. * //执行操作
  4690. * range.collapse();
  4691. *
  4692. * //结果选区
  4693. * //“|”表示选区已闭合
  4694. * //<b>xx<i>xxx</i><span>xx|x</span>xxx</b>
  4695. *
  4696. * </script>
  4697. * ```
  4698. */
  4699. /**
  4700. * 闭合当前选区,根据给定的toStart参数项决定是向当前选区开始处闭合还是向结束处闭合,
  4701. * 如果toStart的值为true,则向开始位置闭合, 反之,向结束位置闭合。
  4702. * @method collapse
  4703. * @param { Boolean } toStart 是否向选区开始处闭合
  4704. * @return { UE.dom.Range } 当前range对象,此时range对象处于闭合状态
  4705. * @see UE.dom.Range:collapse()
  4706. * @example
  4707. * ```html
  4708. * <!-- 选区示例 -->
  4709. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4710. *
  4711. * <script>
  4712. *
  4713. * //执行操作
  4714. * range.collapse( true );
  4715. *
  4716. * //结果选区
  4717. * //“|”表示选区已闭合
  4718. * //<b>xx<i>xxx</i><span>|xxx</span>xxx</b>
  4719. *
  4720. * </script>
  4721. * ```
  4722. */
  4723. collapse: function (toStart) {
  4724. var me = this;
  4725. if (toStart) {
  4726. me.endContainer = me.startContainer;
  4727. me.endOffset = me.startOffset;
  4728. } else {
  4729. me.startContainer = me.endContainer;
  4730. me.startOffset = me.endOffset;
  4731. }
  4732. me.collapsed = true;
  4733. return me;
  4734. },
  4735. /**
  4736. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置
  4737. * @method shrinkBoundary
  4738. * @return { UE.dom.Range } 当前range对象
  4739. * @example
  4740. * ```html
  4741. * <span>xx<b>xx[</b>xxxxx]</span> => <span>xx<b>xx</b>[xxxxx]</span>
  4742. * ```
  4743. *
  4744. * @example
  4745. * ```html
  4746. * <!-- 选区示例 -->
  4747. * <b>x[xx</b><i>]xxx</i>
  4748. *
  4749. * <script>
  4750. *
  4751. * //执行收缩
  4752. * range.shrinkBoundary();
  4753. *
  4754. * //结果选区
  4755. * //<b>x[xx]</b><i>xxx</i>
  4756. * </script>
  4757. * ```
  4758. *
  4759. * @example
  4760. * ```html
  4761. * [<b><i>xxxx</i>xxxxxxx</b>] => <b><i>[xxxx</i>xxxxxxx]</b>
  4762. * ```
  4763. */
  4764. /**
  4765. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置,
  4766. * 如果ignoreEnd的值为true,则忽略对结束位置的调整
  4767. * @method shrinkBoundary
  4768. * @param { Boolean } ignoreEnd 是否忽略对结束位置的调整
  4769. * @return { UE.dom.Range } 当前range对象
  4770. * @see UE.dom.domUtils.Range:shrinkBoundary()
  4771. */
  4772. shrinkBoundary: function (ignoreEnd) {
  4773. var me = this, child,
  4774. collapsed = me.collapsed;
  4775. function check(node) {
  4776. return node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName]
  4777. }
  4778. while (me.startContainer.nodeType == 1 //是element
  4779. && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element
  4780. && check(child)) {
  4781. me.setStart(child, 0);
  4782. }
  4783. if (collapsed) {
  4784. return me.collapse(true);
  4785. }
  4786. if (!ignoreEnd) {
  4787. while (me.endContainer.nodeType == 1//是element
  4788. && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错
  4789. && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element
  4790. && check(child)) {
  4791. me.setEnd(child, child.childNodes.length);
  4792. }
  4793. }
  4794. return me;
  4795. },
  4796. /**
  4797. * 获取离当前选区内包含的所有节点最近的公共祖先节点,
  4798. * @method getCommonAncestor
  4799. * @remind 返回的公共祖先节点一定不是range自身的容器节点, 但有可能是一个文本节点
  4800. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4801. * @example
  4802. * ```html
  4803. * //选区示例
  4804. * <span>xxx<b>x[x<em>xx]x</em>xxx</b>xx</span>
  4805. * <script>
  4806. *
  4807. * var node = range.getCommonAncestor();
  4808. *
  4809. * //公共祖先节点是: b节点
  4810. * //输出: B
  4811. * console.log(node.tagName);
  4812. *
  4813. * </script>
  4814. * ```
  4815. */
  4816. /**
  4817. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4818. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4819. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点
  4820. * @method getCommonAncestor
  4821. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4822. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4823. * @see UE.dom.Range:getCommonAncestor()
  4824. * @example
  4825. * ```html
  4826. * <body>
  4827. *
  4828. * <!-- 选区示例 -->
  4829. * <b>xxx<i>xxxx<span>xx[x</span>xx]x</i>xxxxxxx</b>
  4830. *
  4831. * <script>
  4832. *
  4833. * var node = range.getCommonAncestor( false );
  4834. *
  4835. * //这里的公共祖先节点是B而不是I, 是因为参数限制了获取到的节点不能是容器节点
  4836. * //output: B
  4837. * console.log( node.tagName );
  4838. *
  4839. * </script>
  4840. *
  4841. * </body>
  4842. * ```
  4843. */
  4844. /**
  4845. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4846. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4847. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点; 同时可以根据
  4848. * ignoreTextNode 参数的取值决定是否忽略类型为文本节点的祖先节点。
  4849. * @method getCommonAncestor
  4850. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4851. * @param { Boolean } ignoreTextNode 获取祖先节点的过程中是否忽略类型为文本节点的祖先节点
  4852. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4853. * @see UE.dom.Range:getCommonAncestor()
  4854. * @see UE.dom.Range:getCommonAncestor(Boolean)
  4855. * @example
  4856. * ```html
  4857. * <body>
  4858. *
  4859. * <!-- 选区示例 -->
  4860. * <b>xxx<i>xxxx<span>x[x]x</span>xxx</i>xxxxxxx</b>
  4861. *
  4862. * <script>
  4863. *
  4864. * var node = range.getCommonAncestor( true, false );
  4865. *
  4866. * //output: SPAN
  4867. * console.log( node.tagName );
  4868. *
  4869. * </script>
  4870. *
  4871. * </body>
  4872. * ```
  4873. */
  4874. getCommonAncestor: function (includeSelf, ignoreTextNode) {
  4875. var me = this,
  4876. start = me.startContainer,
  4877. end = me.endContainer;
  4878. if (start === end) {
  4879. if (includeSelf && selectOneNode(this)) {
  4880. start = start.childNodes[me.startOffset];
  4881. if (start.nodeType == 1)
  4882. return start;
  4883. }
  4884. //只有在上来就相等的情况下才会出现是文本的情况
  4885. return ignoreTextNode && start.nodeType == 3 ? start.parentNode : start;
  4886. }
  4887. return domUtils.getCommonAncestor(start, end);
  4888. },
  4889. /**
  4890. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上
  4891. * @method trimBoundary
  4892. * @remind 该操作有可能会引起文本节点被切开
  4893. * @return { UE.dom.Range } 当前range对象
  4894. * @example
  4895. * ```html
  4896. *
  4897. * //选区示例
  4898. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4899. *
  4900. * <script>
  4901. * //未调整前, 选区的开始容器和结束都是文本节点
  4902. * //执行调整
  4903. * range.trimBoundary();
  4904. *
  4905. * //调整之后, 容器节点变成了i节点
  4906. * //<b>xxx[<i>xxxxx</i>]xxx</b>
  4907. * </script>
  4908. * ```
  4909. */
  4910. /**
  4911. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上,
  4912. * 可以根据 ignoreEnd 参数的值决定是否调整对结束边界的调整
  4913. * @method trimBoundary
  4914. * @param { Boolean } ignoreEnd 是否忽略对结束边界的调整
  4915. * @return { UE.dom.Range } 当前range对象
  4916. * @example
  4917. * ```html
  4918. *
  4919. * //选区示例
  4920. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4921. *
  4922. * <script>
  4923. * //未调整前, 选区的开始容器和结束都是文本节点
  4924. * //执行调整
  4925. * range.trimBoundary( true );
  4926. *
  4927. * //调整之后, 开始容器节点变成了i节点
  4928. * //但是, 结束容器没有发生变化
  4929. * //<b>xxx[<i>xxxxx]</i>xxx</b>
  4930. * </script>
  4931. * ```
  4932. */
  4933. trimBoundary: function (ignoreEnd) {
  4934. this.txtToElmBoundary();
  4935. var start = this.startContainer,
  4936. offset = this.startOffset,
  4937. collapsed = this.collapsed,
  4938. end = this.endContainer;
  4939. if (start.nodeType == 3) {
  4940. if (offset == 0) {
  4941. this.setStartBefore(start);
  4942. } else {
  4943. if (offset >= start.nodeValue.length) {
  4944. this.setStartAfter(start);
  4945. } else {
  4946. var textNode = domUtils.split(start, offset);
  4947. //跟新结束边界
  4948. if (start === end) {
  4949. this.setEnd(textNode, this.endOffset - offset);
  4950. } else if (start.parentNode === end) {
  4951. this.endOffset += 1;
  4952. }
  4953. this.setStartBefore(textNode);
  4954. }
  4955. }
  4956. if (collapsed) {
  4957. return this.collapse(true);
  4958. }
  4959. }
  4960. if (!ignoreEnd) {
  4961. offset = this.endOffset;
  4962. end = this.endContainer;
  4963. if (end.nodeType == 3) {
  4964. if (offset == 0) {
  4965. this.setEndBefore(end);
  4966. } else {
  4967. offset < end.nodeValue.length && domUtils.split(end, offset);
  4968. this.setEndAfter(end);
  4969. }
  4970. }
  4971. }
  4972. return this;
  4973. },
  4974. /**
  4975. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则什么也不做
  4976. * @method txtToElmBoundary
  4977. * @remind 该操作不会修改dom节点
  4978. * @return { UE.dom.Range } 当前range对象
  4979. */
  4980. /**
  4981. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则根据参数项
  4982. * ignoreCollapsed 的值决定是否执行该调整
  4983. * @method txtToElmBoundary
  4984. * @param { Boolean } ignoreCollapsed 是否忽略选区的闭合状态, 如果该参数取值为true, 则
  4985. * 不论选区是否闭合, 都会执行该操作, 反之, 则不会对闭合的选区执行该操作
  4986. * @return { UE.dom.Range } 当前range对象
  4987. */
  4988. txtToElmBoundary: function (ignoreCollapsed) {
  4989. function adjust(r, c) {
  4990. var container = r[c + 'Container'],
  4991. offset = r[c + 'Offset'];
  4992. if (container.nodeType == 3) {
  4993. if (!offset) {
  4994. r['set' + c.replace(/(\w)/, function (a) {
  4995. return a.toUpperCase();
  4996. }) + 'Before'](container);
  4997. } else if (offset >= container.nodeValue.length) {
  4998. r['set' + c.replace(/(\w)/, function (a) {
  4999. return a.toUpperCase();
  5000. }) + 'After'](container);
  5001. }
  5002. }
  5003. }
  5004. if (ignoreCollapsed || !this.collapsed) {
  5005. adjust(this, 'start');
  5006. adjust(this, 'end');
  5007. }
  5008. return this;
  5009. },
  5010. /**
  5011. * 在当前选区的开始位置前插入节点,新插入的节点会被该range包含
  5012. * @method insertNode
  5013. * @param { Node } node 需要插入的节点
  5014. * @remind 插入的节点可以是一个DocumentFragment依次插入多个节点
  5015. * @return { UE.dom.Range } 当前range对象
  5016. */
  5017. insertNode: function (node) {
  5018. var first = node, length = 1;
  5019. if (node.nodeType == 11) {
  5020. first = node.firstChild;
  5021. length = node.childNodes.length;
  5022. }
  5023. this.trimBoundary(true);
  5024. var start = this.startContainer,
  5025. offset = this.startOffset;
  5026. var nextNode = start.childNodes[offset];
  5027. if (nextNode) {
  5028. start.insertBefore(node, nextNode);
  5029. } else {
  5030. start.appendChild(node);
  5031. }
  5032. if (first.parentNode === this.endContainer) {
  5033. this.endOffset = this.endOffset + length;
  5034. }
  5035. return this.setStartBefore(first);
  5036. },
  5037. /**
  5038. * 闭合选区到当前选区的开始位置, 并且定位光标到闭合后的位置
  5039. * @method setCursor
  5040. * @return { UE.dom.Range } 当前range对象
  5041. * @see UE.dom.Range:collapse()
  5042. */
  5043. /**
  5044. * 闭合选区,可以根据参数toEnd的值控制选区是向前闭合还是向后闭合, 并且定位光标到闭合后的位置。
  5045. * @method setCursor
  5046. * @param { Boolean } toEnd 是否向后闭合, 如果为true, 则闭合选区时, 将向结束容器方向闭合,
  5047. * 反之,则向开始容器方向闭合
  5048. * @return { UE.dom.Range } 当前range对象
  5049. * @see UE.dom.Range:collapse(Boolean)
  5050. */
  5051. setCursor: function (toEnd, noFillData) {
  5052. return this.collapse(!toEnd).select(noFillData);
  5053. },
  5054. /**
  5055. * 创建当前range的一个书签,记录下当前range的位置,方便当dom树改变时,还能找回原来的选区位置
  5056. * @method createBookmark
  5057. * @param { Boolean } serialize 控制返回的标记位置是对当前位置的引用还是ID,如果该值为true,则
  5058. * 返回标记位置的ID, 反之则返回标记位置节点的引用
  5059. * @return { Object } 返回一个书签记录键值对, 其包含的key有: start => 开始标记的ID或者引用,
  5060. * end => 结束标记的ID或引用, id => 当前标记的类型, 如果为true,则表示
  5061. * 返回的记录的类型为ID, 反之则为引用
  5062. */
  5063. createBookmark: function (serialize, same) {
  5064. var endNode,
  5065. startNode = this.document.createElement('span');
  5066. startNode.style.cssText = 'display:none;line-height:0px;';
  5067. startNode.appendChild(this.document.createTextNode('\u200D'));
  5068. startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++);
  5069. if (!this.collapsed) {
  5070. endNode = startNode.cloneNode(true);
  5071. endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++);
  5072. }
  5073. this.insertNode(startNode);
  5074. if (endNode) {
  5075. this.collapse().insertNode(endNode).setEndBefore(endNode);
  5076. }
  5077. this.setStartAfter(startNode);
  5078. return {
  5079. start: serialize ? startNode.id : startNode,
  5080. end: endNode ? serialize ? endNode.id : endNode : null,
  5081. id: serialize
  5082. }
  5083. },
  5084. /**
  5085. * 调整当前range的边界到书签位置,并删除该书签对象所标记的位置内的节点
  5086. * @method moveToBookmark
  5087. * @param { BookMark } bookmark createBookmark所创建的标签对象
  5088. * @return { UE.dom.Range } 当前range对象
  5089. * @see UE.dom.Range:createBookmark(Boolean)
  5090. */
  5091. moveToBookmark: function (bookmark) {
  5092. var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start,
  5093. end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end;
  5094. this.setStartBefore(start);
  5095. domUtils.remove(start);
  5096. if (end) {
  5097. this.setEndBefore(end);
  5098. domUtils.remove(end);
  5099. } else {
  5100. this.collapse(true);
  5101. }
  5102. return this;
  5103. },
  5104. /**
  5105. * 调整range的边界,使其"放大"到最近的父节点
  5106. * @method enlarge
  5107. * @remind 会引起选区的变化
  5108. * @return { UE.dom.Range } 当前range对象
  5109. */
  5110. /**
  5111. * 调整range的边界,使其"放大"到最近的父节点,根据参数 toBlock 的取值, 可以
  5112. * 要求扩大之后的父节点是block节点
  5113. * @method enlarge
  5114. * @param { Boolean } toBlock 是否要求扩大之后的父节点必须是block节点
  5115. * @return { UE.dom.Range } 当前range对象
  5116. */
  5117. enlarge: function (toBlock, stopFn) {
  5118. var isBody = domUtils.isBody,
  5119. pre, node, tmp = this.document.createTextNode('');
  5120. if (toBlock) {
  5121. node = this.startContainer;
  5122. if (node.nodeType == 1) {
  5123. if (node.childNodes[this.startOffset]) {
  5124. pre = node = node.childNodes[this.startOffset]
  5125. } else {
  5126. node.appendChild(tmp);
  5127. pre = node = tmp;
  5128. }
  5129. } else {
  5130. pre = node;
  5131. }
  5132. while (1) {
  5133. if (domUtils.isBlockElm(node)) {
  5134. node = pre;
  5135. while ((pre = node.previousSibling) && !domUtils.isBlockElm(pre)) {
  5136. node = pre;
  5137. }
  5138. this.setStartBefore(node);
  5139. break;
  5140. }
  5141. pre = node;
  5142. node = node.parentNode;
  5143. }
  5144. node = this.endContainer;
  5145. if (node.nodeType == 1) {
  5146. if (pre = node.childNodes[this.endOffset]) {
  5147. node.insertBefore(tmp, pre);
  5148. } else {
  5149. node.appendChild(tmp);
  5150. }
  5151. pre = node = tmp;
  5152. } else {
  5153. pre = node;
  5154. }
  5155. while (1) {
  5156. if (domUtils.isBlockElm(node)) {
  5157. node = pre;
  5158. while ((pre = node.nextSibling) && !domUtils.isBlockElm(pre)) {
  5159. node = pre;
  5160. }
  5161. this.setEndAfter(node);
  5162. break;
  5163. }
  5164. pre = node;
  5165. node = node.parentNode;
  5166. }
  5167. if (tmp.parentNode === this.endContainer) {
  5168. this.endOffset--;
  5169. }
  5170. domUtils.remove(tmp);
  5171. }
  5172. // 扩展边界到最大
  5173. if (!this.collapsed) {
  5174. while (this.startOffset == 0) {
  5175. if (stopFn && stopFn(this.startContainer)) {
  5176. break;
  5177. }
  5178. if (isBody(this.startContainer)) {
  5179. break;
  5180. }
  5181. this.setStartBefore(this.startContainer);
  5182. }
  5183. while (this.endOffset == (this.endContainer.nodeType == 1 ? this.endContainer.childNodes.length : this.endContainer.nodeValue.length)) {
  5184. if (stopFn && stopFn(this.endContainer)) {
  5185. break;
  5186. }
  5187. if (isBody(this.endContainer)) {
  5188. break;
  5189. }
  5190. this.setEndAfter(this.endContainer);
  5191. }
  5192. }
  5193. return this;
  5194. },
  5195. enlargeToBlockElm: function (ignoreEnd) {
  5196. while (!domUtils.isBlockElm(this.startContainer)) {
  5197. this.setStartBefore(this.startContainer);
  5198. }
  5199. if (!ignoreEnd) {
  5200. while (!domUtils.isBlockElm(this.endContainer)) {
  5201. this.setEndAfter(this.endContainer);
  5202. }
  5203. }
  5204. return this;
  5205. },
  5206. /**
  5207. * 调整Range的边界,使其"缩小"到最合适的位置
  5208. * @method adjustmentBoundary
  5209. * @return { UE.dom.Range } 当前range对象
  5210. * @see UE.dom.Range:shrinkBoundary()
  5211. */
  5212. adjustmentBoundary: function () {
  5213. if (!this.collapsed) {
  5214. while (!domUtils.isBody(this.startContainer) &&
  5215. this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length &&
  5216. this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5217. ) {
  5218. this.setStartAfter(this.startContainer);
  5219. }
  5220. while (!domUtils.isBody(this.endContainer) && !this.endOffset &&
  5221. this.endContainer[this.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5222. ) {
  5223. this.setEndBefore(this.endContainer);
  5224. }
  5225. }
  5226. return this;
  5227. },
  5228. /**
  5229. * 给range选区中的内容添加给定的inline标签
  5230. * @method applyInlineStyle
  5231. * @param { String } tagName 需要添加的标签名
  5232. * @example
  5233. * ```html
  5234. * <p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong") ==> <p>xxxx[<strong>xxxx</strong>]x</p>
  5235. * ```
  5236. */
  5237. /**
  5238. * 给range选区中的内容添加给定的inline标签, 并且为标签附加上一些初始化属性。
  5239. * @method applyInlineStyle
  5240. * @param { String } tagName 需要添加的标签名
  5241. * @param { Object } attrs 跟随新添加的标签的属性
  5242. * @return { UE.dom.Range } 当前选区
  5243. * @example
  5244. * ```html
  5245. * <p>xxxx[xxxx]x</p>
  5246. *
  5247. * ==>
  5248. *
  5249. * <!-- 执行操作 -->
  5250. * range.applyInlineStyle("strong",{"style":"font-size:12px"})
  5251. *
  5252. * ==>
  5253. *
  5254. * <p>xxxx[<strong style="font-size:12px">xxxx</strong>]x</p>
  5255. * ```
  5256. */
  5257. applyInlineStyle: function (tagName, attrs, list) {
  5258. if (this.collapsed) return this;
  5259. this.trimBoundary().enlarge(false,
  5260. function (node) {
  5261. return node.nodeType == 1 && domUtils.isBlockElm(node)
  5262. }).adjustmentBoundary();
  5263. var bookmark = this.createBookmark(),
  5264. end = bookmark.end,
  5265. filterFn = function (node) {
  5266. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  5267. },
  5268. current = domUtils.getNextDomNode(bookmark.start, false, filterFn),
  5269. node,
  5270. pre,
  5271. range = this.cloneRange();
  5272. while (current && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5273. if (current.nodeType == 3 || dtd[tagName][current.tagName]) {
  5274. range.setStartBefore(current);
  5275. node = current;
  5276. while (node && (node.nodeType == 3 || dtd[tagName][node.tagName]) && node !== end) {
  5277. pre = node;
  5278. node = domUtils.getNextDomNode(node, node.nodeType == 1, null, function (parent) {
  5279. return dtd[tagName][parent.tagName];
  5280. });
  5281. }
  5282. var frag = range.setEndAfter(pre).extractContents(), elm;
  5283. if (list && list.length > 0) {
  5284. var level, top;
  5285. top = level = list[0].cloneNode(false);
  5286. for (var i = 1, ci; ci = list[i++];) {
  5287. level.appendChild(ci.cloneNode(false));
  5288. level = level.firstChild;
  5289. }
  5290. elm = level;
  5291. } else {
  5292. elm = range.document.createElement(tagName);
  5293. }
  5294. if (attrs) {
  5295. domUtils.setAttributes(elm, attrs);
  5296. }
  5297. elm.appendChild(frag);
  5298. range.insertNode(list ? top : elm);
  5299. //处理下滑线在a上的情况
  5300. var aNode;
  5301. if (tagName == 'span' && attrs.style && /text\-decoration/.test(attrs.style) && (aNode = domUtils.findParentByTagName(elm, 'a', true))) {
  5302. domUtils.setAttributes(aNode, attrs);
  5303. domUtils.remove(elm, true);
  5304. elm = aNode;
  5305. } else {
  5306. domUtils.mergeSibling(elm);
  5307. domUtils.clearEmptySibling(elm);
  5308. }
  5309. //去除子节点相同的
  5310. domUtils.mergeChild(elm, attrs);
  5311. current = domUtils.getNextDomNode(elm, false, filterFn);
  5312. domUtils.mergeToParent(elm);
  5313. if (node === end) {
  5314. break;
  5315. }
  5316. } else {
  5317. current = domUtils.getNextDomNode(current, true, filterFn);
  5318. }
  5319. }
  5320. return this.moveToBookmark(bookmark);
  5321. },
  5322. /**
  5323. * 移除当前选区内指定的inline标签,但保留其中的内容
  5324. * @method removeInlineStyle
  5325. * @param { String } tagName 需要移除的标签名
  5326. * @return { UE.dom.Range } 当前的range对象
  5327. * @example
  5328. * ```html
  5329. * xx[x<span>xxx<em>yyy</em>zz]z</span> => range.removeInlineStyle(["em"]) => xx[x<span>xxxyyyzz]z</span>
  5330. * ```
  5331. */
  5332. /**
  5333. * 移除当前选区内指定的一组inline标签,但保留其中的内容
  5334. * @method removeInlineStyle
  5335. * @param { Array } tagNameArr 需要移除的标签名的数组
  5336. * @return { UE.dom.Range } 当前的range对象
  5337. * @see UE.dom.Range:removeInlineStyle(String)
  5338. */
  5339. removeInlineStyle: function (tagNames) {
  5340. if (this.collapsed) return this;
  5341. tagNames = utils.isArray(tagNames) ? tagNames : [tagNames];
  5342. this.shrinkBoundary().adjustmentBoundary();
  5343. var start = this.startContainer, end = this.endContainer;
  5344. while (1) {
  5345. if (start.nodeType == 1) {
  5346. if (utils.indexOf(tagNames, start.tagName.toLowerCase()) > -1) {
  5347. break;
  5348. }
  5349. if (start.tagName.toLowerCase() == 'body') {
  5350. start = null;
  5351. break;
  5352. }
  5353. }
  5354. start = start.parentNode;
  5355. }
  5356. while (1) {
  5357. if (end.nodeType == 1) {
  5358. if (utils.indexOf(tagNames, end.tagName.toLowerCase()) > -1) {
  5359. break;
  5360. }
  5361. if (end.tagName.toLowerCase() == 'body') {
  5362. end = null;
  5363. break;
  5364. }
  5365. }
  5366. end = end.parentNode;
  5367. }
  5368. var bookmark = this.createBookmark(),
  5369. frag,
  5370. tmpRange;
  5371. if (start) {
  5372. tmpRange = this.cloneRange().setEndBefore(bookmark.start).setStartBefore(start);
  5373. frag = tmpRange.extractContents();
  5374. tmpRange.insertNode(frag);
  5375. domUtils.clearEmptySibling(start, true);
  5376. start.parentNode.insertBefore(bookmark.start, start);
  5377. }
  5378. if (end) {
  5379. tmpRange = this.cloneRange().setStartAfter(bookmark.end).setEndAfter(end);
  5380. frag = tmpRange.extractContents();
  5381. tmpRange.insertNode(frag);
  5382. domUtils.clearEmptySibling(end, false, true);
  5383. end.parentNode.insertBefore(bookmark.end, end.nextSibling);
  5384. }
  5385. var current = domUtils.getNextDomNode(bookmark.start, false, function (node) {
  5386. return node.nodeType == 1;
  5387. }), next;
  5388. while (current && current !== bookmark.end) {
  5389. next = domUtils.getNextDomNode(current, true, function (node) {
  5390. return node.nodeType == 1;
  5391. });
  5392. if (utils.indexOf(tagNames, current.tagName.toLowerCase()) > -1) {
  5393. domUtils.remove(current, true);
  5394. }
  5395. current = next;
  5396. }
  5397. return this.moveToBookmark(bookmark);
  5398. },
  5399. /**
  5400. * 获取当前选中的自闭合的节点
  5401. * @method getClosedNode
  5402. * @return { Node | NULL } 如果当前选中的是自闭合节点, 则返回该节点, 否则返回NULL
  5403. */
  5404. getClosedNode: function () {
  5405. var node;
  5406. if (!this.collapsed) {
  5407. var range = this.cloneRange().adjustmentBoundary().shrinkBoundary();
  5408. if (selectOneNode(range)) {
  5409. var child = range.startContainer.childNodes[range.startOffset];
  5410. if (child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) {
  5411. node = child;
  5412. }
  5413. }
  5414. }
  5415. return node;
  5416. },
  5417. /**
  5418. * 在页面上高亮range所表示的选区
  5419. * @method select
  5420. * @return { UE.dom.Range } 返回当前Range对象
  5421. */
  5422. //这里不区分ie9以上,trace:3824
  5423. select: browser.ie ? function (noFillData, textRange) {
  5424. var nativeRange;
  5425. if (!this.collapsed)
  5426. this.shrinkBoundary();
  5427. var node = this.getClosedNode();
  5428. if (node && !textRange) {
  5429. try {
  5430. nativeRange = this.document.body.createControlRange();
  5431. nativeRange.addElement(node);
  5432. nativeRange.select();
  5433. } catch (e) { }
  5434. return this;
  5435. }
  5436. var bookmark = this.createBookmark(),
  5437. start = bookmark.start,
  5438. end;
  5439. nativeRange = this.document.body.createTextRange();
  5440. nativeRange.moveToElementText(start);
  5441. nativeRange.moveStart('character', 1);
  5442. if (!this.collapsed) {
  5443. var nativeRangeEnd = this.document.body.createTextRange();
  5444. end = bookmark.end;
  5445. nativeRangeEnd.moveToElementText(end);
  5446. nativeRange.setEndPoint('EndToEnd', nativeRangeEnd);
  5447. } else {
  5448. if (!noFillData && this.startContainer.nodeType != 3) {
  5449. //使用<span>|x<span>固定住光标
  5450. var tmpText = this.document.createTextNode(fillChar),
  5451. tmp = this.document.createElement('span');
  5452. tmp.appendChild(this.document.createTextNode(fillChar));
  5453. start.parentNode.insertBefore(tmp, start);
  5454. start.parentNode.insertBefore(tmpText, start);
  5455. //当点b,i,u时,不能清除i上边的b
  5456. removeFillData(this.document, tmpText);
  5457. fillData = tmpText;
  5458. mergeSibling(tmp, 'previousSibling');
  5459. mergeSibling(start, 'nextSibling');
  5460. nativeRange.moveStart('character', -1);
  5461. nativeRange.collapse(true);
  5462. }
  5463. }
  5464. this.moveToBookmark(bookmark);
  5465. tmp && domUtils.remove(tmp);
  5466. //IE在隐藏状态下不支持range操作,catch一下
  5467. try {
  5468. nativeRange.select();
  5469. } catch (e) {
  5470. }
  5471. return this;
  5472. } : function (notInsertFillData) {
  5473. function checkOffset(rng) {
  5474. function check(node, offset, dir) {
  5475. if (node.nodeType == 3 && node.nodeValue.length < offset) {
  5476. rng[dir + 'Offset'] = node.nodeValue.length
  5477. }
  5478. }
  5479. check(rng.startContainer, rng.startOffset, 'start');
  5480. check(rng.endContainer, rng.endOffset, 'end');
  5481. }
  5482. var win = domUtils.getWindow(this.document),
  5483. sel = win.getSelection(),
  5484. txtNode;
  5485. //FF下关闭自动长高时滚动条在关闭dialog时会跳
  5486. //ff下如果不body.focus将不能定位闭合光标到编辑器内
  5487. browser.gecko ? this.document.body.focus() : win.focus();
  5488. if (sel) {
  5489. sel.removeAllRanges();
  5490. // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断
  5491. // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR'
  5492. if (this.collapsed && !notInsertFillData) {
  5493. // //opear如果没有节点接着,原生的不能够定位,不能在body的第一级插入空白节点
  5494. // if (notInsertFillData && browser.opera && !domUtils.isBody(this.startContainer) && this.startContainer.nodeType == 1) {
  5495. // var tmp = this.document.createTextNode('');
  5496. // this.insertNode(tmp).setStart(tmp, 0).collapse(true);
  5497. // }
  5498. //
  5499. //处理光标落在文本节点的情况
  5500. //处理以下的情况
  5501. //<b>|xxxx</b>
  5502. //<b>xxxx</b>|xxxx
  5503. //xxxx<b>|</b>
  5504. var start = this.startContainer, child = start;
  5505. if (start.nodeType == 1) {
  5506. child = start.childNodes[this.startOffset];
  5507. }
  5508. if (!(start.nodeType == 3 && this.startOffset) &&
  5509. (child ?
  5510. (!child.previousSibling || child.previousSibling.nodeType != 3)
  5511. :
  5512. (!start.lastChild || start.lastChild.nodeType != 3)
  5513. )
  5514. ) {
  5515. txtNode = this.document.createTextNode(fillChar);
  5516. //跟着前边走
  5517. this.insertNode(txtNode);
  5518. removeFillData(this.document, txtNode);
  5519. mergeSibling(txtNode, 'previousSibling');
  5520. mergeSibling(txtNode, 'nextSibling');
  5521. fillData = txtNode;
  5522. this.setStart(txtNode, browser.webkit ? 1 : 0).collapse(true);
  5523. }
  5524. }
  5525. var nativeRange = this.document.createRange();
  5526. if (this.collapsed && browser.opera && this.startContainer.nodeType == 1) {
  5527. var child = this.startContainer.childNodes[this.startOffset];
  5528. if (!child) {
  5529. //往前靠拢
  5530. child = this.startContainer.lastChild;
  5531. if (child && domUtils.isBr(child)) {
  5532. this.setStartBefore(child).collapse(true);
  5533. }
  5534. } else {
  5535. //向后靠拢
  5536. while (child && domUtils.isBlockElm(child)) {
  5537. if (child.nodeType == 1 && child.childNodes[0]) {
  5538. child = child.childNodes[0]
  5539. } else {
  5540. break;
  5541. }
  5542. }
  5543. child && this.setStartBefore(child).collapse(true)
  5544. }
  5545. }
  5546. //是createAddress最后一位算的不准,现在这里进行微调
  5547. checkOffset(this);
  5548. nativeRange.setStart(this.startContainer, this.startOffset);
  5549. nativeRange.setEnd(this.endContainer, this.endOffset);
  5550. sel.addRange(nativeRange);
  5551. }
  5552. return this;
  5553. },
  5554. /**
  5555. * 滚动到当前range开始的位置
  5556. * @method scrollToView
  5557. * @param { Window } win 当前range对象所属的window对象
  5558. * @return { UE.dom.Range } 当前Range对象
  5559. */
  5560. /**
  5561. * 滚动到距离当前range开始位置 offset 的位置处
  5562. * @method scrollToView
  5563. * @param { Window } win 当前range对象所属的window对象
  5564. * @param { Number } offset 距离range开始位置处的偏移量, 如果为正数, 则向下偏移, 反之, 则向上偏移
  5565. * @return { UE.dom.Range } 当前Range对象
  5566. */
  5567. scrollToView: function (win, offset) {
  5568. win = win ? window : domUtils.getWindow(this.document);
  5569. var me = this,
  5570. span = me.document.createElement('span');
  5571. //trace:717
  5572. span.innerHTML = '&nbsp;';
  5573. me.cloneRange().insertNode(span);
  5574. domUtils.scrollToView(span, win, offset);
  5575. domUtils.remove(span);
  5576. return me;
  5577. },
  5578. /**
  5579. * 判断当前选区内容是否占位符
  5580. * @private
  5581. * @method inFillChar
  5582. * @return { Boolean } 如果是占位符返回true,否则返回false
  5583. */
  5584. inFillChar: function () {
  5585. var start = this.startContainer;
  5586. if (this.collapsed && start.nodeType == 3
  5587. && start.nodeValue.replace(new RegExp('^' + domUtils.fillChar), '').length + 1 == start.nodeValue.length
  5588. ) {
  5589. return true;
  5590. }
  5591. return false;
  5592. },
  5593. /**
  5594. * 保存
  5595. * @method createAddress
  5596. * @private
  5597. * @return { Boolean } 返回开始和结束的位置
  5598. * @example
  5599. * ```html
  5600. * <body>
  5601. * <p>
  5602. * aaaa
  5603. * <em>
  5604. * <!-- 选区开始 -->
  5605. * bbbb
  5606. * <!-- 选区结束 -->
  5607. * </em>
  5608. * </p>
  5609. *
  5610. * <script>
  5611. * //output: {startAddress:[0,1,0,0],endAddress:[0,1,0,4]}
  5612. * console.log( range.createAddress() );
  5613. * </script>
  5614. * </body>
  5615. * ```
  5616. */
  5617. createAddress: function (ignoreEnd, ignoreTxt) {
  5618. var addr = {}, me = this;
  5619. function getAddress(isStart) {
  5620. var node = isStart ? me.startContainer : me.endContainer;
  5621. var parents = domUtils.findParents(node, true, function (node) { return !domUtils.isBody(node) }),
  5622. addrs = [];
  5623. for (var i = 0, ci; ci = parents[i++];) {
  5624. addrs.push(domUtils.getNodeIndex(ci, ignoreTxt));
  5625. }
  5626. var firstIndex = 0;
  5627. if (ignoreTxt) {
  5628. if (node.nodeType == 3) {
  5629. var tmpNode = node.previousSibling;
  5630. while (tmpNode && tmpNode.nodeType == 3) {
  5631. firstIndex += tmpNode.nodeValue.replace(fillCharReg, '').length;
  5632. tmpNode = tmpNode.previousSibling;
  5633. }
  5634. firstIndex += (isStart ? me.startOffset : me.endOffset)// - (fillCharReg.test(node.nodeValue) ? 1 : 0 )
  5635. } else {
  5636. node = node.childNodes[isStart ? me.startOffset : me.endOffset];
  5637. if (node) {
  5638. firstIndex = domUtils.getNodeIndex(node, ignoreTxt);
  5639. } else {
  5640. node = isStart ? me.startContainer : me.endContainer;
  5641. var first = node.firstChild;
  5642. while (first) {
  5643. if (domUtils.isFillChar(first)) {
  5644. first = first.nextSibling;
  5645. continue;
  5646. }
  5647. firstIndex++;
  5648. if (first.nodeType == 3) {
  5649. while (first && first.nodeType == 3) {
  5650. first = first.nextSibling;
  5651. }
  5652. } else {
  5653. first = first.nextSibling;
  5654. }
  5655. }
  5656. }
  5657. }
  5658. } else {
  5659. firstIndex = isStart ? domUtils.isFillChar(node) ? 0 : me.startOffset : me.endOffset
  5660. }
  5661. if (firstIndex < 0) {
  5662. firstIndex = 0;
  5663. }
  5664. addrs.push(firstIndex);
  5665. return addrs;
  5666. }
  5667. addr.startAddress = getAddress(true);
  5668. if (!ignoreEnd) {
  5669. addr.endAddress = me.collapsed ? [].concat(addr.startAddress) : getAddress();
  5670. }
  5671. return addr;
  5672. },
  5673. /**
  5674. * 保存
  5675. * @method createAddress
  5676. * @private
  5677. * @return { Boolean } 返回开始和结束的位置
  5678. * @example
  5679. * ```html
  5680. * <body>
  5681. * <p>
  5682. * aaaa
  5683. * <em>
  5684. * <!-- 选区开始 -->
  5685. * bbbb
  5686. * <!-- 选区结束 -->
  5687. * </em>
  5688. * </p>
  5689. *
  5690. * <script>
  5691. * var range = editor.selection.getRange();
  5692. * range.moveToAddress({startAddress:[0,1,0,0],endAddress:[0,1,0,4]});
  5693. * range.select();
  5694. * //output: 'bbbb'
  5695. * console.log(editor.selection.getText());
  5696. * </script>
  5697. * </body>
  5698. * ```
  5699. */
  5700. moveToAddress: function (addr, ignoreEnd) {
  5701. var me = this;
  5702. function getNode(address, isStart) {
  5703. var tmpNode = me.document.body,
  5704. parentNode, offset;
  5705. for (var i = 0, ci, l = address.length; i < l; i++) {
  5706. ci = address[i];
  5707. parentNode = tmpNode;
  5708. tmpNode = tmpNode.childNodes[ci];
  5709. if (!tmpNode) {
  5710. offset = ci;
  5711. break;
  5712. }
  5713. }
  5714. if (isStart) {
  5715. if (tmpNode) {
  5716. me.setStartBefore(tmpNode)
  5717. } else {
  5718. me.setStart(parentNode, offset)
  5719. }
  5720. } else {
  5721. if (tmpNode) {
  5722. me.setEndBefore(tmpNode)
  5723. } else {
  5724. me.setEnd(parentNode, offset)
  5725. }
  5726. }
  5727. }
  5728. getNode(addr.startAddress, true);
  5729. !ignoreEnd && addr.endAddress && getNode(addr.endAddress);
  5730. return me;
  5731. },
  5732. /**
  5733. * 判断给定的Range对象是否和当前Range对象表示的是同一个选区
  5734. * @method equals
  5735. * @param { UE.dom.Range } 需要判断的Range对象
  5736. * @return { Boolean } 如果给定的Range对象与当前Range对象表示的是同一个选区, 则返回true, 否则返回false
  5737. */
  5738. equals: function (rng) {
  5739. for (var p in this) {
  5740. if (this.hasOwnProperty(p)) {
  5741. if (this[p] !== rng[p])
  5742. return false
  5743. }
  5744. }
  5745. return true;
  5746. },
  5747. /**
  5748. * 遍历range内的节点。每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5749. * 作为其参数。
  5750. * @method traversal
  5751. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5752. * @return { UE.dom.Range } 当前range对象
  5753. * @example
  5754. * ```html
  5755. *
  5756. * <body>
  5757. *
  5758. * <!-- 选区开始 -->
  5759. * <span></span>
  5760. * <a></a>
  5761. * <!-- 选区结束 -->
  5762. * </body>
  5763. *
  5764. * <script>
  5765. *
  5766. * //output: <span></span><a></a>
  5767. * console.log( range.cloneContents() );
  5768. *
  5769. * range.traversal( function ( node ) {
  5770. *
  5771. * if ( node.nodeType === 1 ) {
  5772. * node.className = "test";
  5773. * }
  5774. *
  5775. * } );
  5776. *
  5777. * //output: <span class="test"></span><a class="test"></a>
  5778. * console.log( range.cloneContents() );
  5779. *
  5780. * </script>
  5781. * ```
  5782. */
  5783. /**
  5784. * 遍历range内的节点。
  5785. * 每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5786. * 作为其参数。
  5787. * 可以通过参数项 filterFn 来指定一个过滤器, 只有符合该过滤器过滤规则的节点才会触
  5788. * 发doFn函数的执行
  5789. * @method traversal
  5790. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5791. * @param { Function } filterFn 过滤器, 该函数接受当前遍历的节点作为参数, 如果该节点满足过滤
  5792. * 规则, 请返回true, 该节点会触发doFn, 否则, 请返回false, 则该节点不
  5793. * 会触发doFn。
  5794. * @return { UE.dom.Range } 当前range对象
  5795. * @see UE.dom.Range:traversal(Function)
  5796. * @example
  5797. * ```html
  5798. *
  5799. * <body>
  5800. *
  5801. * <!-- 选区开始 -->
  5802. * <span></span>
  5803. * <a></a>
  5804. * <!-- 选区结束 -->
  5805. * </body>
  5806. *
  5807. * <script>
  5808. *
  5809. * //output: <span></span><a></a>
  5810. * console.log( range.cloneContents() );
  5811. *
  5812. * range.traversal( function ( node ) {
  5813. *
  5814. * node.className = "test";
  5815. *
  5816. * }, function ( node ) {
  5817. * return node.nodeType === 1;
  5818. * } );
  5819. *
  5820. * //output: <span class="test"></span><a class="test"></a>
  5821. * console.log( range.cloneContents() );
  5822. *
  5823. * </script>
  5824. * ```
  5825. */
  5826. traversal: function (doFn, filterFn) {
  5827. if (this.collapsed)
  5828. return this;
  5829. var bookmark = this.createBookmark(),
  5830. end = bookmark.end,
  5831. current = domUtils.getNextDomNode(bookmark.start, false, filterFn);
  5832. while (current && current !== end && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5833. var tmpNode = domUtils.getNextDomNode(current, false, filterFn);
  5834. doFn(current);
  5835. current = tmpNode;
  5836. }
  5837. return this.moveToBookmark(bookmark);
  5838. }
  5839. };
  5840. })();
  5841. // core/Selection.js
  5842. /**
  5843. * 选集
  5844. * @file
  5845. * @module UE.dom
  5846. * @class Selection
  5847. * @since 1.2.6.1
  5848. */
  5849. /**
  5850. * 选区集合
  5851. * @unfile
  5852. * @module UE.dom
  5853. * @class Selection
  5854. */
  5855. (function () {
  5856. function getBoundaryInformation(range, start) {
  5857. var getIndex = domUtils.getNodeIndex;
  5858. range = range.duplicate();
  5859. range.collapse(start);
  5860. var parent = range.parentElement();
  5861. //如果节点里没有子节点,直接退出
  5862. if (!parent.hasChildNodes()) {
  5863. return { container: parent, offset: 0 };
  5864. }
  5865. var siblings = parent.children,
  5866. child,
  5867. testRange = range.duplicate(),
  5868. startIndex = 0, endIndex = siblings.length - 1, index = -1,
  5869. distance;
  5870. while (startIndex <= endIndex) {
  5871. index = Math.floor((startIndex + endIndex) / 2);
  5872. child = siblings[index];
  5873. testRange.moveToElementText(child);
  5874. var position = testRange.compareEndPoints('StartToStart', range);
  5875. if (position > 0) {
  5876. endIndex = index - 1;
  5877. } else if (position < 0) {
  5878. startIndex = index + 1;
  5879. } else {
  5880. //trace:1043
  5881. return { container: parent, offset: getIndex(child) };
  5882. }
  5883. }
  5884. if (index == -1) {
  5885. testRange.moveToElementText(parent);
  5886. testRange.setEndPoint('StartToStart', range);
  5887. distance = testRange.text.replace(/(\r\n|\r)/g, '\n').length;
  5888. siblings = parent.childNodes;
  5889. if (!distance) {
  5890. child = siblings[siblings.length - 1];
  5891. return { container: child, offset: child.nodeValue.length };
  5892. }
  5893. var i = siblings.length;
  5894. while (distance > 0) {
  5895. distance -= siblings[--i].nodeValue.length;
  5896. }
  5897. return { container: siblings[i], offset: -distance };
  5898. }
  5899. testRange.collapse(position > 0);
  5900. testRange.setEndPoint(position > 0 ? 'StartToStart' : 'EndToStart', range);
  5901. distance = testRange.text.replace(/(\r\n|\r)/g, '\n').length;
  5902. if (!distance) {
  5903. return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ?
  5904. { container: parent, offset: getIndex(child) + (position > 0 ? 0 : 1) } :
  5905. { container: child, offset: position > 0 ? 0 : child.childNodes.length }
  5906. }
  5907. while (distance > 0) {
  5908. try {
  5909. var pre = child;
  5910. child = child[position > 0 ? 'previousSibling' : 'nextSibling'];
  5911. distance -= child.nodeValue.length;
  5912. } catch (e) {
  5913. return { container: parent, offset: getIndex(pre) };
  5914. }
  5915. }
  5916. return { container: child, offset: position > 0 ? -distance : child.nodeValue.length + distance }
  5917. }
  5918. /**
  5919. * 将ieRange转换为Range对象
  5920. * @param {Range} ieRange ieRange对象
  5921. * @param {Range} range Range对象
  5922. * @return {Range} range 返回转换后的Range对象
  5923. */
  5924. function transformIERangeToRange(ieRange, range) {
  5925. if (ieRange.item) {
  5926. range.selectNode(ieRange.item(0));
  5927. } else {
  5928. var bi = getBoundaryInformation(ieRange, true);
  5929. range.setStart(bi.container, bi.offset);
  5930. if (ieRange.compareEndPoints('StartToEnd', ieRange) != 0) {
  5931. bi = getBoundaryInformation(ieRange, false);
  5932. range.setEnd(bi.container, bi.offset);
  5933. }
  5934. }
  5935. return range;
  5936. }
  5937. /**
  5938. * 获得ieRange
  5939. * @param {Selection} sel Selection对象
  5940. * @return {ieRange} 得到ieRange
  5941. */
  5942. function _getIERange(sel) {
  5943. var ieRange;
  5944. //ie下有可能报错
  5945. try {
  5946. ieRange = sel.getNative().createRange();
  5947. } catch (e) {
  5948. return null;
  5949. }
  5950. var el = ieRange.item ? ieRange.item(0) : ieRange.parentElement();
  5951. if ((el.ownerDocument || el) === sel.document) {
  5952. return ieRange;
  5953. }
  5954. return null;
  5955. }
  5956. var Selection = dom.Selection = function (doc) {
  5957. var me = this, iframe;
  5958. me.document = doc;
  5959. if (browser.ie9below) {
  5960. iframe = domUtils.getWindow(doc).frameElement;
  5961. domUtils.on(iframe, 'beforedeactivate', function () {
  5962. me._bakIERange = me.getIERange();
  5963. });
  5964. domUtils.on(iframe, 'activate', function () {
  5965. try {
  5966. if (!_getIERange(me) && me._bakIERange) {
  5967. me._bakIERange.select();
  5968. }
  5969. } catch (ex) {
  5970. }
  5971. me._bakIERange = null;
  5972. });
  5973. }
  5974. iframe = doc = null;
  5975. };
  5976. Selection.prototype = {
  5977. rangeInBody: function (rng, txtRange) {
  5978. var node = browser.ie9below || txtRange ? rng.item ? rng.item() : rng.parentElement() : rng.startContainer;
  5979. return node === this.document.body || domUtils.inDoc(node, this.document);
  5980. },
  5981. /**
  5982. * 获取原生seleciton对象
  5983. * @method getNative
  5984. * @return { Object } 获得selection对象
  5985. * @example
  5986. * ```javascript
  5987. * editor.selection.getNative();
  5988. * ```
  5989. */
  5990. getNative: function () {
  5991. var doc = this.document;
  5992. try {
  5993. return !doc ? null : browser.ie9below ? doc.selection : domUtils.getWindow(doc).getSelection();
  5994. } catch (e) {
  5995. return null;
  5996. }
  5997. },
  5998. /**
  5999. * 获得ieRange
  6000. * @method getIERange
  6001. * @return { Object } 返回ie原生的Range
  6002. * @example
  6003. * ```javascript
  6004. * editor.selection.getIERange();
  6005. * ```
  6006. */
  6007. getIERange: function () {
  6008. var ieRange = _getIERange(this);
  6009. if (!ieRange) {
  6010. if (this._bakIERange) {
  6011. return this._bakIERange;
  6012. }
  6013. }
  6014. return ieRange;
  6015. },
  6016. /**
  6017. * 缓存当前选区的range和选区的开始节点
  6018. * @method cache
  6019. */
  6020. cache: function () {
  6021. this.clear();
  6022. this._cachedRange = this.getRange();
  6023. this._cachedStartElement = this.getStart();
  6024. this._cachedStartElementPath = this.getStartElementPath();
  6025. },
  6026. /**
  6027. * 获取选区开始位置的父节点到body
  6028. * @method getStartElementPath
  6029. * @return { Array } 返回父节点集合
  6030. * @example
  6031. * ```javascript
  6032. * editor.selection.getStartElementPath();
  6033. * ```
  6034. */
  6035. getStartElementPath: function () {
  6036. if (this._cachedStartElementPath) {
  6037. return this._cachedStartElementPath;
  6038. }
  6039. var start = this.getStart();
  6040. if (start) {
  6041. return domUtils.findParents(start, true, null, true)
  6042. }
  6043. return [];
  6044. },
  6045. /**
  6046. * 清空缓存
  6047. * @method clear
  6048. */
  6049. clear: function () {
  6050. this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null;
  6051. },
  6052. /**
  6053. * 编辑器是否得到了选区
  6054. * @method isFocus
  6055. */
  6056. isFocus: function () {
  6057. try {
  6058. if (browser.ie9below) {
  6059. var nativeRange = _getIERange(this);
  6060. return !!(nativeRange && this.rangeInBody(nativeRange));
  6061. } else {
  6062. return !!this.getNative().rangeCount;
  6063. }
  6064. } catch (e) {
  6065. return false;
  6066. }
  6067. },
  6068. /**
  6069. * 获取选区对应的Range
  6070. * @method getRange
  6071. * @return { Object } 得到Range对象
  6072. * @example
  6073. * ```javascript
  6074. * editor.selection.getRange();
  6075. * ```
  6076. */
  6077. getRange: function () {
  6078. var me = this;
  6079. function optimze(range) {
  6080. var child = me.document.body.firstChild,
  6081. collapsed = range.collapsed;
  6082. while (child && child.firstChild) {
  6083. range.setStart(child, 0);
  6084. child = child.firstChild;
  6085. }
  6086. if (!range.startContainer) {
  6087. range.setStart(me.document.body, 0)
  6088. }
  6089. if (collapsed) {
  6090. range.collapse(true);
  6091. }
  6092. }
  6093. if (me._cachedRange != null) {
  6094. return this._cachedRange;
  6095. }
  6096. var range = new baidu.editor.dom.Range(me.document);
  6097. if (browser.ie9below) {
  6098. var nativeRange = me.getIERange();
  6099. if (nativeRange) {
  6100. //备份的_bakIERange可能已经实效了,dom树发生了变化比如从源码模式切回来,所以try一下,实效就放到body开始位置
  6101. try {
  6102. transformIERangeToRange(nativeRange, range);
  6103. } catch (e) {
  6104. optimze(range);
  6105. }
  6106. } else {
  6107. optimze(range);
  6108. }
  6109. } else {
  6110. var sel = me.getNative();
  6111. if (sel && sel.rangeCount) {
  6112. var firstRange = sel.getRangeAt(0);
  6113. var lastRange = sel.getRangeAt(sel.rangeCount - 1);
  6114. range.setStart(firstRange.startContainer, firstRange.startOffset).setEnd(lastRange.endContainer, lastRange.endOffset);
  6115. if (range.collapsed && domUtils.isBody(range.startContainer) && !range.startOffset) {
  6116. optimze(range);
  6117. }
  6118. } else {
  6119. //trace:1734 有可能已经不在dom树上了,标识的节点
  6120. if (this._bakRange && domUtils.inDoc(this._bakRange.startContainer, this.document)) {
  6121. return this._bakRange;
  6122. }
  6123. optimze(range);
  6124. }
  6125. }
  6126. return this._bakRange = range;
  6127. },
  6128. /**
  6129. * 获取开始元素,用于状态反射
  6130. * @method getStart
  6131. * @return { Element } 获得开始元素
  6132. * @example
  6133. * ```javascript
  6134. * editor.selection.getStart();
  6135. * ```
  6136. */
  6137. getStart: function () {
  6138. if (this._cachedStartElement) {
  6139. return this._cachedStartElement;
  6140. }
  6141. var range = browser.ie9below ? this.getIERange() : this.getRange(),
  6142. tmpRange,
  6143. start, tmp, parent;
  6144. if (browser.ie9below) {
  6145. if (!range) {
  6146. //todo 给第一个值可能会有问题
  6147. return this.document.body.firstChild;
  6148. }
  6149. //control元素
  6150. if (range.item) {
  6151. return range.item(0);
  6152. }
  6153. tmpRange = range.duplicate();
  6154. //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx
  6155. tmpRange.text.length > 0 && tmpRange.moveStart('character', 1);
  6156. tmpRange.collapse(1);
  6157. start = tmpRange.parentElement();
  6158. parent = tmp = range.parentElement();
  6159. while (tmp = tmp.parentNode) {
  6160. if (tmp == start) {
  6161. start = parent;
  6162. break;
  6163. }
  6164. }
  6165. } else {
  6166. range.shrinkBoundary();
  6167. start = range.startContainer;
  6168. if (start.nodeType == 1 && start.hasChildNodes()) {
  6169. start = start.childNodes[Math.min(start.childNodes.length - 1, range.startOffset)];
  6170. }
  6171. if (start.nodeType == 3) {
  6172. return start.parentNode;
  6173. }
  6174. }
  6175. return start;
  6176. },
  6177. /**
  6178. * 得到选区中的文本
  6179. * @method getText
  6180. * @return { String } 选区中包含的文本
  6181. * @example
  6182. * ```javascript
  6183. * editor.selection.getText();
  6184. * ```
  6185. */
  6186. getText: function () {
  6187. var nativeSel, nativeRange;
  6188. if (this.isFocus() && (nativeSel = this.getNative())) {
  6189. nativeRange = browser.ie9below ? nativeSel.createRange() : nativeSel.getRangeAt(0);
  6190. return browser.ie9below ? nativeRange.text : nativeRange.toString();
  6191. }
  6192. return '';
  6193. },
  6194. /**
  6195. * 清除选区
  6196. * @method clearRange
  6197. * @example
  6198. * ```javascript
  6199. * editor.selection.clearRange();
  6200. * ```
  6201. */
  6202. clearRange: function () {
  6203. this.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  6204. }
  6205. };
  6206. })();
  6207. // core/Editor.js
  6208. /**
  6209. * 编辑器主类,包含编辑器提供的大部分公用接口
  6210. * @file
  6211. * @module UE
  6212. * @class Editor
  6213. * @since 1.2.6.1
  6214. */
  6215. /**
  6216. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  6217. * @unfile
  6218. * @module UE
  6219. */
  6220. /**
  6221. * UEditor的核心类,为用户提供与编辑器交互的接口。
  6222. * @unfile
  6223. * @module UE
  6224. * @class Editor
  6225. */
  6226. (function () {
  6227. var uid = 0, _selectionChangeTimer;
  6228. /**
  6229. * 获取编辑器的html内容,赋值到编辑器所在表单的textarea文本域里面
  6230. * @private
  6231. * @method setValue
  6232. * @param { UE.Editor } editor 编辑器事例
  6233. */
  6234. function setValue(form, editor) {
  6235. var textarea;
  6236. if (editor.textarea) {
  6237. if (utils.isString(editor.textarea)) {
  6238. for (var i = 0, ti, tis = domUtils.getElementsByTagName(form, 'textarea'); ti = tis[i++];) {
  6239. if (ti.id == 'ueditor_textarea_' + editor.options.textarea) {
  6240. textarea = ti;
  6241. break;
  6242. }
  6243. }
  6244. } else {
  6245. textarea = editor.textarea;
  6246. }
  6247. }
  6248. if (!textarea) {
  6249. form.appendChild(textarea = domUtils.createElement(document, 'textarea', {
  6250. 'name': editor.options.textarea,
  6251. 'id': 'ueditor_textarea_' + editor.options.textarea,
  6252. 'style': "display:none"
  6253. }));
  6254. //不要产生多个textarea
  6255. editor.textarea = textarea;
  6256. }
  6257. !textarea.getAttribute('name') && textarea.setAttribute('name', editor.options.textarea);
  6258. textarea.value = editor.hasContents() ?
  6259. (editor.options.allHtmlEnabled ? editor.getAllHtml() : editor.getContent(null, null, true)) :
  6260. ''
  6261. }
  6262. function loadPlugins(me) {
  6263. //初始化插件
  6264. for (var pi in UE.plugins) {
  6265. UE.plugins[pi].call(me);
  6266. }
  6267. }
  6268. function checkCurLang(I18N) {
  6269. for (var lang in I18N) {
  6270. return lang
  6271. }
  6272. }
  6273. function langReadied(me) {
  6274. me.langIsReady = true;
  6275. me.fireEvent("langReady");
  6276. }
  6277. /**
  6278. * 编辑器准备就绪后会触发该事件
  6279. * @module UE
  6280. * @class Editor
  6281. * @event ready
  6282. * @remind render方法执行完成之后,会触发该事件
  6283. * @remind
  6284. * @example
  6285. * ```javascript
  6286. * editor.addListener( 'ready', function( editor ) {
  6287. * editor.execCommand( 'focus' ); //编辑器家在完成后,让编辑器拿到焦点
  6288. * } );
  6289. * ```
  6290. */
  6291. /**
  6292. * 执行destroy方法,会触发该事件
  6293. * @module UE
  6294. * @class Editor
  6295. * @event destroy
  6296. * @see UE.Editor:destroy()
  6297. */
  6298. /**
  6299. * 执行reset方法,会触发该事件
  6300. * @module UE
  6301. * @class Editor
  6302. * @event reset
  6303. * @see UE.Editor:reset()
  6304. */
  6305. /**
  6306. * 执行focus方法,会触发该事件
  6307. * @module UE
  6308. * @class Editor
  6309. * @event focus
  6310. * @see UE.Editor:focus(Boolean)
  6311. */
  6312. /**
  6313. * 语言加载完成会触发该事件
  6314. * @module UE
  6315. * @class Editor
  6316. * @event langReady
  6317. */
  6318. /**
  6319. * 运行命令之后会触发该命令
  6320. * @module UE
  6321. * @class Editor
  6322. * @event beforeExecCommand
  6323. */
  6324. /**
  6325. * 运行命令之后会触发该命令
  6326. * @module UE
  6327. * @class Editor
  6328. * @event afterExecCommand
  6329. */
  6330. /**
  6331. * 运行命令之前会触发该命令
  6332. * @module UE
  6333. * @class Editor
  6334. * @event firstBeforeExecCommand
  6335. */
  6336. /**
  6337. * 在getContent方法执行之前会触发该事件
  6338. * @module UE
  6339. * @class Editor
  6340. * @event beforeGetContent
  6341. * @see UE.Editor:getContent()
  6342. */
  6343. /**
  6344. * 在getContent方法执行之后会触发该事件
  6345. * @module UE
  6346. * @class Editor
  6347. * @event afterGetContent
  6348. * @see UE.Editor:getContent()
  6349. */
  6350. /**
  6351. * 在getAllHtml方法执行时会触发该事件
  6352. * @module UE
  6353. * @class Editor
  6354. * @event getAllHtml
  6355. * @see UE.Editor:getAllHtml()
  6356. */
  6357. /**
  6358. * 在setContent方法执行之前会触发该事件
  6359. * @module UE
  6360. * @class Editor
  6361. * @event beforeSetContent
  6362. * @see UE.Editor:setContent(String)
  6363. */
  6364. /**
  6365. * 在setContent方法执行之后会触发该事件
  6366. * @module UE
  6367. * @class Editor
  6368. * @event afterSetContent
  6369. * @see UE.Editor:setContent(String)
  6370. */
  6371. /**
  6372. * 每当编辑器内部选区发生改变时,将触发该事件
  6373. * @event selectionchange
  6374. * @warning 该事件的触发非常频繁,不建议在该事件的处理过程中做重量级的处理
  6375. * @example
  6376. * ```javascript
  6377. * editor.addListener( 'selectionchange', function( editor ) {
  6378. * console.log('选区发生改变');
  6379. * }
  6380. */
  6381. /**
  6382. * 在所有selectionchange的监听函数执行之前,会触发该事件
  6383. * @module UE
  6384. * @class Editor
  6385. * @event beforeSelectionChange
  6386. * @see UE.Editor:selectionchange
  6387. */
  6388. /**
  6389. * 在所有selectionchange的监听函数执行完之后,会触发该事件
  6390. * @module UE
  6391. * @class Editor
  6392. * @event afterSelectionChange
  6393. * @see UE.Editor:selectionchange
  6394. */
  6395. /**
  6396. * 编辑器内容发生改变时会触发该事件
  6397. * @module UE
  6398. * @class Editor
  6399. * @event contentChange
  6400. */
  6401. /**
  6402. * 以默认参数构建一个编辑器实例
  6403. * @constructor
  6404. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6405. * @example
  6406. * ```javascript
  6407. * var editor = new UE.Editor();
  6408. * editor.execCommand('blod');
  6409. * ```
  6410. * @see UE.Config
  6411. */
  6412. /**
  6413. * 以给定的参数集合创建一个编辑器实例,对于未指定的参数,将应用默认参数。
  6414. * @constructor
  6415. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6416. * @param { Object } setting 创建编辑器的参数
  6417. * @example
  6418. * ```javascript
  6419. * var editor = new UE.Editor();
  6420. * editor.execCommand('blod');
  6421. * ```
  6422. * @see UE.Config
  6423. */
  6424. var Editor = UE.Editor = function (options) {
  6425. var me = this;
  6426. me.uid = uid++;
  6427. EventBase.call(me);
  6428. me.commands = {};
  6429. me.options = utils.extend(utils.clone(options || {}), UEDITOR_CONFIG, true);
  6430. me.shortcutkeys = {};
  6431. me.inputRules = [];
  6432. me.outputRules = [];
  6433. //设置默认的常用属性
  6434. me.setOpt(Editor.defaultOptions(me));
  6435. /* 尝试异步加载后台配置 */
  6436. me.loadServerConfig();
  6437. if (!utils.isEmptyObject(UE.I18N)) {
  6438. //修改默认的语言类型
  6439. me.options.lang = checkCurLang(UE.I18N);
  6440. UE.plugin.load(me);
  6441. langReadied(me);
  6442. } else {
  6443. utils.loadFile(document, {
  6444. src: me.options.langPath + me.options.lang + "/" + me.options.lang + ".js",
  6445. tag: "script",
  6446. type: "text/javascript",
  6447. defer: "defer"
  6448. }, function () {
  6449. UE.plugin.load(me);
  6450. langReadied(me);
  6451. });
  6452. }
  6453. UE.instants['ueditorInstant' + me.uid] = me;
  6454. };
  6455. Editor.prototype = {
  6456. registerCommand: function (name, obj) {
  6457. this.commands[name] = obj;
  6458. },
  6459. /**
  6460. * 编辑器对外提供的监听ready事件的接口, 通过调用该方法,达到的效果与监听ready事件是一致的
  6461. * @method ready
  6462. * @param { Function } fn 编辑器ready之后所执行的回调, 如果在注册事件之前编辑器已经ready,将会
  6463. * 立即触发该回调。
  6464. * @remind 需要等待编辑器加载完成后才能执行的代码,可以使用该方法传入
  6465. * @example
  6466. * ```javascript
  6467. * editor.ready( function( editor ) {
  6468. * editor.setContent('初始化完毕');
  6469. * } );
  6470. * ```
  6471. * @see UE.Editor.event:ready
  6472. */
  6473. ready: function (fn) {
  6474. var me = this;
  6475. if (fn) {
  6476. me.isReady ? fn.apply(me) : me.addListener('ready', fn);
  6477. }
  6478. },
  6479. /**
  6480. * 该方法是提供给插件里面使用,设置配置项默认值
  6481. * @method setOpt
  6482. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6483. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6484. * @param { String } key 编辑器的可接受的选项名称
  6485. * @param { * } val 该选项可接受的值
  6486. * @example
  6487. * ```javascript
  6488. * editor.setOpt( 'initContent', '欢迎使用编辑器' );
  6489. * ```
  6490. */
  6491. /**
  6492. * 该方法是提供给插件里面使用,以{key:value}集合的方式设置插件内用到的配置项默认值
  6493. * @method setOpt
  6494. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6495. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6496. * @param { Object } options 将要设置的选项的键值对对象
  6497. * @example
  6498. * ```javascript
  6499. * editor.setOpt( {
  6500. * 'initContent': '欢迎使用编辑器'
  6501. * } );
  6502. * ```
  6503. */
  6504. setOpt: function (key, val) {
  6505. var obj = {};
  6506. if (utils.isString(key)) {
  6507. obj[key] = val
  6508. } else {
  6509. obj = key;
  6510. }
  6511. utils.extend(this.options, obj, true);
  6512. },
  6513. getOpt: function (key) {
  6514. return this.options[key]
  6515. },
  6516. /**
  6517. * 销毁编辑器实例,使用textarea代替
  6518. * @method destroy
  6519. * @example
  6520. * ```javascript
  6521. * editor.destroy();
  6522. * ```
  6523. */
  6524. destroy: function () {
  6525. var me = this;
  6526. me.fireEvent('destroy');
  6527. var container = me.container.parentNode;
  6528. var textarea = me.textarea;
  6529. if (!textarea) {
  6530. textarea = document.createElement('textarea');
  6531. container.parentNode.insertBefore(textarea, container);
  6532. } else {
  6533. textarea.style.display = ''
  6534. }
  6535. textarea.style.width = me.iframe.offsetWidth + 'px';
  6536. textarea.style.height = me.iframe.offsetHeight + 'px';
  6537. textarea.value = me.getContent();
  6538. textarea.id = me.key;
  6539. container.innerHTML = '';
  6540. domUtils.remove(container);
  6541. var key = me.key;
  6542. //trace:2004
  6543. for (var p in me) {
  6544. if (me.hasOwnProperty(p)) {
  6545. delete this[p];
  6546. }
  6547. }
  6548. UE.delEditor(key);
  6549. },
  6550. /**
  6551. * 渲染编辑器的DOM到指定容器
  6552. * @method render
  6553. * @param { String } containerId 指定一个容器ID
  6554. * @remind 执行该方法,会触发ready事件
  6555. * @warning 必须且只能调用一次
  6556. */
  6557. /**
  6558. * 渲染编辑器的DOM到指定容器
  6559. * @method render
  6560. * @param { Element } containerDom 直接指定容器对象
  6561. * @remind 执行该方法,会触发ready事件
  6562. * @warning 必须且只能调用一次
  6563. */
  6564. render: function (container) {
  6565. var me = this,
  6566. options = me.options,
  6567. getStyleValue = function (attr) {
  6568. return parseInt(domUtils.getComputedStyle(container, attr));
  6569. };
  6570. if (utils.isString(container)) {
  6571. container = document.getElementById(container);
  6572. }
  6573. if (container) {
  6574. if (options.initialFrameWidth) {
  6575. options.minFrameWidth = options.initialFrameWidth
  6576. } else {
  6577. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6578. }
  6579. if (options.initialFrameHeight) {
  6580. options.minFrameHeight = options.initialFrameHeight
  6581. } else {
  6582. options.initialFrameHeight = options.minFrameHeight = container.offsetHeight;
  6583. }
  6584. container.style.width = /%$/.test(options.initialFrameWidth) ? '100%' : options.initialFrameWidth -
  6585. getStyleValue("padding-left") - getStyleValue("padding-right") + 'px';
  6586. container.style.height = /%$/.test(options.initialFrameHeight) ? '100%' : options.initialFrameHeight -
  6587. getStyleValue("padding-top") - getStyleValue("padding-bottom") + 'px';
  6588. container.style.zIndex = options.zIndex;
  6589. var html = (ie && browser.version < 9 ? '' : '<!DOCTYPE html>') +
  6590. '<html xmlns=\'http://www.w3.org/1999/xhtml\' class=\'view\' ><head>' +
  6591. '<style type=\'text/css\'>' +
  6592. //设置四周的留边
  6593. '.view{padding:0;word-wrap:break-word;cursor:text;height:90%;}\n' +
  6594. //设置默认字体和字号
  6595. //font-family不能呢随便改,在safari下fillchar会有解析问题
  6596. 'body{margin:8px;font-family:sans-serif;font-size:16px;}' +
  6597. //设置段落间距
  6598. 'p{margin:5px 0;}</style>' +
  6599. (options.iframeCssUrl ? '<link rel=\'stylesheet\' type=\'text/css\' href=\'' + utils.unhtml(options.iframeCssUrl) + '\'/>' : '') +
  6600. (options.initialStyle ? '<style>' + options.initialStyle + '</style>' : '') +
  6601. '</head><body class=\'view\' ></body>' +
  6602. '<script type=\'text/javascript\' ' + (ie ? 'defer=\'defer\'' : '') + ' id=\'_initialScript\'>' +
  6603. 'setTimeout(function(){editor = window.parent.UE.instants[\'ueditorInstant' + me.uid + '\'];editor._setup(document);},0);' +
  6604. 'var _tmpScript = document.getElementById(\'_initialScript\');_tmpScript.parentNode.removeChild(_tmpScript);</script></html>';
  6605. container.appendChild(domUtils.createElement(document, 'iframe', {
  6606. id: 'ueditor_' + me.uid,
  6607. width: "100%",
  6608. height: "100%",
  6609. frameborder: "0",
  6610. //先注释掉了,加的原因忘记了,但开启会直接导致全屏模式下内容多时不会出现滚动条
  6611. // scrolling :'no',
  6612. src: 'javascript:void(function(){document.open();' + (options.customDomain && document.domain != location.hostname ? 'document.domain="' + document.domain + '";' : '') +
  6613. 'document.write("' + html + '");document.close();}())'
  6614. }));
  6615. container.style.overflow = 'hidden';
  6616. //解决如果是给定的百分比,会导致高度算不对的问题
  6617. setTimeout(function () {
  6618. if (/%$/.test(options.initialFrameWidth)) {
  6619. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6620. //如果这里给定宽度,会导致ie在拖动窗口大小时,编辑区域不随着变化
  6621. // container.style.width = options.initialFrameWidth + 'px';
  6622. }
  6623. if (/%$/.test(options.initialFrameHeight)) {
  6624. options.minFrameHeight = options.initialFrameHeight = container.offsetHeight;
  6625. container.style.height = options.initialFrameHeight + 'px';
  6626. }
  6627. })
  6628. }
  6629. },
  6630. /**
  6631. * 编辑器初始化
  6632. * @method _setup
  6633. * @private
  6634. * @param { Element } doc 编辑器Iframe中的文档对象
  6635. */
  6636. _setup: function (doc) {
  6637. var me = this,
  6638. options = me.options;
  6639. if (ie) {
  6640. doc.body.disabled = true;
  6641. doc.body.contentEditable = true;
  6642. doc.body.disabled = false;
  6643. } else {
  6644. doc.body.contentEditable = true;
  6645. }
  6646. doc.body.spellcheck = false;
  6647. me.document = doc;
  6648. me.window = doc.defaultView || doc.parentWindow;
  6649. me.iframe = me.window.frameElement;
  6650. me.body = doc.body;
  6651. me.selection = new dom.Selection(doc);
  6652. //gecko初始化就能得到range,无法判断isFocus了
  6653. var geckoSel;
  6654. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  6655. geckoSel.removeAllRanges();
  6656. }
  6657. this._initEvents();
  6658. //为form提交提供一个隐藏的textarea
  6659. for (var form = this.iframe.parentNode; !domUtils.isBody(form); form = form.parentNode) {
  6660. if (form.tagName == 'FORM') {
  6661. me.form = form;
  6662. if (me.options.autoSyncData) {
  6663. domUtils.on(me.window, 'blur', function () {
  6664. setValue(form, me);
  6665. });
  6666. } else {
  6667. domUtils.on(form, 'submit', function () {
  6668. setValue(this, me);
  6669. });
  6670. }
  6671. break;
  6672. }
  6673. }
  6674. if (options.initialContent) {
  6675. if (options.autoClearinitialContent) {
  6676. var oldExecCommand = me.execCommand;
  6677. me.execCommand = function () {
  6678. me.fireEvent('firstBeforeExecCommand');
  6679. return oldExecCommand.apply(me, arguments);
  6680. };
  6681. this._setDefaultContent(options.initialContent);
  6682. } else
  6683. this.setContent(options.initialContent, false, true);
  6684. }
  6685. //编辑器不能为空内容
  6686. if (domUtils.isEmptyNode(me.body)) {
  6687. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  6688. }
  6689. //如果要求focus, 就把光标定位到内容开始
  6690. if (options.focus) {
  6691. setTimeout(function () {
  6692. me.focus(me.options.focusInEnd);
  6693. //如果自动清除开着,就不需要做selectionchange;
  6694. !me.options.autoClearinitialContent && me._selectionChange();
  6695. }, 0);
  6696. }
  6697. if (!me.container) {
  6698. me.container = this.iframe.parentNode;
  6699. }
  6700. if (options.fullscreen && me.ui) {
  6701. me.ui.setFullScreen(true);
  6702. }
  6703. try {
  6704. me.document.execCommand('2D-position', false, false);
  6705. } catch (e) {
  6706. }
  6707. try {
  6708. me.document.execCommand('enableInlineTableEditing', false, false);
  6709. } catch (e) {
  6710. }
  6711. try {
  6712. me.document.execCommand('enableObjectResizing', false, false);
  6713. } catch (e) {
  6714. }
  6715. //挂接快捷键
  6716. me._bindshortcutKeys();
  6717. me.isReady = 1;
  6718. me.fireEvent('ready');
  6719. options.onready && options.onready.call(me);
  6720. if (!browser.ie9below) {
  6721. domUtils.on(me.window, ['blur', 'focus'], function (e) {
  6722. //chrome下会出现alt+tab切换时,导致选区位置不对
  6723. if (e.type == 'blur') {
  6724. me._bakRange = me.selection.getRange();
  6725. try {
  6726. me._bakNativeRange = me.selection.getNative().getRangeAt(0);
  6727. me.selection.getNative().removeAllRanges();
  6728. } catch (e) {
  6729. me._bakNativeRange = null;
  6730. }
  6731. } else {
  6732. try {
  6733. me._bakRange && me._bakRange.select();
  6734. } catch (e) {
  6735. }
  6736. }
  6737. });
  6738. }
  6739. //trace:1518 ff3.6body不够寛,会导致点击空白处无法获得焦点
  6740. if (browser.gecko && browser.version <= 10902) {
  6741. //修复ff3.6初始化进来,不能点击获得焦点
  6742. me.body.contentEditable = false;
  6743. setTimeout(function () {
  6744. me.body.contentEditable = true;
  6745. }, 100);
  6746. setInterval(function () {
  6747. me.body.style.height = me.iframe.offsetHeight - 20 + 'px'
  6748. }, 100)
  6749. }
  6750. !options.isShow && me.setHide();
  6751. options.readonly && me.setDisabled();
  6752. },
  6753. /**
  6754. * 同步数据到编辑器所在的form
  6755. * 从编辑器的容器节点向上查找form元素,若找到,就同步编辑内容到找到的form里,为提交数据做准备,主要用于是手动提交的情况
  6756. * 后台取得数据的键值,使用你容器上的name属性,如果没有就使用参数里的textarea项
  6757. * @method sync
  6758. * @example
  6759. * ```javascript
  6760. * editor.sync();
  6761. * form.sumbit(); //form变量已经指向了form元素
  6762. * ```
  6763. */
  6764. /**
  6765. * 根据传入的formId,在页面上查找要同步数据的表单,若找到,就同步编辑内容到找到的form里,为提交数据做准备
  6766. * 后台取得数据的键值,该键值默认使用给定的编辑器容器的name属性,如果没有name属性则使用参数项里给定的“textarea”项
  6767. * @method sync
  6768. * @param { String } formID 指定一个要同步数据的form的id,编辑器的数据会同步到你指定form下
  6769. */
  6770. sync: function (formId) {
  6771. var me = this,
  6772. form = formId ? document.getElementById(formId) :
  6773. domUtils.findParent(me.iframe.parentNode, function (node) {
  6774. return node.tagName == 'FORM'
  6775. }, true);
  6776. form && setValue(form, me);
  6777. },
  6778. /**
  6779. * 设置编辑器高度
  6780. * @method setHeight
  6781. * @remind 当配置项autoHeightEnabled为真时,该方法无效
  6782. * @param { Number } number 设置的高度值,纯数值,不带单位
  6783. * @example
  6784. * ```javascript
  6785. * editor.setHeight(number);
  6786. * ```
  6787. */
  6788. setHeight: function (height, notSetHeight) {
  6789. if (height !== parseInt(this.iframe.parentNode.style.height)) {
  6790. this.iframe.parentNode.style.height = height + 'px';
  6791. }
  6792. !notSetHeight && (this.options.minFrameHeight = this.options.initialFrameHeight = height);
  6793. this.body.style.height = height + 'px';
  6794. !notSetHeight && this.trigger('setHeight')
  6795. },
  6796. /**
  6797. * 为编辑器的编辑命令提供快捷键
  6798. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6799. * @method addshortcutkey
  6800. * @param { Object } keyset 命令名和快捷键键值对对象,多个按钮的快捷键用“+”分隔
  6801. * @example
  6802. * ```javascript
  6803. * editor.addshortcutkey({
  6804. * "Bold" : "ctrl+66",//^B
  6805. * "Italic" : "ctrl+73", //^I
  6806. * });
  6807. * ```
  6808. */
  6809. /**
  6810. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6811. * @method addshortcutkey
  6812. * @param { String } cmd 触发快捷键时,响应的命令
  6813. * @param { String } keys 快捷键的字符串,多个按钮用“+”分隔
  6814. * @example
  6815. * ```javascript
  6816. * editor.addshortcutkey("Underline", "ctrl+85"); //^U
  6817. * ```
  6818. */
  6819. addshortcutkey: function (cmd, keys) {
  6820. var obj = {};
  6821. if (keys) {
  6822. obj[cmd] = keys
  6823. } else {
  6824. obj = cmd;
  6825. }
  6826. utils.extend(this.shortcutkeys, obj)
  6827. },
  6828. /**
  6829. * 对编辑器设置keydown事件监听,绑定快捷键和命令,当快捷键组合触发成功,会响应对应的命令
  6830. * @method _bindshortcutKeys
  6831. * @private
  6832. */
  6833. _bindshortcutKeys: function () {
  6834. var me = this, shortcutkeys = this.shortcutkeys;
  6835. me.addListener('keydown', function (type, e) {
  6836. var keyCode = e.keyCode || e.which;
  6837. for (var i in shortcutkeys) {
  6838. var tmp = shortcutkeys[i].split(',');
  6839. for (var t = 0, ti; ti = tmp[t++];) {
  6840. ti = ti.split(':');
  6841. var key = ti[0], param = ti[1];
  6842. if (/^(ctrl)(\+shift)?\+(\d+)$/.test(key.toLowerCase()) || /^(\d+)$/.test(key)) {
  6843. if (((RegExp.$1 == 'ctrl' ? (e.ctrlKey || e.metaKey) : 0)
  6844. && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1)
  6845. && keyCode == RegExp.$3
  6846. ) ||
  6847. keyCode == RegExp.$1
  6848. ) {
  6849. if (me.queryCommandState(i, param) != -1)
  6850. me.execCommand(i, param);
  6851. domUtils.preventDefault(e);
  6852. }
  6853. }
  6854. }
  6855. }
  6856. });
  6857. },
  6858. /**
  6859. * 获取编辑器的内容
  6860. * @method getContent
  6861. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6862. * @return { String } 编辑器的内容字符串, 如果编辑器的内容为空,或者是空的标签内容(如:”&lt;p&gt;&lt;br/&gt;&lt;/p&gt;“), 则返回空字符串
  6863. * @example
  6864. * ```javascript
  6865. * //编辑器html内容:<p>1<strong>2<em>34</em>5</strong>6</p>
  6866. * var content = editor.getContent(); //返回值:<p>1<strong>2<em>34</em>5</strong>6</p>
  6867. * ```
  6868. */
  6869. /**
  6870. * 获取编辑器的内容。 可以通过参数定义编辑器内置的判空规则
  6871. * @method getContent
  6872. * @param { Function } fn 自定的判空规则, 要求该方法返回一个boolean类型的值,
  6873. * 代表当前编辑器的内容是否空,
  6874. * 如果返回true, 则该方法将直接返回空字符串;如果返回false,则编辑器将返回
  6875. * 经过内置过滤规则处理后的内容。
  6876. * @remind 该方法在处理包含有初始化内容的时候能起到很好的作用。
  6877. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6878. * @return { String } 编辑器的内容字符串
  6879. * @example
  6880. * ```javascript
  6881. * // editor 是一个编辑器的实例
  6882. * var content = editor.getContent( function ( editor ) {
  6883. * return editor.body.innerHTML === '欢迎使用UEditor'; //返回空字符串
  6884. * } );
  6885. * ```
  6886. */
  6887. getContent: function (cmd, fn, notSetCursor, ignoreBlank, formatter) {
  6888. var me = this;
  6889. if (cmd && utils.isFunction(cmd)) {
  6890. fn = cmd;
  6891. cmd = '';
  6892. }
  6893. if (fn ? !fn() : !this.hasContents()) {
  6894. return '';
  6895. }
  6896. me.fireEvent('beforegetcontent');
  6897. var root = UE.htmlparser(me.body.innerHTML, ignoreBlank);
  6898. me.filterOutputRule(root);
  6899. me.fireEvent('aftergetcontent', cmd, root);
  6900. return root.toHtml(formatter);
  6901. },
  6902. /**
  6903. * 取得完整的html代码,可以直接显示成完整的html文档
  6904. * @method getAllHtml
  6905. * @return { String } 编辑器的内容html文档字符串
  6906. * @eaxmple
  6907. * ```javascript
  6908. * editor.getAllHtml(); //返回格式大致是: <html><head>...</head><body>...</body></html>
  6909. * ```
  6910. */
  6911. getAllHtml: function () {
  6912. var me = this,
  6913. headHtml = [],
  6914. html = '';
  6915. me.fireEvent('getAllHtml', headHtml);
  6916. if (browser.ie && browser.version > 8) {
  6917. var headHtmlForIE9 = '';
  6918. utils.each(me.document.styleSheets, function (si) {
  6919. headHtmlForIE9 += (si.href ? '<link rel="stylesheet" type="text/css" href="' + si.href + '" />' : '<style>' + si.cssText + '</style>');
  6920. });
  6921. utils.each(me.document.getElementsByTagName('script'), function (si) {
  6922. headHtmlForIE9 += si.outerHTML;
  6923. });
  6924. }
  6925. return '<html><head>' + (me.options.charset ? '<meta http-equiv="Content-Type" content="text/html; charset=' + me.options.charset + '"/>' : '')
  6926. + (headHtmlForIE9 || me.document.getElementsByTagName('head')[0].innerHTML) + headHtml.join('\n') + '</head>'
  6927. + '<body ' + (ie && browser.version < 9 ? 'class="view"' : '') + '>' + me.getContent(null, null, true) + '</body></html>';
  6928. },
  6929. /**
  6930. * 得到编辑器的纯文本内容,但会保留段落格式
  6931. * @method getPlainTxt
  6932. * @return { String } 编辑器带段落格式的纯文本内容字符串
  6933. * @example
  6934. * ```javascript
  6935. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6936. * console.log(editor.getPlainTxt()); //输出:"1\n2\n
  6937. * ```
  6938. */
  6939. getPlainTxt: function () {
  6940. var reg = new RegExp(domUtils.fillChar, 'g'),
  6941. html = this.body.innerHTML.replace(/[\n\r]/g, '');//ie要先去了\n在处理
  6942. html = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
  6943. .replace(/<br\/?>/gi, '\n')
  6944. .replace(/<[^>/]+>/g, '')
  6945. .replace(/(\n)?<\/([^>]+)>/g, function (a, b, c) {
  6946. return dtd.$block[c] ? '\n' : b ? b : '';
  6947. });
  6948. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6949. return html.replace(reg, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' ');
  6950. },
  6951. /**
  6952. * 获取编辑器中的纯文本内容,没有段落格式
  6953. * @method getContentTxt
  6954. * @return { String } 编辑器不带段落格式的纯文本内容字符串
  6955. * @example
  6956. * ```javascript
  6957. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6958. * console.log(editor.getPlainTxt()); //输出:"12
  6959. * ```
  6960. */
  6961. getContentTxt: function () {
  6962. var reg = new RegExp(domUtils.fillChar, 'g');
  6963. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6964. return this.body[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').replace(/\u00a0/g, ' ');
  6965. },
  6966. /**
  6967. * 设置编辑器的内容,可修改编辑器当前的html内容
  6968. * @method setContent
  6969. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6970. * @warning 该方法会触发selectionchange事件
  6971. * @param { String } html 要插入的html内容
  6972. * @example
  6973. * ```javascript
  6974. * editor.getContent('<p>test</p>');
  6975. * ```
  6976. */
  6977. /**
  6978. * 设置编辑器的内容,可修改编辑器当前的html内容
  6979. * @method setContent
  6980. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6981. * @warning 该方法会触发selectionchange事件
  6982. * @param { String } html 要插入的html内容
  6983. * @param { Boolean } isAppendTo 若传入true,不清空原来的内容,在最后插入内容,否则,清空内容再插入
  6984. * @example
  6985. * ```javascript
  6986. * //假设设置前的编辑器内容是 <p>old text</p>
  6987. * editor.setContent('<p>new text</p>', true); //插入的结果是<p>old text</p><p>new text</p>
  6988. * ```
  6989. */
  6990. setContent: function (html, isAppendTo, notFireSelectionchange) {
  6991. var me = this;
  6992. me.fireEvent('beforesetcontent', html);
  6993. var root = UE.htmlparser(html);
  6994. me.filterInputRule(root);
  6995. html = root.toHtml();
  6996. me.body.innerHTML = (isAppendTo ? me.body.innerHTML : '') + html;
  6997. function isCdataDiv(node) {
  6998. return node.tagName == 'DIV' && node.getAttribute('cdata_tag');
  6999. }
  7000. //给文本或者inline节点套p标签
  7001. if (me.options.enterTag == 'p') {
  7002. var child = this.body.firstChild, tmpNode;
  7003. if (!child || child.nodeType == 1 &&
  7004. (dtd.$cdata[child.tagName] || isCdataDiv(child) ||
  7005. domUtils.isCustomeNode(child)
  7006. )
  7007. && child === this.body.lastChild) {
  7008. this.body.innerHTML = '<p>' + (browser.ie ? '&nbsp;' : '<br/>') + '</p>' + this.body.innerHTML;
  7009. } else {
  7010. var p = me.document.createElement('p');
  7011. while (child) {
  7012. while (child && (child.nodeType == 3 || child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName])) {
  7013. tmpNode = child.nextSibling;
  7014. p.appendChild(child);
  7015. child = tmpNode;
  7016. }
  7017. if (p.firstChild) {
  7018. if (!child) {
  7019. me.body.appendChild(p);
  7020. break;
  7021. } else {
  7022. child.parentNode.insertBefore(p, child);
  7023. p = me.document.createElement('p');
  7024. }
  7025. }
  7026. child = child.nextSibling;
  7027. }
  7028. }
  7029. }
  7030. me.fireEvent('aftersetcontent');
  7031. me.fireEvent('contentchange');
  7032. !notFireSelectionchange && me._selectionChange();
  7033. //清除保存的选区
  7034. me._bakRange = me._bakIERange = me._bakNativeRange = null;
  7035. //trace:1742 setContent后gecko能得到焦点问题
  7036. var geckoSel;
  7037. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  7038. geckoSel.removeAllRanges();
  7039. }
  7040. if (me.options.autoSyncData) {
  7041. me.form && setValue(me.form, me);
  7042. }
  7043. },
  7044. /**
  7045. * 让编辑器获得焦点,默认focus到编辑器头部
  7046. * @method focus
  7047. * @example
  7048. * ```javascript
  7049. * editor.focus()
  7050. * ```
  7051. */
  7052. /**
  7053. * 让编辑器获得焦点,toEnd确定focus位置
  7054. * @method focus
  7055. * @param { Boolean } toEnd 默认focus到编辑器头部,toEnd为true时focus到内容尾部
  7056. * @example
  7057. * ```javascript
  7058. * editor.focus(true)
  7059. * ```
  7060. */
  7061. focus: function (toEnd) {
  7062. try {
  7063. var me = this,
  7064. rng = me.selection.getRange();
  7065. if (toEnd) {
  7066. var node = me.body.lastChild;
  7067. if (node && node.nodeType == 1 && !dtd.$empty[node.tagName]) {
  7068. if (domUtils.isEmptyBlock(node)) {
  7069. rng.setStartAtFirst(node)
  7070. } else {
  7071. rng.setStartAtLast(node)
  7072. }
  7073. rng.collapse(true);
  7074. }
  7075. rng.setCursor(true);
  7076. } else {
  7077. if (!rng.collapsed && domUtils.isBody(rng.startContainer) && rng.startOffset == 0) {
  7078. var node = me.body.firstChild;
  7079. if (node && node.nodeType == 1 && !dtd.$empty[node.tagName]) {
  7080. rng.setStartAtFirst(node).collapse(true);
  7081. }
  7082. }
  7083. rng.select(true);
  7084. }
  7085. this.fireEvent('focus selectionchange');
  7086. } catch (e) {
  7087. }
  7088. },
  7089. isFocus: function () {
  7090. return this.selection.isFocus();
  7091. },
  7092. blur: function () {
  7093. var sel = this.selection.getNative();
  7094. if (sel.empty && browser.ie) {
  7095. var nativeRng = document.body.createTextRange();
  7096. nativeRng.moveToElementText(document.body);
  7097. nativeRng.collapse(true);
  7098. nativeRng.select();
  7099. sel.empty()
  7100. } else {
  7101. sel.removeAllRanges()
  7102. }
  7103. //this.fireEvent('blur selectionchange');
  7104. },
  7105. /**
  7106. * 初始化UE事件及部分事件代理
  7107. * @method _initEvents
  7108. * @private
  7109. */
  7110. _initEvents: function () {
  7111. var me = this,
  7112. doc = me.document,
  7113. win = me.window;
  7114. me._proxyDomEvent = utils.bind(me._proxyDomEvent, me);
  7115. domUtils.on(doc, ['click', 'contextmenu', 'mousedown', 'keydown', 'keyup', 'keypress', 'mouseup', 'mouseover', 'mouseout', 'selectstart'], me._proxyDomEvent);
  7116. domUtils.on(win, ['focus', 'blur'], me._proxyDomEvent);
  7117. domUtils.on(me.body, 'drop', function (e) {
  7118. //阻止ff下默认的弹出新页面打开图片
  7119. if (browser.gecko && e.stopPropagation) { e.stopPropagation(); }
  7120. me.fireEvent('contentchange')
  7121. });
  7122. domUtils.on(doc, ['mouseup', 'keydown'], function (evt) {
  7123. //特殊键不触发selectionchange
  7124. if (evt.type == 'keydown' && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)) {
  7125. return;
  7126. }
  7127. if (evt.button == 2) return;
  7128. me._selectionChange(250, evt);
  7129. });
  7130. },
  7131. /**
  7132. * 触发事件代理
  7133. * @method _proxyDomEvent
  7134. * @private
  7135. * @return { * } fireEvent的返回值
  7136. * @see UE.EventBase:fireEvent(String)
  7137. */
  7138. _proxyDomEvent: function (evt) {
  7139. if (this.fireEvent('before' + evt.type.replace(/^on/, '').toLowerCase()) === false) {
  7140. return false;
  7141. }
  7142. if (this.fireEvent(evt.type.replace(/^on/, ''), evt) === false) {
  7143. return false;
  7144. }
  7145. return this.fireEvent('after' + evt.type.replace(/^on/, '').toLowerCase())
  7146. },
  7147. /**
  7148. * 变化选区
  7149. * @method _selectionChange
  7150. * @private
  7151. */
  7152. _selectionChange: function (delay, evt) {
  7153. var me = this;
  7154. //有光标才做selectionchange 为了解决未focus时点击source不能触发更改工具栏状态的问题(source命令notNeedUndo=1)
  7155. // if ( !me.selection.isFocus() ){
  7156. // return;
  7157. // }
  7158. var hackForMouseUp = false;
  7159. var mouseX, mouseY;
  7160. if (browser.ie && browser.version < 9 && evt && evt.type == 'mouseup') {
  7161. var range = this.selection.getRange();
  7162. if (!range.collapsed) {
  7163. hackForMouseUp = true;
  7164. mouseX = evt.clientX;
  7165. mouseY = evt.clientY;
  7166. }
  7167. }
  7168. clearTimeout(_selectionChangeTimer);
  7169. _selectionChangeTimer = setTimeout(function () {
  7170. if (!me.selection || !me.selection.getNative()) {
  7171. return;
  7172. }
  7173. //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时,可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值.
  7174. //IE下如果用户是拖拽一段已选择文本,则不会触发mouseup事件,所以这里的特殊处理不会对其有影响
  7175. var ieRange;
  7176. if (hackForMouseUp && me.selection.getNative().type == 'None') {
  7177. ieRange = me.document.body.createTextRange();
  7178. try {
  7179. ieRange.moveToPoint(mouseX, mouseY);
  7180. } catch (ex) {
  7181. ieRange = null;
  7182. }
  7183. }
  7184. var bakGetIERange;
  7185. if (ieRange) {
  7186. bakGetIERange = me.selection.getIERange;
  7187. me.selection.getIERange = function () {
  7188. return ieRange;
  7189. };
  7190. }
  7191. me.selection.cache();
  7192. if (bakGetIERange) {
  7193. me.selection.getIERange = bakGetIERange;
  7194. }
  7195. if (me.selection._cachedRange && me.selection._cachedStartElement) {
  7196. me.fireEvent('beforeselectionchange');
  7197. // 第二个参数causeByUi为true代表由用户交互造成的selectionchange.
  7198. me.fireEvent('selectionchange', !!evt);
  7199. me.fireEvent('afterselectionchange');
  7200. me.selection.clear();
  7201. }
  7202. }, delay || 50);
  7203. },
  7204. /**
  7205. * 执行编辑命令
  7206. * @method _callCmdFn
  7207. * @private
  7208. * @param { String } fnName 函数名称
  7209. * @param { * } args 传给命令函数的参数
  7210. * @return { * } 返回命令函数运行的返回值
  7211. */
  7212. _callCmdFn: function (fnName, args) {
  7213. var cmdName = args[0].toLowerCase(),
  7214. cmd, cmdFn;
  7215. cmd = this.commands[cmdName] || UE.commands[cmdName];
  7216. cmdFn = cmd && cmd[fnName];
  7217. //没有querycommandstate或者没有command的都默认返回0
  7218. if ((!cmd || !cmdFn) && fnName == 'queryCommandState') {
  7219. return 0;
  7220. } else if (cmdFn) {
  7221. return cmdFn.apply(this, args);
  7222. }
  7223. },
  7224. /**
  7225. * 执行编辑命令cmdName,完成富文本编辑效果
  7226. * @method execCommand
  7227. * @param { String } cmdName 需要执行的命令
  7228. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7229. * @return { * } 返回命令函数运行的返回值
  7230. * @example
  7231. * ```javascript
  7232. * editor.execCommand(cmdName);
  7233. * ```
  7234. */
  7235. execCommand: function (cmdName) {
  7236. cmdName = cmdName.toLowerCase();
  7237. var me = this,
  7238. result,
  7239. cmd = me.commands[cmdName] || UE.commands[cmdName];
  7240. if (!cmd || !cmd.execCommand) {
  7241. return null;
  7242. }
  7243. if (!cmd.notNeedUndo && !me.__hasEnterExecCommand) {
  7244. me.__hasEnterExecCommand = true;
  7245. if (me.queryCommandState.apply(me, arguments) != -1) {
  7246. me.fireEvent('saveScene');
  7247. me.fireEvent.apply(me, ['beforeexeccommand', cmdName].concat(arguments));
  7248. result = this._callCmdFn('execCommand', arguments);
  7249. //保存场景时,做了内容对比,再看是否进行contentchange触发,这里多触发了一次,去掉
  7250. // (!cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange');
  7251. me.fireEvent.apply(me, ['afterexeccommand', cmdName].concat(arguments));
  7252. me.fireEvent('saveScene');
  7253. }
  7254. me.__hasEnterExecCommand = false;
  7255. } else {
  7256. result = this._callCmdFn('execCommand', arguments);
  7257. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange')
  7258. }
  7259. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me._selectionChange();
  7260. return result;
  7261. },
  7262. /**
  7263. * 根据传入的command命令,查选编辑器当前的选区,返回命令的状态
  7264. * @method queryCommandState
  7265. * @param { String } cmdName 需要查询的命令名称
  7266. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7267. * @return { Number } number 返回放前命令的状态,返回值三种情况:(-1|0|1)
  7268. * @example
  7269. * ```javascript
  7270. * editor.queryCommandState(cmdName) => (-1|0|1)
  7271. * ```
  7272. * @see COMMAND.LIST
  7273. */
  7274. queryCommandState: function (cmdName) {
  7275. return this._callCmdFn('queryCommandState', arguments);
  7276. },
  7277. /**
  7278. * 根据传入的command命令,查选编辑器当前的选区,根据命令返回相关的值
  7279. * @method queryCommandValue
  7280. * @param { String } cmdName 需要查询的命令名称
  7281. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7282. * @remind 只有部分插件有此方法
  7283. * @return { * } 返回每个命令特定的当前状态值
  7284. * @grammar editor.queryCommandValue(cmdName) => {*}
  7285. * @see COMMAND.LIST
  7286. */
  7287. queryCommandValue: function (cmdName) {
  7288. return this._callCmdFn('queryCommandValue', arguments);
  7289. },
  7290. /**
  7291. * 检查编辑区域中是否有内容
  7292. * @method hasContents
  7293. * @remind 默认有文本内容,或者有以下节点都不认为是空
  7294. * table,ul,ol,dl,iframe,area,base,col,hr,img,embed,input,link,meta,param
  7295. * @return { Boolean } 检查有内容返回true,否则返回false
  7296. * @example
  7297. * ```javascript
  7298. * editor.hasContents()
  7299. * ```
  7300. */
  7301. /**
  7302. * 检查编辑区域中是否有内容,若包含参数tags中的节点类型,直接返回true
  7303. * @method hasContents
  7304. * @param { Array } tags 传入数组判断时用到的节点类型
  7305. * @return { Boolean } 若文档中包含tags数组里对应的tag,返回true,否则返回false
  7306. * @example
  7307. * ```javascript
  7308. * editor.hasContents(['span']);
  7309. * ```
  7310. */
  7311. hasContents: function (tags) {
  7312. if (tags) {
  7313. for (var i = 0, ci; ci = tags[i++];) {
  7314. if (this.document.getElementsByTagName(ci).length > 0) {
  7315. return true;
  7316. }
  7317. }
  7318. }
  7319. if (!domUtils.isEmptyBlock(this.body)) {
  7320. return true
  7321. }
  7322. //随时添加,定义的特殊标签如果存在,不能认为是空
  7323. tags = ['div'];
  7324. for (i = 0; ci = tags[i++];) {
  7325. var nodes = domUtils.getElementsByTagName(this.document, ci);
  7326. for (var n = 0, cn; cn = nodes[n++];) {
  7327. if (domUtils.isCustomeNode(cn)) {
  7328. return true;
  7329. }
  7330. }
  7331. }
  7332. return false;
  7333. },
  7334. /**
  7335. * 重置编辑器,可用来做多个tab使用同一个编辑器实例
  7336. * @method reset
  7337. * @remind 此方法会清空编辑器内容,清空回退列表,会触发reset事件
  7338. * @example
  7339. * ```javascript
  7340. * editor.reset()
  7341. * ```
  7342. */
  7343. reset: function () {
  7344. this.fireEvent('reset');
  7345. },
  7346. /**
  7347. * 设置当前编辑区域可以编辑
  7348. * @method setEnabled
  7349. * @example
  7350. * ```javascript
  7351. * editor.setEnabled()
  7352. * ```
  7353. */
  7354. setEnabled: function () {
  7355. var me = this, range;
  7356. if (me.body.contentEditable == 'false') {
  7357. me.body.contentEditable = true;
  7358. range = me.selection.getRange();
  7359. //有可能内容丢失了
  7360. try {
  7361. range.moveToBookmark(me.lastBk);
  7362. delete me.lastBk
  7363. } catch (e) {
  7364. range.setStartAtFirst(me.body).collapse(true)
  7365. }
  7366. range.select(true);
  7367. if (me.bkqueryCommandState) {
  7368. me.queryCommandState = me.bkqueryCommandState;
  7369. delete me.bkqueryCommandState;
  7370. }
  7371. if (me.bkqueryCommandValue) {
  7372. me.queryCommandValue = me.bkqueryCommandValue;
  7373. delete me.bkqueryCommandValue;
  7374. }
  7375. me.fireEvent('selectionchange');
  7376. }
  7377. },
  7378. enable: function () {
  7379. return this.setEnabled();
  7380. },
  7381. /** 设置当前编辑区域不可编辑
  7382. * @method setDisabled
  7383. */
  7384. /** 设置当前编辑区域不可编辑,except中的命令除外
  7385. * @method setDisabled
  7386. * @param { String } except 例外命令的字符串
  7387. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7388. * @example
  7389. * ```javascript
  7390. * editor.setDisabled('bold'); //禁用工具栏中除加粗之外的所有功能
  7391. * ```
  7392. */
  7393. /** 设置当前编辑区域不可编辑,except中的命令除外
  7394. * @method setDisabled
  7395. * @param { Array } except 例外命令的字符串数组,数组中的命令仍然可以执行
  7396. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7397. * @example
  7398. * ```javascript
  7399. * editor.setDisabled(['bold','insertimage']); //禁用工具栏中除加粗和插入图片之外的所有功能
  7400. * ```
  7401. */
  7402. setDisabled: function (except) {
  7403. var me = this;
  7404. except = except ? utils.isArray(except) ? except : [except] : [];
  7405. if (me.body.contentEditable == 'true') {
  7406. if (!me.lastBk) {
  7407. me.lastBk = me.selection.getRange().createBookmark(true);
  7408. }
  7409. me.body.contentEditable = false;
  7410. me.bkqueryCommandState = me.queryCommandState;
  7411. me.bkqueryCommandValue = me.queryCommandValue;
  7412. me.queryCommandState = function (type) {
  7413. if (utils.indexOf(except, type) != -1) {
  7414. return me.bkqueryCommandState.apply(me, arguments);
  7415. }
  7416. return -1;
  7417. };
  7418. me.queryCommandValue = function (type) {
  7419. if (utils.indexOf(except, type) != -1) {
  7420. return me.bkqueryCommandValue.apply(me, arguments);
  7421. }
  7422. return null;
  7423. };
  7424. me.fireEvent('selectionchange');
  7425. }
  7426. },
  7427. disable: function (except) {
  7428. return this.setDisabled(except);
  7429. },
  7430. /**
  7431. * 设置默认内容
  7432. * @method _setDefaultContent
  7433. * @private
  7434. * @param { String } cont 要存入的内容
  7435. */
  7436. _setDefaultContent: function () {
  7437. function clear() {
  7438. var me = this;
  7439. if (me.document.getElementById('initContent')) {
  7440. me.body.innerHTML = '<p>' + (ie ? '' : '<br/>') + '</p>';
  7441. me.removeListener('firstBeforeExecCommand focus', clear);
  7442. setTimeout(function () {
  7443. me.focus();
  7444. me._selectionChange();
  7445. }, 0)
  7446. }
  7447. }
  7448. return function (cont) {
  7449. var me = this;
  7450. me.body.innerHTML = '<p id="initContent">' + cont + '</p>';
  7451. me.addListener('firstBeforeExecCommand focus', clear);
  7452. }
  7453. }(),
  7454. /**
  7455. * 显示编辑器
  7456. * @method setShow
  7457. * @example
  7458. * ```javascript
  7459. * editor.setShow()
  7460. * ```
  7461. */
  7462. setShow: function () {
  7463. var me = this, range = me.selection.getRange();
  7464. if (me.container.style.display == 'none') {
  7465. //有可能内容丢失了
  7466. try {
  7467. range.moveToBookmark(me.lastBk);
  7468. delete me.lastBk
  7469. } catch (e) {
  7470. range.setStartAtFirst(me.body).collapse(true)
  7471. }
  7472. //ie下focus实效,所以做了个延迟
  7473. setTimeout(function () {
  7474. range.select(true);
  7475. }, 100);
  7476. me.container.style.display = '';
  7477. }
  7478. },
  7479. show: function () {
  7480. return this.setShow();
  7481. },
  7482. /**
  7483. * 隐藏编辑器
  7484. * @method setHide
  7485. * @example
  7486. * ```javascript
  7487. * editor.setHide()
  7488. * ```
  7489. */
  7490. setHide: function () {
  7491. var me = this;
  7492. if (!me.lastBk) {
  7493. me.lastBk = me.selection.getRange().createBookmark(true);
  7494. }
  7495. me.container.style.display = 'none'
  7496. },
  7497. hide: function () {
  7498. return this.setHide();
  7499. },
  7500. /**
  7501. * 根据指定的路径,获取对应的语言资源
  7502. * @method getLang
  7503. * @param { String } path 路径根据的是lang目录下的语言文件的路径结构
  7504. * @return { Object | String } 根据路径返回语言资源的Json格式对象或者语言字符串
  7505. * @example
  7506. * ```javascript
  7507. * editor.getLang('contextMenu.delete'); //如果当前是中文,那返回是的是'删除'
  7508. * ```
  7509. */
  7510. getLang: function (path) {
  7511. // HaoChuan9421
  7512. if (!this.options) {
  7513. return '';
  7514. }
  7515. var lang = UE.I18N[this.options.lang];
  7516. if (!lang) {
  7517. throw Error("not import language file");
  7518. }
  7519. path = (path || "").split(".");
  7520. for (var i = 0, ci; ci = path[i++];) {
  7521. lang = lang[ci];
  7522. if (!lang) break;
  7523. }
  7524. return lang;
  7525. },
  7526. /**
  7527. * 计算编辑器html内容字符串的长度
  7528. * @method getContentLength
  7529. * @return { Number } 返回计算的长度
  7530. * @example
  7531. * ```javascript
  7532. * //编辑器html内容<p><strong>132</strong></p>
  7533. * editor.getContentLength() //返回27
  7534. * ```
  7535. */
  7536. /**
  7537. * 计算编辑器当前纯文本内容的长度
  7538. * @method getContentLength
  7539. * @param { Boolean } ingoneHtml 传入true时,只按照纯文本来计算
  7540. * @return { Number } 返回计算的长度,内容中有hr/img/iframe标签,长度加1
  7541. * @example
  7542. * ```javascript
  7543. * //编辑器html内容<p><strong>132</strong></p>
  7544. * editor.getContentLength() //返回3
  7545. * ```
  7546. */
  7547. getContentLength: function (ingoneHtml, tagNames) {
  7548. var count = this.getContent(false, false, true).length;
  7549. if (ingoneHtml) {
  7550. tagNames = (tagNames || []).concat(['hr', 'img', 'iframe']);
  7551. count = this.getContentTxt().replace(/[\t\r\n]+/g, '').length;
  7552. for (var i = 0, ci; ci = tagNames[i++];) {
  7553. count += this.document.getElementsByTagName(ci).length;
  7554. }
  7555. }
  7556. return count;
  7557. },
  7558. /**
  7559. * 注册输入过滤规则
  7560. * @method addInputRule
  7561. * @param { Function } rule 要添加的过滤规则
  7562. * @example
  7563. * ```javascript
  7564. * editor.addInputRule(function(root){
  7565. * $.each(root.getNodesByTagName('div'),function(i,node){
  7566. * node.tagName="p";
  7567. * });
  7568. * });
  7569. * ```
  7570. */
  7571. addInputRule: function (rule) {
  7572. this.inputRules.push(rule);
  7573. },
  7574. /**
  7575. * 执行注册的过滤规则
  7576. * @method filterInputRule
  7577. * @param { UE.uNode } root 要过滤的uNode节点
  7578. * @remind 执行editor.setContent方法和执行'inserthtml'命令后,会运行该过滤函数
  7579. * @example
  7580. * ```javascript
  7581. * editor.filterInputRule(editor.body);
  7582. * ```
  7583. * @see UE.Editor:addInputRule
  7584. */
  7585. filterInputRule: function (root) {
  7586. for (var i = 0, ci; ci = this.inputRules[i++];) {
  7587. ci.call(this, root)
  7588. }
  7589. },
  7590. /**
  7591. * 注册输出过滤规则
  7592. * @method addOutputRule
  7593. * @param { Function } rule 要添加的过滤规则
  7594. * @example
  7595. * ```javascript
  7596. * editor.addOutputRule(function(root){
  7597. * $.each(root.getNodesByTagName('p'),function(i,node){
  7598. * node.tagName="div";
  7599. * });
  7600. * });
  7601. * ```
  7602. */
  7603. addOutputRule: function (rule) {
  7604. this.outputRules.push(rule)
  7605. },
  7606. /**
  7607. * 根据输出过滤规则,过滤编辑器内容
  7608. * @method filterOutputRule
  7609. * @remind 执行editor.getContent方法的时候,会先运行该过滤函数
  7610. * @param { UE.uNode } root 要过滤的uNode节点
  7611. * @example
  7612. * ```javascript
  7613. * editor.filterOutputRule(editor.body);
  7614. * ```
  7615. * @see UE.Editor:addOutputRule
  7616. */
  7617. filterOutputRule: function (root) {
  7618. for (var i = 0, ci; ci = this.outputRules[i++];) {
  7619. ci.call(this, root)
  7620. }
  7621. },
  7622. /**
  7623. * 根据action名称获取请求的路径
  7624. * @method getActionUrl
  7625. * @remind 假如没有设置serverUrl,会根据imageUrl设置默认的controller路径
  7626. * @param { String } action action名称
  7627. * @example
  7628. * ```javascript
  7629. * editor.getActionUrl('config'); //返回 "/ueditor/php/controller.php?action=config"
  7630. * editor.getActionUrl('image'); //返回 "/ueditor/php/controller.php?action=uplaodimage"
  7631. * editor.getActionUrl('scrawl'); //返回 "/ueditor/php/controller.php?action=uplaodscrawl"
  7632. * editor.getActionUrl('imageManager'); //返回 "/ueditor/php/controller.php?action=listimage"
  7633. * ```
  7634. */
  7635. getActionUrl: function (action) {
  7636. var actionName = this.getOpt(action) || action,
  7637. imageUrl = this.getOpt('imageUrl'),
  7638. serverUrl = this.getOpt('serverUrl');
  7639. if (!serverUrl && imageUrl) {
  7640. serverUrl = imageUrl.replace(/^(.*[\/]).+([\.].+)$/, '$1controller$2');
  7641. }
  7642. if (serverUrl) {
  7643. serverUrl = serverUrl + (serverUrl.indexOf('?') == -1 ? '?' : '&') + 'action=' + (actionName || '');
  7644. return utils.formatUrl(serverUrl);
  7645. } else {
  7646. return '';
  7647. }
  7648. }
  7649. };
  7650. utils.inherits(Editor, EventBase);
  7651. })();
  7652. // core/Editor.defaultoptions.js
  7653. //维护编辑器一下默认的不在插件中的配置项
  7654. UE.Editor.defaultOptions = function (editor) {
  7655. var _url = editor.options.UEDITOR_HOME_URL;
  7656. return {
  7657. isShow: true,
  7658. initialContent: '',
  7659. initialStyle: '',
  7660. autoClearinitialContent: false,
  7661. iframeCssUrl: _url + 'themes/iframe.css',
  7662. textarea: 'editorValue',
  7663. focus: false,
  7664. focusInEnd: true,
  7665. autoClearEmptyNode: true,
  7666. fullscreen: false,
  7667. readonly: false,
  7668. zIndex: 999,
  7669. imagePopup: true,
  7670. enterTag: 'p',
  7671. customDomain: false,
  7672. lang: 'zh-cn',
  7673. langPath: _url + 'lang/',
  7674. theme: 'default',
  7675. themePath: _url + 'themes/',
  7676. allHtmlEnabled: false,
  7677. scaleEnabled: false,
  7678. tableNativeEditInFF: false,
  7679. autoSyncData: true,
  7680. fileNameFormat: '{time}{rand:6}'
  7681. }
  7682. };
  7683. // core/loadconfig.js
  7684. (function () {
  7685. UE.Editor.prototype.loadServerConfig = function () {
  7686. var me = this;
  7687. setTimeout(function () {
  7688. try {
  7689. me.options.imageUrl && me.setOpt('serverUrl', me.options.imageUrl.replace(/^(.*[\/]).+([\.].+)$/, '$1controller$2'));
  7690. var configUrl = me.getActionUrl('config'),
  7691. isJsonp = utils.isCrossDomainUrl(configUrl);
  7692. /* 发出ajax请求 */
  7693. me._serverConfigLoaded = false;
  7694. configUrl && UE.ajax.request(configUrl, {
  7695. 'method': 'GET',
  7696. 'dataType': isJsonp ? 'jsonp' : '',
  7697. 'onsuccess': function (r) {
  7698. try {
  7699. var config = isJsonp ? r : eval("(" + r.responseText + ")");
  7700. utils.extend(me.options, config);
  7701. me.fireEvent('serverConfigLoaded');
  7702. me._serverConfigLoaded = true;
  7703. } catch (e) {
  7704. showErrorMsg(me.getLang('loadconfigFormatError'));
  7705. }
  7706. },
  7707. 'onerror': function () {
  7708. showErrorMsg(me.getLang('loadconfigHttpError'));
  7709. }
  7710. });
  7711. } catch (e) {
  7712. showErrorMsg(me.getLang('loadconfigError'));
  7713. }
  7714. });
  7715. function showErrorMsg(msg) {
  7716. console && console.error(msg);
  7717. //me.fireEvent('showMessage', {
  7718. // 'title': msg,
  7719. // 'type': 'error'
  7720. //});
  7721. }
  7722. };
  7723. UE.Editor.prototype.isServerConfigLoaded = function () {
  7724. var me = this;
  7725. return me._serverConfigLoaded || false;
  7726. };
  7727. UE.Editor.prototype.afterConfigReady = function (handler) {
  7728. if (!handler || !utils.isFunction(handler)) return;
  7729. var me = this;
  7730. var readyHandler = function () {
  7731. handler.apply(me, arguments);
  7732. me.removeListener('serverConfigLoaded', readyHandler);
  7733. };
  7734. if (me.isServerConfigLoaded()) {
  7735. handler.call(me, 'serverConfigLoaded');
  7736. } else {
  7737. me.addListener('serverConfigLoaded', readyHandler);
  7738. }
  7739. };
  7740. })();
  7741. // core/ajax.js
  7742. /**
  7743. * @file
  7744. * @module UE.ajax
  7745. * @since 1.2.6.1
  7746. */
  7747. /**
  7748. * 提供对ajax请求的支持
  7749. * @module UE.ajax
  7750. */
  7751. UE.ajax = function () {
  7752. //创建一个ajaxRequest对象
  7753. var fnStr = 'XMLHttpRequest()';
  7754. try {
  7755. new ActiveXObject("Msxml2.XMLHTTP");
  7756. fnStr = 'ActiveXObject(\'Msxml2.XMLHTTP\')';
  7757. } catch (e) {
  7758. try {
  7759. new ActiveXObject("Microsoft.XMLHTTP");
  7760. fnStr = 'ActiveXObject(\'Microsoft.XMLHTTP\')'
  7761. } catch (e) {
  7762. }
  7763. }
  7764. var creatAjaxRequest = new Function('return new ' + fnStr);
  7765. /**
  7766. * 将json参数转化成适合ajax提交的参数列表
  7767. * @param json
  7768. */
  7769. function json2str(json) {
  7770. var strArr = [];
  7771. for (var i in json) {
  7772. //忽略默认的几个参数
  7773. if (i == "method" || i == "timeout" || i == "async" || i == "dataType" || i == "callback") continue;
  7774. //忽略控制
  7775. if (json[i] == undefined || json[i] == null) continue;
  7776. //传递过来的对象和函数不在提交之列
  7777. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  7778. strArr.push(encodeURIComponent(i) + "=" + encodeURIComponent(json[i]));
  7779. } else if (utils.isArray(json[i])) {
  7780. //支持传数组内容
  7781. for (var j = 0; j < json[i].length; j++) {
  7782. strArr.push(encodeURIComponent(i) + "[]=" + encodeURIComponent(json[i][j]));
  7783. }
  7784. }
  7785. }
  7786. return strArr.join("&");
  7787. }
  7788. function doAjax(url, ajaxOptions) {
  7789. var xhr = creatAjaxRequest(),
  7790. //是否超时
  7791. timeIsOut = false,
  7792. //默认参数
  7793. defaultAjaxOptions = {
  7794. method: "POST",
  7795. timeout: 5000,
  7796. async: true,
  7797. data: {},//需要传递对象的话只能覆盖
  7798. onsuccess: function () {
  7799. },
  7800. onerror: function () {
  7801. }
  7802. };
  7803. if (typeof url === "object") {
  7804. ajaxOptions = url;
  7805. url = ajaxOptions.url;
  7806. }
  7807. if (!xhr || !url) return;
  7808. var ajaxOpts = ajaxOptions ? utils.extend(defaultAjaxOptions, ajaxOptions) : defaultAjaxOptions;
  7809. var submitStr = json2str(ajaxOpts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  7810. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  7811. if (!utils.isEmptyObject(ajaxOpts.data)) {
  7812. submitStr += (submitStr ? "&" : "") + json2str(ajaxOpts.data);
  7813. }
  7814. //超时检测
  7815. var timerID = setTimeout(function () {
  7816. if (xhr.readyState != 4) {
  7817. timeIsOut = true;
  7818. xhr.abort();
  7819. clearTimeout(timerID);
  7820. }
  7821. }, ajaxOpts.timeout);
  7822. var method = ajaxOpts.method.toUpperCase();
  7823. var str = url + (url.indexOf("?") == -1 ? "?" : "&") + (method == "POST" ? "" : submitStr + "&noCache=" + +new Date);
  7824. xhr.open(method, str, ajaxOpts.async);
  7825. xhr.onreadystatechange = function () {
  7826. if (xhr.readyState == 4) {
  7827. if (!timeIsOut && xhr.status == 200) {
  7828. ajaxOpts.onsuccess(xhr);
  7829. } else {
  7830. ajaxOpts.onerror(xhr);
  7831. }
  7832. }
  7833. };
  7834. if (method == "POST") {
  7835. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  7836. xhr.send(submitStr);
  7837. } else {
  7838. xhr.send(null);
  7839. }
  7840. }
  7841. function doJsonp(url, opts) {
  7842. console.log(url, opts, 111)
  7843. //
  7844. var successhandler = opts.onsuccess || function () { },
  7845. scr = document.createElement('SCRIPT'),
  7846. options = opts || {},
  7847. charset = options['charset'],
  7848. callbackField = options['jsonp'] || 'callback',
  7849. callbackFnName,
  7850. timeOut = options['timeOut'] || 0,
  7851. timer,
  7852. reg = new RegExp('(\\?|&)' + callbackField + '=([^&]*)'),
  7853. matches;
  7854. if (utils.isFunction(successhandler)) {
  7855. callbackFnName = 'bd__editor__' + Math.floor(Math.random() * 2147483648).toString(36);
  7856. window[callbackFnName] = getCallBack(0);
  7857. } else if (utils.isString(successhandler)) {
  7858. callbackFnName = successhandler;
  7859. } else {
  7860. if (matches = reg.exec(url)) {
  7861. callbackFnName = matches[2];
  7862. }
  7863. }
  7864. url = url.replace(reg, '\x241' + callbackField + '=' + callbackFnName);
  7865. if (url.search(reg) < 0) {
  7866. url += (url.indexOf('?') < 0 ? '?' : '&') + callbackField + '=' + callbackFnName;
  7867. }
  7868. var queryStr = json2str(opts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  7869. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  7870. if (!utils.isEmptyObject(opts.data)) {
  7871. queryStr += (queryStr ? "&" : "") + json2str(opts.data);
  7872. }
  7873. if (queryStr) {
  7874. url = url.replace(/\?/, '?' + queryStr + '&');
  7875. }
  7876. scr.onerror = getCallBack(1);
  7877. if (timeOut) {
  7878. timer = setTimeout(getCallBack(1), timeOut);
  7879. }
  7880. createScriptTag(scr, url, charset);
  7881. function createScriptTag(scr, url, charset) {
  7882. scr.setAttribute('type', 'text/javascript');
  7883. scr.setAttribute('defer', 'defer');
  7884. charset && scr.setAttribute('charset', charset);
  7885. scr.setAttribute('src', url);
  7886. document.getElementsByTagName('head')[0].appendChild(scr);
  7887. }
  7888. function getCallBack(onTimeOut) {
  7889. return function () {
  7890. try {
  7891. if (onTimeOut) {
  7892. options.onerror && options.onerror();
  7893. } else {
  7894. try {
  7895. clearTimeout(timer);
  7896. console.log(arguments, 2222)
  7897. successhandler.apply(window, arguments);
  7898. } catch (e) { }
  7899. }
  7900. } catch (exception) {
  7901. options.onerror && options.onerror.call(window, exception);
  7902. } finally {
  7903. options.oncomplete && options.oncomplete.apply(window, arguments);
  7904. scr.parentNode && scr.parentNode.removeChild(scr);
  7905. window[callbackFnName] = null;
  7906. try {
  7907. delete window[callbackFnName];
  7908. } catch (e) { }
  7909. }
  7910. }
  7911. }
  7912. }
  7913. return {
  7914. /**
  7915. * 根据给定的参数项,向指定的url发起一个ajax请求。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7916. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调
  7917. * @method request
  7918. * @param { URLString } url ajax请求的url地址
  7919. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7920. * @example
  7921. * ```javascript
  7922. * //向sayhello.php发起一个异步的Ajax GET请求, 请求超时时间为10s, 请求完成后执行相应的回调。
  7923. * UE.ajax.requeset( 'sayhello.php', {
  7924. *
  7925. * //请求方法。可选值: 'GET', 'POST',默认值是'POST'
  7926. * method: 'GET',
  7927. *
  7928. * //超时时间。 默认为5000, 单位是ms
  7929. * timeout: 10000,
  7930. *
  7931. * //是否是异步请求。 true为异步请求, false为同步请求
  7932. * async: true,
  7933. *
  7934. * //请求携带的数据。如果请求为GET请求, data会经过stringify后附加到请求url之后。
  7935. * data: {
  7936. * name: 'ueditor'
  7937. * },
  7938. *
  7939. * //请求成功后的回调, 该回调接受当前的XMLHttpRequest对象作为参数。
  7940. * onsuccess: function ( xhr ) {
  7941. * console.log( xhr.responseText );
  7942. * },
  7943. *
  7944. * //请求失败或者超时后的回调。
  7945. * onerror: function ( xhr ) {
  7946. * alert( 'Ajax请求失败' );
  7947. * }
  7948. *
  7949. * } );
  7950. * ```
  7951. */
  7952. /**
  7953. * 根据给定的参数项发起一个ajax请求, 参数项里必须包含一个url地址。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7954. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调。
  7955. * @method request
  7956. * @warning 如果在参数项里未提供一个key为“url”的地址值,则该请求将直接退出。
  7957. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7958. * @example
  7959. * ```javascript
  7960. *
  7961. * //向sayhello.php发起一个异步的Ajax POST请求, 请求超时时间为5s, 请求完成后不执行任何回调。
  7962. * UE.ajax.requeset( 'sayhello.php', {
  7963. *
  7964. * //请求的地址, 该项是必须的。
  7965. * url: 'sayhello.php'
  7966. *
  7967. * } );
  7968. * ```
  7969. */
  7970. request: function (url, opts) {
  7971. if (opts && opts.dataType == 'jsonp') {
  7972. doJsonp(url, opts);
  7973. } else {
  7974. doAjax(url, opts);
  7975. }
  7976. },
  7977. getJSONP: function (url, data, fn) {
  7978. var opts = {
  7979. 'data': data,
  7980. 'oncomplete': fn
  7981. };
  7982. doJsonp(url, opts);
  7983. }
  7984. };
  7985. }();
  7986. // core/filterword.js
  7987. /**
  7988. * UE过滤word的静态方法
  7989. * @file
  7990. */
  7991. /**
  7992. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  7993. * @module UE
  7994. */
  7995. /**
  7996. * 根据传入html字符串过滤word
  7997. * @module UE
  7998. * @since 1.2.6.1
  7999. * @method filterWord
  8000. * @param { String } html html字符串
  8001. * @return { String } 已过滤后的结果字符串
  8002. * @example
  8003. * ```javascript
  8004. * UE.filterWord(html);
  8005. * ```
  8006. */
  8007. var filterWord = UE.filterWord = function () {
  8008. //是否是word过来的内容
  8009. function isWordDocument(str) {
  8010. return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<(v|o):|lang=)/ig.test(str);
  8011. }
  8012. //去掉小数
  8013. function transUnit(v) {
  8014. v = v.replace(/[\d.]+\w+/g, function (m) {
  8015. return utils.transUnitToPx(m);
  8016. });
  8017. return v;
  8018. }
  8019. function filterPasteWord(str) {
  8020. return str.replace(/[\t\r\n]+/g, ' ')
  8021. .replace(/<!--[\s\S]*?-->/ig, "")
  8022. //转换图片
  8023. .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi, function (str) {
  8024. //opera能自己解析出image所这里直接返回空
  8025. if (browser.opera) {
  8026. return '';
  8027. }
  8028. try {
  8029. //有可能是bitmap占为图,无用,直接过滤掉,主要体现在粘贴excel表格中
  8030. if (/Bitmap/i.test(str)) {
  8031. return '';
  8032. }
  8033. var width = str.match(/width:([ \d.]*p[tx])/i)[1],
  8034. height = str.match(/height:([ \d.]*p[tx])/i)[1],
  8035. src = str.match(/src=\s*"([^"]*)"/i)[1];
  8036. return '<img width="' + transUnit(width) + '" height="' + transUnit(height) + '" src="' + src + '" />';
  8037. } catch (e) {
  8038. return '';
  8039. }
  8040. })
  8041. //针对wps添加的多余标签处理
  8042. .replace(/<\/?div[^>]*>/g, '')
  8043. //去掉多余的属性
  8044. .replace(/v:\w+=(["']?)[^'"]+\1/g, '')
  8045. .replace(/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "")
  8046. .replace(/<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>")
  8047. //去掉多余的属性
  8048. .replace(/\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/ig, function (str, name, marks, val) {
  8049. //保留list的标示
  8050. return name == 'class' && val == 'MsoListParagraph' ? str : ''
  8051. })
  8052. //清除多余的font/span不能匹配&nbsp;有可能是空格
  8053. .replace(/<(font|span)[^>]*>(\s*)<\/\1>/gi, function (a, b, c) {
  8054. return c.replace(/[\t\r\n ]+/g, ' ')
  8055. })
  8056. //处理style的问题
  8057. .replace(/(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function (str, tag, tmp, style) {
  8058. var n = [],
  8059. s = style.replace(/^\s+|\s+$/, '')
  8060. .replace(/&#39;/g, '\'')
  8061. .replace(/&quot;/gi, "'")
  8062. .replace(/[\d.]+(cm|pt)/g, function (str) {
  8063. return utils.transUnitToPx(str)
  8064. })
  8065. .split(/;\s*/g);
  8066. for (var i = 0, v; v = s[i]; i++) {
  8067. var name, value,
  8068. parts = v.split(":");
  8069. if (parts.length == 2) {
  8070. name = parts[0].toLowerCase();
  8071. value = parts[1].toLowerCase();
  8072. if (/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g, '').length == 0
  8073. ||
  8074. /^(margin)\w*/.test(name) && /^0\w+$/.test(value)
  8075. ) {
  8076. continue;
  8077. }
  8078. switch (name) {
  8079. case "mso-padding-alt":
  8080. case "mso-padding-top-alt":
  8081. case "mso-padding-right-alt":
  8082. case "mso-padding-bottom-alt":
  8083. case "mso-padding-left-alt":
  8084. case "mso-margin-alt":
  8085. case "mso-margin-top-alt":
  8086. case "mso-margin-right-alt":
  8087. case "mso-margin-bottom-alt":
  8088. case "mso-margin-left-alt":
  8089. //ie下会出现挤到一起的情况
  8090. //case "mso-table-layout-alt":
  8091. case "mso-height":
  8092. case "mso-width":
  8093. case "mso-vertical-align-alt":
  8094. //trace:1819 ff下会解析出padding在table上
  8095. if (!/<table/.test(tag))
  8096. n[i] = name.replace(/^mso-|-alt$/g, "") + ":" + transUnit(value);
  8097. continue;
  8098. case "horiz-align":
  8099. n[i] = "text-align:" + value;
  8100. continue;
  8101. case "vert-align":
  8102. n[i] = "vertical-align:" + value;
  8103. continue;
  8104. case "font-color":
  8105. case "mso-foreground":
  8106. n[i] = "color:" + value;
  8107. continue;
  8108. case "mso-background":
  8109. case "mso-highlight":
  8110. n[i] = "background:" + value;
  8111. continue;
  8112. case "mso-default-height":
  8113. n[i] = "min-height:" + transUnit(value);
  8114. continue;
  8115. case "mso-default-width":
  8116. n[i] = "min-width:" + transUnit(value);
  8117. continue;
  8118. case "mso-padding-between-alt":
  8119. n[i] = "border-collapse:separate;border-spacing:" + transUnit(value);
  8120. continue;
  8121. case "text-line-through":
  8122. if ((value == "single") || (value == "double")) {
  8123. n[i] = "text-decoration:line-through";
  8124. }
  8125. continue;
  8126. case "mso-zero-height":
  8127. if (value == "yes") {
  8128. n[i] = "display:none";
  8129. }
  8130. continue;
  8131. // case 'background':
  8132. // break;
  8133. case 'margin':
  8134. if (!/[1-9]/.test(value)) {
  8135. continue;
  8136. }
  8137. }
  8138. if (/^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?:decor|trans)|top-bar|version|vnd|word-break)/.test(name)
  8139. ||
  8140. /text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value)
  8141. ) {
  8142. continue;
  8143. }
  8144. n[i] = name + ":" + parts[1];
  8145. }
  8146. }
  8147. return tag + (n.length ? ' style="' + n.join(';').replace(/;{2,}/g, ';') + '"' : '');
  8148. })
  8149. }
  8150. return function (html) {
  8151. return (isWordDocument(html) ? filterPasteWord(html) : html);
  8152. };
  8153. }();
  8154. // core/node.js
  8155. /**
  8156. * 编辑器模拟的节点类
  8157. * @file
  8158. * @module UE
  8159. * @class uNode
  8160. * @since 1.2.6.1
  8161. */
  8162. /**
  8163. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8164. * @unfile
  8165. * @module UE
  8166. */
  8167. (function () {
  8168. /**
  8169. * 编辑器模拟的节点类
  8170. * @unfile
  8171. * @module UE
  8172. * @class uNode
  8173. */
  8174. /**
  8175. * 通过一个键值对,创建一个uNode对象
  8176. * @constructor
  8177. * @param { Object } attr 传入要创建的uNode的初始属性
  8178. * @example
  8179. * ```javascript
  8180. * var node = new uNode({
  8181. * type:'element',
  8182. * tagName:'span',
  8183. * attrs:{style:'font-size:14px;'}
  8184. * }
  8185. * ```
  8186. */
  8187. var uNode = UE.uNode = function (obj) {
  8188. this.type = obj.type;
  8189. this.data = obj.data;
  8190. this.tagName = obj.tagName;
  8191. this.parentNode = obj.parentNode;
  8192. this.attrs = obj.attrs || {};
  8193. this.children = obj.children;
  8194. };
  8195. var notTransAttrs = {
  8196. 'href': 1,
  8197. 'src': 1,
  8198. '_src': 1,
  8199. '_href': 1,
  8200. 'cdata_data': 1
  8201. };
  8202. var notTransTagName = {
  8203. style: 1,
  8204. script: 1
  8205. };
  8206. var indentChar = ' ',
  8207. breakChar = '\n';
  8208. function insertLine(arr, current, begin) {
  8209. arr.push(breakChar);
  8210. return current + (begin ? 1 : -1);
  8211. }
  8212. function insertIndent(arr, current) {
  8213. //插入缩进
  8214. for (var i = 0; i < current; i++) {
  8215. arr.push(indentChar);
  8216. }
  8217. }
  8218. //创建uNode的静态方法
  8219. //支持标签和html
  8220. uNode.createElement = function (html) {
  8221. if (/[<>]/.test(html)) {
  8222. return UE.htmlparser(html).children[0]
  8223. } else {
  8224. return new uNode({
  8225. type: 'element',
  8226. children: [],
  8227. tagName: html
  8228. })
  8229. }
  8230. };
  8231. uNode.createText = function (data, noTrans) {
  8232. return new UE.uNode({
  8233. type: 'text',
  8234. 'data': noTrans ? data : utils.unhtml(data || '')
  8235. })
  8236. };
  8237. function nodeToHtml(node, arr, formatter, current) {
  8238. switch (node.type) {
  8239. case 'root':
  8240. for (var i = 0, ci; ci = node.children[i++];) {
  8241. //插入新行
  8242. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  8243. insertLine(arr, current, true);
  8244. insertIndent(arr, current)
  8245. }
  8246. nodeToHtml(ci, arr, formatter, current)
  8247. }
  8248. break;
  8249. case 'text':
  8250. isText(node, arr);
  8251. break;
  8252. case 'element':
  8253. isElement(node, arr, formatter, current);
  8254. break;
  8255. case 'comment':
  8256. isComment(node, arr, formatter);
  8257. }
  8258. return arr;
  8259. }
  8260. function isText(node, arr) {
  8261. if (node.parentNode.tagName == 'pre') {
  8262. //源码模式下输入html标签,不能做转换处理,直接输出
  8263. arr.push(node.data)
  8264. } else {
  8265. arr.push(notTransTagName[node.parentNode.tagName] ? utils.html(node.data) : node.data.replace(/[ ]{2}/g, ' &nbsp;'))
  8266. }
  8267. }
  8268. function isElement(node, arr, formatter, current) {
  8269. var attrhtml = '';
  8270. if (node.attrs) {
  8271. attrhtml = [];
  8272. var attrs = node.attrs;
  8273. for (var a in attrs) {
  8274. //这里就针对
  8275. //<p>'<img src='http://nsclick.baidu.com/u.gif?&asdf=\"sdf&asdfasdfs;asdf'></p>
  8276. //这里边的\"做转换,要不用innerHTML直接被截断了,属性src
  8277. //有可能做的不够
  8278. attrhtml.push(a + (attrs[a] !== undefined ? '="' + (notTransAttrs[a] ? utils.html(attrs[a]).replace(/["]/g, function (a) {
  8279. return '&quot;'
  8280. }) : utils.unhtml(attrs[a])) + '"' : ''))
  8281. }
  8282. attrhtml = attrhtml.join(' ');
  8283. }
  8284. arr.push('<' + node.tagName +
  8285. (attrhtml ? ' ' + attrhtml : '') +
  8286. (dtd.$empty[node.tagName] ? '\/' : '') + '>'
  8287. );
  8288. //插入新行
  8289. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  8290. if (node.children && node.children.length) {
  8291. current = insertLine(arr, current, true);
  8292. insertIndent(arr, current)
  8293. }
  8294. }
  8295. if (node.children && node.children.length) {
  8296. for (var i = 0, ci; ci = node.children[i++];) {
  8297. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  8298. insertLine(arr, current);
  8299. insertIndent(arr, current)
  8300. }
  8301. nodeToHtml(ci, arr, formatter, current)
  8302. }
  8303. }
  8304. if (!dtd.$empty[node.tagName]) {
  8305. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  8306. if (node.children && node.children.length) {
  8307. current = insertLine(arr, current);
  8308. insertIndent(arr, current)
  8309. }
  8310. }
  8311. arr.push('<\/' + node.tagName + '>');
  8312. }
  8313. }
  8314. function isComment(node, arr) {
  8315. arr.push('<!--' + node.data + '-->');
  8316. }
  8317. function getNodeById(root, id) {
  8318. var node;
  8319. if (root.type == 'element' && root.getAttr('id') == id) {
  8320. return root;
  8321. }
  8322. if (root.children && root.children.length) {
  8323. for (var i = 0, ci; ci = root.children[i++];) {
  8324. if (node = getNodeById(ci, id)) {
  8325. return node;
  8326. }
  8327. }
  8328. }
  8329. }
  8330. function getNodesByTagName(node, tagName, arr) {
  8331. if (node.type == 'element' && node.tagName == tagName) {
  8332. arr.push(node);
  8333. }
  8334. if (node.children && node.children.length) {
  8335. for (var i = 0, ci; ci = node.children[i++];) {
  8336. getNodesByTagName(ci, tagName, arr)
  8337. }
  8338. }
  8339. }
  8340. function nodeTraversal(root, fn) {
  8341. if (root.children && root.children.length) {
  8342. for (var i = 0, ci; ci = root.children[i];) {
  8343. nodeTraversal(ci, fn);
  8344. //ci被替换的情况,这里就不再走 fn了
  8345. if (ci.parentNode) {
  8346. if (ci.children && ci.children.length) {
  8347. fn(ci)
  8348. }
  8349. if (ci.parentNode) i++
  8350. }
  8351. }
  8352. } else {
  8353. fn(root)
  8354. }
  8355. }
  8356. uNode.prototype = {
  8357. /**
  8358. * 当前节点对象,转换成html文本
  8359. * @method toHtml
  8360. * @return { String } 返回转换后的html字符串
  8361. * @example
  8362. * ```javascript
  8363. * node.toHtml();
  8364. * ```
  8365. */
  8366. /**
  8367. * 当前节点对象,转换成html文本
  8368. * @method toHtml
  8369. * @param { Boolean } formatter 是否格式化返回值
  8370. * @return { String } 返回转换后的html字符串
  8371. * @example
  8372. * ```javascript
  8373. * node.toHtml( true );
  8374. * ```
  8375. */
  8376. toHtml: function (formatter) {
  8377. var arr = [];
  8378. nodeToHtml(this, arr, formatter, 0);
  8379. return arr.join('')
  8380. },
  8381. /**
  8382. * 获取节点的html内容
  8383. * @method innerHTML
  8384. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8385. * @return { String } 返回节点的html内容
  8386. * @example
  8387. * ```javascript
  8388. * var htmlstr = node.innerHTML();
  8389. * ```
  8390. */
  8391. /**
  8392. * 设置节点的html内容
  8393. * @method innerHTML
  8394. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8395. * @param { String } htmlstr 传入要设置的html内容
  8396. * @return { UE.uNode } 返回节点本身
  8397. * @example
  8398. * ```javascript
  8399. * node.innerHTML('<span>text</span>');
  8400. * ```
  8401. */
  8402. innerHTML: function (htmlstr) {
  8403. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8404. return this;
  8405. }
  8406. if (utils.isString(htmlstr)) {
  8407. if (this.children) {
  8408. for (var i = 0, ci; ci = this.children[i++];) {
  8409. ci.parentNode = null;
  8410. }
  8411. }
  8412. this.children = [];
  8413. var tmpRoot = UE.htmlparser(htmlstr);
  8414. for (var i = 0, ci; ci = tmpRoot.children[i++];) {
  8415. this.children.push(ci);
  8416. ci.parentNode = this;
  8417. }
  8418. return this;
  8419. } else {
  8420. var tmpRoot = new UE.uNode({
  8421. type: 'root',
  8422. children: this.children
  8423. });
  8424. return tmpRoot.toHtml();
  8425. }
  8426. },
  8427. /**
  8428. * 获取节点的纯文本内容
  8429. * @method innerText
  8430. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8431. * @return { String } 返回节点的存文本内容
  8432. * @example
  8433. * ```javascript
  8434. * var textStr = node.innerText();
  8435. * ```
  8436. */
  8437. /**
  8438. * 设置节点的纯文本内容
  8439. * @method innerText
  8440. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8441. * @param { String } textStr 传入要设置的文本内容
  8442. * @return { UE.uNode } 返回节点本身
  8443. * @example
  8444. * ```javascript
  8445. * node.innerText('<span>text</span>');
  8446. * ```
  8447. */
  8448. innerText: function (textStr, noTrans) {
  8449. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8450. return this;
  8451. }
  8452. if (textStr) {
  8453. if (this.children) {
  8454. for (var i = 0, ci; ci = this.children[i++];) {
  8455. ci.parentNode = null;
  8456. }
  8457. }
  8458. this.children = [];
  8459. this.appendChild(uNode.createText(textStr, noTrans));
  8460. return this;
  8461. } else {
  8462. return this.toHtml().replace(/<[^>]+>/g, '');
  8463. }
  8464. },
  8465. /**
  8466. * 获取当前对象的data属性
  8467. * @method getData
  8468. * @return { Object } 若节点的type值是elemenet,返回空字符串,否则返回节点的data属性
  8469. * @example
  8470. * ```javascript
  8471. * node.getData();
  8472. * ```
  8473. */
  8474. getData: function () {
  8475. if (this.type == 'element')
  8476. return '';
  8477. return this.data
  8478. },
  8479. /**
  8480. * 获取当前节点下的第一个子节点
  8481. * @method firstChild
  8482. * @return { UE.uNode } 返回第一个子节点
  8483. * @example
  8484. * ```javascript
  8485. * node.firstChild(); //返回第一个子节点
  8486. * ```
  8487. */
  8488. firstChild: function () {
  8489. // if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8490. // return this;
  8491. // }
  8492. return this.children ? this.children[0] : null;
  8493. },
  8494. /**
  8495. * 获取当前节点下的最后一个子节点
  8496. * @method lastChild
  8497. * @return { UE.uNode } 返回最后一个子节点
  8498. * @example
  8499. * ```javascript
  8500. * node.lastChild(); //返回最后一个子节点
  8501. * ```
  8502. */
  8503. lastChild: function () {
  8504. // if (this.type != 'element' || dtd.$empty[this.tagName] ) {
  8505. // return this;
  8506. // }
  8507. return this.children ? this.children[this.children.length - 1] : null;
  8508. },
  8509. /**
  8510. * 获取和当前节点有相同父亲节点的前一个节点
  8511. * @method previousSibling
  8512. * @return { UE.uNode } 返回前一个节点
  8513. * @example
  8514. * ```javascript
  8515. * node.children[2].previousSibling(); //返回子节点node.children[1]
  8516. * ```
  8517. */
  8518. previousSibling: function () {
  8519. var parent = this.parentNode;
  8520. for (var i = 0, ci; ci = parent.children[i]; i++) {
  8521. if (ci === this) {
  8522. return i == 0 ? null : parent.children[i - 1];
  8523. }
  8524. }
  8525. },
  8526. /**
  8527. * 获取和当前节点有相同父亲节点的后一个节点
  8528. * @method nextSibling
  8529. * @return { UE.uNode } 返回后一个节点,找不到返回null
  8530. * @example
  8531. * ```javascript
  8532. * node.children[2].nextSibling(); //如果有,返回子节点node.children[3]
  8533. * ```
  8534. */
  8535. nextSibling: function () {
  8536. var parent = this.parentNode;
  8537. for (var i = 0, ci; ci = parent.children[i++];) {
  8538. if (ci === this) {
  8539. return parent.children[i];
  8540. }
  8541. }
  8542. },
  8543. /**
  8544. * 用新的节点替换当前节点
  8545. * @method replaceChild
  8546. * @param { UE.uNode } target 要替换成该节点参数
  8547. * @param { UE.uNode } source 要被替换掉的节点
  8548. * @return { UE.uNode } 返回替换之后的节点对象
  8549. * @example
  8550. * ```javascript
  8551. * node.replaceChild(newNode, childNode); //用newNode替换childNode,childNode是node的子节点
  8552. * ```
  8553. */
  8554. replaceChild: function (target, source) {
  8555. if (this.children) {
  8556. if (target.parentNode) {
  8557. target.parentNode.removeChild(target);
  8558. }
  8559. for (var i = 0, ci; ci = this.children[i]; i++) {
  8560. if (ci === source) {
  8561. this.children.splice(i, 1, target);
  8562. source.parentNode = null;
  8563. target.parentNode = this;
  8564. return target;
  8565. }
  8566. }
  8567. }
  8568. },
  8569. /**
  8570. * 在节点的子节点列表最后位置插入一个节点
  8571. * @method appendChild
  8572. * @param { UE.uNode } node 要插入的节点
  8573. * @return { UE.uNode } 返回刚插入的子节点
  8574. * @example
  8575. * ```javascript
  8576. * node.appendChild( newNode ); //在node内插入子节点newNode
  8577. * ```
  8578. */
  8579. appendChild: function (node) {
  8580. if (this.type == 'root' || (this.type == 'element' && !dtd.$empty[this.tagName])) {
  8581. if (!this.children) {
  8582. this.children = []
  8583. }
  8584. if (node.parentNode) {
  8585. node.parentNode.removeChild(node);
  8586. }
  8587. for (var i = 0, ci; ci = this.children[i]; i++) {
  8588. if (ci === node) {
  8589. this.children.splice(i, 1);
  8590. break;
  8591. }
  8592. }
  8593. this.children.push(node);
  8594. node.parentNode = this;
  8595. return node;
  8596. }
  8597. },
  8598. /**
  8599. * 在传入节点的前面插入一个节点
  8600. * @method insertBefore
  8601. * @param { UE.uNode } target 要插入的节点
  8602. * @param { UE.uNode } source 在该参数节点前面插入
  8603. * @return { UE.uNode } 返回刚插入的子节点
  8604. * @example
  8605. * ```javascript
  8606. * node.parentNode.insertBefore(newNode, node); //在node节点后面插入newNode
  8607. * ```
  8608. */
  8609. insertBefore: function (target, source) {
  8610. if (this.children) {
  8611. if (target.parentNode) {
  8612. target.parentNode.removeChild(target);
  8613. }
  8614. for (var i = 0, ci; ci = this.children[i]; i++) {
  8615. if (ci === source) {
  8616. this.children.splice(i, 0, target);
  8617. target.parentNode = this;
  8618. return target;
  8619. }
  8620. }
  8621. }
  8622. },
  8623. /**
  8624. * 在传入节点的后面插入一个节点
  8625. * @method insertAfter
  8626. * @param { UE.uNode } target 要插入的节点
  8627. * @param { UE.uNode } source 在该参数节点后面插入
  8628. * @return { UE.uNode } 返回刚插入的子节点
  8629. * @example
  8630. * ```javascript
  8631. * node.parentNode.insertAfter(newNode, node); //在node节点后面插入newNode
  8632. * ```
  8633. */
  8634. insertAfter: function (target, source) {
  8635. if (this.children) {
  8636. if (target.parentNode) {
  8637. target.parentNode.removeChild(target);
  8638. }
  8639. for (var i = 0, ci; ci = this.children[i]; i++) {
  8640. if (ci === source) {
  8641. this.children.splice(i + 1, 0, target);
  8642. target.parentNode = this;
  8643. return target;
  8644. }
  8645. }
  8646. }
  8647. },
  8648. /**
  8649. * 从当前节点的子节点列表中,移除节点
  8650. * @method removeChild
  8651. * @param { UE.uNode } node 要移除的节点引用
  8652. * @param { Boolean } keepChildren 是否保留移除节点的子节点,若传入true,自动把移除节点的子节点插入到移除的位置
  8653. * @return { * } 返回刚移除的子节点
  8654. * @example
  8655. * ```javascript
  8656. * node.removeChild(childNode,true); //在node的子节点列表中移除child节点,并且吧child的子节点插入到移除的位置
  8657. * ```
  8658. */
  8659. removeChild: function (node, keepChildren) {
  8660. if (this.children) {
  8661. for (var i = 0, ci; ci = this.children[i]; i++) {
  8662. if (ci === node) {
  8663. this.children.splice(i, 1);
  8664. ci.parentNode = null;
  8665. if (keepChildren && ci.children && ci.children.length) {
  8666. for (var j = 0, cj; cj = ci.children[j]; j++) {
  8667. this.children.splice(i + j, 0, cj);
  8668. cj.parentNode = this;
  8669. }
  8670. }
  8671. return ci;
  8672. }
  8673. }
  8674. }
  8675. },
  8676. /**
  8677. * 获取当前节点所代表的元素属性,即获取attrs对象下的属性值
  8678. * @method getAttr
  8679. * @param { String } attrName 要获取的属性名称
  8680. * @return { * } 返回attrs对象下的属性值
  8681. * @example
  8682. * ```javascript
  8683. * node.getAttr('title');
  8684. * ```
  8685. */
  8686. getAttr: function (attrName) {
  8687. return this.attrs && this.attrs[attrName.toLowerCase()]
  8688. },
  8689. /**
  8690. * 设置当前节点所代表的元素属性,即设置attrs对象下的属性值
  8691. * @method setAttr
  8692. * @param { String } attrName 要设置的属性名称
  8693. * @param { * } attrVal 要设置的属性值,类型视设置的属性而定
  8694. * @return { * } 返回attrs对象下的属性值
  8695. * @example
  8696. * ```javascript
  8697. * node.setAttr('title','标题');
  8698. * ```
  8699. */
  8700. setAttr: function (attrName, attrVal) {
  8701. if (!attrName) {
  8702. delete this.attrs;
  8703. return;
  8704. }
  8705. if (!this.attrs) {
  8706. this.attrs = {};
  8707. }
  8708. if (utils.isObject(attrName)) {
  8709. for (var a in attrName) {
  8710. if (!attrName[a]) {
  8711. delete this.attrs[a]
  8712. } else {
  8713. this.attrs[a.toLowerCase()] = attrName[a];
  8714. }
  8715. }
  8716. } else {
  8717. if (!attrVal) {
  8718. delete this.attrs[attrName]
  8719. } else {
  8720. this.attrs[attrName.toLowerCase()] = attrVal;
  8721. }
  8722. }
  8723. },
  8724. /**
  8725. * 获取当前节点在父节点下的位置索引
  8726. * @method getIndex
  8727. * @return { Number } 返回索引数值,如果没有父节点,返回-1
  8728. * @example
  8729. * ```javascript
  8730. * node.getIndex();
  8731. * ```
  8732. */
  8733. getIndex: function () {
  8734. var parent = this.parentNode;
  8735. for (var i = 0, ci; ci = parent.children[i]; i++) {
  8736. if (ci === this) {
  8737. return i;
  8738. }
  8739. }
  8740. return -1;
  8741. },
  8742. /**
  8743. * 在当前节点下,根据id查找节点
  8744. * @method getNodeById
  8745. * @param { String } id 要查找的id
  8746. * @return { UE.uNode } 返回找到的节点
  8747. * @example
  8748. * ```javascript
  8749. * node.getNodeById('textId');
  8750. * ```
  8751. */
  8752. getNodeById: function (id) {
  8753. var node;
  8754. if (this.children && this.children.length) {
  8755. for (var i = 0, ci; ci = this.children[i++];) {
  8756. if (node = getNodeById(ci, id)) {
  8757. return node;
  8758. }
  8759. }
  8760. }
  8761. },
  8762. /**
  8763. * 在当前节点下,根据元素名称查找节点列表
  8764. * @method getNodesByTagName
  8765. * @param { String } tagNames 要查找的元素名称
  8766. * @return { Array } 返回找到的节点列表
  8767. * @example
  8768. * ```javascript
  8769. * node.getNodesByTagName('span');
  8770. * ```
  8771. */
  8772. getNodesByTagName: function (tagNames) {
  8773. tagNames = utils.trim(tagNames).replace(/[ ]{2,}/g, ' ').split(' ');
  8774. var arr = [], me = this;
  8775. utils.each(tagNames, function (tagName) {
  8776. if (me.children && me.children.length) {
  8777. for (var i = 0, ci; ci = me.children[i++];) {
  8778. getNodesByTagName(ci, tagName, arr)
  8779. }
  8780. }
  8781. });
  8782. return arr;
  8783. },
  8784. /**
  8785. * 根据样式名称,获取节点的样式值
  8786. * @method getStyle
  8787. * @param { String } name 要获取的样式名称
  8788. * @return { String } 返回样式值
  8789. * @example
  8790. * ```javascript
  8791. * node.getStyle('font-size');
  8792. * ```
  8793. */
  8794. getStyle: function (name) {
  8795. var cssStyle = this.getAttr('style');
  8796. if (!cssStyle) {
  8797. return ''
  8798. }
  8799. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+)', 'i');
  8800. var match = cssStyle.match(reg);
  8801. if (match && match[0]) {
  8802. return match[2]
  8803. }
  8804. return '';
  8805. },
  8806. /**
  8807. * 给节点设置样式
  8808. * @method setStyle
  8809. * @param { String } name 要设置的的样式名称
  8810. * @param { String } val 要设置的的样值
  8811. * @example
  8812. * ```javascript
  8813. * node.setStyle('font-size', '12px');
  8814. * ```
  8815. */
  8816. setStyle: function (name, val) {
  8817. function exec(name, val) {
  8818. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+;?)', 'gi');
  8819. cssStyle = cssStyle.replace(reg, '$1');
  8820. if (val) {
  8821. cssStyle = name + ':' + utils.unhtml(val) + ';' + cssStyle
  8822. }
  8823. }
  8824. var cssStyle = this.getAttr('style');
  8825. if (!cssStyle) {
  8826. cssStyle = '';
  8827. }
  8828. if (utils.isObject(name)) {
  8829. for (var a in name) {
  8830. exec(a, name[a])
  8831. }
  8832. } else {
  8833. exec(name, val)
  8834. }
  8835. this.setAttr('style', utils.trim(cssStyle))
  8836. },
  8837. /**
  8838. * 传入一个函数,递归遍历当前节点下的所有节点
  8839. * @method traversal
  8840. * @param { Function } fn 遍历到节点的时,传入节点作为参数,运行此函数
  8841. * @example
  8842. * ```javascript
  8843. * traversal(node, function(){
  8844. * console.log(node.type);
  8845. * });
  8846. * ```
  8847. */
  8848. traversal: function (fn) {
  8849. if (this.children && this.children.length) {
  8850. nodeTraversal(this, fn);
  8851. }
  8852. return this;
  8853. }
  8854. }
  8855. })();
  8856. // core/htmlparser.js
  8857. /**
  8858. * html字符串转换成uNode节点
  8859. * @file
  8860. * @module UE
  8861. * @since 1.2.6.1
  8862. */
  8863. /**
  8864. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8865. * @unfile
  8866. * @module UE
  8867. */
  8868. /**
  8869. * html字符串转换成uNode节点的静态方法
  8870. * @method htmlparser
  8871. * @param { String } htmlstr 要转换的html代码
  8872. * @param { Boolean } ignoreBlank 若设置为true,转换的时候忽略\n\r\t等空白字符
  8873. * @return { uNode } 给定的html片段转换形成的uNode对象
  8874. * @example
  8875. * ```javascript
  8876. * var root = UE.htmlparser('<p><b>htmlparser</b></p>', true);
  8877. * ```
  8878. */
  8879. var htmlparser = UE.htmlparser = function (htmlstr, ignoreBlank) {
  8880. //todo 原来的方式 [^"'<>\/] 有\/就不能配对上 <TD vAlign=top background=../AAA.JPG> 这样的标签了
  8881. //先去掉了,加上的原因忘了,这里先记录
  8882. var re_tag = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/<>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g,
  8883. re_attr = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g;
  8884. //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除
  8885. var allowEmptyTags = {
  8886. b: 1, code: 1, i: 1, u: 1, strike: 1, s: 1, tt: 1, strong: 1, q: 1, samp: 1, em: 1, span: 1,
  8887. sub: 1, img: 1, sup: 1, font: 1, big: 1, small: 1, iframe: 1, a: 1, br: 1, pre: 1
  8888. };
  8889. htmlstr = htmlstr.replace(new RegExp(domUtils.fillChar, 'g'), '');
  8890. if (!ignoreBlank) {
  8891. htmlstr = htmlstr.replace(new RegExp('[\\r\\t\\n' + (ignoreBlank ? '' : ' ') + ']*<\/?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n' + (ignoreBlank ? '' : ' ') + ']*', 'g'), function (a, b) {
  8892. //br暂时单独处理
  8893. if (b && allowEmptyTags[b.toLowerCase()]) {
  8894. return a.replace(/(^[\n\r]+)|([\n\r]+$)/g, '');
  8895. }
  8896. return a.replace(new RegExp('^[\\r\\n' + (ignoreBlank ? '' : ' ') + ']+'), '').replace(new RegExp('[\\r\\n' + (ignoreBlank ? '' : ' ') + ']+$'), '');
  8897. });
  8898. }
  8899. var notTransAttrs = {
  8900. 'href': 1,
  8901. 'src': 1
  8902. };
  8903. var uNode = UE.uNode,
  8904. needParentNode = {
  8905. 'td': 'tr',
  8906. 'tr': ['tbody', 'thead', 'tfoot'],
  8907. 'tbody': 'table',
  8908. 'th': 'tr',
  8909. 'thead': 'table',
  8910. 'tfoot': 'table',
  8911. 'caption': 'table',
  8912. 'li': ['ul', 'ol'],
  8913. 'dt': 'dl',
  8914. 'dd': 'dl',
  8915. 'option': 'select'
  8916. },
  8917. needChild = {
  8918. 'ol': 'li',
  8919. 'ul': 'li'
  8920. };
  8921. function text(parent, data) {
  8922. if (needChild[parent.tagName]) {
  8923. var tmpNode = uNode.createElement(needChild[parent.tagName]);
  8924. parent.appendChild(tmpNode);
  8925. tmpNode.appendChild(uNode.createText(data));
  8926. parent = tmpNode;
  8927. } else {
  8928. parent.appendChild(uNode.createText(data));
  8929. }
  8930. }
  8931. function element(parent, tagName, htmlattr) {
  8932. var needParentTag;
  8933. if (needParentTag = needParentNode[tagName]) {
  8934. var tmpParent = parent, hasParent;
  8935. while (tmpParent.type != 'root') {
  8936. if (utils.isArray(needParentTag) ? utils.indexOf(needParentTag, tmpParent.tagName) != -1 : needParentTag == tmpParent.tagName) {
  8937. parent = tmpParent;
  8938. hasParent = true;
  8939. break;
  8940. }
  8941. tmpParent = tmpParent.parentNode;
  8942. }
  8943. if (!hasParent) {
  8944. parent = element(parent, utils.isArray(needParentTag) ? needParentTag[0] : needParentTag)
  8945. }
  8946. }
  8947. //按dtd处理嵌套
  8948. // if(parent.type != 'root' && !dtd[parent.tagName][tagName])
  8949. // parent = parent.parentNode;
  8950. var elm = new uNode({
  8951. parentNode: parent,
  8952. type: 'element',
  8953. tagName: tagName.toLowerCase(),
  8954. //是自闭合的处理一下
  8955. children: dtd.$empty[tagName] ? null : []
  8956. });
  8957. //如果属性存在,处理属性
  8958. if (htmlattr) {
  8959. var attrs = {}, match;
  8960. while (match = re_attr.exec(htmlattr)) {
  8961. attrs[match[1].toLowerCase()] = notTransAttrs[match[1].toLowerCase()] ? (match[2] || match[3] || match[4]) : utils.unhtml(match[2] || match[3] || match[4])
  8962. }
  8963. elm.attrs = attrs;
  8964. }
  8965. //trace:3970
  8966. // //如果parent下不能放elm
  8967. // if(dtd.$inline[parent.tagName] && dtd.$block[elm.tagName] && !dtd[parent.tagName][elm.tagName]){
  8968. // parent = parent.parentNode;
  8969. // elm.parentNode = parent;
  8970. // }
  8971. parent.children.push(elm);
  8972. //如果是自闭合节点返回父亲节点
  8973. return dtd.$empty[tagName] ? parent : elm
  8974. }
  8975. function comment(parent, data) {
  8976. parent.children.push(new uNode({
  8977. type: 'comment',
  8978. data: data,
  8979. parentNode: parent
  8980. }));
  8981. }
  8982. var match, currentIndex = 0, nextIndex = 0;
  8983. //设置根节点
  8984. var root = new uNode({
  8985. type: 'root',
  8986. children: []
  8987. });
  8988. var currentParent = root;
  8989. while (match = re_tag.exec(htmlstr)) {
  8990. currentIndex = match.index;
  8991. try {
  8992. if (currentIndex > nextIndex) {
  8993. //text node
  8994. text(currentParent, htmlstr.slice(nextIndex, currentIndex));
  8995. }
  8996. if (match[3]) {
  8997. if (dtd.$cdata[currentParent.tagName]) {
  8998. text(currentParent, match[0]);
  8999. } else {
  9000. //start tag
  9001. currentParent = element(currentParent, match[3].toLowerCase(), match[4]);
  9002. }
  9003. } else if (match[1]) {
  9004. if (currentParent.type != 'root') {
  9005. if (dtd.$cdata[currentParent.tagName] && !dtd.$cdata[match[1]]) {
  9006. text(currentParent, match[0]);
  9007. } else {
  9008. var tmpParent = currentParent;
  9009. while (currentParent.type == 'element' && currentParent.tagName != match[1].toLowerCase()) {
  9010. currentParent = currentParent.parentNode;
  9011. if (currentParent.type == 'root') {
  9012. currentParent = tmpParent;
  9013. throw 'break'
  9014. }
  9015. }
  9016. //end tag
  9017. currentParent = currentParent.parentNode;
  9018. }
  9019. }
  9020. } else if (match[2]) {
  9021. //comment
  9022. comment(currentParent, match[2])
  9023. }
  9024. } catch (e) { }
  9025. nextIndex = re_tag.lastIndex;
  9026. }
  9027. //如果结束是文本,就有可能丢掉,所以这里手动判断一下
  9028. //例如 <li>sdfsdfsdf<li>sdfsdfsdfsdf
  9029. if (nextIndex < htmlstr.length) {
  9030. text(currentParent, htmlstr.slice(nextIndex));
  9031. }
  9032. return root;
  9033. };
  9034. // core/filternode.js
  9035. /**
  9036. * UE过滤节点的静态方法
  9037. * @file
  9038. */
  9039. /**
  9040. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  9041. * @module UE
  9042. */
  9043. /**
  9044. * 根据传入节点和过滤规则过滤相应节点
  9045. * @module UE
  9046. * @since 1.2.6.1
  9047. * @method filterNode
  9048. * @param { Object } root 指定root节点
  9049. * @param { Object } rules 过滤规则json对象
  9050. * @example
  9051. * ```javascript
  9052. * UE.filterNode(root,editor.options.filterRules);
  9053. * ```
  9054. */
  9055. var filterNode = UE.filterNode = function () {
  9056. function filterNode(node, rules) {
  9057. switch (node.type) {
  9058. case 'text':
  9059. break;
  9060. case 'element':
  9061. var val;
  9062. if (val = rules[node.tagName]) {
  9063. if (val === '-') {
  9064. node.parentNode.removeChild(node)
  9065. } else if (utils.isFunction(val)) {
  9066. var parentNode = node.parentNode,
  9067. index = node.getIndex();
  9068. val(node);
  9069. if (node.parentNode) {
  9070. if (node.children) {
  9071. for (var i = 0, ci; ci = node.children[i];) {
  9072. filterNode(ci, rules);
  9073. if (ci.parentNode) {
  9074. i++;
  9075. }
  9076. }
  9077. }
  9078. } else {
  9079. for (var i = index, ci; ci = parentNode.children[i];) {
  9080. filterNode(ci, rules);
  9081. if (ci.parentNode) {
  9082. i++;
  9083. }
  9084. }
  9085. }
  9086. } else {
  9087. var attrs = val['$'];
  9088. if (attrs && node.attrs) {
  9089. var tmpAttrs = {}, tmpVal;
  9090. for (var a in attrs) {
  9091. tmpVal = node.getAttr(a);
  9092. //todo 只先对style单独处理
  9093. if (a == 'style' && utils.isArray(attrs[a])) {
  9094. var tmpCssStyle = [];
  9095. utils.each(attrs[a], function (v) {
  9096. var tmp;
  9097. if (tmp = node.getStyle(v)) {
  9098. tmpCssStyle.push(v + ':' + tmp);
  9099. }
  9100. });
  9101. tmpVal = tmpCssStyle.join(';')
  9102. }
  9103. if (tmpVal) {
  9104. tmpAttrs[a] = tmpVal;
  9105. }
  9106. }
  9107. node.attrs = tmpAttrs;
  9108. }
  9109. if (node.children) {
  9110. for (var i = 0, ci; ci = node.children[i];) {
  9111. filterNode(ci, rules);
  9112. if (ci.parentNode) {
  9113. i++;
  9114. }
  9115. }
  9116. }
  9117. }
  9118. } else {
  9119. //如果不在名单里扣出子节点并删除该节点,cdata除外
  9120. if (dtd.$cdata[node.tagName]) {
  9121. node.parentNode.removeChild(node)
  9122. } else {
  9123. var parentNode = node.parentNode,
  9124. index = node.getIndex();
  9125. node.parentNode.removeChild(node, true);
  9126. for (var i = index, ci; ci = parentNode.children[i];) {
  9127. filterNode(ci, rules);
  9128. if (ci.parentNode) {
  9129. i++;
  9130. }
  9131. }
  9132. }
  9133. }
  9134. break;
  9135. case 'comment':
  9136. node.parentNode.removeChild(node)
  9137. }
  9138. }
  9139. return function (root, rules) {
  9140. if (utils.isEmptyObject(rules)) {
  9141. return root;
  9142. }
  9143. var val;
  9144. if (val = rules['-']) {
  9145. utils.each(val.split(' '), function (k) {
  9146. rules[k] = '-'
  9147. })
  9148. }
  9149. for (var i = 0, ci; ci = root.children[i];) {
  9150. filterNode(ci, rules);
  9151. if (ci.parentNode) {
  9152. i++;
  9153. }
  9154. }
  9155. return root;
  9156. }
  9157. }();
  9158. // core/plugin.js
  9159. /**
  9160. * Created with JetBrains PhpStorm.
  9161. * User: campaign
  9162. * Date: 10/8/13
  9163. * Time: 6:15 PM
  9164. * To change this template use File | Settings | File Templates.
  9165. */
  9166. UE.plugin = function () {
  9167. var _plugins = {};
  9168. return {
  9169. register: function (pluginName, fn, oldOptionName, afterDisabled) {
  9170. if (oldOptionName && utils.isFunction(oldOptionName)) {
  9171. afterDisabled = oldOptionName;
  9172. oldOptionName = null
  9173. }
  9174. _plugins[pluginName] = {
  9175. optionName: oldOptionName || pluginName,
  9176. execFn: fn,
  9177. //当插件被禁用时执行
  9178. afterDisabled: afterDisabled
  9179. }
  9180. },
  9181. load: function (editor) {
  9182. utils.each(_plugins, function (plugin) {
  9183. var _export = plugin.execFn.call(editor);
  9184. if (editor.options[plugin.optionName] !== false) {
  9185. if (_export) {
  9186. //后边需要再做扩展
  9187. utils.each(_export, function (v, k) {
  9188. switch (k.toLowerCase()) {
  9189. case 'shortcutkey':
  9190. editor.addshortcutkey(v);
  9191. break;
  9192. case 'bindevents':
  9193. utils.each(v, function (fn, eventName) {
  9194. editor.addListener(eventName, fn);
  9195. });
  9196. break;
  9197. case 'bindmultievents':
  9198. utils.each(utils.isArray(v) ? v : [v], function (event) {
  9199. var types = utils.trim(event.type).split(/\s+/);
  9200. utils.each(types, function (eventName) {
  9201. editor.addListener(eventName, event.handler);
  9202. });
  9203. });
  9204. break;
  9205. case 'commands':
  9206. utils.each(v, function (execFn, execName) {
  9207. editor.commands[execName] = execFn
  9208. });
  9209. break;
  9210. case 'outputrule':
  9211. editor.addOutputRule(v);
  9212. break;
  9213. case 'inputrule':
  9214. editor.addInputRule(v);
  9215. break;
  9216. case 'defaultoptions':
  9217. editor.setOpt(v)
  9218. }
  9219. })
  9220. }
  9221. } else if (plugin.afterDisabled) {
  9222. plugin.afterDisabled.call(editor)
  9223. }
  9224. });
  9225. //向下兼容
  9226. utils.each(UE.plugins, function (plugin) {
  9227. plugin.call(editor);
  9228. });
  9229. },
  9230. run: function (pluginName, editor) {
  9231. var plugin = _plugins[pluginName];
  9232. if (plugin) {
  9233. plugin.exeFn.call(editor)
  9234. }
  9235. }
  9236. }
  9237. }();
  9238. // core/keymap.js
  9239. var keymap = UE.keymap = {
  9240. 'Backspace': 8,
  9241. 'Tab': 9,
  9242. 'Enter': 13,
  9243. 'Shift': 16,
  9244. 'Control': 17,
  9245. 'Alt': 18,
  9246. 'CapsLock': 20,
  9247. 'Esc': 27,
  9248. 'Spacebar': 32,
  9249. 'PageUp': 33,
  9250. 'PageDown': 34,
  9251. 'End': 35,
  9252. 'Home': 36,
  9253. 'Left': 37,
  9254. 'Up': 38,
  9255. 'Right': 39,
  9256. 'Down': 40,
  9257. 'Insert': 45,
  9258. 'Del': 46,
  9259. 'NumLock': 144,
  9260. 'Cmd': 91,
  9261. '=': 187,
  9262. '-': 189,
  9263. "b": 66,
  9264. 'i': 73,
  9265. //回退
  9266. 'z': 90,
  9267. 'y': 89,
  9268. //粘贴
  9269. 'v': 86,
  9270. 'x': 88,
  9271. 's': 83,
  9272. 'n': 78
  9273. };
  9274. // core/localstorage.js
  9275. //存储媒介封装
  9276. var LocalStorage = UE.LocalStorage = (function () {
  9277. var storage = window.localStorage || getUserData() || null,
  9278. LOCAL_FILE = 'localStorage';
  9279. return {
  9280. saveLocalData: function (key, data) {
  9281. if (storage && data) {
  9282. storage.setItem(key, data);
  9283. return true;
  9284. }
  9285. return false;
  9286. },
  9287. getLocalData: function (key) {
  9288. if (storage) {
  9289. return storage.getItem(key);
  9290. }
  9291. return null;
  9292. },
  9293. removeItem: function (key) {
  9294. storage && storage.removeItem(key);
  9295. }
  9296. };
  9297. function getUserData() {
  9298. var container = document.createElement("div");
  9299. container.style.display = "none";
  9300. if (!container.addBehavior) {
  9301. return null;
  9302. }
  9303. container.addBehavior("#default#userdata");
  9304. return {
  9305. getItem: function (key) {
  9306. var result = null;
  9307. try {
  9308. document.body.appendChild(container);
  9309. container.load(LOCAL_FILE);
  9310. result = container.getAttribute(key);
  9311. document.body.removeChild(container);
  9312. } catch (e) {
  9313. }
  9314. return result;
  9315. },
  9316. setItem: function (key, value) {
  9317. document.body.appendChild(container);
  9318. container.setAttribute(key, value);
  9319. container.save(LOCAL_FILE);
  9320. document.body.removeChild(container);
  9321. },
  9322. //// 暂时没有用到
  9323. //clear: function () {
  9324. //
  9325. // var expiresTime = new Date();
  9326. // expiresTime.setFullYear(expiresTime.getFullYear() - 1);
  9327. // document.body.appendChild(container);
  9328. // container.expires = expiresTime.toUTCString();
  9329. // container.save(LOCAL_FILE);
  9330. // document.body.removeChild(container);
  9331. //
  9332. //},
  9333. removeItem: function (key) {
  9334. document.body.appendChild(container);
  9335. container.removeAttribute(key);
  9336. container.save(LOCAL_FILE);
  9337. document.body.removeChild(container);
  9338. }
  9339. };
  9340. }
  9341. })();
  9342. (function () {
  9343. var ROOTKEY = 'ueditor_preference';
  9344. UE.Editor.prototype.setPreferences = function (key, value) {
  9345. var obj = {};
  9346. if (utils.isString(key)) {
  9347. obj[key] = value;
  9348. } else {
  9349. obj = key;
  9350. }
  9351. var data = LocalStorage.getLocalData(ROOTKEY);
  9352. if (data && (data = utils.str2json(data))) {
  9353. utils.extend(data, obj);
  9354. } else {
  9355. data = obj;
  9356. }
  9357. data && LocalStorage.saveLocalData(ROOTKEY, utils.json2str(data));
  9358. };
  9359. UE.Editor.prototype.getPreferences = function (key) {
  9360. var data = LocalStorage.getLocalData(ROOTKEY);
  9361. if (data && (data = utils.str2json(data))) {
  9362. return key ? data[key] : data
  9363. }
  9364. return null;
  9365. };
  9366. UE.Editor.prototype.removePreferences = function (key) {
  9367. var data = LocalStorage.getLocalData(ROOTKEY);
  9368. if (data && (data = utils.str2json(data))) {
  9369. data[key] = undefined;
  9370. delete data[key]
  9371. }
  9372. data && LocalStorage.saveLocalData(ROOTKEY, utils.json2str(data));
  9373. };
  9374. })();
  9375. // plugins/defaultfilter.js
  9376. ///import core
  9377. ///plugin 编辑器默认的过滤转换机制
  9378. UE.plugins['defaultfilter'] = function () {
  9379. var me = this;
  9380. me.setOpt({
  9381. 'allowDivTransToP': true,
  9382. 'disabledTableInTable': true
  9383. });
  9384. //默认的过滤处理
  9385. //进入编辑器的内容处理
  9386. me.addInputRule(function (root) {
  9387. var allowDivTransToP = this.options.allowDivTransToP;
  9388. var val;
  9389. function tdParent(node) {
  9390. while (node && node.type == 'element') {
  9391. if (node.tagName == 'td') {
  9392. return true;
  9393. }
  9394. node = node.parentNode;
  9395. }
  9396. return false;
  9397. }
  9398. //进行默认的处理
  9399. root.traversal(function (node) {
  9400. if (node.type == 'element') {
  9401. if (!dtd.$cdata[node.tagName] && me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9402. if (!node.firstChild()) node.parentNode.removeChild(node);
  9403. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9404. node.parentNode.removeChild(node, true)
  9405. }
  9406. return;
  9407. }
  9408. switch (node.tagName) {
  9409. case 'style':
  9410. case 'script':
  9411. node.setAttr({
  9412. cdata_tag: node.tagName,
  9413. cdata_data: (node.innerHTML() || ''),
  9414. '_ue_custom_node_': 'true'
  9415. });
  9416. node.tagName = 'div';
  9417. node.innerHTML('');
  9418. break;
  9419. case 'a':
  9420. if (val = node.getAttr('href')) {
  9421. node.setAttr('_href', val)
  9422. }
  9423. break;
  9424. case 'img':
  9425. //todo base64暂时去掉,后边做远程图片上传后,干掉这个
  9426. if (val = node.getAttr('src')) {
  9427. if (/^data:/.test(val)) {
  9428. node.parentNode.removeChild(node);
  9429. break;
  9430. }
  9431. }
  9432. node.setAttr('_src', node.getAttr('src'));
  9433. break;
  9434. case 'span':
  9435. if (browser.webkit && (val = node.getStyle('white-space'))) {
  9436. if (/nowrap|normal/.test(val)) {
  9437. node.setStyle('white-space', '');
  9438. if (me.options.autoClearEmptyNode && utils.isEmptyObject(node.attrs)) {
  9439. node.parentNode.removeChild(node, true)
  9440. }
  9441. }
  9442. }
  9443. val = node.getAttr('id');
  9444. if (val && /^_baidu_bookmark_/i.test(val)) {
  9445. node.parentNode.removeChild(node)
  9446. }
  9447. break;
  9448. case 'p':
  9449. if (val = node.getAttr('align')) {
  9450. node.setAttr('align');
  9451. node.setStyle('text-align', val)
  9452. }
  9453. //trace:3431
  9454. // var cssStyle = node.getAttr('style');
  9455. // if (cssStyle) {
  9456. // cssStyle = cssStyle.replace(/(margin|padding)[^;]+/g, '');
  9457. // node.setAttr('style', cssStyle)
  9458. //
  9459. // }
  9460. //p标签不允许嵌套
  9461. utils.each(node.children, function (n) {
  9462. if (n.type == 'element' && n.tagName == 'p') {
  9463. var next = n.nextSibling();
  9464. node.parentNode.insertAfter(n, node);
  9465. var last = n;
  9466. while (next) {
  9467. var tmp = next.nextSibling();
  9468. node.parentNode.insertAfter(next, last);
  9469. last = next;
  9470. next = tmp;
  9471. }
  9472. return false;
  9473. }
  9474. });
  9475. if (!node.firstChild()) {
  9476. node.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  9477. }
  9478. break;
  9479. case 'div':
  9480. if (node.getAttr('cdata_tag')) {
  9481. break;
  9482. }
  9483. //针对代码这里不处理插入代码的div
  9484. val = node.getAttr('class');
  9485. if (val && /^line number\d+/.test(val)) {
  9486. break;
  9487. }
  9488. if (!allowDivTransToP) {
  9489. break;
  9490. }
  9491. var tmpNode, p = UE.uNode.createElement('p');
  9492. while (tmpNode = node.firstChild()) {
  9493. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  9494. p.appendChild(tmpNode);
  9495. } else {
  9496. if (p.firstChild()) {
  9497. node.parentNode.insertBefore(p, node);
  9498. p = UE.uNode.createElement('p');
  9499. } else {
  9500. node.parentNode.insertBefore(tmpNode, node);
  9501. }
  9502. }
  9503. }
  9504. if (p.firstChild()) {
  9505. node.parentNode.insertBefore(p, node);
  9506. }
  9507. node.parentNode.removeChild(node);
  9508. break;
  9509. case 'dl':
  9510. node.tagName = 'ul';
  9511. break;
  9512. case 'dt':
  9513. case 'dd':
  9514. node.tagName = 'li';
  9515. break;
  9516. case 'li':
  9517. var className = node.getAttr('class');
  9518. if (!className || !/list\-/.test(className)) {
  9519. node.setAttr()
  9520. }
  9521. var tmpNodes = node.getNodesByTagName('ol ul');
  9522. UE.utils.each(tmpNodes, function (n) {
  9523. node.parentNode.insertAfter(n, node);
  9524. });
  9525. break;
  9526. case 'td':
  9527. case 'th':
  9528. case 'caption':
  9529. if (!node.children || !node.children.length) {
  9530. node.appendChild(browser.ie11below ? UE.uNode.createText(' ') : UE.uNode.createElement('br'))
  9531. }
  9532. break;
  9533. case 'table':
  9534. if (me.options.disabledTableInTable && tdParent(node)) {
  9535. node.parentNode.insertBefore(UE.uNode.createText(node.innerText()), node);
  9536. node.parentNode.removeChild(node)
  9537. }
  9538. }
  9539. }
  9540. // if(node.type == 'comment'){
  9541. // node.parentNode.removeChild(node);
  9542. // }
  9543. })
  9544. });
  9545. //从编辑器出去的内容处理
  9546. me.addOutputRule(function (root) {
  9547. var val;
  9548. root.traversal(function (node) {
  9549. if (node.type == 'element') {
  9550. if (me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9551. if (!node.firstChild()) node.parentNode.removeChild(node);
  9552. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9553. node.parentNode.removeChild(node, true)
  9554. }
  9555. return;
  9556. }
  9557. switch (node.tagName) {
  9558. case 'div':
  9559. if (val = node.getAttr('cdata_tag')) {
  9560. node.tagName = val;
  9561. node.appendChild(UE.uNode.createText(node.getAttr('cdata_data')));
  9562. node.setAttr({ cdata_tag: '', cdata_data: '', '_ue_custom_node_': '' });
  9563. }
  9564. break;
  9565. case 'a':
  9566. if (val = node.getAttr('_href')) {
  9567. node.setAttr({
  9568. 'href': utils.html(val),
  9569. '_href': ''
  9570. })
  9571. }
  9572. break;
  9573. break;
  9574. case 'span':
  9575. val = node.getAttr('id');
  9576. if (val && /^_baidu_bookmark_/i.test(val)) {
  9577. node.parentNode.removeChild(node)
  9578. }
  9579. break;
  9580. case 'img':
  9581. if (val = node.getAttr('_src')) {
  9582. node.setAttr({
  9583. 'src': node.getAttr('_src'),
  9584. '_src': ''
  9585. })
  9586. }
  9587. }
  9588. }
  9589. })
  9590. });
  9591. };
  9592. // plugins/inserthtml.js
  9593. /**
  9594. * 插入html字符串插件
  9595. * @file
  9596. * @since 1.2.6.1
  9597. */
  9598. /**
  9599. * 插入html代码
  9600. * @command inserthtml
  9601. * @method execCommand
  9602. * @param { String } cmd 命令字符串
  9603. * @param { String } html 插入的html字符串
  9604. * @remaind 插入的标签内容是在当前的选区位置上插入,如果当前是闭合状态,那直接插入内容, 如果当前是选中状态,将先清除当前选中内容后,再做插入
  9605. * @warning 注意:该命令会对当前选区的位置,对插入的内容进行过滤转换处理。 过滤的规则遵循html语意化的原则。
  9606. * @example
  9607. * ```javascript
  9608. * //xxx[BB]xxx 当前选区为非闭合选区,选中BB这两个文本
  9609. * //执行命令,插入<b>CC</b>
  9610. * //插入后的效果 xxx<b>CC</b>xxx
  9611. * //<p>xx|xxx</p> 当前选区为闭合状态
  9612. * //插入<p>CC</p>
  9613. * //结果 <p>xx</p><p>CC</p><p>xxx</p>
  9614. * //<p>xxxx</p>|</p>xxx</p> 当前选区在两个p标签之间
  9615. * //插入 xxxx
  9616. * //结果 <p>xxxx</p><p>xxxx</p></p>xxx</p>
  9617. * ```
  9618. */
  9619. UE.commands['inserthtml'] = {
  9620. execCommand: function (command, html, notNeedFilter) {
  9621. var me = this,
  9622. range,
  9623. div;
  9624. if (!html) {
  9625. return;
  9626. }
  9627. if (me.fireEvent('beforeinserthtml', html) === true) {
  9628. return;
  9629. }
  9630. range = me.selection.getRange();
  9631. div = range.document.createElement('div');
  9632. div.style.display = 'inline';
  9633. if (!notNeedFilter) {
  9634. var root = UE.htmlparser(html);
  9635. //如果给了过滤规则就先进行过滤
  9636. if (me.options.filterRules) {
  9637. UE.filterNode(root, me.options.filterRules);
  9638. }
  9639. //执行默认的处理
  9640. me.filterInputRule(root);
  9641. html = root.toHtml()
  9642. }
  9643. div.innerHTML = utils.trim(html);
  9644. if (!range.collapsed) {
  9645. var tmpNode = range.startContainer;
  9646. if (domUtils.isFillChar(tmpNode)) {
  9647. range.setStartBefore(tmpNode)
  9648. }
  9649. tmpNode = range.endContainer;
  9650. if (domUtils.isFillChar(tmpNode)) {
  9651. range.setEndAfter(tmpNode)
  9652. }
  9653. range.txtToElmBoundary();
  9654. //结束边界可能放到了br的前边,要把br包含进来
  9655. // x[xxx]<br/>
  9656. if (range.endContainer && range.endContainer.nodeType == 1) {
  9657. tmpNode = range.endContainer.childNodes[range.endOffset];
  9658. if (tmpNode && domUtils.isBr(tmpNode)) {
  9659. range.setEndAfter(tmpNode);
  9660. }
  9661. }
  9662. if (range.startOffset == 0) {
  9663. tmpNode = range.startContainer;
  9664. if (domUtils.isBoundaryNode(tmpNode, 'firstChild')) {
  9665. tmpNode = range.endContainer;
  9666. if (range.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode, 'lastChild')) {
  9667. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  9668. range.setStart(me.body.firstChild, 0).collapse(true)
  9669. }
  9670. }
  9671. }
  9672. !range.collapsed && range.deleteContents();
  9673. if (range.startContainer.nodeType == 1) {
  9674. var child = range.startContainer.childNodes[range.startOffset], pre;
  9675. if (child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)) {
  9676. range.setEnd(pre, pre.childNodes.length).collapse();
  9677. while (child.firstChild) {
  9678. pre.appendChild(child.firstChild);
  9679. }
  9680. domUtils.remove(child);
  9681. }
  9682. }
  9683. }
  9684. var child, parent, pre, tmp, hadBreak = 0, nextNode;
  9685. //如果当前位置选中了fillchar要干掉,要不会产生空行
  9686. if (range.inFillChar()) {
  9687. child = range.startContainer;
  9688. if (domUtils.isFillChar(child)) {
  9689. range.setStartBefore(child).collapse(true);
  9690. domUtils.remove(child);
  9691. } else if (domUtils.isFillChar(child, true)) {
  9692. child.nodeValue = child.nodeValue.replace(fillCharReg, '');
  9693. range.startOffset--;
  9694. range.collapsed && range.collapse(true)
  9695. }
  9696. }
  9697. //列表单独处理
  9698. var li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  9699. if (li) {
  9700. var next, last;
  9701. while (child = div.firstChild) {
  9702. //针对hr单独处理一下先
  9703. while (child && (child.nodeType == 3 || !domUtils.isBlockElm(child) || child.tagName == 'HR')) {
  9704. next = child.nextSibling;
  9705. range.insertNode(child).collapse();
  9706. last = child;
  9707. child = next;
  9708. }
  9709. if (child) {
  9710. if (/^(ol|ul)$/i.test(child.tagName)) {
  9711. while (child.firstChild) {
  9712. last = child.firstChild;
  9713. domUtils.insertAfter(li, child.firstChild);
  9714. li = li.nextSibling;
  9715. }
  9716. domUtils.remove(child)
  9717. } else {
  9718. var tmpLi;
  9719. next = child.nextSibling;
  9720. tmpLi = me.document.createElement('li');
  9721. domUtils.insertAfter(li, tmpLi);
  9722. tmpLi.appendChild(child);
  9723. last = child;
  9724. child = next;
  9725. li = tmpLi;
  9726. }
  9727. }
  9728. }
  9729. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  9730. if (domUtils.isEmptyBlock(li)) {
  9731. domUtils.remove(li)
  9732. }
  9733. if (last) {
  9734. range.setStartAfter(last).collapse(true).select(true)
  9735. }
  9736. } else {
  9737. while (child = div.firstChild) {
  9738. if (hadBreak) {
  9739. var p = me.document.createElement('p');
  9740. while (child && (child.nodeType == 3 || !dtd.$block[child.tagName])) {
  9741. nextNode = child.nextSibling;
  9742. p.appendChild(child);
  9743. child = nextNode;
  9744. }
  9745. if (p.firstChild) {
  9746. child = p
  9747. }
  9748. }
  9749. range.insertNode(child);
  9750. nextNode = child.nextSibling;
  9751. if (!hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm(child)) {
  9752. parent = domUtils.findParent(child, function (node) { return domUtils.isBlockElm(node); });
  9753. if (parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)) {
  9754. if (!dtd[parent.tagName][child.nodeName]) {
  9755. pre = parent;
  9756. } else {
  9757. tmp = child.parentNode;
  9758. while (tmp !== parent) {
  9759. pre = tmp;
  9760. tmp = tmp.parentNode;
  9761. }
  9762. }
  9763. domUtils.breakParent(child, pre || tmp);
  9764. //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p>
  9765. var pre = child.previousSibling;
  9766. domUtils.trimWhiteTextNode(pre);
  9767. if (!pre.childNodes.length) {
  9768. domUtils.remove(pre);
  9769. }
  9770. //trace:2012,在非ie的情况,切开后剩下的节点有可能不能点入光标添加br占位
  9771. if (!browser.ie &&
  9772. (next = child.nextSibling) &&
  9773. domUtils.isBlockElm(next) &&
  9774. next.lastChild &&
  9775. !domUtils.isBr(next.lastChild)) {
  9776. next.appendChild(me.document.createElement('br'));
  9777. }
  9778. hadBreak = 1;
  9779. }
  9780. }
  9781. var next = child.nextSibling;
  9782. if (!div.firstChild && next && domUtils.isBlockElm(next)) {
  9783. range.setStart(next, 0).collapse(true);
  9784. break;
  9785. }
  9786. range.setEndAfter(child).collapse();
  9787. }
  9788. child = range.startContainer;
  9789. if (nextNode && domUtils.isBr(nextNode)) {
  9790. domUtils.remove(nextNode)
  9791. }
  9792. //用chrome可能有空白展位符
  9793. if (domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)) {
  9794. if (nextNode = child.nextSibling) {
  9795. domUtils.remove(child);
  9796. if (nextNode.nodeType == 1 && dtd.$block[nextNode.tagName]) {
  9797. range.setStart(nextNode, 0).collapse(true).shrinkBoundary()
  9798. }
  9799. } else {
  9800. try {
  9801. child.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  9802. } catch (e) {
  9803. range.setStartBefore(child);
  9804. domUtils.remove(child)
  9805. }
  9806. }
  9807. }
  9808. //加上true因为在删除表情等时会删两次,第一次是删的fillData
  9809. try {
  9810. range.select(true);
  9811. } catch (e) { }
  9812. }
  9813. setTimeout(function () {
  9814. range = me.selection.getRange();
  9815. range.scrollToView(me.autoHeightEnabled, me.autoHeightEnabled ? domUtils.getXY(me.iframe).y : 0);
  9816. me.fireEvent('afterinserthtml', html);
  9817. }, 200);
  9818. }
  9819. };
  9820. // plugins/autotypeset.js
  9821. /**
  9822. * 自动排版
  9823. * @file
  9824. * @since 1.2.6.1
  9825. */
  9826. /**
  9827. * 对当前编辑器的内容执行自动排版, 排版的行为根据config配置文件里的“autotypeset”选项进行控制。
  9828. * @command autotypeset
  9829. * @method execCommand
  9830. * @param { String } cmd 命令字符串
  9831. * @example
  9832. * ```javascript
  9833. * editor.execCommand( 'autotypeset' );
  9834. * ```
  9835. */
  9836. UE.plugins['autotypeset'] = function () {
  9837. this.setOpt({
  9838. 'autotypeset': {
  9839. mergeEmptyline: true, //合并空行
  9840. removeClass: true, //去掉冗余的class
  9841. removeEmptyline: false, //去掉空行
  9842. textAlign: "left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版
  9843. imageBlockLine: 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版
  9844. pasteFilter: false, //根据规则过滤没事粘贴进来的内容
  9845. clearFontSize: false, //去掉所有的内嵌字号,使用编辑器默认的字号
  9846. clearFontFamily: false, //去掉所有的内嵌字体,使用编辑器默认的字体
  9847. removeEmptyNode: false, // 去掉空节点
  9848. //可以去掉的标签
  9849. removeTagNames: utils.extend({ div: 1 }, dtd.$removeEmpty),
  9850. indent: false, // 行首缩进
  9851. indentValue: '2em', //行首缩进的大小
  9852. bdc2sb: false,
  9853. tobdc: false
  9854. }
  9855. });
  9856. var me = this,
  9857. opt = me.options.autotypeset,
  9858. remainClass = {
  9859. 'selectTdClass': 1,
  9860. 'pagebreak': 1,
  9861. 'anchorclass': 1
  9862. },
  9863. remainTag = {
  9864. 'li': 1
  9865. },
  9866. tags = {
  9867. div: 1,
  9868. p: 1,
  9869. //trace:2183 这些也认为是行
  9870. blockquote: 1, center: 1, h1: 1, h2: 1, h3: 1, h4: 1, h5: 1, h6: 1,
  9871. span: 1
  9872. },
  9873. highlightCont;
  9874. //升级了版本,但配置项目里没有autotypeset
  9875. if (!opt) {
  9876. return;
  9877. }
  9878. readLocalOpts();
  9879. function isLine(node, notEmpty) {
  9880. if (!node || node.nodeType == 3)
  9881. return 0;
  9882. if (domUtils.isBr(node))
  9883. return 1;
  9884. if (node && node.parentNode && tags[node.tagName.toLowerCase()]) {
  9885. if (highlightCont && highlightCont.contains(node)
  9886. ||
  9887. node.getAttribute('pagebreak')
  9888. ) {
  9889. return 0;
  9890. }
  9891. return notEmpty ? !domUtils.isEmptyBlock(node) : domUtils.isEmptyBlock(node, new RegExp('[\\s' + domUtils.fillChar
  9892. + ']', 'g'));
  9893. }
  9894. }
  9895. function removeNotAttributeSpan(node) {
  9896. if (!node.style.cssText) {
  9897. domUtils.removeAttributes(node, ['style']);
  9898. if (node.tagName.toLowerCase() == 'span' && domUtils.hasNoAttributes(node)) {
  9899. domUtils.remove(node, true);
  9900. }
  9901. }
  9902. }
  9903. function autotype(type, html) {
  9904. var me = this, cont;
  9905. if (html) {
  9906. if (!opt.pasteFilter) {
  9907. return;
  9908. }
  9909. cont = me.document.createElement('div');
  9910. cont.innerHTML = html.html;
  9911. } else {
  9912. cont = me.document.body;
  9913. }
  9914. var nodes = domUtils.getElementsByTagName(cont, '*');
  9915. // 行首缩进,段落方向,段间距,段内间距
  9916. for (var i = 0, ci; ci = nodes[i++];) {
  9917. if (me.fireEvent('excludeNodeinautotype', ci) === true) {
  9918. continue;
  9919. }
  9920. //font-size
  9921. if (opt.clearFontSize && ci.style.fontSize) {
  9922. domUtils.removeStyle(ci, 'font-size');
  9923. removeNotAttributeSpan(ci);
  9924. }
  9925. //font-family
  9926. if (opt.clearFontFamily && ci.style.fontFamily) {
  9927. domUtils.removeStyle(ci, 'font-family');
  9928. removeNotAttributeSpan(ci);
  9929. }
  9930. if (isLine(ci)) {
  9931. //合并空行
  9932. if (opt.mergeEmptyline) {
  9933. var next = ci.nextSibling, tmpNode, isBr = domUtils.isBr(ci);
  9934. while (isLine(next)) {
  9935. tmpNode = next;
  9936. next = tmpNode.nextSibling;
  9937. if (isBr && (!next || next && !domUtils.isBr(next))) {
  9938. break;
  9939. }
  9940. domUtils.remove(tmpNode);
  9941. }
  9942. }
  9943. //去掉空行,保留占位的空行
  9944. if (opt.removeEmptyline && domUtils.inDoc(ci, cont) && !remainTag[ci.parentNode.tagName.toLowerCase()]) {
  9945. if (domUtils.isBr(ci)) {
  9946. next = ci.nextSibling;
  9947. if (next && !domUtils.isBr(next)) {
  9948. continue;
  9949. }
  9950. }
  9951. domUtils.remove(ci);
  9952. continue;
  9953. }
  9954. }
  9955. if (isLine(ci, true) && ci.tagName != 'SPAN') {
  9956. if (opt.indent) {
  9957. ci.style.textIndent = opt.indentValue;
  9958. }
  9959. if (opt.textAlign) {
  9960. ci.style.textAlign = opt.textAlign;
  9961. }
  9962. // if(opt.lineHeight)
  9963. // ci.style.lineHeight = opt.lineHeight + 'cm';
  9964. }
  9965. //去掉class,保留的class不去掉
  9966. if (opt.removeClass && ci.className && !remainClass[ci.className.toLowerCase()]) {
  9967. if (highlightCont && highlightCont.contains(ci)) {
  9968. continue;
  9969. }
  9970. domUtils.removeAttributes(ci, ['class']);
  9971. }
  9972. //表情不处理
  9973. if (opt.imageBlockLine && ci.tagName.toLowerCase() == 'img' && !ci.getAttribute('emotion')) {
  9974. if (html) {
  9975. var img = ci;
  9976. switch (opt.imageBlockLine) {
  9977. case 'left':
  9978. case 'right':
  9979. case 'none':
  9980. var pN = img.parentNode, tmpNode, pre, next;
  9981. while (dtd.$inline[pN.tagName] || pN.tagName == 'A') {
  9982. pN = pN.parentNode;
  9983. }
  9984. tmpNode = pN;
  9985. if (tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode, 'text-align') == 'center') {
  9986. if (!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode, function (node) { return !domUtils.isBr(node) && !domUtils.isWhitespace(node) }) == 1) {
  9987. pre = tmpNode.previousSibling;
  9988. next = tmpNode.nextSibling;
  9989. if (pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)) {
  9990. pre.appendChild(tmpNode.firstChild);
  9991. while (next.firstChild) {
  9992. pre.appendChild(next.firstChild);
  9993. }
  9994. domUtils.remove(tmpNode);
  9995. domUtils.remove(next);
  9996. } else {
  9997. domUtils.setStyle(tmpNode, 'text-align', '');
  9998. }
  9999. }
  10000. }
  10001. domUtils.setStyle(img, 'float', opt.imageBlockLine);
  10002. break;
  10003. case 'center':
  10004. if (me.queryCommandValue('imagefloat') != 'center') {
  10005. pN = img.parentNode;
  10006. domUtils.setStyle(img, 'float', 'none');
  10007. tmpNode = img;
  10008. while (pN && domUtils.getChildCount(pN, function (node) { return !domUtils.isBr(node) && !domUtils.isWhitespace(node) }) == 1
  10009. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')) {
  10010. tmpNode = pN;
  10011. pN = pN.parentNode;
  10012. }
  10013. var pNode = me.document.createElement('p');
  10014. domUtils.setAttributes(pNode, {
  10015. style: 'text-align:center'
  10016. });
  10017. tmpNode.parentNode.insertBefore(pNode, tmpNode);
  10018. pNode.appendChild(tmpNode);
  10019. domUtils.setStyle(tmpNode, 'float', '');
  10020. }
  10021. }
  10022. } else {
  10023. var range = me.selection.getRange();
  10024. range.selectNode(ci).select();
  10025. me.execCommand('imagefloat', opt.imageBlockLine);
  10026. }
  10027. }
  10028. //去掉冗余的标签
  10029. if (opt.removeEmptyNode) {
  10030. if (opt.removeTagNames[ci.tagName.toLowerCase()] && domUtils.hasNoAttributes(ci) && domUtils.isEmptyBlock(ci)) {
  10031. domUtils.remove(ci);
  10032. }
  10033. }
  10034. }
  10035. if (opt.tobdc) {
  10036. var root = UE.htmlparser(cont.innerHTML);
  10037. root.traversal(function (node) {
  10038. if (node.type == 'text') {
  10039. node.data = ToDBC(node.data)
  10040. }
  10041. });
  10042. cont.innerHTML = root.toHtml()
  10043. }
  10044. if (opt.bdc2sb) {
  10045. var root = UE.htmlparser(cont.innerHTML);
  10046. root.traversal(function (node) {
  10047. if (node.type == 'text') {
  10048. node.data = DBC2SB(node.data)
  10049. }
  10050. });
  10051. cont.innerHTML = root.toHtml()
  10052. }
  10053. if (html) {
  10054. html.html = cont.innerHTML;
  10055. }
  10056. }
  10057. if (opt.pasteFilter) {
  10058. me.addListener('beforepaste', autotype);
  10059. }
  10060. function DBC2SB(str) {
  10061. var result = '';
  10062. for (var i = 0; i < str.length; i++) {
  10063. var code = str.charCodeAt(i); //获取当前字符的unicode编码
  10064. if (code >= 65281 && code <= 65373)//在这个unicode编码范围中的是所有的英文字母已经各种字符
  10065. {
  10066. result += String.fromCharCode(str.charCodeAt(i) - 65248); //把全角字符的unicode编码转换为对应半角字符的unicode码
  10067. } else if (code == 12288)//空格
  10068. {
  10069. result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
  10070. } else {
  10071. result += str.charAt(i);
  10072. }
  10073. }
  10074. return result;
  10075. }
  10076. function ToDBC(txtstring) {
  10077. txtstring = utils.html(txtstring);
  10078. var tmp = "";
  10079. var mark = "";/*用于判断,如果是html尖括里的标记,则不进行全角的转换*/
  10080. for (var i = 0; i < txtstring.length; i++) {
  10081. if (txtstring.charCodeAt(i) == 32) {
  10082. tmp = tmp + String.fromCharCode(12288);
  10083. }
  10084. else if (txtstring.charCodeAt(i) < 127) {
  10085. tmp = tmp + String.fromCharCode(txtstring.charCodeAt(i) + 65248);
  10086. }
  10087. else {
  10088. tmp += txtstring.charAt(i);
  10089. }
  10090. }
  10091. return tmp;
  10092. }
  10093. function readLocalOpts() {
  10094. var cookieOpt = me.getPreferences('autotypeset');
  10095. utils.extend(me.options.autotypeset, cookieOpt);
  10096. }
  10097. me.commands['autotypeset'] = {
  10098. execCommand: function () {
  10099. me.removeListener('beforepaste', autotype);
  10100. if (opt.pasteFilter) {
  10101. me.addListener('beforepaste', autotype);
  10102. }
  10103. autotype.call(me)
  10104. }
  10105. };
  10106. };
  10107. // plugins/autosubmit.js
  10108. /**
  10109. * 快捷键提交
  10110. * @file
  10111. * @since 1.2.6.1
  10112. */
  10113. /**
  10114. * 提交表单
  10115. * @command autosubmit
  10116. * @method execCommand
  10117. * @param { String } cmd 命令字符串
  10118. * @example
  10119. * ```javascript
  10120. * editor.execCommand( 'autosubmit' );
  10121. * ```
  10122. */
  10123. UE.plugin.register('autosubmit', function () {
  10124. return {
  10125. shortcutkey: {
  10126. "autosubmit": "ctrl+13" //手动提交
  10127. },
  10128. commands: {
  10129. 'autosubmit': {
  10130. execCommand: function () {
  10131. var me = this,
  10132. form = domUtils.findParentByTagName(me.iframe, "form", false);
  10133. if (form) {
  10134. if (me.fireEvent("beforesubmit") === false) {
  10135. return;
  10136. }
  10137. me.sync();
  10138. form.submit();
  10139. }
  10140. }
  10141. }
  10142. }
  10143. }
  10144. });
  10145. // plugins/background.js
  10146. /**
  10147. * 背景插件,为UEditor提供设置背景功能
  10148. * @file
  10149. * @since 1.2.6.1
  10150. */
  10151. UE.plugin.register('background', function () {
  10152. var me = this,
  10153. cssRuleId = 'editor_background',
  10154. isSetColored,
  10155. reg = new RegExp('body[\\s]*\\{(.+)\\}', 'i');
  10156. function stringToObj(str) {
  10157. var obj = {}, styles = str.split(';');
  10158. utils.each(styles, function (v) {
  10159. var index = v.indexOf(':'),
  10160. key = utils.trim(v.substr(0, index)).toLowerCase();
  10161. key && (obj[key] = utils.trim(v.substr(index + 1) || ''));
  10162. });
  10163. return obj;
  10164. }
  10165. function setBackground(obj) {
  10166. if (obj) {
  10167. var styles = [];
  10168. for (var name in obj) {
  10169. if (obj.hasOwnProperty(name)) {
  10170. styles.push(name + ":" + obj[name] + '; ');
  10171. }
  10172. }
  10173. utils.cssRule(cssRuleId, styles.length ? ('body{' + styles.join("") + '}') : '', me.document);
  10174. } else {
  10175. utils.cssRule(cssRuleId, '', me.document)
  10176. }
  10177. }
  10178. //重写editor.hasContent方法
  10179. var orgFn = me.hasContents;
  10180. me.hasContents = function () {
  10181. if (me.queryCommandValue('background')) {
  10182. return true
  10183. }
  10184. return orgFn.apply(me, arguments);
  10185. };
  10186. return {
  10187. bindEvents: {
  10188. 'getAllHtml': function (type, headHtml) {
  10189. var body = this.body,
  10190. su = domUtils.getComputedStyle(body, "background-image"),
  10191. url = "";
  10192. if (su.indexOf(me.options.imagePath) > 0) {
  10193. url = su.substring(su.indexOf(me.options.imagePath), su.length - 1).replace(/"|\(|\)/ig, "");
  10194. } else {
  10195. url = su != "none" ? su.replace(/url\("?|"?\)/ig, "") : "";
  10196. }
  10197. var html = '<style type="text/css">body{';
  10198. var bgObj = {
  10199. "background-color": domUtils.getComputedStyle(body, "background-color") || "#ffffff",
  10200. 'background-image': url ? 'url(' + url + ')' : '',
  10201. 'background-repeat': domUtils.getComputedStyle(body, "background-repeat") || "",
  10202. 'background-position': browser.ie ? (domUtils.getComputedStyle(body, "background-position-x") + " " + domUtils.getComputedStyle(body, "background-position-y")) : domUtils.getComputedStyle(body, "background-position"),
  10203. 'height': domUtils.getComputedStyle(body, "height")
  10204. };
  10205. for (var name in bgObj) {
  10206. if (bgObj.hasOwnProperty(name)) {
  10207. html += name + ":" + bgObj[name] + "; ";
  10208. }
  10209. }
  10210. html += '}</style> ';
  10211. headHtml.push(html);
  10212. },
  10213. 'aftersetcontent': function () {
  10214. if (isSetColored == false) setBackground();
  10215. }
  10216. },
  10217. inputRule: function (root) {
  10218. isSetColored = false;
  10219. utils.each(root.getNodesByTagName('p'), function (p) {
  10220. var styles = p.getAttr('data-background');
  10221. if (styles) {
  10222. isSetColored = true;
  10223. setBackground(stringToObj(styles));
  10224. p.parentNode.removeChild(p);
  10225. }
  10226. })
  10227. },
  10228. outputRule: function (root) {
  10229. var me = this,
  10230. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  10231. if (styles) {
  10232. root.appendChild(UE.uNode.createElement('<p style="display:none;" data-background="' + utils.trim(styles[1].replace(/"/g, '').replace(/[\s]+/g, ' ')) + '"><br/></p>'));
  10233. }
  10234. },
  10235. commands: {
  10236. 'background': {
  10237. execCommand: function (cmd, obj) {
  10238. setBackground(obj);
  10239. },
  10240. queryCommandValue: function () {
  10241. var me = this,
  10242. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  10243. return styles ? stringToObj(styles[1]) : null;
  10244. },
  10245. notNeedUndo: true
  10246. }
  10247. }
  10248. }
  10249. });
  10250. // plugins/image.js
  10251. /**
  10252. * 图片插入、排版插件
  10253. * @file
  10254. * @since 1.2.6.1
  10255. */
  10256. /**
  10257. * 图片对齐方式
  10258. * @command imagefloat
  10259. * @method execCommand
  10260. * @remind 值center为独占一行居中
  10261. * @param { String } cmd 命令字符串
  10262. * @param { String } align 对齐方式,可传left、right、none、center
  10263. * @remaind center表示图片独占一行
  10264. * @example
  10265. * ```javascript
  10266. * editor.execCommand( 'imagefloat', 'center' );
  10267. * ```
  10268. */
  10269. /**
  10270. * 如果选区所在位置是图片区域
  10271. * @command imagefloat
  10272. * @method queryCommandValue
  10273. * @param { String } cmd 命令字符串
  10274. * @return { String } 返回图片对齐方式
  10275. * @example
  10276. * ```javascript
  10277. * editor.queryCommandValue( 'imagefloat' );
  10278. * ```
  10279. */
  10280. UE.commands['imagefloat'] = {
  10281. execCommand: function (cmd, align) {
  10282. var me = this,
  10283. range = me.selection.getRange();
  10284. if (!range.collapsed) {
  10285. var img = range.getClosedNode();
  10286. if (img && img.tagName == 'IMG') {
  10287. switch (align) {
  10288. case 'left':
  10289. case 'right':
  10290. case 'none':
  10291. var pN = img.parentNode, tmpNode, pre, next;
  10292. while (dtd.$inline[pN.tagName] || pN.tagName == 'A') {
  10293. pN = pN.parentNode;
  10294. }
  10295. tmpNode = pN;
  10296. if (tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode, 'text-align') == 'center') {
  10297. if (!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode, function (node) {
  10298. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  10299. }) == 1) {
  10300. pre = tmpNode.previousSibling;
  10301. next = tmpNode.nextSibling;
  10302. if (pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)) {
  10303. pre.appendChild(tmpNode.firstChild);
  10304. while (next.firstChild) {
  10305. pre.appendChild(next.firstChild);
  10306. }
  10307. domUtils.remove(tmpNode);
  10308. domUtils.remove(next);
  10309. } else {
  10310. domUtils.setStyle(tmpNode, 'text-align', '');
  10311. }
  10312. }
  10313. range.selectNode(img).select();
  10314. }
  10315. domUtils.setStyle(img, 'float', align == 'none' ? '' : align);
  10316. if (align == 'none') {
  10317. domUtils.removeAttributes(img, 'align');
  10318. }
  10319. break;
  10320. case 'center':
  10321. if (me.queryCommandValue('imagefloat') != 'center') {
  10322. pN = img.parentNode;
  10323. domUtils.setStyle(img, 'float', '');
  10324. domUtils.removeAttributes(img, 'align');
  10325. tmpNode = img;
  10326. while (pN && domUtils.getChildCount(pN, function (node) {
  10327. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  10328. }) == 1
  10329. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')) {
  10330. tmpNode = pN;
  10331. pN = pN.parentNode;
  10332. }
  10333. range.setStartBefore(tmpNode).setCursor(false);
  10334. pN = me.document.createElement('div');
  10335. pN.appendChild(tmpNode);
  10336. domUtils.setStyle(tmpNode, 'float', '');
  10337. me.execCommand('insertHtml', '<p id="_img_parent_tmp" style="text-align:center">' + pN.innerHTML + '</p>');
  10338. tmpNode = me.document.getElementById('_img_parent_tmp');
  10339. tmpNode.removeAttribute('id');
  10340. tmpNode = tmpNode.firstChild;
  10341. range.selectNode(tmpNode).select();
  10342. //去掉后边多余的元素
  10343. next = tmpNode.parentNode.nextSibling;
  10344. if (next && domUtils.isEmptyNode(next)) {
  10345. domUtils.remove(next);
  10346. }
  10347. }
  10348. break;
  10349. }
  10350. }
  10351. }
  10352. },
  10353. queryCommandValue: function () {
  10354. var range = this.selection.getRange(),
  10355. startNode, floatStyle;
  10356. if (range.collapsed) {
  10357. return 'none';
  10358. }
  10359. startNode = range.getClosedNode();
  10360. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  10361. floatStyle = domUtils.getComputedStyle(startNode, 'float') || startNode.getAttribute('align');
  10362. if (floatStyle == 'none') {
  10363. floatStyle = domUtils.getComputedStyle(startNode.parentNode, 'text-align') == 'center' ? 'center' : floatStyle;
  10364. }
  10365. return {
  10366. left: 1,
  10367. right: 1,
  10368. center: 1
  10369. }[floatStyle] ? floatStyle : 'none';
  10370. }
  10371. return 'none';
  10372. },
  10373. queryCommandState: function () {
  10374. var range = this.selection.getRange(),
  10375. startNode;
  10376. if (range.collapsed) return -1;
  10377. startNode = range.getClosedNode();
  10378. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  10379. return 0;
  10380. }
  10381. return -1;
  10382. }
  10383. };
  10384. /**
  10385. * 插入图片
  10386. * @command insertimage
  10387. * @method execCommand
  10388. * @param { String } cmd 命令字符串
  10389. * @param { Object } opt 属性键值对,这些属性都将被复制到当前插入图片
  10390. * @remind 该命令第二个参数可接受一个图片配置项对象的数组,可以插入多张图片,
  10391. * 此时数组的每一个元素都是一个Object类型的图片属性集合。
  10392. * @example
  10393. * ```javascript
  10394. * editor.execCommand( 'insertimage', {
  10395. * src:'a/b/c.jpg',
  10396. * width:'100',
  10397. * height:'100'
  10398. * } );
  10399. * ```
  10400. * @example
  10401. * ```javascript
  10402. * editor.execCommand( 'insertimage', [{
  10403. * src:'a/b/c.jpg',
  10404. * width:'100',
  10405. * height:'100'
  10406. * },{
  10407. * src:'a/b/d.jpg',
  10408. * width:'100',
  10409. * height:'100'
  10410. * }] );
  10411. * ```
  10412. */
  10413. UE.commands['insertimage'] = {
  10414. execCommand: function (cmd, opt) {
  10415. opt = utils.isArray(opt) ? opt : [opt];
  10416. if (!opt.length) {
  10417. return;
  10418. }
  10419. var me = this,
  10420. range = me.selection.getRange(),
  10421. img = range.getClosedNode();
  10422. if (me.fireEvent('beforeinsertimage', opt) === true) {
  10423. return;
  10424. }
  10425. function unhtmlData(imgCi) {
  10426. utils.each('width,height,border,hspace,vspace'.split(','), function (item) {
  10427. if (imgCi[item]) {
  10428. imgCi[item] = parseInt(imgCi[item], 10) || 0;
  10429. }
  10430. });
  10431. utils.each('src,_src'.split(','), function (item) {
  10432. if (imgCi[item]) {
  10433. imgCi[item] = utils.unhtmlForUrl(imgCi[item]);
  10434. }
  10435. });
  10436. utils.each('title,alt'.split(','), function (item) {
  10437. if (imgCi[item]) {
  10438. imgCi[item] = utils.unhtml(imgCi[item]);
  10439. }
  10440. });
  10441. }
  10442. if (img && /img/i.test(img.tagName) && (img.className != "edui-faked-video" || img.className.indexOf("edui-upload-video") != -1) && !img.getAttribute("word_img")) {
  10443. var first = opt.shift();
  10444. var floatStyle = first['floatStyle'];
  10445. delete first['floatStyle'];
  10446. //// img.style.border = (first.border||0) +"px solid #000";
  10447. //// img.style.margin = (first.margin||0) +"px";
  10448. // img.style.cssText += ';margin:' + (first.margin||0) +"px;" + 'border:' + (first.border||0) +"px solid #000";
  10449. domUtils.setAttributes(img, first);
  10450. me.execCommand('imagefloat', floatStyle);
  10451. if (opt.length > 0) {
  10452. range.setStartAfter(img).setCursor(false, true);
  10453. me.execCommand('insertimage', opt);
  10454. }
  10455. } else {
  10456. var html = [], str = '', ci;
  10457. ci = opt[0];
  10458. if (opt.length == 1) {
  10459. unhtmlData(ci);
  10460. str = '<img src="' + ci.src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  10461. (ci.width ? 'width="' + ci.width + '" ' : '') +
  10462. (ci.height ? ' height="' + ci.height + '" ' : '') +
  10463. (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') +
  10464. (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') +
  10465. (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') +
  10466. (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') +
  10467. (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') +
  10468. (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>';
  10469. if (ci['floatStyle'] == 'center') {
  10470. str = '<p style="text-align: center">' + str + '</p>';
  10471. }
  10472. html.push(str);
  10473. } else {
  10474. for (var i = 0; ci = opt[i++];) {
  10475. unhtmlData(ci);
  10476. str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + ci.src + '" ' +
  10477. (ci.width ? 'width="' + ci.width + '" ' : '') + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  10478. (ci.height ? ' height="' + ci.height + '" ' : '') +
  10479. ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') +
  10480. (ci.border || '') + '" ' +
  10481. (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>';
  10482. html.push(str);
  10483. }
  10484. }
  10485. me.execCommand('insertHtml', html.join(''));
  10486. }
  10487. me.fireEvent('afterinsertimage', opt)
  10488. }
  10489. };
  10490. // plugins/justify.js
  10491. /**
  10492. * 段落格式
  10493. * @file
  10494. * @since 1.2.6.1
  10495. */
  10496. /**
  10497. * 段落对齐方式
  10498. * @command justify
  10499. * @method execCommand
  10500. * @param { String } cmd 命令字符串
  10501. * @param { String } align 对齐方式:left => 居左,right => 居右,center => 居中,justify => 两端对齐
  10502. * @example
  10503. * ```javascript
  10504. * editor.execCommand( 'justify', 'center' );
  10505. * ```
  10506. */
  10507. /**
  10508. * 如果选区所在位置是段落区域,返回当前段落对齐方式
  10509. * @command justify
  10510. * @method queryCommandValue
  10511. * @param { String } cmd 命令字符串
  10512. * @return { String } 返回段落对齐方式
  10513. * @example
  10514. * ```javascript
  10515. * editor.queryCommandValue( 'justify' );
  10516. * ```
  10517. */
  10518. UE.plugins['justify'] = function () {
  10519. var me = this,
  10520. block = domUtils.isBlockElm,
  10521. defaultValue = {
  10522. left: 1,
  10523. right: 1,
  10524. center: 1,
  10525. justify: 1
  10526. },
  10527. doJustify = function (range, style) {
  10528. var bookmark = range.createBookmark(),
  10529. filterFn = function (node) {
  10530. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  10531. };
  10532. range.enlarge(true);
  10533. var bookmark2 = range.createBookmark(),
  10534. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn),
  10535. tmpRange = range.cloneRange(),
  10536. tmpNode;
  10537. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  10538. if (current.nodeType == 3 || !block(current)) {
  10539. tmpRange.setStartBefore(current);
  10540. while (current && current !== bookmark2.end && !block(current)) {
  10541. tmpNode = current;
  10542. current = domUtils.getNextDomNode(current, false, null, function (node) {
  10543. return !block(node);
  10544. });
  10545. }
  10546. tmpRange.setEndAfter(tmpNode);
  10547. var common = tmpRange.getCommonAncestor();
  10548. if (!domUtils.isBody(common) && block(common)) {
  10549. domUtils.setStyles(common, utils.isString(style) ? { 'text-align': style } : style);
  10550. current = common;
  10551. } else {
  10552. var p = range.document.createElement('p');
  10553. domUtils.setStyles(p, utils.isString(style) ? { 'text-align': style } : style);
  10554. var frag = tmpRange.extractContents();
  10555. p.appendChild(frag);
  10556. tmpRange.insertNode(p);
  10557. current = p;
  10558. }
  10559. current = domUtils.getNextDomNode(current, false, filterFn);
  10560. } else {
  10561. current = domUtils.getNextDomNode(current, true, filterFn);
  10562. }
  10563. }
  10564. return range.moveToBookmark(bookmark2).moveToBookmark(bookmark);
  10565. };
  10566. UE.commands['justify'] = {
  10567. execCommand: function (cmdName, align) {
  10568. var range = this.selection.getRange(),
  10569. txt;
  10570. //闭合时单独处理
  10571. if (range.collapsed) {
  10572. txt = this.document.createTextNode('p');
  10573. range.insertNode(txt);
  10574. }
  10575. doJustify(range, align);
  10576. if (txt) {
  10577. range.setStartBefore(txt).collapse(true);
  10578. domUtils.remove(txt);
  10579. }
  10580. range.select();
  10581. return true;
  10582. },
  10583. queryCommandValue: function () {
  10584. var startNode = this.selection.getStart(),
  10585. value = domUtils.getComputedStyle(startNode, 'text-align');
  10586. return defaultValue[value] ? value : 'left';
  10587. },
  10588. queryCommandState: function () {
  10589. var start = this.selection.getStart(),
  10590. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  10591. return cell ? -1 : 0;
  10592. }
  10593. };
  10594. };
  10595. // plugins/font.js
  10596. /**
  10597. * 字体颜色,背景色,字号,字体,下划线,删除线
  10598. * @file
  10599. * @since 1.2.6.1
  10600. */
  10601. /**
  10602. * 字体颜色
  10603. * @command forecolor
  10604. * @method execCommand
  10605. * @param { String } cmd 命令字符串
  10606. * @param { String } value 色值(必须十六进制)
  10607. * @example
  10608. * ```javascript
  10609. * editor.execCommand( 'forecolor', '#000' );
  10610. * ```
  10611. */
  10612. /**
  10613. * 返回选区字体颜色
  10614. * @command forecolor
  10615. * @method queryCommandValue
  10616. * @param { String } cmd 命令字符串
  10617. * @return { String } 返回字体颜色
  10618. * @example
  10619. * ```javascript
  10620. * editor.queryCommandValue( 'forecolor' );
  10621. * ```
  10622. */
  10623. /**
  10624. * 字体背景颜色
  10625. * @command backcolor
  10626. * @method execCommand
  10627. * @param { String } cmd 命令字符串
  10628. * @param { String } value 色值(必须十六进制)
  10629. * @example
  10630. * ```javascript
  10631. * editor.execCommand( 'backcolor', '#000' );
  10632. * ```
  10633. */
  10634. /**
  10635. * 返回选区字体颜色
  10636. * @command backcolor
  10637. * @method queryCommandValue
  10638. * @param { String } cmd 命令字符串
  10639. * @return { String } 返回字体背景颜色
  10640. * @example
  10641. * ```javascript
  10642. * editor.queryCommandValue( 'backcolor' );
  10643. * ```
  10644. */
  10645. /**
  10646. * 字体大小
  10647. * @command fontsize
  10648. * @method execCommand
  10649. * @param { String } cmd 命令字符串
  10650. * @param { String } value 字体大小
  10651. * @example
  10652. * ```javascript
  10653. * editor.execCommand( 'fontsize', '14px' );
  10654. * ```
  10655. */
  10656. /**
  10657. * 返回选区字体大小
  10658. * @command fontsize
  10659. * @method queryCommandValue
  10660. * @param { String } cmd 命令字符串
  10661. * @return { String } 返回字体大小
  10662. * @example
  10663. * ```javascript
  10664. * editor.queryCommandValue( 'fontsize' );
  10665. * ```
  10666. */
  10667. /**
  10668. * 字体样式
  10669. * @command fontfamily
  10670. * @method execCommand
  10671. * @param { String } cmd 命令字符串
  10672. * @param { String } value 字体样式
  10673. * @example
  10674. * ```javascript
  10675. * editor.execCommand( 'fontfamily', '微软雅黑' );
  10676. * ```
  10677. */
  10678. /**
  10679. * 返回选区字体样式
  10680. * @command fontfamily
  10681. * @method queryCommandValue
  10682. * @param { String } cmd 命令字符串
  10683. * @return { String } 返回字体样式
  10684. * @example
  10685. * ```javascript
  10686. * editor.queryCommandValue( 'fontfamily' );
  10687. * ```
  10688. */
  10689. /**
  10690. * 字体下划线,与删除线互斥
  10691. * @command underline
  10692. * @method execCommand
  10693. * @param { String } cmd 命令字符串
  10694. * @example
  10695. * ```javascript
  10696. * editor.execCommand( 'underline' );
  10697. * ```
  10698. */
  10699. /**
  10700. * 字体删除线,与下划线互斥
  10701. * @command strikethrough
  10702. * @method execCommand
  10703. * @param { String } cmd 命令字符串
  10704. * @example
  10705. * ```javascript
  10706. * editor.execCommand( 'strikethrough' );
  10707. * ```
  10708. */
  10709. /**
  10710. * 字体边框
  10711. * @command fontborder
  10712. * @method execCommand
  10713. * @param { String } cmd 命令字符串
  10714. * @example
  10715. * ```javascript
  10716. * editor.execCommand( 'fontborder' );
  10717. * ```
  10718. */
  10719. UE.plugins['font'] = function () {
  10720. var me = this,
  10721. fonts = {
  10722. 'forecolor': 'color',
  10723. 'backcolor': 'background-color',
  10724. 'fontsize': 'font-size',
  10725. 'fontfamily': 'font-family',
  10726. 'underline': 'text-decoration',
  10727. 'strikethrough': 'text-decoration',
  10728. 'fontborder': 'border'
  10729. },
  10730. needCmd = { 'underline': 1, 'strikethrough': 1, 'fontborder': 1 },
  10731. needSetChild = {
  10732. 'forecolor': 'color',
  10733. 'backcolor': 'background-color',
  10734. 'fontsize': 'font-size',
  10735. 'fontfamily': 'font-family'
  10736. };
  10737. me.setOpt({
  10738. 'fontfamily': [
  10739. { name: 'songti', val: '宋体,SimSun' },
  10740. { name: 'yahei', val: '微软雅黑,Microsoft YaHei' },
  10741. { name: 'kaiti', val: '楷体,楷体_GB2312, SimKai' },
  10742. { name: 'heiti', val: '黑体, SimHei' },
  10743. { name: 'lishu', val: '隶书, SimLi' },
  10744. { name: 'andaleMono', val: 'andale mono' },
  10745. { name: 'arial', val: 'arial, helvetica,sans-serif' },
  10746. { name: 'arialBlack', val: 'arial black,avant garde' },
  10747. { name: 'comicSansMs', val: 'comic sans ms' },
  10748. { name: 'impact', val: 'impact,chicago' },
  10749. { name: 'timesNewRoman', val: 'times new roman' }
  10750. ],
  10751. 'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36]
  10752. });
  10753. function mergeWithParent(node) {
  10754. var parent;
  10755. while (parent = node.parentNode) {
  10756. if (parent.tagName == 'SPAN' && domUtils.getChildCount(parent, function (child) {
  10757. return !domUtils.isBookmarkNode(child) && !domUtils.isBr(child)
  10758. }) == 1) {
  10759. parent.style.cssText += node.style.cssText;
  10760. domUtils.remove(node, true);
  10761. node = parent;
  10762. } else {
  10763. break;
  10764. }
  10765. }
  10766. }
  10767. function mergeChild(rng, cmdName, value) {
  10768. if (needSetChild[cmdName]) {
  10769. rng.adjustmentBoundary();
  10770. if (!rng.collapsed && rng.startContainer.nodeType == 1) {
  10771. var start = rng.startContainer.childNodes[rng.startOffset];
  10772. if (start && domUtils.isTagNode(start, 'span')) {
  10773. var bk = rng.createBookmark();
  10774. utils.each(domUtils.getElementsByTagName(start, 'span'), function (span) {
  10775. if (!span.parentNode || domUtils.isBookmarkNode(span)) return;
  10776. if (cmdName == 'backcolor' && domUtils.getComputedStyle(span, 'background-color').toLowerCase() === value) {
  10777. return;
  10778. }
  10779. domUtils.removeStyle(span, needSetChild[cmdName]);
  10780. if (span.style.cssText.replace(/^\s+$/, '').length == 0) {
  10781. domUtils.remove(span, true)
  10782. }
  10783. });
  10784. rng.moveToBookmark(bk)
  10785. }
  10786. }
  10787. }
  10788. }
  10789. function mergesibling(rng, cmdName, value) {
  10790. var collapsed = rng.collapsed,
  10791. bk = rng.createBookmark(), common;
  10792. if (collapsed) {
  10793. common = bk.start.parentNode;
  10794. while (dtd.$inline[common.tagName]) {
  10795. common = common.parentNode;
  10796. }
  10797. } else {
  10798. common = domUtils.getCommonAncestor(bk.start, bk.end);
  10799. }
  10800. utils.each(domUtils.getElementsByTagName(common, 'span'), function (span) {
  10801. if (!span.parentNode || domUtils.isBookmarkNode(span)) return;
  10802. if (/\s*border\s*:\s*none;?\s*/i.test(span.style.cssText)) {
  10803. if (/^\s*border\s*:\s*none;?\s*$/.test(span.style.cssText)) {
  10804. domUtils.remove(span, true);
  10805. } else {
  10806. domUtils.removeStyle(span, 'border');
  10807. }
  10808. return
  10809. }
  10810. if (/border/i.test(span.style.cssText) && span.parentNode.tagName == 'SPAN' && /border/i.test(span.parentNode.style.cssText)) {
  10811. span.style.cssText = span.style.cssText.replace(/border[^:]*:[^;]+;?/gi, '');
  10812. }
  10813. if (!(cmdName == 'fontborder' && value == 'none')) {
  10814. var next = span.nextSibling;
  10815. while (next && next.nodeType == 1 && next.tagName == 'SPAN') {
  10816. if (domUtils.isBookmarkNode(next) && cmdName == 'fontborder') {
  10817. span.appendChild(next);
  10818. next = span.nextSibling;
  10819. continue;
  10820. }
  10821. if (next.style.cssText == span.style.cssText) {
  10822. domUtils.moveChild(next, span);
  10823. domUtils.remove(next);
  10824. }
  10825. if (span.nextSibling === next)
  10826. break;
  10827. next = span.nextSibling;
  10828. }
  10829. }
  10830. mergeWithParent(span);
  10831. if (browser.ie && browser.version > 8) {
  10832. //拷贝父亲们的特别的属性,这里只做背景颜色的处理
  10833. var parent = domUtils.findParent(span, function (n) { return n.tagName == 'SPAN' && /background-color/.test(n.style.cssText) });
  10834. if (parent && !/background-color/.test(span.style.cssText)) {
  10835. span.style.backgroundColor = parent.style.backgroundColor;
  10836. }
  10837. }
  10838. });
  10839. rng.moveToBookmark(bk);
  10840. mergeChild(rng, cmdName, value)
  10841. }
  10842. me.addInputRule(function (root) {
  10843. utils.each(root.getNodesByTagName('u s del font strike'), function (node) {
  10844. if (node.tagName == 'font') {
  10845. var cssStyle = [];
  10846. for (var p in node.attrs) {
  10847. switch (p) {
  10848. case 'size':
  10849. cssStyle.push('font-size:' +
  10850. ({
  10851. '1': '10',
  10852. '2': '12',
  10853. '3': '16',
  10854. '4': '18',
  10855. '5': '24',
  10856. '6': '32',
  10857. '7': '48'
  10858. }[node.attrs[p]] || node.attrs[p]) + 'px');
  10859. break;
  10860. case 'color':
  10861. cssStyle.push('color:' + node.attrs[p]);
  10862. break;
  10863. case 'face':
  10864. cssStyle.push('font-family:' + node.attrs[p]);
  10865. break;
  10866. case 'style':
  10867. cssStyle.push(node.attrs[p]);
  10868. }
  10869. }
  10870. node.attrs = {
  10871. 'style': cssStyle.join(';')
  10872. };
  10873. } else {
  10874. var val = node.tagName == 'u' ? 'underline' : 'line-through';
  10875. node.attrs = {
  10876. 'style': (node.getAttr('style') || '') + 'text-decoration:' + val + ';'
  10877. }
  10878. }
  10879. node.tagName = 'span';
  10880. });
  10881. // utils.each(root.getNodesByTagName('span'), function (node) {
  10882. // var val;
  10883. // if(val = node.getAttr('class')){
  10884. // if(/fontstrikethrough/.test(val)){
  10885. // node.setStyle('text-decoration','line-through');
  10886. // if(node.attrs['class']){
  10887. // node.attrs['class'] = node.attrs['class'].replace(/fontstrikethrough/,'');
  10888. // }else{
  10889. // node.setAttr('class')
  10890. // }
  10891. // }
  10892. // if(/fontborder/.test(val)){
  10893. // node.setStyle('border','1px solid #000');
  10894. // if(node.attrs['class']){
  10895. // node.attrs['class'] = node.attrs['class'].replace(/fontborder/,'');
  10896. // }else{
  10897. // node.setAttr('class')
  10898. // }
  10899. // }
  10900. // }
  10901. // });
  10902. });
  10903. // me.addOutputRule(function(root){
  10904. // utils.each(root.getNodesByTagName('span'), function (node) {
  10905. // var val;
  10906. // if(val = node.getStyle('text-decoration')){
  10907. // if(/line-through/.test(val)){
  10908. // if(node.attrs['class']){
  10909. // node.attrs['class'] += ' fontstrikethrough';
  10910. // }else{
  10911. // node.setAttr('class','fontstrikethrough')
  10912. // }
  10913. // }
  10914. //
  10915. // node.setStyle('text-decoration')
  10916. // }
  10917. // if(val = node.getStyle('border')){
  10918. // if(/1px/.test(val) && /solid/.test(val)){
  10919. // if(node.attrs['class']){
  10920. // node.attrs['class'] += ' fontborder';
  10921. //
  10922. // }else{
  10923. // node.setAttr('class','fontborder')
  10924. // }
  10925. // }
  10926. // node.setStyle('border')
  10927. //
  10928. // }
  10929. // });
  10930. // });
  10931. for (var p in fonts) {
  10932. (function (cmd, style) {
  10933. UE.commands[cmd] = {
  10934. execCommand: function (cmdName, value) {
  10935. value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' :
  10936. cmdName == 'fontborder' ? '1px solid #000' :
  10937. 'line-through');
  10938. var me = this,
  10939. range = this.selection.getRange(),
  10940. text;
  10941. if (value == 'default') {
  10942. if (range.collapsed) {
  10943. text = me.document.createTextNode('font');
  10944. range.insertNode(text).select();
  10945. }
  10946. me.execCommand('removeFormat', 'span,a', style);
  10947. if (text) {
  10948. range.setStartBefore(text).collapse(true);
  10949. domUtils.remove(text);
  10950. }
  10951. mergesibling(range, cmdName, value);
  10952. range.select()
  10953. } else {
  10954. if (!range.collapsed) {
  10955. if (needCmd[cmd] && me.queryCommandValue(cmd)) {
  10956. me.execCommand('removeFormat', 'span,a', style);
  10957. }
  10958. range = me.selection.getRange();
  10959. range.applyInlineStyle('span', { 'style': style + ':' + value });
  10960. mergesibling(range, cmdName, value);
  10961. range.select();
  10962. } else {
  10963. var span = domUtils.findParentByTagName(range.startContainer, 'span', true);
  10964. text = me.document.createTextNode('font');
  10965. if (span && !span.children.length && !span[browser.ie ? 'innerText' : 'textContent'].replace(fillCharReg, '').length) {
  10966. //for ie hack when enter
  10967. range.insertNode(text);
  10968. if (needCmd[cmd]) {
  10969. range.selectNode(text).select();
  10970. me.execCommand('removeFormat', 'span,a', style, null);
  10971. span = domUtils.findParentByTagName(text, 'span', true);
  10972. range.setStartBefore(text);
  10973. }
  10974. span && (span.style.cssText += ';' + style + ':' + value);
  10975. range.collapse(true).select();
  10976. } else {
  10977. range.insertNode(text);
  10978. range.selectNode(text).select();
  10979. span = range.document.createElement('span');
  10980. if (needCmd[cmd]) {
  10981. //a标签内的不处理跳过
  10982. if (domUtils.findParentByTagName(text, 'a', true)) {
  10983. range.setStartBefore(text).setCursor();
  10984. domUtils.remove(text);
  10985. return;
  10986. }
  10987. me.execCommand('removeFormat', 'span,a', style);
  10988. }
  10989. span.style.cssText = style + ':' + value;
  10990. text.parentNode.insertBefore(span, text);
  10991. //修复,span套span 但样式不继承的问题
  10992. if (!browser.ie || browser.ie && browser.version == 9) {
  10993. var spanParent = span.parentNode;
  10994. while (!domUtils.isBlockElm(spanParent)) {
  10995. if (spanParent.tagName == 'SPAN') {
  10996. //opera合并style不会加入";"
  10997. span.style.cssText = spanParent.style.cssText + ";" + span.style.cssText;
  10998. }
  10999. spanParent = spanParent.parentNode;
  11000. }
  11001. }
  11002. if (opera) {
  11003. setTimeout(function () {
  11004. range.setStart(span, 0).collapse(true);
  11005. mergesibling(range, cmdName, value);
  11006. range.select();
  11007. });
  11008. } else {
  11009. range.setStart(span, 0).collapse(true);
  11010. mergesibling(range, cmdName, value);
  11011. range.select();
  11012. }
  11013. //trace:981
  11014. //domUtils.mergeToParent(span)
  11015. }
  11016. domUtils.remove(text);
  11017. }
  11018. }
  11019. return true;
  11020. },
  11021. queryCommandValue: function (cmdName) {
  11022. var startNode = this.selection.getStart();
  11023. //trace:946
  11024. if (cmdName == 'underline' || cmdName == 'strikethrough') {
  11025. var tmpNode = startNode, value;
  11026. while (tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)) {
  11027. if (tmpNode.nodeType == 1) {
  11028. value = domUtils.getComputedStyle(tmpNode, style);
  11029. if (value != 'none') {
  11030. return value;
  11031. }
  11032. }
  11033. tmpNode = tmpNode.parentNode;
  11034. }
  11035. return 'none';
  11036. }
  11037. if (cmdName == 'fontborder') {
  11038. var tmp = startNode, val;
  11039. while (tmp && dtd.$inline[tmp.tagName]) {
  11040. if (val = domUtils.getComputedStyle(tmp, 'border')) {
  11041. if (/1px/.test(val) && /solid/.test(val)) {
  11042. return val;
  11043. }
  11044. }
  11045. tmp = tmp.parentNode;
  11046. }
  11047. return ''
  11048. }
  11049. if (cmdName == 'FontSize') {
  11050. var styleVal = domUtils.getComputedStyle(startNode, style),
  11051. tmp = /^([\d\.]+)(\w+)$/.exec(styleVal);
  11052. if (tmp) {
  11053. return Math.floor(tmp[1]) + tmp[2];
  11054. }
  11055. return styleVal;
  11056. }
  11057. return domUtils.getComputedStyle(startNode, style);
  11058. },
  11059. queryCommandState: function (cmdName) {
  11060. if (!needCmd[cmdName])
  11061. return 0;
  11062. var val = this.queryCommandValue(cmdName);
  11063. if (cmdName == 'fontborder') {
  11064. return /1px/.test(val) && /solid/.test(val)
  11065. } else {
  11066. return cmdName == 'underline' ? /underline/.test(val) : /line\-through/.test(val);
  11067. }
  11068. }
  11069. };
  11070. })(p, fonts[p]);
  11071. }
  11072. };
  11073. // plugins/link.js
  11074. /**
  11075. * 超链接
  11076. * @file
  11077. * @since 1.2.6.1
  11078. */
  11079. /**
  11080. * 插入超链接
  11081. * @command link
  11082. * @method execCommand
  11083. * @param { String } cmd 命令字符串
  11084. * @param { Object } options 设置自定义属性,例如:url、title、target
  11085. * @example
  11086. * ```javascript
  11087. * editor.execCommand( 'link', '{
  11088. * url:'ueditor.baidu.com',
  11089. * title:'ueditor',
  11090. * target:'_blank'
  11091. * }' );
  11092. * ```
  11093. */
  11094. /**
  11095. * 返回当前选中的第一个超链接节点
  11096. * @command link
  11097. * @method queryCommandValue
  11098. * @param { String } cmd 命令字符串
  11099. * @return { Element } 超链接节点
  11100. * @example
  11101. * ```javascript
  11102. * editor.queryCommandValue( 'link' );
  11103. * ```
  11104. */
  11105. /**
  11106. * 取消超链接
  11107. * @command unlink
  11108. * @method execCommand
  11109. * @param { String } cmd 命令字符串
  11110. * @example
  11111. * ```javascript
  11112. * editor.execCommand( 'unlink');
  11113. * ```
  11114. */
  11115. UE.plugins['link'] = function () {
  11116. function optimize(range) {
  11117. var start = range.startContainer, end = range.endContainer;
  11118. if (start = domUtils.findParentByTagName(start, 'a', true)) {
  11119. range.setStartBefore(start);
  11120. }
  11121. if (end = domUtils.findParentByTagName(end, 'a', true)) {
  11122. range.setEndAfter(end);
  11123. }
  11124. }
  11125. UE.commands['unlink'] = {
  11126. execCommand: function () {
  11127. var range = this.selection.getRange(),
  11128. bookmark;
  11129. if (range.collapsed && !domUtils.findParentByTagName(range.startContainer, 'a', true)) {
  11130. return;
  11131. }
  11132. bookmark = range.createBookmark();
  11133. optimize(range);
  11134. range.removeInlineStyle('a').moveToBookmark(bookmark).select();
  11135. },
  11136. queryCommandState: function () {
  11137. return !this.highlight && this.queryCommandValue('link') ? 0 : -1;
  11138. }
  11139. };
  11140. function doLink(range, opt, me) {
  11141. var rngClone = range.cloneRange(),
  11142. link = me.queryCommandValue('link');
  11143. optimize(range = range.adjustmentBoundary());
  11144. var start = range.startContainer;
  11145. if (start.nodeType == 1 && link) {
  11146. start = start.childNodes[range.startOffset];
  11147. if (start && start.nodeType == 1 && start.tagName == 'A' && /^(?:https?|ftp|file)\s*:\s*\/\//.test(start[browser.ie ? 'innerText' : 'textContent'])) {
  11148. start[browser.ie ? 'innerText' : 'textContent'] = utils.html(opt.textValue || opt.href);
  11149. }
  11150. }
  11151. if (!rngClone.collapsed || link) {
  11152. range.removeInlineStyle('a');
  11153. rngClone = range.cloneRange();
  11154. }
  11155. if (rngClone.collapsed) {
  11156. var a = range.document.createElement('a'),
  11157. text = '';
  11158. if (opt.textValue) {
  11159. text = utils.html(opt.textValue);
  11160. delete opt.textValue;
  11161. } else {
  11162. text = utils.html(opt.href);
  11163. }
  11164. domUtils.setAttributes(a, opt);
  11165. start = domUtils.findParentByTagName(rngClone.startContainer, 'a', true);
  11166. if (start && domUtils.isInNodeEndBoundary(rngClone, start)) {
  11167. range.setStartAfter(start).collapse(true);
  11168. }
  11169. a[browser.ie ? 'innerText' : 'textContent'] = text;
  11170. range.insertNode(a).selectNode(a);
  11171. } else {
  11172. range.applyInlineStyle('a', opt);
  11173. }
  11174. }
  11175. UE.commands['link'] = {
  11176. execCommand: function (cmdName, opt) {
  11177. var range;
  11178. opt._href && (opt._href = utils.unhtml(opt._href, /[<">]/g));
  11179. opt.href && (opt.href = utils.unhtml(opt.href, /[<">]/g));
  11180. opt.textValue && (opt.textValue = utils.unhtml(opt.textValue, /[<">]/g));
  11181. doLink(range = this.selection.getRange(), opt, this);
  11182. //闭合都不加占位符,如果加了会在a后边多个占位符节点,导致a是图片背景组成的列表,出现空白问题
  11183. range.collapse().select(true);
  11184. },
  11185. queryCommandValue: function () {
  11186. var range = this.selection.getRange(),
  11187. node;
  11188. if (range.collapsed) {
  11189. // node = this.selection.getStart();
  11190. //在ie下getstart()取值偏上了
  11191. node = range.startContainer;
  11192. node = node.nodeType == 1 ? node : node.parentNode;
  11193. if (node && (node = domUtils.findParentByTagName(node, 'a', true)) && !domUtils.isInNodeEndBoundary(range, node)) {
  11194. return node;
  11195. }
  11196. } else {
  11197. //trace:1111 如果是<p><a>xx</a></p> startContainer是p就会找不到a
  11198. range.shrinkBoundary();
  11199. var start = range.startContainer.nodeType == 3 || !range.startContainer.childNodes[range.startOffset] ? range.startContainer : range.startContainer.childNodes[range.startOffset],
  11200. end = range.endContainer.nodeType == 3 || range.endOffset == 0 ? range.endContainer : range.endContainer.childNodes[range.endOffset - 1],
  11201. common = range.getCommonAncestor();
  11202. node = domUtils.findParentByTagName(common, 'a', true);
  11203. if (!node && common.nodeType == 1) {
  11204. var as = common.getElementsByTagName('a'),
  11205. ps, pe;
  11206. for (var i = 0, ci; ci = as[i++];) {
  11207. ps = domUtils.getPosition(ci, start), pe = domUtils.getPosition(ci, end);
  11208. if ((ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  11209. &&
  11210. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  11211. ) {
  11212. node = ci;
  11213. break;
  11214. }
  11215. }
  11216. }
  11217. return node;
  11218. }
  11219. },
  11220. queryCommandState: function () {
  11221. //判断如果是视频的话连接不可用
  11222. //fix 853
  11223. var img = this.selection.getRange().getClosedNode(),
  11224. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video") != -1);
  11225. return flag ? -1 : 0;
  11226. }
  11227. };
  11228. };
  11229. // plugins/iframe.js
  11230. ///import core
  11231. ///import plugins\inserthtml.js
  11232. ///commands 插入框架
  11233. ///commandsName InsertFrame
  11234. ///commandsTitle 插入Iframe
  11235. ///commandsDialog dialogs\insertframe
  11236. UE.plugins['insertframe'] = function () {
  11237. var me = this;
  11238. function deleteIframe() {
  11239. me._iframe && delete me._iframe;
  11240. }
  11241. me.addListener("selectionchange", function () {
  11242. deleteIframe();
  11243. });
  11244. };
  11245. // plugins/scrawl.js
  11246. ///import core
  11247. ///commands 涂鸦
  11248. ///commandsName Scrawl
  11249. ///commandsTitle 涂鸦
  11250. ///commandsDialog dialogs\scrawl
  11251. UE.commands['scrawl'] = {
  11252. queryCommandState: function () {
  11253. return (browser.ie && browser.version <= 8) ? -1 : 0;
  11254. }
  11255. };
  11256. // plugins/removeformat.js
  11257. /**
  11258. * 清除格式
  11259. * @file
  11260. * @since 1.2.6.1
  11261. */
  11262. /**
  11263. * 清除文字样式
  11264. * @command removeformat
  11265. * @method execCommand
  11266. * @param { String } cmd 命令字符串
  11267. * @param {String} tags 以逗号隔开的标签。如:strong
  11268. * @param {String} style 样式如:color
  11269. * @param {String} attrs 属性如:width
  11270. * @example
  11271. * ```javascript
  11272. * editor.execCommand( 'removeformat', 'strong','color','width' );
  11273. * ```
  11274. */
  11275. UE.plugins['removeformat'] = function () {
  11276. var me = this;
  11277. me.setOpt({
  11278. 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var',
  11279. 'removeFormatAttributes': 'class,style,lang,width,height,align,hspace,valign'
  11280. });
  11281. me.commands['removeformat'] = {
  11282. execCommand: function (cmdName, tags, style, attrs, notIncludeA) {
  11283. var tagReg = new RegExp('^(?:' + (tags || this.options.removeFormatTags).replace(/,/g, '|') + ')$', 'i'),
  11284. removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split(','),
  11285. range = new dom.Range(this.document),
  11286. bookmark, node, parent,
  11287. filter = function (node) {
  11288. return node.nodeType == 1;
  11289. };
  11290. function isRedundantSpan(node) {
  11291. if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span') {
  11292. return 0;
  11293. }
  11294. if (browser.ie) {
  11295. //ie 下判断实效,所以只能简单用style来判断
  11296. //return node.style.cssText == '' ? 1 : 0;
  11297. var attrs = node.attributes;
  11298. if (attrs.length) {
  11299. for (var i = 0, l = attrs.length; i < l; i++) {
  11300. if (attrs[i].specified) {
  11301. return 0;
  11302. }
  11303. }
  11304. return 1;
  11305. }
  11306. }
  11307. return !node.attributes.length;
  11308. }
  11309. function doRemove(range) {
  11310. var bookmark1 = range.createBookmark();
  11311. if (range.collapsed) {
  11312. range.enlarge(true);
  11313. }
  11314. //不能把a标签切了
  11315. if (!notIncludeA) {
  11316. var aNode = domUtils.findParentByTagName(range.startContainer, 'a', true);
  11317. if (aNode) {
  11318. range.setStartBefore(aNode);
  11319. }
  11320. aNode = domUtils.findParentByTagName(range.endContainer, 'a', true);
  11321. if (aNode) {
  11322. range.setEndAfter(aNode);
  11323. }
  11324. }
  11325. bookmark = range.createBookmark();
  11326. node = bookmark.start;
  11327. //切开始
  11328. while ((parent = node.parentNode) && !domUtils.isBlockElm(parent)) {
  11329. domUtils.breakParent(node, parent);
  11330. domUtils.clearEmptySibling(node);
  11331. }
  11332. if (bookmark.end) {
  11333. //切结束
  11334. node = bookmark.end;
  11335. while ((parent = node.parentNode) && !domUtils.isBlockElm(parent)) {
  11336. domUtils.breakParent(node, parent);
  11337. domUtils.clearEmptySibling(node);
  11338. }
  11339. //开始去除样式
  11340. var current = domUtils.getNextDomNode(bookmark.start, false, filter),
  11341. next;
  11342. while (current) {
  11343. if (current == bookmark.end) {
  11344. break;
  11345. }
  11346. next = domUtils.getNextDomNode(current, true, filter);
  11347. if (!dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode(current)) {
  11348. if (tagReg.test(current.tagName)) {
  11349. if (style) {
  11350. domUtils.removeStyle(current, style);
  11351. if (isRedundantSpan(current) && style != 'text-decoration') {
  11352. domUtils.remove(current, true);
  11353. }
  11354. } else {
  11355. domUtils.remove(current, true);
  11356. }
  11357. } else {
  11358. //trace:939 不能把list上的样式去掉
  11359. if (!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]) {
  11360. domUtils.removeAttributes(current, removeFormatAttributes);
  11361. if (isRedundantSpan(current)) {
  11362. domUtils.remove(current, true);
  11363. }
  11364. }
  11365. }
  11366. }
  11367. current = next;
  11368. }
  11369. }
  11370. //trace:1035
  11371. //trace:1096 不能把td上的样式去掉,比如边框
  11372. var pN = bookmark.start.parentNode;
  11373. if (domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]) {
  11374. domUtils.removeAttributes(pN, removeFormatAttributes);
  11375. }
  11376. pN = bookmark.end.parentNode;
  11377. if (bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]) {
  11378. domUtils.removeAttributes(pN, removeFormatAttributes);
  11379. }
  11380. range.moveToBookmark(bookmark).moveToBookmark(bookmark1);
  11381. //清除冗余的代码 <b><bookmark></b>
  11382. var node = range.startContainer,
  11383. tmp,
  11384. collapsed = range.collapsed;
  11385. while (node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]) {
  11386. tmp = node.parentNode;
  11387. range.setStartBefore(node);
  11388. //trace:937
  11389. //更新结束边界
  11390. if (range.startContainer === range.endContainer) {
  11391. range.endOffset--;
  11392. }
  11393. domUtils.remove(node);
  11394. node = tmp;
  11395. }
  11396. if (!collapsed) {
  11397. node = range.endContainer;
  11398. while (node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]) {
  11399. tmp = node.parentNode;
  11400. range.setEndBefore(node);
  11401. domUtils.remove(node);
  11402. node = tmp;
  11403. }
  11404. }
  11405. }
  11406. range = this.selection.getRange();
  11407. doRemove(range);
  11408. range.select();
  11409. }
  11410. };
  11411. };
  11412. // plugins/blockquote.js
  11413. /**
  11414. * 添加引用
  11415. * @file
  11416. * @since 1.2.6.1
  11417. */
  11418. /**
  11419. * 添加引用
  11420. * @command blockquote
  11421. * @method execCommand
  11422. * @param { String } cmd 命令字符串
  11423. * @example
  11424. * ```javascript
  11425. * editor.execCommand( 'blockquote' );
  11426. * ```
  11427. */
  11428. /**
  11429. * 添加引用
  11430. * @command blockquote
  11431. * @method execCommand
  11432. * @param { String } cmd 命令字符串
  11433. * @param { Object } attrs 节点属性
  11434. * @example
  11435. * ```javascript
  11436. * editor.execCommand( 'blockquote',{
  11437. * style: "color: red;"
  11438. * } );
  11439. * ```
  11440. */
  11441. UE.plugins['blockquote'] = function () {
  11442. var me = this;
  11443. function getObj(editor) {
  11444. return domUtils.filterNodeList(editor.selection.getStartElementPath(), 'blockquote');
  11445. }
  11446. me.commands['blockquote'] = {
  11447. execCommand: function (cmdName, attrs) {
  11448. var range = this.selection.getRange(),
  11449. obj = getObj(this),
  11450. blockquote = dtd.blockquote,
  11451. bookmark = range.createBookmark();
  11452. if (obj) {
  11453. var start = range.startContainer,
  11454. startBlock = domUtils.isBlockElm(start) ? start : domUtils.findParent(start, function (node) { return domUtils.isBlockElm(node) }),
  11455. end = range.endContainer,
  11456. endBlock = domUtils.isBlockElm(end) ? end : domUtils.findParent(end, function (node) { return domUtils.isBlockElm(node) });
  11457. //处理一下li
  11458. startBlock = domUtils.findParentByTagName(startBlock, 'li', true) || startBlock;
  11459. endBlock = domUtils.findParentByTagName(endBlock, 'li', true) || endBlock;
  11460. if (startBlock.tagName == 'LI' || startBlock.tagName == 'TD' || startBlock === obj || domUtils.isBody(startBlock)) {
  11461. domUtils.remove(obj, true);
  11462. } else {
  11463. domUtils.breakParent(startBlock, obj);
  11464. }
  11465. if (startBlock !== endBlock) {
  11466. obj = domUtils.findParentByTagName(endBlock, 'blockquote');
  11467. if (obj) {
  11468. if (endBlock.tagName == 'LI' || endBlock.tagName == 'TD' || domUtils.isBody(endBlock)) {
  11469. obj.parentNode && domUtils.remove(obj, true);
  11470. } else {
  11471. domUtils.breakParent(endBlock, obj);
  11472. }
  11473. }
  11474. }
  11475. var blockquotes = domUtils.getElementsByTagName(this.document, 'blockquote');
  11476. for (var i = 0, bi; bi = blockquotes[i++];) {
  11477. if (!bi.childNodes.length) {
  11478. domUtils.remove(bi);
  11479. } else if (domUtils.getPosition(bi, startBlock) & domUtils.POSITION_FOLLOWING && domUtils.getPosition(bi, endBlock) & domUtils.POSITION_PRECEDING) {
  11480. domUtils.remove(bi, true);
  11481. }
  11482. }
  11483. } else {
  11484. var tmpRange = range.cloneRange(),
  11485. node = tmpRange.startContainer.nodeType == 1 ? tmpRange.startContainer : tmpRange.startContainer.parentNode,
  11486. preNode = node,
  11487. doEnd = 1;
  11488. //调整开始
  11489. while (1) {
  11490. if (domUtils.isBody(node)) {
  11491. if (preNode !== node) {
  11492. if (range.collapsed) {
  11493. tmpRange.selectNode(preNode);
  11494. doEnd = 0;
  11495. } else {
  11496. tmpRange.setStartBefore(preNode);
  11497. }
  11498. } else {
  11499. tmpRange.setStart(node, 0);
  11500. }
  11501. break;
  11502. }
  11503. if (!blockquote[node.tagName]) {
  11504. if (range.collapsed) {
  11505. tmpRange.selectNode(preNode);
  11506. } else {
  11507. tmpRange.setStartBefore(preNode);
  11508. }
  11509. break;
  11510. }
  11511. preNode = node;
  11512. node = node.parentNode;
  11513. }
  11514. //调整结束
  11515. if (doEnd) {
  11516. preNode = node = node = tmpRange.endContainer.nodeType == 1 ? tmpRange.endContainer : tmpRange.endContainer.parentNode;
  11517. while (1) {
  11518. if (domUtils.isBody(node)) {
  11519. if (preNode !== node) {
  11520. tmpRange.setEndAfter(preNode);
  11521. } else {
  11522. tmpRange.setEnd(node, node.childNodes.length);
  11523. }
  11524. break;
  11525. }
  11526. if (!blockquote[node.tagName]) {
  11527. tmpRange.setEndAfter(preNode);
  11528. break;
  11529. }
  11530. preNode = node;
  11531. node = node.parentNode;
  11532. }
  11533. }
  11534. node = range.document.createElement('blockquote');
  11535. domUtils.setAttributes(node, attrs);
  11536. node.appendChild(tmpRange.extractContents());
  11537. tmpRange.insertNode(node);
  11538. //去除重复的
  11539. var childs = domUtils.getElementsByTagName(node, 'blockquote');
  11540. for (var i = 0, ci; ci = childs[i++];) {
  11541. if (ci.parentNode) {
  11542. domUtils.remove(ci, true);
  11543. }
  11544. }
  11545. }
  11546. range.moveToBookmark(bookmark).select();
  11547. },
  11548. queryCommandState: function () {
  11549. return getObj(this) ? 1 : 0;
  11550. }
  11551. };
  11552. };
  11553. // plugins/convertcase.js
  11554. /**
  11555. * 大小写转换
  11556. * @file
  11557. * @since 1.2.6.1
  11558. */
  11559. /**
  11560. * 把选区内文本变大写,与“tolowercase”命令互斥
  11561. * @command touppercase
  11562. * @method execCommand
  11563. * @param { String } cmd 命令字符串
  11564. * @example
  11565. * ```javascript
  11566. * editor.execCommand( 'touppercase' );
  11567. * ```
  11568. */
  11569. /**
  11570. * 把选区内文本变小写,与“touppercase”命令互斥
  11571. * @command tolowercase
  11572. * @method execCommand
  11573. * @param { String } cmd 命令字符串
  11574. * @example
  11575. * ```javascript
  11576. * editor.execCommand( 'tolowercase' );
  11577. * ```
  11578. */
  11579. UE.commands['touppercase'] =
  11580. UE.commands['tolowercase'] = {
  11581. execCommand: function (cmd) {
  11582. var me = this;
  11583. var rng = me.selection.getRange();
  11584. if (rng.collapsed) {
  11585. return rng;
  11586. }
  11587. var bk = rng.createBookmark(),
  11588. bkEnd = bk.end,
  11589. filterFn = function (node) {
  11590. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  11591. },
  11592. curNode = domUtils.getNextDomNode(bk.start, false, filterFn);
  11593. while (curNode && (domUtils.getPosition(curNode, bkEnd) & domUtils.POSITION_PRECEDING)) {
  11594. if (curNode.nodeType == 3) {
  11595. curNode.nodeValue = curNode.nodeValue[cmd == 'touppercase' ? 'toUpperCase' : 'toLowerCase']();
  11596. }
  11597. curNode = domUtils.getNextDomNode(curNode, true, filterFn);
  11598. if (curNode === bkEnd) {
  11599. break;
  11600. }
  11601. }
  11602. rng.moveToBookmark(bk).select();
  11603. }
  11604. };
  11605. // plugins/indent.js
  11606. /**
  11607. * 首行缩进
  11608. * @file
  11609. * @since 1.2.6.1
  11610. */
  11611. /**
  11612. * 缩进
  11613. * @command indent
  11614. * @method execCommand
  11615. * @param { String } cmd 命令字符串
  11616. * @example
  11617. * ```javascript
  11618. * editor.execCommand( 'indent' );
  11619. * ```
  11620. */
  11621. UE.commands['indent'] = {
  11622. execCommand: function () {
  11623. var me = this, value = me.queryCommandState("indent") ? "0em" : (me.options.indentValue || '2em');
  11624. me.execCommand('Paragraph', 'p', { style: 'text-indent:' + value });
  11625. },
  11626. queryCommandState: function () {
  11627. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(), 'p h1 h2 h3 h4 h5 h6');
  11628. return pN && pN.style.textIndent && parseInt(pN.style.textIndent) ? 1 : 0;
  11629. }
  11630. };
  11631. // plugins/print.js
  11632. /**
  11633. * 打印
  11634. * @file
  11635. * @since 1.2.6.1
  11636. */
  11637. /**
  11638. * 打印
  11639. * @command print
  11640. * @method execCommand
  11641. * @param { String } cmd 命令字符串
  11642. * @example
  11643. * ```javascript
  11644. * editor.execCommand( 'print' );
  11645. * ```
  11646. */
  11647. UE.commands['print'] = {
  11648. execCommand: function () {
  11649. this.window.print();
  11650. },
  11651. notNeedUndo: 1
  11652. };
  11653. // plugins/preview.js
  11654. /**
  11655. * 预览
  11656. * @file
  11657. * @since 1.2.6.1
  11658. */
  11659. /**
  11660. * 预览
  11661. * @command preview
  11662. * @method execCommand
  11663. * @param { String } cmd 命令字符串
  11664. * @example
  11665. * ```javascript
  11666. * editor.execCommand( 'preview' );
  11667. * ```
  11668. */
  11669. UE.commands['preview'] = {
  11670. execCommand: function () {
  11671. var w = window.open('', '_blank', ''),
  11672. d = w.document;
  11673. d.open();
  11674. d.write('<!DOCTYPE html><html><head><meta charset="utf-8"/><script src="' + this.options.UEDITOR_HOME_URL + 'ueditor.parse.js"></script><script>' +
  11675. "setTimeout(function(){uParse('div',{rootPath: '" + this.options.UEDITOR_HOME_URL + "'})},300)" +
  11676. '</script></head><body><div>' + this.getContent(null, null, true) + '</div></body></html>');
  11677. d.close();
  11678. },
  11679. notNeedUndo: 1
  11680. };
  11681. // plugins/selectall.js
  11682. /**
  11683. * 全选
  11684. * @file
  11685. * @since 1.2.6.1
  11686. */
  11687. /**
  11688. * 选中所有内容
  11689. * @command selectall
  11690. * @method execCommand
  11691. * @param { String } cmd 命令字符串
  11692. * @example
  11693. * ```javascript
  11694. * editor.execCommand( 'selectall' );
  11695. * ```
  11696. */
  11697. UE.plugins['selectall'] = function () {
  11698. var me = this;
  11699. me.commands['selectall'] = {
  11700. execCommand: function () {
  11701. //去掉了原生的selectAll,因为会出现报错和当内容为空时,不能出现闭合状态的光标
  11702. var me = this, body = me.body,
  11703. range = me.selection.getRange();
  11704. range.selectNodeContents(body);
  11705. if (domUtils.isEmptyBlock(body)) {
  11706. //opera不能自动合并到元素的里边,要手动处理一下
  11707. if (browser.opera && body.firstChild && body.firstChild.nodeType == 1) {
  11708. range.setStartAtFirst(body.firstChild);
  11709. }
  11710. range.collapse(true);
  11711. }
  11712. range.select(true);
  11713. },
  11714. notNeedUndo: 1
  11715. };
  11716. //快捷键
  11717. me.addshortcutkey({
  11718. "selectAll": "ctrl+65"
  11719. });
  11720. };
  11721. // plugins/paragraph.js
  11722. /**
  11723. * 段落样式
  11724. * @file
  11725. * @since 1.2.6.1
  11726. */
  11727. /**
  11728. * 段落格式
  11729. * @command paragraph
  11730. * @method execCommand
  11731. * @param { String } cmd 命令字符串
  11732. * @param {String} style 标签值为:'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
  11733. * @param {Object} attrs 标签的属性
  11734. * @example
  11735. * ```javascript
  11736. * editor.execCommand( 'Paragraph','h1','{
  11737. * class:'test'
  11738. * }' );
  11739. * ```
  11740. */
  11741. /**
  11742. * 返回选区内节点标签名
  11743. * @command paragraph
  11744. * @method queryCommandValue
  11745. * @param { String } cmd 命令字符串
  11746. * @return { String } 节点标签名
  11747. * @example
  11748. * ```javascript
  11749. * editor.queryCommandValue( 'Paragraph' );
  11750. * ```
  11751. */
  11752. UE.plugins['paragraph'] = function () {
  11753. var me = this,
  11754. block = domUtils.isBlockElm,
  11755. notExchange = ['TD', 'LI', 'PRE'],
  11756. doParagraph = function (range, style, attrs, sourceCmdName) {
  11757. var bookmark = range.createBookmark(),
  11758. filterFn = function (node) {
  11759. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  11760. },
  11761. para;
  11762. range.enlarge(true);
  11763. var bookmark2 = range.createBookmark(),
  11764. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn),
  11765. tmpRange = range.cloneRange(),
  11766. tmpNode;
  11767. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  11768. if (current.nodeType == 3 || !block(current)) {
  11769. tmpRange.setStartBefore(current);
  11770. while (current && current !== bookmark2.end && !block(current)) {
  11771. tmpNode = current;
  11772. current = domUtils.getNextDomNode(current, false, null, function (node) {
  11773. return !block(node);
  11774. });
  11775. }
  11776. tmpRange.setEndAfter(tmpNode);
  11777. para = range.document.createElement(style);
  11778. if (attrs) {
  11779. domUtils.setAttributes(para, attrs);
  11780. if (sourceCmdName && sourceCmdName == 'customstyle' && attrs.style) {
  11781. para.style.cssText = attrs.style;
  11782. }
  11783. }
  11784. para.appendChild(tmpRange.extractContents());
  11785. //需要内容占位
  11786. if (domUtils.isEmptyNode(para)) {
  11787. domUtils.fillChar(range.document, para);
  11788. }
  11789. tmpRange.insertNode(para);
  11790. var parent = para.parentNode;
  11791. //如果para上一级是一个block元素且不是body,td就删除它
  11792. if (block(parent) && !domUtils.isBody(para.parentNode) && utils.indexOf(notExchange, parent.tagName) == -1) {
  11793. //存储dir,style
  11794. if (!(sourceCmdName && sourceCmdName == 'customstyle')) {
  11795. parent.getAttribute('dir') && para.setAttribute('dir', parent.getAttribute('dir'));
  11796. //trace:1070
  11797. parent.style.cssText && (para.style.cssText = parent.style.cssText + ';' + para.style.cssText);
  11798. //trace:1030
  11799. parent.style.textAlign && !para.style.textAlign && (para.style.textAlign = parent.style.textAlign);
  11800. parent.style.textIndent && !para.style.textIndent && (para.style.textIndent = parent.style.textIndent);
  11801. parent.style.padding && !para.style.padding && (para.style.padding = parent.style.padding);
  11802. }
  11803. //trace:1706 选择的就是h1-6要删除
  11804. if (attrs && /h\d/i.test(parent.tagName) && !/h\d/i.test(para.tagName)) {
  11805. domUtils.setAttributes(parent, attrs);
  11806. if (sourceCmdName && sourceCmdName == 'customstyle' && attrs.style) {
  11807. parent.style.cssText = attrs.style;
  11808. }
  11809. domUtils.remove(para, true);
  11810. para = parent;
  11811. } else {
  11812. domUtils.remove(para.parentNode, true);
  11813. }
  11814. }
  11815. if (utils.indexOf(notExchange, parent.tagName) != -1) {
  11816. current = parent;
  11817. } else {
  11818. current = para;
  11819. }
  11820. current = domUtils.getNextDomNode(current, false, filterFn);
  11821. } else {
  11822. current = domUtils.getNextDomNode(current, true, filterFn);
  11823. }
  11824. }
  11825. return range.moveToBookmark(bookmark2).moveToBookmark(bookmark);
  11826. };
  11827. me.setOpt('paragraph', { 'p': '', 'h1': '', 'h2': '', 'h3': '', 'h4': '', 'h5': '', 'h6': '' });
  11828. me.commands['paragraph'] = {
  11829. execCommand: function (cmdName, style, attrs, sourceCmdName) {
  11830. var range = this.selection.getRange();
  11831. //闭合时单独处理
  11832. if (range.collapsed) {
  11833. var txt = this.document.createTextNode('p');
  11834. range.insertNode(txt);
  11835. //去掉冗余的fillchar
  11836. if (browser.ie) {
  11837. var node = txt.previousSibling;
  11838. if (node && domUtils.isWhitespace(node)) {
  11839. domUtils.remove(node);
  11840. }
  11841. node = txt.nextSibling;
  11842. if (node && domUtils.isWhitespace(node)) {
  11843. domUtils.remove(node);
  11844. }
  11845. }
  11846. }
  11847. range = doParagraph(range, style, attrs, sourceCmdName);
  11848. if (txt) {
  11849. range.setStartBefore(txt).collapse(true);
  11850. pN = txt.parentNode;
  11851. domUtils.remove(txt);
  11852. if (domUtils.isBlockElm(pN) && domUtils.isEmptyNode(pN)) {
  11853. domUtils.fillNode(this.document, pN);
  11854. }
  11855. }
  11856. if (browser.gecko && range.collapsed && range.startContainer.nodeType == 1) {
  11857. var child = range.startContainer.childNodes[range.startOffset];
  11858. if (child && child.nodeType == 1 && child.tagName.toLowerCase() == style) {
  11859. range.setStart(child, 0).collapse(true);
  11860. }
  11861. }
  11862. //trace:1097 原来有true,原因忘了,但去了就不能清除多余的占位符了
  11863. range.select();
  11864. return true;
  11865. },
  11866. queryCommandValue: function () {
  11867. var node = domUtils.filterNodeList(this.selection.getStartElementPath(), 'p h1 h2 h3 h4 h5 h6');
  11868. return node ? node.tagName.toLowerCase() : '';
  11869. }
  11870. };
  11871. };
  11872. // plugins/directionality.js
  11873. /**
  11874. * 设置文字输入的方向的插件
  11875. * @file
  11876. * @since 1.2.6.1
  11877. */
  11878. (function () {
  11879. var block = domUtils.isBlockElm,
  11880. getObj = function (editor) {
  11881. // var startNode = editor.selection.getStart(),
  11882. // parents;
  11883. // if ( startNode ) {
  11884. // //查找所有的是block的父亲节点
  11885. // parents = domUtils.findParents( startNode, true, block, true );
  11886. // for ( var i = 0,ci; ci = parents[i++]; ) {
  11887. // if ( ci.getAttribute( 'dir' ) ) {
  11888. // return ci;
  11889. // }
  11890. // }
  11891. // }
  11892. return domUtils.filterNodeList(editor.selection.getStartElementPath(), function (n) { return n && n.nodeType == 1 && n.getAttribute('dir') });
  11893. },
  11894. doDirectionality = function (range, editor, forward) {
  11895. var bookmark,
  11896. filterFn = function (node) {
  11897. return node.nodeType == 1 ? !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  11898. },
  11899. obj = getObj(editor);
  11900. if (obj && range.collapsed) {
  11901. obj.setAttribute('dir', forward);
  11902. return range;
  11903. }
  11904. bookmark = range.createBookmark();
  11905. range.enlarge(true);
  11906. var bookmark2 = range.createBookmark(),
  11907. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn),
  11908. tmpRange = range.cloneRange(),
  11909. tmpNode;
  11910. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  11911. if (current.nodeType == 3 || !block(current)) {
  11912. tmpRange.setStartBefore(current);
  11913. while (current && current !== bookmark2.end && !block(current)) {
  11914. tmpNode = current;
  11915. current = domUtils.getNextDomNode(current, false, null, function (node) {
  11916. return !block(node);
  11917. });
  11918. }
  11919. tmpRange.setEndAfter(tmpNode);
  11920. var common = tmpRange.getCommonAncestor();
  11921. if (!domUtils.isBody(common) && block(common)) {
  11922. //遍历到了block节点
  11923. common.setAttribute('dir', forward);
  11924. current = common;
  11925. } else {
  11926. //没有遍历到,添加一个block节点
  11927. var p = range.document.createElement('p');
  11928. p.setAttribute('dir', forward);
  11929. var frag = tmpRange.extractContents();
  11930. p.appendChild(frag);
  11931. tmpRange.insertNode(p);
  11932. current = p;
  11933. }
  11934. current = domUtils.getNextDomNode(current, false, filterFn);
  11935. } else {
  11936. current = domUtils.getNextDomNode(current, true, filterFn);
  11937. }
  11938. }
  11939. return range.moveToBookmark(bookmark2).moveToBookmark(bookmark);
  11940. };
  11941. /**
  11942. * 文字输入方向
  11943. * @command directionality
  11944. * @method execCommand
  11945. * @param { String } cmdName 命令字符串
  11946. * @param { String } forward 传入'ltr'表示从左向右输入,传入'rtl'表示从右向左输入
  11947. * @example
  11948. * ```javascript
  11949. * editor.execCommand( 'directionality', 'ltr');
  11950. * ```
  11951. */
  11952. /**
  11953. * 查询当前选区的文字输入方向
  11954. * @command directionality
  11955. * @method queryCommandValue
  11956. * @param { String } cmdName 命令字符串
  11957. * @return { String } 返回'ltr'表示从左向右输入,返回'rtl'表示从右向左输入
  11958. * @example
  11959. * ```javascript
  11960. * editor.queryCommandValue( 'directionality');
  11961. * ```
  11962. */
  11963. UE.commands['directionality'] = {
  11964. execCommand: function (cmdName, forward) {
  11965. var range = this.selection.getRange();
  11966. //闭合时单独处理
  11967. if (range.collapsed) {
  11968. var txt = this.document.createTextNode('d');
  11969. range.insertNode(txt);
  11970. }
  11971. doDirectionality(range, this, forward);
  11972. if (txt) {
  11973. range.setStartBefore(txt).collapse(true);
  11974. domUtils.remove(txt);
  11975. }
  11976. range.select();
  11977. return true;
  11978. },
  11979. queryCommandValue: function () {
  11980. var node = getObj(this);
  11981. return node ? node.getAttribute('dir') : 'ltr';
  11982. }
  11983. };
  11984. })();
  11985. // plugins/horizontal.js
  11986. /**
  11987. * 插入分割线插件
  11988. * @file
  11989. * @since 1.2.6.1
  11990. */
  11991. /**
  11992. * 插入分割线
  11993. * @command horizontal
  11994. * @method execCommand
  11995. * @param { String } cmdName 命令字符串
  11996. * @example
  11997. * ```javascript
  11998. * editor.execCommand( 'horizontal' );
  11999. * ```
  12000. */
  12001. UE.plugins['horizontal'] = function () {
  12002. var me = this;
  12003. me.commands['horizontal'] = {
  12004. execCommand: function (cmdName) {
  12005. var me = this;
  12006. if (me.queryCommandState(cmdName) !== -1) {
  12007. me.execCommand('insertHtml', '<hr>');
  12008. var range = me.selection.getRange(),
  12009. start = range.startContainer;
  12010. if (start.nodeType == 1 && !start.childNodes[range.startOffset]) {
  12011. var tmp;
  12012. if (tmp = start.childNodes[range.startOffset - 1]) {
  12013. if (tmp.nodeType == 1 && tmp.tagName == 'HR') {
  12014. if (me.options.enterTag == 'p') {
  12015. tmp = me.document.createElement('p');
  12016. range.insertNode(tmp);
  12017. range.setStart(tmp, 0).setCursor();
  12018. } else {
  12019. tmp = me.document.createElement('br');
  12020. range.insertNode(tmp);
  12021. range.setStartBefore(tmp).setCursor();
  12022. }
  12023. }
  12024. }
  12025. }
  12026. return true;
  12027. }
  12028. },
  12029. //边界在table里不能加分隔线
  12030. queryCommandState: function () {
  12031. return domUtils.filterNodeList(this.selection.getStartElementPath(), 'table') ? -1 : 0;
  12032. }
  12033. };
  12034. // me.addListener('delkeyup',function(){
  12035. // var rng = this.selection.getRange();
  12036. // if(browser.ie && browser.version > 8){
  12037. // rng.txtToElmBoundary(true);
  12038. // if(domUtils.isStartInblock(rng)){
  12039. // var tmpNode = rng.startContainer;
  12040. // var pre = tmpNode.previousSibling;
  12041. // if(pre && domUtils.isTagNode(pre,'hr')){
  12042. // domUtils.remove(pre);
  12043. // rng.select();
  12044. // return;
  12045. // }
  12046. // }
  12047. // }
  12048. // if(domUtils.isBody(rng.startContainer)){
  12049. // var hr = rng.startContainer.childNodes[rng.startOffset -1];
  12050. // if(hr && hr.nodeName == 'HR'){
  12051. // var next = hr.nextSibling;
  12052. // if(next){
  12053. // rng.setStart(next,0)
  12054. // }else if(hr.previousSibling){
  12055. // rng.setStartAtLast(hr.previousSibling)
  12056. // }else{
  12057. // var p = this.document.createElement('p');
  12058. // hr.parentNode.insertBefore(p,hr);
  12059. // domUtils.fillNode(this.document,p);
  12060. // rng.setStart(p,0);
  12061. // }
  12062. // domUtils.remove(hr);
  12063. // rng.setCursor(false,true);
  12064. // }
  12065. // }
  12066. // })
  12067. me.addListener('delkeydown', function (name, evt) {
  12068. var rng = this.selection.getRange();
  12069. rng.txtToElmBoundary(true);
  12070. if (domUtils.isStartInblock(rng)) {
  12071. var tmpNode = rng.startContainer;
  12072. var pre = tmpNode.previousSibling;
  12073. if (pre && domUtils.isTagNode(pre, 'hr')) {
  12074. domUtils.remove(pre);
  12075. rng.select();
  12076. domUtils.preventDefault(evt);
  12077. return true;
  12078. }
  12079. }
  12080. })
  12081. };
  12082. // plugins/time.js
  12083. /**
  12084. * 插入时间和日期
  12085. * @file
  12086. * @since 1.2.6.1
  12087. */
  12088. /**
  12089. * 插入时间,默认格式:12:59:59
  12090. * @command time
  12091. * @method execCommand
  12092. * @param { String } cmd 命令字符串
  12093. * @example
  12094. * ```javascript
  12095. * editor.execCommand( 'time');
  12096. * ```
  12097. */
  12098. /**
  12099. * 插入日期,默认格式:2013-08-30
  12100. * @command date
  12101. * @method execCommand
  12102. * @param { String } cmd 命令字符串
  12103. * @example
  12104. * ```javascript
  12105. * editor.execCommand( 'date');
  12106. * ```
  12107. */
  12108. UE.commands['time'] = UE.commands["date"] = {
  12109. execCommand: function (cmd, format) {
  12110. var date = new Date;
  12111. function formatTime(date, format) {
  12112. var hh = ('0' + date.getHours()).slice(-2),
  12113. ii = ('0' + date.getMinutes()).slice(-2),
  12114. ss = ('0' + date.getSeconds()).slice(-2);
  12115. format = format || 'hh:ii:ss';
  12116. return format.replace(/hh/ig, hh).replace(/ii/ig, ii).replace(/ss/ig, ss);
  12117. }
  12118. function formatDate(date, format) {
  12119. var yyyy = ('000' + date.getFullYear()).slice(-4),
  12120. yy = yyyy.slice(-2),
  12121. mm = ('0' + (date.getMonth() + 1)).slice(-2),
  12122. dd = ('0' + date.getDate()).slice(-2);
  12123. format = format || 'yyyy-mm-dd';
  12124. return format.replace(/yyyy/ig, yyyy).replace(/yy/ig, yy).replace(/mm/ig, mm).replace(/dd/ig, dd);
  12125. }
  12126. this.execCommand('insertHtml', cmd == "time" ? formatTime(date, format) : formatDate(date, format));
  12127. }
  12128. };
  12129. // plugins/rowspacing.js
  12130. /**
  12131. * 段前段后间距插件
  12132. * @file
  12133. * @since 1.2.6.1
  12134. */
  12135. /**
  12136. * 设置段间距
  12137. * @command rowspacing
  12138. * @method execCommand
  12139. * @param { String } cmd 命令字符串
  12140. * @param { String } value 段间距的值,以px为单位
  12141. * @param { String } dir 间距位置,top或bottom,分别表示段前和段后
  12142. * @example
  12143. * ```javascript
  12144. * editor.execCommand( 'rowspacing', '10', 'top' );
  12145. * ```
  12146. */
  12147. UE.plugins['rowspacing'] = function () {
  12148. var me = this;
  12149. me.setOpt({
  12150. 'rowspacingtop': ['5', '10', '15', '20', '25'],
  12151. 'rowspacingbottom': ['5', '10', '15', '20', '25']
  12152. });
  12153. me.commands['rowspacing'] = {
  12154. execCommand: function (cmdName, value, dir) {
  12155. this.execCommand('paragraph', 'p', { style: 'margin-' + dir + ':' + value + 'px' });
  12156. return true;
  12157. },
  12158. queryCommandValue: function (cmdName, dir) {
  12159. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(), function (node) { return domUtils.isBlockElm(node) }),
  12160. value;
  12161. //trace:1026
  12162. if (pN) {
  12163. value = domUtils.getComputedStyle(pN, 'margin-' + dir).replace(/[^\d]/g, '');
  12164. return !value ? 0 : value;
  12165. }
  12166. return 0;
  12167. }
  12168. };
  12169. };
  12170. // plugins/lineheight.js
  12171. /**
  12172. * 设置行内间距
  12173. * @file
  12174. * @since 1.2.6.1
  12175. */
  12176. UE.plugins['lineheight'] = function () {
  12177. var me = this;
  12178. me.setOpt({ 'lineheight': ['1', '1.5', '1.75', '2', '3', '4', '5'] });
  12179. /**
  12180. * 行距
  12181. * @command lineheight
  12182. * @method execCommand
  12183. * @param { String } cmdName 命令字符串
  12184. * @param { String } value 传入的行高值, 该值是当前字体的倍数, 例如: 1.5, 1.75
  12185. * @example
  12186. * ```javascript
  12187. * editor.execCommand( 'lineheight', 1.5);
  12188. * ```
  12189. */
  12190. /**
  12191. * 查询当前选区内容的行高大小
  12192. * @command lineheight
  12193. * @method queryCommandValue
  12194. * @param { String } cmd 命令字符串
  12195. * @return { String } 返回当前行高大小
  12196. * @example
  12197. * ```javascript
  12198. * editor.queryCommandValue( 'lineheight' );
  12199. * ```
  12200. */
  12201. me.commands['lineheight'] = {
  12202. execCommand: function (cmdName, value) {
  12203. this.execCommand('paragraph', 'p', { style: 'line-height:' + (value == "1" ? "normal" : value + 'em') });
  12204. return true;
  12205. },
  12206. queryCommandValue: function () {
  12207. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(), function (node) { return domUtils.isBlockElm(node) });
  12208. if (pN) {
  12209. var value = domUtils.getComputedStyle(pN, 'line-height');
  12210. return value == 'normal' ? 1 : value.replace(/[^\d.]*/ig, "");
  12211. }
  12212. }
  12213. };
  12214. };
  12215. // plugins/insertcode.js
  12216. /**
  12217. * 插入代码插件
  12218. * @file
  12219. * @since 1.2.6.1
  12220. */
  12221. UE.plugins['insertcode'] = function () {
  12222. var me = this;
  12223. me.ready(function () {
  12224. utils.cssRule('pre', 'pre{margin:.5em 0;padding:.4em .6em;border-radius:8px;background:#f8f8f8;}',
  12225. me.document)
  12226. });
  12227. me.setOpt('insertcode', {
  12228. 'as3': 'ActionScript3',
  12229. 'bash': 'Bash/Shell',
  12230. 'cpp': 'C/C++',
  12231. 'css': 'Css',
  12232. 'cf': 'CodeFunction',
  12233. 'c#': 'C#',
  12234. 'delphi': 'Delphi',
  12235. 'diff': 'Diff',
  12236. 'erlang': 'Erlang',
  12237. 'groovy': 'Groovy',
  12238. 'html': 'Html',
  12239. 'java': 'Java',
  12240. 'jfx': 'JavaFx',
  12241. 'js': 'Javascript',
  12242. 'pl': 'Perl',
  12243. 'php': 'Php',
  12244. 'plain': 'Plain Text',
  12245. 'ps': 'PowerShell',
  12246. 'python': 'Python',
  12247. 'ruby': 'Ruby',
  12248. 'scala': 'Scala',
  12249. 'sql': 'Sql',
  12250. 'vb': 'Vb',
  12251. 'xml': 'Xml'
  12252. });
  12253. /**
  12254. * 插入代码
  12255. * @command insertcode
  12256. * @method execCommand
  12257. * @param { String } cmd 命令字符串
  12258. * @param { String } lang 插入代码的语言
  12259. * @example
  12260. * ```javascript
  12261. * editor.execCommand( 'insertcode', 'javascript' );
  12262. * ```
  12263. */
  12264. /**
  12265. * 如果选区所在位置是插入插入代码区域,返回代码的语言
  12266. * @command insertcode
  12267. * @method queryCommandValue
  12268. * @param { String } cmd 命令字符串
  12269. * @return { String } 返回代码的语言
  12270. * @example
  12271. * ```javascript
  12272. * editor.queryCommandValue( 'insertcode' );
  12273. * ```
  12274. */
  12275. me.commands['insertcode'] = {
  12276. execCommand: function (cmd, lang) {
  12277. var me = this,
  12278. rng = me.selection.getRange(),
  12279. pre = domUtils.findParentByTagName(rng.startContainer, 'pre', true);
  12280. if (pre) {
  12281. pre.className = 'brush:' + lang + ';toolbar:false;';
  12282. } else {
  12283. var code = '';
  12284. if (rng.collapsed) {
  12285. code = browser.ie && browser.ie11below ? (browser.version <= 8 ? '&nbsp;' : '') : '<br/>';
  12286. } else {
  12287. var frag = rng.extractContents();
  12288. var div = me.document.createElement('div');
  12289. div.appendChild(frag);
  12290. utils.each(UE.filterNode(UE.htmlparser(div.innerHTML.replace(/[\r\t]/g, '')), me.options.filterTxtRules).children, function (node) {
  12291. if (browser.ie && browser.ie11below && browser.version > 8) {
  12292. if (node.type == 'element') {
  12293. if (node.tagName == 'br') {
  12294. code += '\n'
  12295. } else if (!dtd.$empty[node.tagName]) {
  12296. utils.each(node.children, function (cn) {
  12297. if (cn.type == 'element') {
  12298. if (cn.tagName == 'br') {
  12299. code += '\n'
  12300. } else if (!dtd.$empty[node.tagName]) {
  12301. code += cn.innerText();
  12302. }
  12303. } else {
  12304. code += cn.data
  12305. }
  12306. })
  12307. if (!/\n$/.test(code)) {
  12308. code += '\n';
  12309. }
  12310. }
  12311. } else {
  12312. code += node.data + '\n'
  12313. }
  12314. if (!node.nextSibling() && /\n$/.test(code)) {
  12315. code = code.replace(/\n$/, '');
  12316. }
  12317. } else {
  12318. if (browser.ie && browser.ie11below) {
  12319. if (node.type == 'element') {
  12320. if (node.tagName == 'br') {
  12321. code += '<br>'
  12322. } else if (!dtd.$empty[node.tagName]) {
  12323. utils.each(node.children, function (cn) {
  12324. if (cn.type == 'element') {
  12325. if (cn.tagName == 'br') {
  12326. code += '<br>'
  12327. } else if (!dtd.$empty[node.tagName]) {
  12328. code += cn.innerText();
  12329. }
  12330. } else {
  12331. code += cn.data
  12332. }
  12333. });
  12334. if (!/br>$/.test(code)) {
  12335. code += '<br>';
  12336. }
  12337. }
  12338. } else {
  12339. code += node.data + '<br>'
  12340. }
  12341. if (!node.nextSibling() && /<br>$/.test(code)) {
  12342. code = code.replace(/<br>$/, '');
  12343. }
  12344. } else {
  12345. code += (node.type == 'element' ? (dtd.$empty[node.tagName] ? '' : node.innerText()) : node.data);
  12346. if (!/br\/?\s*>$/.test(code)) {
  12347. if (!node.nextSibling())
  12348. return;
  12349. code += '<br>'
  12350. }
  12351. }
  12352. }
  12353. });
  12354. }
  12355. me.execCommand('inserthtml', '<pre id="coder"class="brush:' + lang + ';toolbar:false">' + code + '</pre>', true);
  12356. pre = me.document.getElementById('coder');
  12357. domUtils.removeAttributes(pre, 'id');
  12358. var tmpNode = pre.previousSibling;
  12359. if (tmpNode && (tmpNode.nodeType == 3 && tmpNode.nodeValue.length == 1 && browser.ie && browser.version == 6 || domUtils.isEmptyBlock(tmpNode))) {
  12360. domUtils.remove(tmpNode)
  12361. }
  12362. var rng = me.selection.getRange();
  12363. if (domUtils.isEmptyBlock(pre)) {
  12364. rng.setStart(pre, 0).setCursor(false, true)
  12365. } else {
  12366. rng.selectNodeContents(pre).select()
  12367. }
  12368. }
  12369. },
  12370. queryCommandValue: function () {
  12371. var path = this.selection.getStartElementPath();
  12372. var lang = '';
  12373. utils.each(path, function (node) {
  12374. if (node.nodeName == 'PRE') {
  12375. var match = node.className.match(/brush:([^;]+)/);
  12376. lang = match && match[1] ? match[1] : '';
  12377. return false;
  12378. }
  12379. });
  12380. return lang;
  12381. }
  12382. };
  12383. me.addInputRule(function (root) {
  12384. utils.each(root.getNodesByTagName('pre'), function (pre) {
  12385. var brs = pre.getNodesByTagName('br');
  12386. if (brs.length) {
  12387. browser.ie && browser.ie11below && browser.version > 8 && utils.each(brs, function (br) {
  12388. var txt = UE.uNode.createText('\n');
  12389. br.parentNode.insertBefore(txt, br);
  12390. br.parentNode.removeChild(br);
  12391. });
  12392. return;
  12393. }
  12394. if (browser.ie && browser.ie11below && browser.version > 8)
  12395. return;
  12396. var code = pre.innerText().split(/\n/);
  12397. pre.innerHTML('');
  12398. utils.each(code, function (c) {
  12399. if (c.length) {
  12400. pre.appendChild(UE.uNode.createText(c));
  12401. }
  12402. pre.appendChild(UE.uNode.createElement('br'))
  12403. })
  12404. })
  12405. });
  12406. me.addOutputRule(function (root) {
  12407. utils.each(root.getNodesByTagName('pre'), function (pre) {
  12408. var code = '';
  12409. utils.each(pre.children, function (n) {
  12410. if (n.type == 'text') {
  12411. //在ie下文本内容有可能末尾带有\n要去掉
  12412. //trace:3396
  12413. code += n.data.replace(/[ ]/g, '&nbsp;').replace(/\n$/, '');
  12414. } else {
  12415. if (n.tagName == 'br') {
  12416. code += '\n'
  12417. } else {
  12418. code += (!dtd.$empty[n.tagName] ? '' : n.innerText());
  12419. }
  12420. }
  12421. });
  12422. pre.innerText(code.replace(/(&nbsp;|\n)+$/, ''))
  12423. })
  12424. });
  12425. //不需要判断highlight的command列表
  12426. me.notNeedCodeQuery = {
  12427. help: 1,
  12428. undo: 1,
  12429. redo: 1,
  12430. source: 1,
  12431. print: 1,
  12432. searchreplace: 1,
  12433. fullscreen: 1,
  12434. preview: 1,
  12435. insertparagraph: 1,
  12436. elementpath: 1,
  12437. insertcode: 1,
  12438. inserthtml: 1,
  12439. selectall: 1
  12440. };
  12441. //将queyCommamndState重置
  12442. var orgQuery = me.queryCommandState;
  12443. me.queryCommandState = function (cmd) {
  12444. var me = this;
  12445. if (!me.notNeedCodeQuery[cmd.toLowerCase()] && me.selection && me.queryCommandValue('insertcode')) {
  12446. return -1;
  12447. }
  12448. return UE.Editor.prototype.queryCommandState.apply(this, arguments)
  12449. };
  12450. me.addListener('beforeenterkeydown', function () {
  12451. var rng = me.selection.getRange();
  12452. var pre = domUtils.findParentByTagName(rng.startContainer, 'pre', true);
  12453. if (pre) {
  12454. me.fireEvent('saveScene');
  12455. if (!rng.collapsed) {
  12456. rng.deleteContents();
  12457. }
  12458. if (!browser.ie || browser.ie9above) {
  12459. var tmpNode = me.document.createElement('br'), pre;
  12460. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true);
  12461. var next = tmpNode.nextSibling;
  12462. if (!next && (!browser.ie || browser.version > 10)) {
  12463. rng.insertNode(tmpNode.cloneNode(false));
  12464. } else {
  12465. rng.setStartAfter(tmpNode);
  12466. }
  12467. pre = tmpNode.previousSibling;
  12468. var tmp;
  12469. while (pre) {
  12470. tmp = pre;
  12471. pre = pre.previousSibling;
  12472. if (!pre || pre.nodeName == 'BR') {
  12473. pre = tmp;
  12474. break;
  12475. }
  12476. }
  12477. if (pre) {
  12478. var str = '';
  12479. while (pre && pre.nodeName != 'BR' && new RegExp('^[\\s' + domUtils.fillChar + ']*$').test(pre.nodeValue)) {
  12480. str += pre.nodeValue;
  12481. pre = pre.nextSibling;
  12482. }
  12483. if (pre.nodeName != 'BR') {
  12484. var match = pre.nodeValue.match(new RegExp('^([\\s' + domUtils.fillChar + ']+)'));
  12485. if (match && match[1]) {
  12486. str += match[1]
  12487. }
  12488. }
  12489. if (str) {
  12490. str = me.document.createTextNode(str);
  12491. rng.insertNode(str).setStartAfter(str);
  12492. }
  12493. }
  12494. rng.collapse(true).select(true);
  12495. } else {
  12496. if (browser.version > 8) {
  12497. var txt = me.document.createTextNode('\n');
  12498. var start = rng.startContainer;
  12499. if (rng.startOffset == 0) {
  12500. var preNode = start.previousSibling;
  12501. if (preNode) {
  12502. rng.insertNode(txt);
  12503. var fillchar = me.document.createTextNode(' ');
  12504. rng.setStartAfter(txt).insertNode(fillchar).setStart(fillchar, 0).collapse(true).select(true)
  12505. }
  12506. } else {
  12507. rng.insertNode(txt).setStartAfter(txt);
  12508. var fillchar = me.document.createTextNode(' ');
  12509. start = rng.startContainer.childNodes[rng.startOffset];
  12510. if (start && !/^\n/.test(start.nodeValue)) {
  12511. rng.setStartBefore(txt)
  12512. }
  12513. rng.insertNode(fillchar).setStart(fillchar, 0).collapse(true).select(true)
  12514. }
  12515. } else {
  12516. var tmpNode = me.document.createElement('br');
  12517. rng.insertNode(tmpNode);
  12518. rng.insertNode(me.document.createTextNode(domUtils.fillChar));
  12519. rng.setStartAfter(tmpNode);
  12520. pre = tmpNode.previousSibling;
  12521. var tmp;
  12522. while (pre) {
  12523. tmp = pre;
  12524. pre = pre.previousSibling;
  12525. if (!pre || pre.nodeName == 'BR') {
  12526. pre = tmp;
  12527. break;
  12528. }
  12529. }
  12530. if (pre) {
  12531. var str = '';
  12532. while (pre && pre.nodeName != 'BR' && new RegExp('^[ ' + domUtils.fillChar + ']*$').test(pre.nodeValue)) {
  12533. str += pre.nodeValue;
  12534. pre = pre.nextSibling;
  12535. }
  12536. if (pre.nodeName != 'BR') {
  12537. var match = pre.nodeValue.match(new RegExp('^([ ' + domUtils.fillChar + ']+)'));
  12538. if (match && match[1]) {
  12539. str += match[1]
  12540. }
  12541. }
  12542. str = me.document.createTextNode(str);
  12543. rng.insertNode(str).setStartAfter(str);
  12544. }
  12545. rng.collapse(true).select();
  12546. }
  12547. }
  12548. me.fireEvent('saveScene');
  12549. return true;
  12550. }
  12551. });
  12552. me.addListener('tabkeydown', function (cmd, evt) {
  12553. var rng = me.selection.getRange();
  12554. var pre = domUtils.findParentByTagName(rng.startContainer, 'pre', true);
  12555. if (pre) {
  12556. me.fireEvent('saveScene');
  12557. if (evt.shiftKey) {
  12558. } else {
  12559. if (!rng.collapsed) {
  12560. var bk = rng.createBookmark();
  12561. var start = bk.start.previousSibling;
  12562. while (start) {
  12563. if (pre.firstChild === start && !domUtils.isBr(start)) {
  12564. pre.insertBefore(me.document.createTextNode(' '), start);
  12565. break;
  12566. }
  12567. if (domUtils.isBr(start)) {
  12568. pre.insertBefore(me.document.createTextNode(' '), start.nextSibling);
  12569. break;
  12570. }
  12571. start = start.previousSibling;
  12572. }
  12573. var end = bk.end;
  12574. start = bk.start.nextSibling;
  12575. if (pre.firstChild === bk.start) {
  12576. pre.insertBefore(me.document.createTextNode(' '), start.nextSibling)
  12577. }
  12578. while (start && start !== end) {
  12579. if (domUtils.isBr(start) && start.nextSibling) {
  12580. if (start.nextSibling === end) {
  12581. break;
  12582. }
  12583. pre.insertBefore(me.document.createTextNode(' '), start.nextSibling)
  12584. }
  12585. start = start.nextSibling;
  12586. }
  12587. rng.moveToBookmark(bk).select();
  12588. } else {
  12589. var tmpNode = me.document.createTextNode(' ');
  12590. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true).select(true);
  12591. }
  12592. }
  12593. me.fireEvent('saveScene');
  12594. return true;
  12595. }
  12596. });
  12597. me.addListener('beforeinserthtml', function (evtName, html) {
  12598. var me = this,
  12599. rng = me.selection.getRange(),
  12600. pre = domUtils.findParentByTagName(rng.startContainer, 'pre', true);
  12601. if (pre) {
  12602. if (!rng.collapsed) {
  12603. rng.deleteContents()
  12604. }
  12605. var htmlstr = '';
  12606. if (browser.ie && browser.version > 8) {
  12607. utils.each(UE.filterNode(UE.htmlparser(html), me.options.filterTxtRules).children, function (node) {
  12608. if (node.type == 'element') {
  12609. if (node.tagName == 'br') {
  12610. htmlstr += '\n'
  12611. } else if (!dtd.$empty[node.tagName]) {
  12612. utils.each(node.children, function (cn) {
  12613. if (cn.type == 'element') {
  12614. if (cn.tagName == 'br') {
  12615. htmlstr += '\n'
  12616. } else if (!dtd.$empty[node.tagName]) {
  12617. htmlstr += cn.innerText();
  12618. }
  12619. } else {
  12620. htmlstr += cn.data
  12621. }
  12622. })
  12623. if (!/\n$/.test(htmlstr)) {
  12624. htmlstr += '\n';
  12625. }
  12626. }
  12627. } else {
  12628. htmlstr += node.data + '\n'
  12629. }
  12630. if (!node.nextSibling() && /\n$/.test(htmlstr)) {
  12631. htmlstr = htmlstr.replace(/\n$/, '');
  12632. }
  12633. });
  12634. var tmpNode = me.document.createTextNode(utils.html(htmlstr.replace(/&nbsp;/g, ' ')));
  12635. rng.insertNode(tmpNode).selectNode(tmpNode).select();
  12636. } else {
  12637. var frag = me.document.createDocumentFragment();
  12638. utils.each(UE.filterNode(UE.htmlparser(html), me.options.filterTxtRules).children, function (node) {
  12639. if (node.type == 'element') {
  12640. if (node.tagName == 'br') {
  12641. frag.appendChild(me.document.createElement('br'))
  12642. } else if (!dtd.$empty[node.tagName]) {
  12643. utils.each(node.children, function (cn) {
  12644. if (cn.type == 'element') {
  12645. if (cn.tagName == 'br') {
  12646. frag.appendChild(me.document.createElement('br'))
  12647. } else if (!dtd.$empty[node.tagName]) {
  12648. frag.appendChild(me.document.createTextNode(utils.html(cn.innerText().replace(/&nbsp;/g, ' '))));
  12649. }
  12650. } else {
  12651. frag.appendChild(me.document.createTextNode(utils.html(cn.data.replace(/&nbsp;/g, ' '))));
  12652. }
  12653. })
  12654. if (frag.lastChild.nodeName != 'BR') {
  12655. frag.appendChild(me.document.createElement('br'))
  12656. }
  12657. }
  12658. } else {
  12659. frag.appendChild(me.document.createTextNode(utils.html(node.data.replace(/&nbsp;/g, ' '))));
  12660. }
  12661. if (!node.nextSibling() && frag.lastChild.nodeName == 'BR') {
  12662. frag.removeChild(frag.lastChild)
  12663. }
  12664. });
  12665. rng.insertNode(frag).select();
  12666. }
  12667. return true;
  12668. }
  12669. });
  12670. //方向键的处理
  12671. me.addListener('keydown', function (cmd, evt) {
  12672. var me = this, keyCode = evt.keyCode || evt.which;
  12673. if (keyCode == 40) {
  12674. var rng = me.selection.getRange(), pre, start = rng.startContainer;
  12675. if (rng.collapsed && (pre = domUtils.findParentByTagName(rng.startContainer, 'pre', true)) && !pre.nextSibling) {
  12676. var last = pre.lastChild
  12677. while (last && last.nodeName == 'BR') {
  12678. last = last.previousSibling;
  12679. }
  12680. if (last === start || rng.startContainer === pre && rng.startOffset == pre.childNodes.length) {
  12681. me.execCommand('insertparagraph');
  12682. domUtils.preventDefault(evt)
  12683. }
  12684. }
  12685. }
  12686. });
  12687. //trace:3395
  12688. me.addListener('delkeydown', function (type, evt) {
  12689. var rng = this.selection.getRange();
  12690. rng.txtToElmBoundary(true);
  12691. var start = rng.startContainer;
  12692. if (domUtils.isTagNode(start, 'pre') && rng.collapsed && domUtils.isStartInblock(rng)) {
  12693. var p = me.document.createElement('p');
  12694. domUtils.fillNode(me.document, p);
  12695. start.parentNode.insertBefore(p, start);
  12696. domUtils.remove(start);
  12697. rng.setStart(p, 0).setCursor(false, true);
  12698. domUtils.preventDefault(evt);
  12699. return true;
  12700. }
  12701. })
  12702. };
  12703. // plugins/cleardoc.js
  12704. /**
  12705. * 清空文档插件
  12706. * @file
  12707. * @since 1.2.6.1
  12708. */
  12709. /**
  12710. * 清空文档
  12711. * @command cleardoc
  12712. * @method execCommand
  12713. * @param { String } cmd 命令字符串
  12714. * @example
  12715. * ```javascript
  12716. * //editor 是编辑器实例
  12717. * editor.execCommand('cleardoc');
  12718. * ```
  12719. */
  12720. UE.commands['cleardoc'] = {
  12721. execCommand: function (cmdName) {
  12722. var me = this,
  12723. enterTag = me.options.enterTag,
  12724. range = me.selection.getRange();
  12725. if (enterTag == "br") {
  12726. me.body.innerHTML = "<br/>";
  12727. range.setStart(me.body, 0).setCursor();
  12728. } else {
  12729. me.body.innerHTML = "<p>" + (ie ? "" : "<br/>") + "</p>";
  12730. range.setStart(me.body.firstChild, 0).setCursor(false, true);
  12731. }
  12732. setTimeout(function () {
  12733. me.fireEvent("clearDoc");
  12734. }, 0);
  12735. }
  12736. };
  12737. // plugins/anchor.js
  12738. /**
  12739. * 锚点插件,为UEditor提供插入锚点支持
  12740. * @file
  12741. * @since 1.2.6.1
  12742. */
  12743. UE.plugin.register('anchor', function () {
  12744. return {
  12745. bindEvents: {
  12746. 'ready': function () {
  12747. utils.cssRule('anchor',
  12748. '.anchorclass{background: url(\''
  12749. + this.options.themePath
  12750. + this.options.theme + '/images/anchor.gif\') no-repeat scroll left center transparent;cursor: auto;display: inline-block;height: 16px;width: 15px;}',
  12751. this.document);
  12752. }
  12753. },
  12754. outputRule: function (root) {
  12755. utils.each(root.getNodesByTagName('img'), function (a) {
  12756. var val;
  12757. if (val = a.getAttr('anchorname')) {
  12758. a.tagName = 'a';
  12759. a.setAttr({
  12760. anchorname: '',
  12761. name: val,
  12762. 'class': ''
  12763. })
  12764. }
  12765. })
  12766. },
  12767. inputRule: function (root) {
  12768. utils.each(root.getNodesByTagName('a'), function (a) {
  12769. var val;
  12770. if ((val = a.getAttr('name')) && !a.getAttr('href')) {
  12771. a.tagName = 'img';
  12772. a.setAttr({
  12773. anchorname: a.getAttr('name'),
  12774. 'class': 'anchorclass'
  12775. });
  12776. a.setAttr('name')
  12777. }
  12778. })
  12779. },
  12780. commands: {
  12781. /**
  12782. * 插入锚点
  12783. * @command anchor
  12784. * @method execCommand
  12785. * @param { String } cmd 命令字符串
  12786. * @param { String } name 锚点名称字符串
  12787. * @example
  12788. * ```javascript
  12789. * //editor 是编辑器实例
  12790. * editor.execCommand('anchor', 'anchor1');
  12791. * ```
  12792. */
  12793. 'anchor': {
  12794. execCommand: function (cmd, name) {
  12795. var range = this.selection.getRange(), img = range.getClosedNode();
  12796. if (img && img.getAttribute('anchorname')) {
  12797. if (name) {
  12798. img.setAttribute('anchorname', name);
  12799. } else {
  12800. range.setStartBefore(img).setCursor();
  12801. domUtils.remove(img);
  12802. }
  12803. } else {
  12804. if (name) {
  12805. //只在选区的开始插入
  12806. var anchor = this.document.createElement('img');
  12807. range.collapse(true);
  12808. domUtils.setAttributes(anchor, {
  12809. 'anchorname': name,
  12810. 'class': 'anchorclass'
  12811. });
  12812. range.insertNode(anchor).setStartAfter(anchor).setCursor(false, true);
  12813. }
  12814. }
  12815. }
  12816. }
  12817. }
  12818. }
  12819. });
  12820. // plugins/wordcount.js
  12821. ///import core
  12822. ///commands 字数统计
  12823. ///commandsName WordCount,wordCount
  12824. ///commandsTitle 字数统计
  12825. /*
  12826. * Created by JetBrains WebStorm.
  12827. * User: taoqili
  12828. * Date: 11-9-7
  12829. * Time: 下午8:18
  12830. * To change this template use File | Settings | File Templates.
  12831. */
  12832. UE.plugins['wordcount'] = function () {
  12833. var me = this;
  12834. me.setOpt('wordCount', true);
  12835. me.addListener('contentchange', function () {
  12836. me.fireEvent('wordcount');
  12837. });
  12838. var timer;
  12839. me.addListener('ready', function () {
  12840. var me = this;
  12841. domUtils.on(me.body, "keyup", function (evt) {
  12842. var code = evt.keyCode || evt.which,
  12843. //忽略的按键,ctr,alt,shift,方向键
  12844. ignores = { "16": 1, "18": 1, "20": 1, "37": 1, "38": 1, "39": 1, "40": 1 };
  12845. if (code in ignores) return;
  12846. clearTimeout(timer);
  12847. timer = setTimeout(function () {
  12848. me.fireEvent('wordcount');
  12849. }, 200)
  12850. })
  12851. });
  12852. };
  12853. // plugins/pagebreak.js
  12854. /**
  12855. * 分页功能插件
  12856. * @file
  12857. * @since 1.2.6.1
  12858. */
  12859. UE.plugins['pagebreak'] = function () {
  12860. var me = this,
  12861. notBreakTags = ['td'];
  12862. me.setOpt('pageBreakTag', '_ueditor_page_break_tag_');
  12863. function fillNode(node) {
  12864. if (domUtils.isEmptyBlock(node)) {
  12865. var firstChild = node.firstChild, tmpNode;
  12866. while (firstChild && firstChild.nodeType == 1 && domUtils.isEmptyBlock(firstChild)) {
  12867. tmpNode = firstChild;
  12868. firstChild = firstChild.firstChild;
  12869. }
  12870. !tmpNode && (tmpNode = node);
  12871. domUtils.fillNode(me.document, tmpNode);
  12872. }
  12873. }
  12874. //分页符样式添加
  12875. me.ready(function () {
  12876. utils.cssRule('pagebreak', '.pagebreak{display:block;clear:both !important;cursor:default !important;width: 100% !important;margin:0;}', me.document);
  12877. });
  12878. function isHr(node) {
  12879. return node && node.nodeType == 1 && node.tagName == 'HR' && node.className == 'pagebreak';
  12880. }
  12881. me.addInputRule(function (root) {
  12882. root.traversal(function (node) {
  12883. if (node.type == 'text' && node.data == me.options.pageBreakTag) {
  12884. var hr = UE.uNode.createElement('<hr class="pagebreak" noshade="noshade" size="5" style="-webkit-user-select: none;">');
  12885. node.parentNode.insertBefore(hr, node);
  12886. node.parentNode.removeChild(node)
  12887. }
  12888. })
  12889. });
  12890. me.addOutputRule(function (node) {
  12891. utils.each(node.getNodesByTagName('hr'), function (n) {
  12892. if (n.getAttr('class') == 'pagebreak') {
  12893. var txt = UE.uNode.createText(me.options.pageBreakTag);
  12894. n.parentNode.insertBefore(txt, n);
  12895. n.parentNode.removeChild(n);
  12896. }
  12897. })
  12898. });
  12899. /**
  12900. * 插入分页符
  12901. * @command pagebreak
  12902. * @method execCommand
  12903. * @param { String } cmd 命令字符串
  12904. * @remind 在表格中插入分页符会把表格切分成两部分
  12905. * @remind 获取编辑器内的数据时, 编辑器会把分页符转换成“_ueditor_page_break_tag_”字符串,
  12906. * 以便于提交数据到服务器端后处理分页。
  12907. * @example
  12908. * ```javascript
  12909. * editor.execCommand( 'pagebreak'); //插入一个hr标签,带有样式类名pagebreak
  12910. * ```
  12911. */
  12912. me.commands['pagebreak'] = {
  12913. execCommand: function () {
  12914. var range = me.selection.getRange(), hr = me.document.createElement('hr');
  12915. domUtils.setAttributes(hr, {
  12916. 'class': 'pagebreak',
  12917. noshade: "noshade",
  12918. size: "5"
  12919. });
  12920. domUtils.unSelectable(hr);
  12921. //table单独处理
  12922. var node = domUtils.findParentByTagName(range.startContainer, notBreakTags, true),
  12923. parents = [], pN;
  12924. if (node) {
  12925. switch (node.tagName) {
  12926. case 'TD':
  12927. pN = node.parentNode;
  12928. if (!pN.previousSibling) {
  12929. var table = domUtils.findParentByTagName(pN, 'table');
  12930. // var tableWrapDiv = table.parentNode;
  12931. // if(tableWrapDiv && tableWrapDiv.nodeType == 1
  12932. // && tableWrapDiv.tagName == 'DIV'
  12933. // && tableWrapDiv.getAttribute('dropdrag')
  12934. // ){
  12935. // domUtils.remove(tableWrapDiv,true);
  12936. // }
  12937. table.parentNode.insertBefore(hr, table);
  12938. parents = domUtils.findParents(hr, true);
  12939. } else {
  12940. pN.parentNode.insertBefore(hr, pN);
  12941. parents = domUtils.findParents(hr);
  12942. }
  12943. pN = parents[1];
  12944. if (hr !== pN) {
  12945. domUtils.breakParent(hr, pN);
  12946. }
  12947. //table要重写绑定一下拖拽
  12948. me.fireEvent('afteradjusttable', me.document);
  12949. }
  12950. } else {
  12951. if (!range.collapsed) {
  12952. range.deleteContents();
  12953. var start = range.startContainer;
  12954. while (!domUtils.isBody(start) && domUtils.isBlockElm(start) && domUtils.isEmptyNode(start)) {
  12955. range.setStartBefore(start).collapse(true);
  12956. domUtils.remove(start);
  12957. start = range.startContainer;
  12958. }
  12959. }
  12960. range.insertNode(hr);
  12961. var pN = hr.parentNode, nextNode;
  12962. while (!domUtils.isBody(pN)) {
  12963. domUtils.breakParent(hr, pN);
  12964. nextNode = hr.nextSibling;
  12965. if (nextNode && domUtils.isEmptyBlock(nextNode)) {
  12966. domUtils.remove(nextNode);
  12967. }
  12968. pN = hr.parentNode;
  12969. }
  12970. nextNode = hr.nextSibling;
  12971. var pre = hr.previousSibling;
  12972. if (isHr(pre)) {
  12973. domUtils.remove(pre);
  12974. } else {
  12975. pre && fillNode(pre);
  12976. }
  12977. if (!nextNode) {
  12978. var p = me.document.createElement('p');
  12979. hr.parentNode.appendChild(p);
  12980. domUtils.fillNode(me.document, p);
  12981. range.setStart(p, 0).collapse(true);
  12982. } else {
  12983. if (isHr(nextNode)) {
  12984. domUtils.remove(nextNode);
  12985. } else {
  12986. fillNode(nextNode);
  12987. }
  12988. range.setEndAfter(hr).collapse(false);
  12989. }
  12990. range.select(true);
  12991. }
  12992. }
  12993. };
  12994. };
  12995. // plugins/wordimage.js
  12996. ///import core
  12997. ///commands 本地图片引导上传
  12998. ///commandsName WordImage
  12999. ///commandsTitle 本地图片引导上传
  13000. ///commandsDialog dialogs\wordimage
  13001. UE.plugin.register('wordimage', function () {
  13002. var me = this,
  13003. images = [];
  13004. return {
  13005. commands: {
  13006. 'wordimage': {
  13007. execCommand: function () {
  13008. var images = domUtils.getElementsByTagName(me.body, "img");
  13009. var urlList = [];
  13010. for (var i = 0, ci; ci = images[i++];) {
  13011. var url = ci.getAttribute("word_img");
  13012. url && urlList.push(url);
  13013. }
  13014. return urlList;
  13015. },
  13016. queryCommandState: function () {
  13017. images = domUtils.getElementsByTagName(me.body, "img");
  13018. for (var i = 0, ci; ci = images[i++];) {
  13019. if (ci.getAttribute("word_img")) {
  13020. return 1;
  13021. }
  13022. }
  13023. return -1;
  13024. },
  13025. notNeedUndo: true
  13026. }
  13027. },
  13028. inputRule: function (root) {
  13029. utils.each(root.getNodesByTagName('img'), function (img) {
  13030. var attrs = img.attrs,
  13031. flag = parseInt(attrs.width) < 128 || parseInt(attrs.height) < 43,
  13032. opt = me.options,
  13033. src = opt.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif';
  13034. if (attrs['src'] && /^(?:(file:\/+))/.test(attrs['src'])) {
  13035. img.setAttr({
  13036. width: attrs.width,
  13037. height: attrs.height,
  13038. alt: attrs.alt,
  13039. word_img: attrs.src,
  13040. src: src,
  13041. 'style': 'background:url(' + (flag ? opt.themePath + opt.theme + '/images/word.gif' : opt.langPath + opt.lang + '/images/localimage.png') + ') no-repeat center center;border:1px solid #ddd'
  13042. })
  13043. }
  13044. })
  13045. }
  13046. }
  13047. });
  13048. // plugins/dragdrop.js
  13049. UE.plugins['dragdrop'] = function () {
  13050. var me = this;
  13051. me.ready(function () {
  13052. domUtils.on(this.body, 'dragend', function () {
  13053. var rng = me.selection.getRange();
  13054. var node = rng.getClosedNode() || me.selection.getStart();
  13055. if (node && node.tagName == 'IMG') {
  13056. var pre = node.previousSibling, next;
  13057. while (next = node.nextSibling) {
  13058. if (next.nodeType == 1 && next.tagName == 'SPAN' && !next.firstChild) {
  13059. domUtils.remove(next)
  13060. } else {
  13061. break;
  13062. }
  13063. }
  13064. if ((pre && pre.nodeType == 1 && !domUtils.isEmptyBlock(pre) || !pre) && (!next || next && !domUtils.isEmptyBlock(next))) {
  13065. if (pre && pre.tagName == 'P' && !domUtils.isEmptyBlock(pre)) {
  13066. pre.appendChild(node);
  13067. domUtils.moveChild(next, pre);
  13068. domUtils.remove(next);
  13069. } else if (next && next.tagName == 'P' && !domUtils.isEmptyBlock(next)) {
  13070. next.insertBefore(node, next.firstChild);
  13071. }
  13072. if (pre && pre.tagName == 'P' && domUtils.isEmptyBlock(pre)) {
  13073. domUtils.remove(pre)
  13074. }
  13075. if (next && next.tagName == 'P' && domUtils.isEmptyBlock(next)) {
  13076. domUtils.remove(next)
  13077. }
  13078. rng.selectNode(node).select();
  13079. me.fireEvent('saveScene');
  13080. }
  13081. }
  13082. })
  13083. });
  13084. me.addListener('keyup', function (type, evt) {
  13085. var keyCode = evt.keyCode || evt.which;
  13086. if (keyCode == 13) {
  13087. var rng = me.selection.getRange(), node;
  13088. if (node = domUtils.findParentByTagName(rng.startContainer, 'p', true)) {
  13089. if (domUtils.getComputedStyle(node, 'text-align') == 'center') {
  13090. domUtils.removeStyle(node, 'text-align')
  13091. }
  13092. }
  13093. }
  13094. })
  13095. };
  13096. // plugins/undo.js
  13097. /**
  13098. * undo redo
  13099. * @file
  13100. * @since 1.2.6.1
  13101. */
  13102. /**
  13103. * 撤销上一次执行的命令
  13104. * @command undo
  13105. * @method execCommand
  13106. * @param { String } cmd 命令字符串
  13107. * @example
  13108. * ```javascript
  13109. * editor.execCommand( 'undo' );
  13110. * ```
  13111. */
  13112. /**
  13113. * 重做上一次执行的命令
  13114. * @command redo
  13115. * @method execCommand
  13116. * @param { String } cmd 命令字符串
  13117. * @example
  13118. * ```javascript
  13119. * editor.execCommand( 'redo' );
  13120. * ```
  13121. */
  13122. UE.plugins['undo'] = function () {
  13123. var saveSceneTimer;
  13124. var me = this,
  13125. maxUndoCount = me.options.maxUndoCount || 20,
  13126. maxInputCount = me.options.maxInputCount || 20,
  13127. fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的</hr>
  13128. var noNeedFillCharTags = {
  13129. ol: 1, ul: 1, table: 1, tbody: 1, tr: 1, body: 1
  13130. };
  13131. var orgState = me.options.autoClearEmptyNode;
  13132. function compareAddr(indexA, indexB) {
  13133. if (indexA.length != indexB.length)
  13134. return 0;
  13135. for (var i = 0, l = indexA.length; i < l; i++) {
  13136. if (indexA[i] != indexB[i])
  13137. return 0
  13138. }
  13139. return 1;
  13140. }
  13141. function compareRangeAddress(rngAddrA, rngAddrB) {
  13142. if (rngAddrA.collapsed != rngAddrB.collapsed) {
  13143. return 0;
  13144. }
  13145. if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
  13146. return 0;
  13147. }
  13148. return 1;
  13149. }
  13150. function UndoManager() {
  13151. this.list = [];
  13152. this.index = 0;
  13153. this.hasUndo = false;
  13154. this.hasRedo = false;
  13155. this.undo = function () {
  13156. if (this.hasUndo) {
  13157. if (!this.list[this.index - 1] && this.list.length == 1) {
  13158. this.reset();
  13159. return;
  13160. }
  13161. while (this.list[this.index].content == this.list[this.index - 1].content) {
  13162. this.index--;
  13163. if (this.index == 0) {
  13164. return this.restore(0);
  13165. }
  13166. }
  13167. this.restore(--this.index);
  13168. }
  13169. };
  13170. this.redo = function () {
  13171. if (this.hasRedo) {
  13172. while (this.list[this.index].content == this.list[this.index + 1].content) {
  13173. this.index++;
  13174. if (this.index == this.list.length - 1) {
  13175. return this.restore(this.index);
  13176. }
  13177. }
  13178. this.restore(++this.index);
  13179. }
  13180. };
  13181. this.restore = function () {
  13182. var me = this.editor;
  13183. var scene = this.list[this.index];
  13184. var root = UE.htmlparser(scene.content.replace(fillchar, ''));
  13185. me.options.autoClearEmptyNode = false;
  13186. me.filterInputRule(root);
  13187. me.options.autoClearEmptyNode = orgState;
  13188. //trace:873
  13189. //去掉展位符
  13190. me.document.body.innerHTML = root.toHtml();
  13191. me.fireEvent('afterscencerestore');
  13192. //处理undo后空格不展位的问题
  13193. if (browser.ie) {
  13194. utils.each(domUtils.getElementsByTagName(me.document, 'td th caption p'), function (node) {
  13195. if (domUtils.isEmptyNode(node)) {
  13196. domUtils.fillNode(me.document, node);
  13197. }
  13198. })
  13199. }
  13200. try {
  13201. var rng = new dom.Range(me.document).moveToAddress(scene.address);
  13202. rng.select(noNeedFillCharTags[rng.startContainer.nodeName.toLowerCase()]);
  13203. } catch (e) { }
  13204. this.update();
  13205. this.clearKey();
  13206. //不能把自己reset了
  13207. me.fireEvent('reset', true);
  13208. };
  13209. this.getScene = function () {
  13210. var me = this.editor;
  13211. var rng = me.selection.getRange(),
  13212. rngAddress = rng.createAddress(false, true);
  13213. me.fireEvent('beforegetscene');
  13214. var root = UE.htmlparser(me.body.innerHTML);
  13215. me.options.autoClearEmptyNode = false;
  13216. me.filterOutputRule(root);
  13217. me.options.autoClearEmptyNode = orgState;
  13218. var cont = root.toHtml();
  13219. //trace:3461
  13220. //这个会引起回退时导致空格丢失的情况
  13221. // browser.ie && (cont = cont.replace(/>&nbsp;</g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
  13222. me.fireEvent('aftergetscene');
  13223. return {
  13224. address: rngAddress,
  13225. content: cont
  13226. }
  13227. };
  13228. this.save = function (notCompareRange, notSetCursor) {
  13229. clearTimeout(saveSceneTimer);
  13230. var currentScene = this.getScene(notSetCursor),
  13231. lastScene = this.list[this.index];
  13232. if (lastScene && lastScene.content != currentScene.content) {
  13233. me.trigger('contentchange')
  13234. }
  13235. //内容相同位置相同不存
  13236. if (lastScene && lastScene.content == currentScene.content &&
  13237. (notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address))
  13238. ) {
  13239. return;
  13240. }
  13241. this.list = this.list.slice(0, this.index + 1);
  13242. this.list.push(currentScene);
  13243. //如果大于最大数量了,就把最前的剔除
  13244. if (this.list.length > maxUndoCount) {
  13245. this.list.shift();
  13246. }
  13247. this.index = this.list.length - 1;
  13248. this.clearKey();
  13249. //跟新undo/redo状态
  13250. this.update();
  13251. };
  13252. this.update = function () {
  13253. this.hasRedo = !!this.list[this.index + 1];
  13254. this.hasUndo = !!this.list[this.index - 1];
  13255. };
  13256. this.reset = function () {
  13257. this.list = [];
  13258. this.index = 0;
  13259. this.hasUndo = false;
  13260. this.hasRedo = false;
  13261. this.clearKey();
  13262. };
  13263. this.clearKey = function () {
  13264. keycont = 0;
  13265. lastKeyCode = null;
  13266. };
  13267. }
  13268. me.undoManger = new UndoManager();
  13269. me.undoManger.editor = me;
  13270. function saveScene() {
  13271. this.undoManger.save();
  13272. }
  13273. me.addListener('saveScene', function () {
  13274. var args = Array.prototype.splice.call(arguments, 1);
  13275. this.undoManger.save.apply(this.undoManger, args);
  13276. });
  13277. // me.addListener('beforeexeccommand', saveScene);
  13278. // me.addListener('afterexeccommand', saveScene);
  13279. me.addListener('reset', function (type, exclude) {
  13280. if (!exclude) {
  13281. this.undoManger.reset();
  13282. }
  13283. });
  13284. me.commands['redo'] = me.commands['undo'] = {
  13285. execCommand: function (cmdName) {
  13286. this.undoManger[cmdName]();
  13287. },
  13288. queryCommandState: function (cmdName) {
  13289. return this.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
  13290. },
  13291. notNeedUndo: 1
  13292. };
  13293. var keys = {
  13294. // /*Backspace*/ 8:1, /*Delete*/ 46:1,
  13295. /*Shift*/ 16: 1, /*Ctrl*/ 17: 1, /*Alt*/ 18: 1,
  13296. 37: 1, 38: 1, 39: 1, 40: 1
  13297. },
  13298. keycont = 0,
  13299. lastKeyCode;
  13300. //输入法状态下不计算字符数
  13301. var inputType = false;
  13302. me.addListener('ready', function () {
  13303. domUtils.on(this.body, 'compositionstart', function () {
  13304. inputType = true;
  13305. });
  13306. domUtils.on(this.body, 'compositionend', function () {
  13307. inputType = false;
  13308. })
  13309. });
  13310. //快捷键
  13311. me.addshortcutkey({
  13312. "Undo": "ctrl+90", //undo
  13313. "Redo": "ctrl+89" //redo
  13314. });
  13315. var isCollapsed = true;
  13316. me.addListener('keydown', function (type, evt) {
  13317. var me = this;
  13318. var keyCode = evt.keyCode || evt.which;
  13319. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  13320. if (inputType)
  13321. return;
  13322. if (!me.selection.getRange().collapsed) {
  13323. me.undoManger.save(false, true);
  13324. isCollapsed = false;
  13325. return;
  13326. }
  13327. if (me.undoManger.list.length == 0) {
  13328. me.undoManger.save(true);
  13329. }
  13330. clearTimeout(saveSceneTimer);
  13331. function save(cont) {
  13332. cont.undoManger.save(false, true);
  13333. cont.fireEvent('selectionchange');
  13334. }
  13335. saveSceneTimer = setTimeout(function () {
  13336. if (inputType) {
  13337. var interalTimer = setInterval(function () {
  13338. if (!inputType) {
  13339. save(me);
  13340. clearInterval(interalTimer)
  13341. }
  13342. }, 300)
  13343. return;
  13344. }
  13345. save(me);
  13346. }, 200);
  13347. lastKeyCode = keyCode;
  13348. keycont++;
  13349. if (keycont >= maxInputCount) {
  13350. save(me)
  13351. }
  13352. }
  13353. });
  13354. me.addListener('keyup', function (type, evt) {
  13355. var keyCode = evt.keyCode || evt.which;
  13356. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  13357. if (inputType)
  13358. return;
  13359. if (!isCollapsed) {
  13360. this.undoManger.save(false, true);
  13361. isCollapsed = true;
  13362. }
  13363. }
  13364. });
  13365. //扩展实例,添加关闭和开启命令undo
  13366. me.stopCmdUndo = function () {
  13367. me.__hasEnterExecCommand = true;
  13368. };
  13369. me.startCmdUndo = function () {
  13370. me.__hasEnterExecCommand = false;
  13371. }
  13372. };
  13373. // plugins/copy.js
  13374. UE.plugin.register('copy', function () {
  13375. var me = this;
  13376. function initZeroClipboard() {
  13377. ZeroClipboard.config({
  13378. debug: false,
  13379. swfPath: me.options.UEDITOR_HOME_URL + 'third-party/zeroclipboard/ZeroClipboard.swf'
  13380. });
  13381. var client = me.zeroclipboard = new ZeroClipboard();
  13382. // 复制内容
  13383. client.on('copy', function (e) {
  13384. var client = e.client,
  13385. rng = me.selection.getRange(),
  13386. div = document.createElement('div');
  13387. div.appendChild(rng.cloneContents());
  13388. client.setText(div.innerText || div.textContent);
  13389. client.setHtml(div.innerHTML);
  13390. rng.select();
  13391. });
  13392. // hover事件传递到target
  13393. client.on('mouseover mouseout', function (e) {
  13394. var target = e.target;
  13395. if (e.type == 'mouseover') {
  13396. domUtils.addClass(target, 'edui-state-hover');
  13397. } else if (e.type == 'mouseout') {
  13398. domUtils.removeClasses(target, 'edui-state-hover');
  13399. }
  13400. });
  13401. // flash加载不成功
  13402. client.on('wrongflash noflash', function () {
  13403. ZeroClipboard.destroy();
  13404. });
  13405. }
  13406. return {
  13407. bindEvents: {
  13408. 'ready': function () {
  13409. if (!browser.ie) {
  13410. if (window.ZeroClipboard) {
  13411. initZeroClipboard();
  13412. } else {
  13413. utils.loadFile(document, {
  13414. src: me.options.UEDITOR_HOME_URL + "third-party/zeroclipboard/ZeroClipboard.js",
  13415. tag: "script",
  13416. type: "text/javascript",
  13417. defer: "defer"
  13418. }, function () {
  13419. initZeroClipboard();
  13420. });
  13421. }
  13422. }
  13423. }
  13424. },
  13425. commands: {
  13426. 'copy': {
  13427. execCommand: function (cmd) {
  13428. if (!me.document.execCommand('copy')) {
  13429. alert(me.getLang('copymsg'));
  13430. }
  13431. }
  13432. }
  13433. }
  13434. }
  13435. });
  13436. // plugins/paste.js
  13437. ///import core
  13438. ///import plugins/inserthtml.js
  13439. ///import plugins/undo.js
  13440. ///import plugins/serialize.js
  13441. ///commands 粘贴
  13442. ///commandsName PastePlain
  13443. ///commandsTitle 纯文本粘贴模式
  13444. /**
  13445. * @description 粘贴
  13446. * @author zhanyi
  13447. */
  13448. UE.plugins['paste'] = function () {
  13449. function getClipboardData(callback) {
  13450. var doc = this.document;
  13451. if (doc.getElementById('baidu_pastebin')) {
  13452. return;
  13453. }
  13454. var range = this.selection.getRange(),
  13455. bk = range.createBookmark(),
  13456. //创建剪贴的容器div
  13457. pastebin = doc.createElement('div');
  13458. pastebin.id = 'baidu_pastebin';
  13459. // Safari 要求div必须有内容,才能粘贴内容进来
  13460. browser.webkit && pastebin.appendChild(doc.createTextNode(domUtils.fillChar + domUtils.fillChar));
  13461. doc.body.appendChild(pastebin);
  13462. //trace:717 隐藏的span不能得到top
  13463. //bk.start.innerHTML = '&nbsp;';
  13464. bk.start.style.display = '';
  13465. pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
  13466. //要在现在光标平行的位置加入,否则会出现跳动的问题
  13467. domUtils.getXY(bk.start).y + 'px';
  13468. range.selectNodeContents(pastebin).select(true);
  13469. setTimeout(function () {
  13470. if (browser.webkit) {
  13471. for (var i = 0, pastebins = doc.querySelectorAll('#baidu_pastebin'), pi; pi = pastebins[i++];) {
  13472. if (domUtils.isEmptyNode(pi)) {
  13473. domUtils.remove(pi);
  13474. } else {
  13475. pastebin = pi;
  13476. break;
  13477. }
  13478. }
  13479. }
  13480. try {
  13481. pastebin.parentNode.removeChild(pastebin);
  13482. } catch (e) {
  13483. }
  13484. range.moveToBookmark(bk).select(true);
  13485. callback(pastebin);
  13486. }, 0);
  13487. }
  13488. var me = this;
  13489. me.setOpt({
  13490. retainOnlyLabelPasted: false
  13491. });
  13492. var txtContent, htmlContent, address;
  13493. function getPureHtml(html) {
  13494. return html.replace(/<(\/?)([\w\-]+)([^>]*)>/gi, function (a, b, tagName, attrs) {
  13495. tagName = tagName.toLowerCase();
  13496. if ({ img: 1 }[tagName]) {
  13497. return a;
  13498. }
  13499. attrs = attrs.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi, function (str, atr, val) {
  13500. if ({
  13501. 'src': 1,
  13502. 'href': 1,
  13503. 'name': 1
  13504. }[atr.toLowerCase()]) {
  13505. return atr + '=' + val + ' '
  13506. }
  13507. return ''
  13508. });
  13509. if ({
  13510. 'span': 1,
  13511. 'div': 1
  13512. }[tagName]) {
  13513. return ''
  13514. } else {
  13515. return '<' + b + tagName + ' ' + utils.trim(attrs) + '>'
  13516. }
  13517. });
  13518. }
  13519. function filter(div) {
  13520. var html;
  13521. if (div.firstChild) {
  13522. //去掉cut中添加的边界值
  13523. var nodes = domUtils.getElementsByTagName(div, 'span');
  13524. for (var i = 0, ni; ni = nodes[i++];) {
  13525. if (ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end') {
  13526. domUtils.remove(ni);
  13527. }
  13528. }
  13529. if (browser.webkit) {
  13530. var brs = div.querySelectorAll('div br');
  13531. for (var i = 0, bi; bi = brs[i++];) {
  13532. var pN = bi.parentNode;
  13533. if (pN.tagName == 'DIV' && pN.childNodes.length == 1) {
  13534. pN.innerHTML = '<p><br/></p>';
  13535. domUtils.remove(pN);
  13536. }
  13537. }
  13538. var divs = div.querySelectorAll('#baidu_pastebin');
  13539. for (var i = 0, di; di = divs[i++];) {
  13540. var tmpP = me.document.createElement('p');
  13541. di.parentNode.insertBefore(tmpP, di);
  13542. while (di.firstChild) {
  13543. tmpP.appendChild(di.firstChild);
  13544. }
  13545. domUtils.remove(di);
  13546. }
  13547. var metas = div.querySelectorAll('meta');
  13548. for (var i = 0, ci; ci = metas[i++];) {
  13549. domUtils.remove(ci);
  13550. }
  13551. var brs = div.querySelectorAll('br');
  13552. for (i = 0; ci = brs[i++];) {
  13553. if (/^apple-/i.test(ci.className)) {
  13554. domUtils.remove(ci);
  13555. }
  13556. }
  13557. }
  13558. if (browser.gecko) {
  13559. var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
  13560. for (i = 0; ci = dirtyNodes[i++];) {
  13561. ci.removeAttribute('_moz_dirty');
  13562. }
  13563. }
  13564. if (!browser.ie) {
  13565. var spans = div.querySelectorAll('span.Apple-style-span');
  13566. for (var i = 0, ci; ci = spans[i++];) {
  13567. domUtils.remove(ci, true);
  13568. }
  13569. }
  13570. //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉
  13571. html = div.innerHTML;//.replace(/>(?:(\s|&nbsp;)*?)</g,'><');
  13572. //过滤word粘贴过来的冗余属性
  13573. html = UE.filterWord(html);
  13574. //取消了忽略空白的第二个参数,粘贴过来的有些是有空白的,会被套上相关的标签
  13575. var root = UE.htmlparser(html);
  13576. //如果给了过滤规则就先进行过滤
  13577. if (me.options.filterRules) {
  13578. UE.filterNode(root, me.options.filterRules);
  13579. }
  13580. //执行默认的处理
  13581. me.filterInputRule(root);
  13582. //针对chrome的处理
  13583. if (browser.webkit) {
  13584. var br = root.lastChild();
  13585. if (br && br.type == 'element' && br.tagName == 'br') {
  13586. root.removeChild(br)
  13587. }
  13588. utils.each(me.body.querySelectorAll('div'), function (node) {
  13589. if (domUtils.isEmptyBlock(node)) {
  13590. domUtils.remove(node, true)
  13591. }
  13592. })
  13593. }
  13594. html = { 'html': root.toHtml() };
  13595. me.fireEvent('beforepaste', html, root);
  13596. //抢了默认的粘贴,那后边的内容就不执行了,比如表格粘贴
  13597. if (!html.html) {
  13598. return;
  13599. }
  13600. root = UE.htmlparser(html.html, true);
  13601. //如果开启了纯文本模式
  13602. if (me.queryCommandState('pasteplain') === 1) {
  13603. me.execCommand('insertHtml', UE.filterNode(root, me.options.filterTxtRules).toHtml(), true);
  13604. } else {
  13605. //文本模式
  13606. UE.filterNode(root, me.options.filterTxtRules);
  13607. txtContent = root.toHtml();
  13608. //完全模式
  13609. htmlContent = html.html;
  13610. address = me.selection.getRange().createAddress(true);
  13611. me.execCommand('insertHtml', me.getOpt('retainOnlyLabelPasted') === true ? getPureHtml(htmlContent) : htmlContent, true);
  13612. }
  13613. me.fireEvent("afterpaste", html);
  13614. }
  13615. }
  13616. me.addListener('pasteTransfer', function (cmd, plainType) {
  13617. if (address && txtContent && htmlContent && txtContent != htmlContent) {
  13618. var range = me.selection.getRange();
  13619. range.moveToAddress(address, true);
  13620. if (!range.collapsed) {
  13621. while (!domUtils.isBody(range.startContainer)
  13622. ) {
  13623. var start = range.startContainer;
  13624. if (start.nodeType == 1) {
  13625. start = start.childNodes[range.startOffset];
  13626. if (!start) {
  13627. range.setStartBefore(range.startContainer);
  13628. continue;
  13629. }
  13630. var pre = start.previousSibling;
  13631. if (pre && pre.nodeType == 3 && new RegExp('^[\n\r\t ' + domUtils.fillChar + ']*$').test(pre.nodeValue)) {
  13632. range.setStartBefore(pre)
  13633. }
  13634. }
  13635. if (range.startOffset == 0) {
  13636. range.setStartBefore(range.startContainer);
  13637. } else {
  13638. break;
  13639. }
  13640. }
  13641. while (!domUtils.isBody(range.endContainer)
  13642. ) {
  13643. var end = range.endContainer;
  13644. if (end.nodeType == 1) {
  13645. end = end.childNodes[range.endOffset];
  13646. if (!end) {
  13647. range.setEndAfter(range.endContainer);
  13648. continue;
  13649. }
  13650. var next = end.nextSibling;
  13651. if (next && next.nodeType == 3 && new RegExp('^[\n\r\t' + domUtils.fillChar + ']*$').test(next.nodeValue)) {
  13652. range.setEndAfter(next)
  13653. }
  13654. }
  13655. if (range.endOffset == range.endContainer[range.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length) {
  13656. range.setEndAfter(range.endContainer);
  13657. } else {
  13658. break;
  13659. }
  13660. }
  13661. }
  13662. range.deleteContents();
  13663. range.select(true);
  13664. me.__hasEnterExecCommand = true;
  13665. var html = htmlContent;
  13666. if (plainType === 2) {
  13667. html = getPureHtml(html);
  13668. } else if (plainType) {
  13669. html = txtContent;
  13670. }
  13671. me.execCommand('inserthtml', html, true);
  13672. me.__hasEnterExecCommand = false;
  13673. var rng = me.selection.getRange();
  13674. while (!domUtils.isBody(rng.startContainer) && !rng.startOffset &&
  13675. rng.startContainer[rng.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  13676. ) {
  13677. rng.setStartBefore(rng.startContainer);
  13678. }
  13679. var tmpAddress = rng.createAddress(true);
  13680. address.endAddress = tmpAddress.startAddress;
  13681. }
  13682. });
  13683. me.addListener('ready', function () {
  13684. domUtils.on(me.body, 'cut', function () {
  13685. var range = me.selection.getRange();
  13686. if (!range.collapsed && me.undoManger) {
  13687. me.undoManger.save();
  13688. }
  13689. });
  13690. //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理
  13691. domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste', function (e) {
  13692. if ((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')) {
  13693. return;
  13694. }
  13695. getClipboardData.call(me, function (div) {
  13696. filter(div);
  13697. });
  13698. });
  13699. });
  13700. me.commands['paste'] = {
  13701. execCommand: function (cmd) {
  13702. if (browser.ie) {
  13703. getClipboardData.call(me, function (div) {
  13704. filter(div);
  13705. });
  13706. me.document.execCommand('paste');
  13707. } else {
  13708. alert(me.getLang('pastemsg'));
  13709. }
  13710. }
  13711. }
  13712. };
  13713. // plugins/puretxtpaste.js
  13714. /**
  13715. * 纯文本粘贴插件
  13716. * @file
  13717. * @since 1.2.6.1
  13718. */
  13719. UE.plugins['pasteplain'] = function () {
  13720. var me = this;
  13721. me.setOpt({
  13722. 'pasteplain': false,
  13723. 'filterTxtRules': function () {
  13724. function transP(node) {
  13725. node.tagName = 'p';
  13726. node.setStyle();
  13727. }
  13728. function removeNode(node) {
  13729. node.parentNode.removeChild(node, true)
  13730. }
  13731. return {
  13732. //直接删除及其字节点内容
  13733. '-': 'script style object iframe embed input select',
  13734. 'p': { $: {} },
  13735. 'br': { $: {} },
  13736. div: function (node) {
  13737. var tmpNode, p = UE.uNode.createElement('p');
  13738. while (tmpNode = node.firstChild()) {
  13739. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  13740. p.appendChild(tmpNode);
  13741. } else {
  13742. if (p.firstChild()) {
  13743. node.parentNode.insertBefore(p, node);
  13744. p = UE.uNode.createElement('p');
  13745. } else {
  13746. node.parentNode.insertBefore(tmpNode, node);
  13747. }
  13748. }
  13749. }
  13750. if (p.firstChild()) {
  13751. node.parentNode.insertBefore(p, node);
  13752. }
  13753. node.parentNode.removeChild(node);
  13754. },
  13755. ol: removeNode,
  13756. ul: removeNode,
  13757. dl: removeNode,
  13758. dt: removeNode,
  13759. dd: removeNode,
  13760. 'li': removeNode,
  13761. 'caption': transP,
  13762. 'th': transP,
  13763. 'tr': transP,
  13764. 'h1': transP, 'h2': transP, 'h3': transP, 'h4': transP, 'h5': transP, 'h6': transP,
  13765. 'td': function (node) {
  13766. //没有内容的td直接删掉
  13767. var txt = !!node.innerText();
  13768. if (txt) {
  13769. node.parentNode.insertAfter(UE.uNode.createText(' &nbsp; &nbsp;'), node);
  13770. }
  13771. node.parentNode.removeChild(node, node.innerText())
  13772. }
  13773. }
  13774. }()
  13775. });
  13776. //暂时这里支持一下老版本的属性
  13777. var pasteplain = me.options.pasteplain;
  13778. /**
  13779. * 启用或取消纯文本粘贴模式
  13780. * @command pasteplain
  13781. * @method execCommand
  13782. * @param { String } cmd 命令字符串
  13783. * @example
  13784. * ```javascript
  13785. * editor.queryCommandState( 'pasteplain' );
  13786. * ```
  13787. */
  13788. /**
  13789. * 查询当前是否处于纯文本粘贴模式
  13790. * @command pasteplain
  13791. * @method queryCommandState
  13792. * @param { String } cmd 命令字符串
  13793. * @return { int } 如果处于纯文本模式,返回1,否则,返回0
  13794. * @example
  13795. * ```javascript
  13796. * editor.queryCommandState( 'pasteplain' );
  13797. * ```
  13798. */
  13799. me.commands['pasteplain'] = {
  13800. queryCommandState: function () {
  13801. return pasteplain ? 1 : 0;
  13802. },
  13803. execCommand: function () {
  13804. pasteplain = !pasteplain | 0;
  13805. },
  13806. notNeedUndo: 1
  13807. };
  13808. };
  13809. // plugins/list.js
  13810. /**
  13811. * 有序列表,无序列表插件
  13812. * @file
  13813. * @since 1.2.6.1
  13814. */
  13815. UE.plugins['list'] = function () {
  13816. var me = this,
  13817. notExchange = {
  13818. 'TD': 1,
  13819. 'PRE': 1,
  13820. 'BLOCKQUOTE': 1
  13821. };
  13822. var customStyle = {
  13823. 'cn': 'cn-1-',
  13824. 'cn1': 'cn-2-',
  13825. 'cn2': 'cn-3-',
  13826. 'num': 'num-1-',
  13827. 'num1': 'num-2-',
  13828. 'num2': 'num-3-',
  13829. 'dash': 'dash',
  13830. 'dot': 'dot'
  13831. };
  13832. me.setOpt({
  13833. 'autoTransWordToList': false,
  13834. 'insertorderedlist': {
  13835. 'num': '',
  13836. 'num1': '',
  13837. 'num2': '',
  13838. 'cn': '',
  13839. 'cn1': '',
  13840. 'cn2': '',
  13841. 'decimal': '',
  13842. 'lower-alpha': '',
  13843. 'lower-roman': '',
  13844. 'upper-alpha': '',
  13845. 'upper-roman': ''
  13846. },
  13847. 'insertunorderedlist': {
  13848. 'circle': '',
  13849. 'disc': '',
  13850. 'square': '',
  13851. 'dash': '',
  13852. 'dot': ''
  13853. },
  13854. listDefaultPaddingLeft: '30',
  13855. listiconpath: 'http://bs.baidu.com/listicon/',
  13856. maxListLevel: -1,//-1不限制
  13857. disablePInList: false
  13858. });
  13859. function listToArray(list) {
  13860. var arr = [];
  13861. for (var p in list) {
  13862. arr.push(p)
  13863. }
  13864. return arr;
  13865. }
  13866. var listStyle = {
  13867. 'OL': listToArray(me.options.insertorderedlist),
  13868. 'UL': listToArray(me.options.insertunorderedlist)
  13869. };
  13870. var liiconpath = me.options.listiconpath;
  13871. //根据用户配置,调整customStyle
  13872. for (var s in customStyle) {
  13873. if (!me.options.insertorderedlist.hasOwnProperty(s) && !me.options.insertunorderedlist.hasOwnProperty(s)) {
  13874. delete customStyle[s];
  13875. }
  13876. }
  13877. me.ready(function () {
  13878. var customCss = [];
  13879. for (var p in customStyle) {
  13880. if (p == 'dash' || p == 'dot') {
  13881. customCss.push('li.list-' + customStyle[p] + '{background-image:url(' + liiconpath + customStyle[p] + '.gif)}');
  13882. customCss.push('ul.custom_' + p + '{list-style:none;}ul.custom_' + p + ' li{background-position:0 3px;background-repeat:no-repeat}');
  13883. } else {
  13884. for (var i = 0; i < 99; i++) {
  13885. customCss.push('li.list-' + customStyle[p] + i + '{background-image:url(' + liiconpath + 'list-' + customStyle[p] + i + '.gif)}')
  13886. }
  13887. customCss.push('ol.custom_' + p + '{list-style:none;}ol.custom_' + p + ' li{background-position:0 3px;background-repeat:no-repeat}');
  13888. }
  13889. switch (p) {
  13890. case 'cn':
  13891. customCss.push('li.list-' + p + '-paddingleft-1{padding-left:25px}');
  13892. customCss.push('li.list-' + p + '-paddingleft-2{padding-left:40px}');
  13893. customCss.push('li.list-' + p + '-paddingleft-3{padding-left:55px}');
  13894. break;
  13895. case 'cn1':
  13896. customCss.push('li.list-' + p + '-paddingleft-1{padding-left:30px}');
  13897. customCss.push('li.list-' + p + '-paddingleft-2{padding-left:40px}');
  13898. customCss.push('li.list-' + p + '-paddingleft-3{padding-left:55px}');
  13899. break;
  13900. case 'cn2':
  13901. customCss.push('li.list-' + p + '-paddingleft-1{padding-left:40px}');
  13902. customCss.push('li.list-' + p + '-paddingleft-2{padding-left:55px}');
  13903. customCss.push('li.list-' + p + '-paddingleft-3{padding-left:68px}');
  13904. break;
  13905. case 'num':
  13906. case 'num1':
  13907. customCss.push('li.list-' + p + '-paddingleft-1{padding-left:25px}');
  13908. break;
  13909. case 'num2':
  13910. customCss.push('li.list-' + p + '-paddingleft-1{padding-left:35px}');
  13911. customCss.push('li.list-' + p + '-paddingleft-2{padding-left:40px}');
  13912. break;
  13913. case 'dash':
  13914. customCss.push('li.list-' + p + '-paddingleft{padding-left:35px}');
  13915. break;
  13916. case 'dot':
  13917. customCss.push('li.list-' + p + '-paddingleft{padding-left:20px}');
  13918. }
  13919. }
  13920. customCss.push('.list-paddingleft-1{padding-left:0}');
  13921. customCss.push('.list-paddingleft-2{padding-left:' + me.options.listDefaultPaddingLeft + 'px}');
  13922. customCss.push('.list-paddingleft-3{padding-left:' + me.options.listDefaultPaddingLeft * 2 + 'px}');
  13923. //如果不给宽度会在自定应样式里出现滚动条
  13924. utils.cssRule('list', 'ol,ul{margin:0;pading:0;' + (browser.ie ? '' : 'width:95%') + '}li{clear:both;}' + customCss.join('\n'), me.document);
  13925. });
  13926. //单独处理剪切的问题
  13927. me.ready(function () {
  13928. domUtils.on(me.body, 'cut', function () {
  13929. setTimeout(function () {
  13930. var rng = me.selection.getRange(), li;
  13931. //trace:3416
  13932. if (!rng.collapsed) {
  13933. if (li = domUtils.findParentByTagName(rng.startContainer, 'li', true)) {
  13934. if (!li.nextSibling && domUtils.isEmptyBlock(li)) {
  13935. var pn = li.parentNode, node;
  13936. if (node = pn.previousSibling) {
  13937. domUtils.remove(pn);
  13938. rng.setStartAtLast(node).collapse(true);
  13939. rng.select(true);
  13940. } else if (node = pn.nextSibling) {
  13941. domUtils.remove(pn);
  13942. rng.setStartAtFirst(node).collapse(true);
  13943. rng.select(true);
  13944. } else {
  13945. var tmpNode = me.document.createElement('p');
  13946. domUtils.fillNode(me.document, tmpNode);
  13947. pn.parentNode.insertBefore(tmpNode, pn);
  13948. domUtils.remove(pn);
  13949. rng.setStart(tmpNode, 0).collapse(true);
  13950. rng.select(true);
  13951. }
  13952. }
  13953. }
  13954. }
  13955. })
  13956. })
  13957. });
  13958. function getStyle(node) {
  13959. var cls = node.className;
  13960. if (domUtils.hasClass(node, /custom_/)) {
  13961. return cls.match(/custom_(\w+)/)[1]
  13962. }
  13963. return domUtils.getStyle(node, 'list-style-type')
  13964. }
  13965. me.addListener('beforepaste', function (type, html) {
  13966. var me = this,
  13967. rng = me.selection.getRange(), li;
  13968. var root = UE.htmlparser(html.html, true);
  13969. if (li = domUtils.findParentByTagName(rng.startContainer, 'li', true)) {
  13970. var list = li.parentNode, tagName = list.tagName == 'OL' ? 'ul' : 'ol';
  13971. utils.each(root.getNodesByTagName(tagName), function (n) {
  13972. n.tagName = list.tagName;
  13973. n.setAttr();
  13974. if (n.parentNode === root) {
  13975. type = getStyle(list) || (list.tagName == 'OL' ? 'decimal' : 'disc')
  13976. } else {
  13977. var className = n.parentNode.getAttr('class');
  13978. if (className && /custom_/.test(className)) {
  13979. type = className.match(/custom_(\w+)/)[1]
  13980. } else {
  13981. type = n.parentNode.getStyle('list-style-type');
  13982. }
  13983. if (!type) {
  13984. type = list.tagName == 'OL' ? 'decimal' : 'disc';
  13985. }
  13986. }
  13987. var index = utils.indexOf(listStyle[list.tagName], type);
  13988. if (n.parentNode !== root)
  13989. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  13990. var currentStyle = listStyle[list.tagName][index];
  13991. if (customStyle[currentStyle]) {
  13992. n.setAttr('class', 'custom_' + currentStyle)
  13993. } else {
  13994. n.setStyle('list-style-type', currentStyle)
  13995. }
  13996. })
  13997. }
  13998. html.html = root.toHtml();
  13999. });
  14000. //导出时,去掉p标签
  14001. me.getOpt('disablePInList') === true && me.addOutputRule(function (root) {
  14002. utils.each(root.getNodesByTagName('li'), function (li) {
  14003. var newChildrens = [], index = 0;
  14004. utils.each(li.children, function (n) {
  14005. if (n.tagName == 'p') {
  14006. var tmpNode;
  14007. while (tmpNode = n.children.pop()) {
  14008. newChildrens.splice(index, 0, tmpNode);
  14009. tmpNode.parentNode = li;
  14010. lastNode = tmpNode;
  14011. }
  14012. tmpNode = newChildrens[newChildrens.length - 1];
  14013. if (!tmpNode || tmpNode.type != 'element' || tmpNode.tagName != 'br') {
  14014. var br = UE.uNode.createElement('br');
  14015. br.parentNode = li;
  14016. newChildrens.push(br);
  14017. }
  14018. index = newChildrens.length;
  14019. }
  14020. });
  14021. if (newChildrens.length) {
  14022. li.children = newChildrens;
  14023. }
  14024. });
  14025. });
  14026. //进入编辑器的li要套p标签
  14027. me.addInputRule(function (root) {
  14028. utils.each(root.getNodesByTagName('li'), function (li) {
  14029. var tmpP = UE.uNode.createElement('p');
  14030. for (var i = 0, ci; ci = li.children[i];) {
  14031. if (ci.type == 'text' || dtd.p[ci.tagName]) {
  14032. tmpP.appendChild(ci);
  14033. } else {
  14034. if (tmpP.firstChild()) {
  14035. li.insertBefore(tmpP, ci);
  14036. tmpP = UE.uNode.createElement('p');
  14037. i = i + 2;
  14038. } else {
  14039. i++;
  14040. }
  14041. }
  14042. }
  14043. if (tmpP.firstChild() && !tmpP.parentNode || !li.firstChild()) {
  14044. li.appendChild(tmpP);
  14045. }
  14046. //trace:3357
  14047. //p不能为空
  14048. if (!tmpP.firstChild()) {
  14049. tmpP.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  14050. }
  14051. //去掉末尾的空白
  14052. var p = li.firstChild();
  14053. var lastChild = p.lastChild();
  14054. if (lastChild && lastChild.type == 'text' && /^\s*$/.test(lastChild.data)) {
  14055. p.removeChild(lastChild)
  14056. }
  14057. });
  14058. if (me.options.autoTransWordToList) {
  14059. var orderlisttype = {
  14060. 'num1': /^\d+\)/,
  14061. 'decimal': /^\d+\./,
  14062. 'lower-alpha': /^[a-z]+\)/,
  14063. 'upper-alpha': /^[A-Z]+\./,
  14064. 'cn': /^[\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+[\u3001]/,
  14065. 'cn2': /^\([\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+\)/
  14066. },
  14067. unorderlisttype = {
  14068. 'square': 'n'
  14069. };
  14070. function checkListType(content, container) {
  14071. var span = container.firstChild();
  14072. if (span && span.type == 'element' && span.tagName == 'span' && /Wingdings|Symbol/.test(span.getStyle('font-family'))) {
  14073. for (var p in unorderlisttype) {
  14074. if (unorderlisttype[p] == span.data) {
  14075. return p
  14076. }
  14077. }
  14078. return 'disc'
  14079. }
  14080. for (var p in orderlisttype) {
  14081. if (orderlisttype[p].test(content)) {
  14082. return p;
  14083. }
  14084. }
  14085. }
  14086. utils.each(root.getNodesByTagName('p'), function (node) {
  14087. if (node.getAttr('class') != 'MsoListParagraph') {
  14088. return
  14089. }
  14090. //word粘贴过来的会带有margin要去掉,但这样也可能会误命中一些央视
  14091. node.setStyle('margin', '');
  14092. node.setStyle('margin-left', '');
  14093. node.setAttr('class', '');
  14094. function appendLi(list, p, type) {
  14095. if (list.tagName == 'ol') {
  14096. if (browser.ie) {
  14097. var first = p.firstChild();
  14098. if (first.type == 'element' && first.tagName == 'span' && orderlisttype[type].test(first.innerText())) {
  14099. p.removeChild(first);
  14100. }
  14101. } else {
  14102. p.innerHTML(p.innerHTML().replace(orderlisttype[type], ''));
  14103. }
  14104. } else {
  14105. p.removeChild(p.firstChild())
  14106. }
  14107. var li = UE.uNode.createElement('li');
  14108. li.appendChild(p);
  14109. list.appendChild(li);
  14110. }
  14111. var tmp = node, type, cacheNode = node;
  14112. if (node.parentNode.tagName != 'li' && (type = checkListType(node.innerText(), node))) {
  14113. var list = UE.uNode.createElement(me.options.insertorderedlist.hasOwnProperty(type) ? 'ol' : 'ul');
  14114. if (customStyle[type]) {
  14115. list.setAttr('class', 'custom_' + type)
  14116. } else {
  14117. list.setStyle('list-style-type', type)
  14118. }
  14119. while (node && node.parentNode.tagName != 'li' && checkListType(node.innerText(), node)) {
  14120. tmp = node.nextSibling();
  14121. if (!tmp) {
  14122. node.parentNode.insertBefore(list, node)
  14123. }
  14124. appendLi(list, node, type);
  14125. node = tmp;
  14126. }
  14127. if (!list.parentNode && node && node.parentNode) {
  14128. node.parentNode.insertBefore(list, node)
  14129. }
  14130. }
  14131. var span = cacheNode.firstChild();
  14132. if (span && span.type == 'element' && span.tagName == 'span' && /^\s*(&nbsp;)+\s*$/.test(span.innerText())) {
  14133. span.parentNode.removeChild(span)
  14134. }
  14135. })
  14136. }
  14137. });
  14138. //调整索引标签
  14139. me.addListener('contentchange', function () {
  14140. adjustListStyle(me.document)
  14141. });
  14142. function adjustListStyle(doc, ignore) {
  14143. utils.each(domUtils.getElementsByTagName(doc, 'ol ul'), function (node) {
  14144. if (!domUtils.inDoc(node, doc))
  14145. return;
  14146. var parent = node.parentNode;
  14147. if (parent.tagName == node.tagName) {
  14148. var nodeStyleType = getStyle(node) || (node.tagName == 'OL' ? 'decimal' : 'disc'),
  14149. parentStyleType = getStyle(parent) || (parent.tagName == 'OL' ? 'decimal' : 'disc');
  14150. if (nodeStyleType == parentStyleType) {
  14151. var styleIndex = utils.indexOf(listStyle[node.tagName], nodeStyleType);
  14152. styleIndex = styleIndex + 1 == listStyle[node.tagName].length ? 0 : styleIndex + 1;
  14153. setListStyle(node, listStyle[node.tagName][styleIndex])
  14154. }
  14155. }
  14156. var index = 0, type = 2;
  14157. if (domUtils.hasClass(node, /custom_/)) {
  14158. if (!(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent, /custom_/))) {
  14159. type = 1;
  14160. }
  14161. } else {
  14162. if (/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent, /custom_/)) {
  14163. type = 3;
  14164. }
  14165. }
  14166. var style = domUtils.getStyle(node, 'list-style-type');
  14167. style && (node.style.cssText = 'list-style-type:' + style);
  14168. node.className = utils.trim(node.className.replace(/list-paddingleft-\w+/, '')) + ' list-paddingleft-' + type;
  14169. utils.each(domUtils.getElementsByTagName(node, 'li'), function (li) {
  14170. li.style.cssText && (li.style.cssText = '');
  14171. if (!li.firstChild) {
  14172. domUtils.remove(li);
  14173. return;
  14174. }
  14175. if (li.parentNode !== node) {
  14176. return;
  14177. }
  14178. index++;
  14179. if (domUtils.hasClass(node, /custom_/)) {
  14180. var paddingLeft = 1, currentStyle = getStyle(node);
  14181. if (node.tagName == 'OL') {
  14182. if (currentStyle) {
  14183. switch (currentStyle) {
  14184. case 'cn':
  14185. case 'cn1':
  14186. case 'cn2':
  14187. if (index > 10 && (index % 10 == 0 || index > 10 && index < 20)) {
  14188. paddingLeft = 2
  14189. } else if (index > 20) {
  14190. paddingLeft = 3
  14191. }
  14192. break;
  14193. case 'num2':
  14194. if (index > 9) {
  14195. paddingLeft = 2
  14196. }
  14197. }
  14198. }
  14199. li.className = 'list-' + customStyle[currentStyle] + index + ' ' + 'list-' + currentStyle + '-paddingleft-' + paddingLeft;
  14200. } else {
  14201. li.className = 'list-' + customStyle[currentStyle] + ' ' + 'list-' + currentStyle + '-paddingleft';
  14202. }
  14203. } else {
  14204. li.className = li.className.replace(/list-[\w\-]+/gi, '');
  14205. }
  14206. var className = li.getAttribute('class');
  14207. if (className !== null && !className.replace(/\s/g, '')) {
  14208. domUtils.removeAttributes(li, 'class')
  14209. }
  14210. });
  14211. !ignore && adjustList(node, node.tagName.toLowerCase(), getStyle(node) || domUtils.getStyle(node, 'list-style-type'), true);
  14212. })
  14213. }
  14214. function adjustList(list, tag, style, ignoreEmpty) {
  14215. var nextList = list.nextSibling;
  14216. if (nextList && nextList.nodeType == 1 && nextList.tagName.toLowerCase() == tag && (getStyle(nextList) || domUtils.getStyle(nextList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  14217. domUtils.moveChild(nextList, list);
  14218. if (nextList.childNodes.length == 0) {
  14219. domUtils.remove(nextList);
  14220. }
  14221. }
  14222. if (nextList && domUtils.isFillChar(nextList)) {
  14223. domUtils.remove(nextList);
  14224. }
  14225. var preList = list.previousSibling;
  14226. if (preList && preList.nodeType == 1 && preList.tagName.toLowerCase() == tag && (getStyle(preList) || domUtils.getStyle(preList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  14227. domUtils.moveChild(list, preList);
  14228. }
  14229. if (preList && domUtils.isFillChar(preList)) {
  14230. domUtils.remove(preList);
  14231. }
  14232. !ignoreEmpty && domUtils.isEmptyBlock(list) && domUtils.remove(list);
  14233. if (getStyle(list)) {
  14234. adjustListStyle(list.ownerDocument, true)
  14235. }
  14236. }
  14237. function setListStyle(list, style) {
  14238. if (customStyle[style]) {
  14239. list.className = 'custom_' + style;
  14240. }
  14241. try {
  14242. domUtils.setStyle(list, 'list-style-type', style);
  14243. } catch (e) { }
  14244. }
  14245. function clearEmptySibling(node) {
  14246. var tmpNode = node.previousSibling;
  14247. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  14248. domUtils.remove(tmpNode);
  14249. }
  14250. tmpNode = node.nextSibling;
  14251. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  14252. domUtils.remove(tmpNode);
  14253. }
  14254. }
  14255. me.addListener('keydown', function (type, evt) {
  14256. function preventAndSave() {
  14257. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  14258. me.fireEvent('contentchange');
  14259. me.undoManger && me.undoManger.save();
  14260. }
  14261. function findList(node, filterFn) {
  14262. while (node && !domUtils.isBody(node)) {
  14263. if (filterFn(node)) {
  14264. return null
  14265. }
  14266. if (node.nodeType == 1 && /[ou]l/i.test(node.tagName)) {
  14267. return node;
  14268. }
  14269. node = node.parentNode;
  14270. }
  14271. return null;
  14272. }
  14273. var keyCode = evt.keyCode || evt.which;
  14274. if (keyCode == 13 && !evt.shiftKey) {//回车
  14275. var rng = me.selection.getRange(),
  14276. parent = domUtils.findParent(rng.startContainer, function (node) { return domUtils.isBlockElm(node) }, true),
  14277. li = domUtils.findParentByTagName(rng.startContainer, 'li', true);
  14278. if (parent && parent.tagName != 'PRE' && !li) {
  14279. var html = parent.innerHTML.replace(new RegExp(domUtils.fillChar, 'g'), '');
  14280. if (/^\s*1\s*\.[^\d]/.test(html)) {
  14281. parent.innerHTML = html.replace(/^\s*1\s*\./, '');
  14282. rng.setStartAtLast(parent).collapse(true).select();
  14283. me.__hasEnterExecCommand = true;
  14284. me.execCommand('insertorderedlist');
  14285. me.__hasEnterExecCommand = false;
  14286. }
  14287. }
  14288. var range = me.selection.getRange(),
  14289. start = findList(range.startContainer, function (node) {
  14290. return node.tagName == 'TABLE';
  14291. }),
  14292. end = range.collapsed ? start : findList(range.endContainer, function (node) {
  14293. return node.tagName == 'TABLE';
  14294. });
  14295. if (start && end && start === end) {
  14296. if (!range.collapsed) {
  14297. start = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14298. end = domUtils.findParentByTagName(range.endContainer, 'li', true);
  14299. if (start && end && start === end) {
  14300. range.deleteContents();
  14301. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14302. if (li && domUtils.isEmptyBlock(li)) {
  14303. pre = li.previousSibling;
  14304. next = li.nextSibling;
  14305. p = me.document.createElement('p');
  14306. domUtils.fillNode(me.document, p);
  14307. parentList = li.parentNode;
  14308. if (pre && next) {
  14309. range.setStart(next, 0).collapse(true).select(true);
  14310. domUtils.remove(li);
  14311. } else {
  14312. if (!pre && !next || !pre) {
  14313. parentList.parentNode.insertBefore(p, parentList);
  14314. } else {
  14315. li.parentNode.parentNode.insertBefore(p, parentList.nextSibling);
  14316. }
  14317. domUtils.remove(li);
  14318. if (!parentList.firstChild) {
  14319. domUtils.remove(parentList);
  14320. }
  14321. range.setStart(p, 0).setCursor();
  14322. }
  14323. preventAndSave();
  14324. return;
  14325. }
  14326. } else {
  14327. var tmpRange = range.cloneRange(),
  14328. bk = tmpRange.collapse(false).createBookmark();
  14329. range.deleteContents();
  14330. tmpRange.moveToBookmark(bk);
  14331. var li = domUtils.findParentByTagName(tmpRange.startContainer, 'li', true);
  14332. clearEmptySibling(li);
  14333. tmpRange.select();
  14334. preventAndSave();
  14335. return;
  14336. }
  14337. }
  14338. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14339. if (li) {
  14340. if (domUtils.isEmptyBlock(li)) {
  14341. bk = range.createBookmark();
  14342. var parentList = li.parentNode;
  14343. if (li !== parentList.lastChild) {
  14344. domUtils.breakParent(li, parentList);
  14345. clearEmptySibling(li);
  14346. } else {
  14347. parentList.parentNode.insertBefore(li, parentList.nextSibling);
  14348. if (domUtils.isEmptyNode(parentList)) {
  14349. domUtils.remove(parentList);
  14350. }
  14351. }
  14352. //嵌套不处理
  14353. if (!dtd.$list[li.parentNode.tagName]) {
  14354. if (!domUtils.isBlockElm(li.firstChild)) {
  14355. p = me.document.createElement('p');
  14356. li.parentNode.insertBefore(p, li);
  14357. while (li.firstChild) {
  14358. p.appendChild(li.firstChild);
  14359. }
  14360. domUtils.remove(li);
  14361. } else {
  14362. domUtils.remove(li, true);
  14363. }
  14364. }
  14365. range.moveToBookmark(bk).select();
  14366. } else {
  14367. var first = li.firstChild;
  14368. if (!first || !domUtils.isBlockElm(first)) {
  14369. var p = me.document.createElement('p');
  14370. !li.firstChild && domUtils.fillNode(me.document, p);
  14371. while (li.firstChild) {
  14372. p.appendChild(li.firstChild);
  14373. }
  14374. li.appendChild(p);
  14375. first = p;
  14376. }
  14377. var span = me.document.createElement('span');
  14378. range.insertNode(span);
  14379. domUtils.breakParent(span, li);
  14380. var nextLi = span.nextSibling;
  14381. first = nextLi.firstChild;
  14382. if (!first) {
  14383. p = me.document.createElement('p');
  14384. domUtils.fillNode(me.document, p);
  14385. nextLi.appendChild(p);
  14386. first = p;
  14387. }
  14388. if (domUtils.isEmptyNode(first)) {
  14389. first.innerHTML = '';
  14390. domUtils.fillNode(me.document, first);
  14391. }
  14392. range.setStart(first, 0).collapse(true).shrinkBoundary().select();
  14393. domUtils.remove(span);
  14394. var pre = nextLi.previousSibling;
  14395. if (pre && domUtils.isEmptyBlock(pre)) {
  14396. pre.innerHTML = '<p></p>';
  14397. domUtils.fillNode(me.document, pre.firstChild);
  14398. }
  14399. }
  14400. // }
  14401. preventAndSave();
  14402. }
  14403. }
  14404. }
  14405. if (keyCode == 8) {
  14406. //修中ie中li下的问题
  14407. range = me.selection.getRange();
  14408. if (range.collapsed && domUtils.isStartInblock(range)) {
  14409. tmpRange = range.cloneRange().trimBoundary();
  14410. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14411. //要在li的最左边,才能处理
  14412. if (li && domUtils.isStartInblock(tmpRange)) {
  14413. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  14414. if (start && start !== li.firstChild) {
  14415. var parentList = domUtils.findParentByTagName(start, ['ol', 'ul']);
  14416. domUtils.breakParent(start, parentList);
  14417. clearEmptySibling(start);
  14418. me.fireEvent('contentchange');
  14419. range.setStart(start, 0).setCursor(false, true);
  14420. me.fireEvent('saveScene');
  14421. domUtils.preventDefault(evt);
  14422. return;
  14423. }
  14424. if (li && (pre = li.previousSibling)) {
  14425. if (keyCode == 46 && li.childNodes.length) {
  14426. return;
  14427. }
  14428. //有可能上边的兄弟节点是个2级菜单,要追加到2级菜单的最后的li
  14429. if (dtd.$list[pre.tagName]) {
  14430. pre = pre.lastChild;
  14431. }
  14432. me.undoManger && me.undoManger.save();
  14433. first = li.firstChild;
  14434. if (domUtils.isBlockElm(first)) {
  14435. if (domUtils.isEmptyNode(first)) {
  14436. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  14437. pre.appendChild(first);
  14438. range.setStart(first, 0).setCursor(false, true);
  14439. //first不是唯一的节点
  14440. while (li.firstChild) {
  14441. pre.appendChild(li.firstChild);
  14442. }
  14443. } else {
  14444. span = me.document.createElement('span');
  14445. range.insertNode(span);
  14446. //判断pre是否是空的节点,如果是<p><br/></p>类型的空节点,干掉p标签防止它占位
  14447. if (domUtils.isEmptyBlock(pre)) {
  14448. pre.innerHTML = '';
  14449. }
  14450. domUtils.moveChild(li, pre);
  14451. range.setStartBefore(span).collapse(true).select(true);
  14452. domUtils.remove(span);
  14453. }
  14454. } else {
  14455. if (domUtils.isEmptyNode(li)) {
  14456. var p = me.document.createElement('p');
  14457. pre.appendChild(p);
  14458. range.setStart(p, 0).setCursor();
  14459. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  14460. } else {
  14461. range.setEnd(pre, pre.childNodes.length).collapse().select(true);
  14462. while (li.firstChild) {
  14463. pre.appendChild(li.firstChild);
  14464. }
  14465. }
  14466. }
  14467. domUtils.remove(li);
  14468. me.fireEvent('contentchange');
  14469. me.fireEvent('saveScene');
  14470. domUtils.preventDefault(evt);
  14471. return;
  14472. }
  14473. //trace:980
  14474. if (li && !li.previousSibling) {
  14475. var parentList = li.parentNode;
  14476. var bk = range.createBookmark();
  14477. if (domUtils.isTagNode(parentList.parentNode, 'ol ul')) {
  14478. parentList.parentNode.insertBefore(li, parentList);
  14479. if (domUtils.isEmptyNode(parentList)) {
  14480. domUtils.remove(parentList)
  14481. }
  14482. } else {
  14483. while (li.firstChild) {
  14484. parentList.parentNode.insertBefore(li.firstChild, parentList);
  14485. }
  14486. domUtils.remove(li);
  14487. if (domUtils.isEmptyNode(parentList)) {
  14488. domUtils.remove(parentList)
  14489. }
  14490. }
  14491. range.moveToBookmark(bk).setCursor(false, true);
  14492. me.fireEvent('contentchange');
  14493. me.fireEvent('saveScene');
  14494. domUtils.preventDefault(evt);
  14495. return;
  14496. }
  14497. }
  14498. }
  14499. }
  14500. });
  14501. me.addListener('keyup', function (type, evt) {
  14502. var keyCode = evt.keyCode || evt.which;
  14503. if (keyCode == 8) {
  14504. var rng = me.selection.getRange(), list;
  14505. if (list = domUtils.findParentByTagName(rng.startContainer, ['ol', 'ul'], true)) {
  14506. adjustList(list, list.tagName.toLowerCase(), getStyle(list) || domUtils.getComputedStyle(list, 'list-style-type'), true)
  14507. }
  14508. }
  14509. });
  14510. //处理tab键
  14511. me.addListener('tabkeydown', function () {
  14512. var range = me.selection.getRange();
  14513. //控制级数
  14514. function checkLevel(li) {
  14515. if (me.options.maxListLevel != -1) {
  14516. var level = li.parentNode, levelNum = 0;
  14517. while (/[ou]l/i.test(level.tagName)) {
  14518. levelNum++;
  14519. level = level.parentNode;
  14520. }
  14521. if (levelNum >= me.options.maxListLevel) {
  14522. return true;
  14523. }
  14524. }
  14525. }
  14526. //只以开始为准
  14527. //todo 后续改进
  14528. var li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14529. if (li) {
  14530. var bk;
  14531. if (range.collapsed) {
  14532. if (checkLevel(li))
  14533. return true;
  14534. var parentLi = li.parentNode,
  14535. list = me.document.createElement(parentLi.tagName),
  14536. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi) || domUtils.getComputedStyle(parentLi, 'list-style-type'));
  14537. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  14538. var currentStyle = listStyle[list.tagName][index];
  14539. setListStyle(list, currentStyle);
  14540. if (domUtils.isStartInblock(range)) {
  14541. me.fireEvent('saveScene');
  14542. bk = range.createBookmark();
  14543. parentLi.insertBefore(list, li);
  14544. list.appendChild(li);
  14545. adjustList(list, list.tagName.toLowerCase(), currentStyle);
  14546. me.fireEvent('contentchange');
  14547. range.moveToBookmark(bk).select(true);
  14548. return true;
  14549. }
  14550. } else {
  14551. me.fireEvent('saveScene');
  14552. bk = range.createBookmark();
  14553. for (var i = 0, closeList, parents = domUtils.findParents(li), ci; ci = parents[i++];) {
  14554. if (domUtils.isTagNode(ci, 'ol ul')) {
  14555. closeList = ci;
  14556. break;
  14557. }
  14558. }
  14559. var current = li;
  14560. if (bk.end) {
  14561. while (current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)) {
  14562. if (checkLevel(current)) {
  14563. current = domUtils.getNextDomNode(current, false, null, function (node) { return node !== closeList });
  14564. continue;
  14565. }
  14566. var parentLi = current.parentNode,
  14567. list = me.document.createElement(parentLi.tagName),
  14568. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi) || domUtils.getComputedStyle(parentLi, 'list-style-type'));
  14569. var currentIndex = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  14570. var currentStyle = listStyle[list.tagName][currentIndex];
  14571. setListStyle(list, currentStyle);
  14572. parentLi.insertBefore(list, current);
  14573. while (current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)) {
  14574. li = current.nextSibling;
  14575. list.appendChild(current);
  14576. if (!li || domUtils.isTagNode(li, 'ol ul')) {
  14577. if (li) {
  14578. while (li = li.firstChild) {
  14579. if (li.tagName == 'LI') {
  14580. break;
  14581. }
  14582. }
  14583. } else {
  14584. li = domUtils.getNextDomNode(current, false, null, function (node) { return node !== closeList });
  14585. }
  14586. break;
  14587. }
  14588. current = li;
  14589. }
  14590. adjustList(list, list.tagName.toLowerCase(), currentStyle);
  14591. current = li;
  14592. }
  14593. }
  14594. me.fireEvent('contentchange');
  14595. range.moveToBookmark(bk).select();
  14596. return true;
  14597. }
  14598. }
  14599. });
  14600. function getLi(start) {
  14601. while (start && !domUtils.isBody(start)) {
  14602. if (start.nodeName == 'TABLE') {
  14603. return null;
  14604. }
  14605. if (start.nodeName == 'LI') {
  14606. return start
  14607. }
  14608. start = start.parentNode;
  14609. }
  14610. }
  14611. /**
  14612. * 有序列表,与“insertunorderedlist”命令互斥
  14613. * @command insertorderedlist
  14614. * @method execCommand
  14615. * @param { String } command 命令字符串
  14616. * @param { String } style 插入的有序列表类型,值为:decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  14617. * @example
  14618. * ```javascript
  14619. * editor.execCommand( 'insertorderedlist','decimal');
  14620. * ```
  14621. */
  14622. /**
  14623. * 查询当前选区内容是否有序列表
  14624. * @command insertorderedlist
  14625. * @method queryCommandState
  14626. * @param { String } cmd 命令字符串
  14627. * @return { int } 如果当前选区是有序列表返回1,否则返回0
  14628. * @example
  14629. * ```javascript
  14630. * editor.queryCommandState( 'insertorderedlist' );
  14631. * ```
  14632. */
  14633. /**
  14634. * 查询当前选区内容是否有序列表
  14635. * @command insertorderedlist
  14636. * @method queryCommandValue
  14637. * @param { String } cmd 命令字符串
  14638. * @return { String } 返回当前有序列表的类型,值为null或decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  14639. * @example
  14640. * ```javascript
  14641. * editor.queryCommandValue( 'insertorderedlist' );
  14642. * ```
  14643. */
  14644. /**
  14645. * 无序列表,与“insertorderedlist”命令互斥
  14646. * @command insertunorderedlist
  14647. * @method execCommand
  14648. * @param { String } command 命令字符串
  14649. * @param { String } style 插入的无序列表类型,值为:circle,disc,square,dash,dot
  14650. * @example
  14651. * ```javascript
  14652. * editor.execCommand( 'insertunorderedlist','circle');
  14653. * ```
  14654. */
  14655. /**
  14656. * 查询当前是否有word文档粘贴进来的图片
  14657. * @command insertunorderedlist
  14658. * @method insertunorderedlist
  14659. * @param { String } command 命令字符串
  14660. * @return { int } 如果当前选区是无序列表返回1,否则返回0
  14661. * @example
  14662. * ```javascript
  14663. * editor.queryCommandState( 'insertunorderedlist' );
  14664. * ```
  14665. */
  14666. /**
  14667. * 查询当前选区内容是否有序列表
  14668. * @command insertunorderedlist
  14669. * @method queryCommandValue
  14670. * @param { String } command 命令字符串
  14671. * @return { String } 返回当前无序列表的类型,值为null或circle,disc,square,dash,dot
  14672. * @example
  14673. * ```javascript
  14674. * editor.queryCommandValue( 'insertunorderedlist' );
  14675. * ```
  14676. */
  14677. me.commands['insertorderedlist'] =
  14678. me.commands['insertunorderedlist'] = {
  14679. execCommand: function (command, style) {
  14680. if (!style) {
  14681. style = command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc';
  14682. }
  14683. var me = this,
  14684. range = this.selection.getRange(),
  14685. filterFn = function (node) {
  14686. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  14687. },
  14688. tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul',
  14689. frag = me.document.createDocumentFragment();
  14690. //去掉是因为会出现选到末尾,导致adjustmentBoundary缩到ol/ul的位置
  14691. //range.shrinkBoundary();//.adjustmentBoundary();
  14692. range.adjustmentBoundary().shrinkBoundary();
  14693. var bko = range.createBookmark(true),
  14694. start = getLi(me.document.getElementById(bko.start)),
  14695. modifyStart = 0,
  14696. end = getLi(me.document.getElementById(bko.end)),
  14697. modifyEnd = 0,
  14698. startParent, endParent,
  14699. list, tmp;
  14700. if (start || end) {
  14701. start && (startParent = start.parentNode);
  14702. if (!bko.end) {
  14703. end = start;
  14704. }
  14705. end && (endParent = end.parentNode);
  14706. if (startParent === endParent) {
  14707. while (start !== end) {
  14708. tmp = start;
  14709. start = start.nextSibling;
  14710. if (!domUtils.isBlockElm(tmp.firstChild)) {
  14711. var p = me.document.createElement('p');
  14712. while (tmp.firstChild) {
  14713. p.appendChild(tmp.firstChild);
  14714. }
  14715. tmp.appendChild(p);
  14716. }
  14717. frag.appendChild(tmp);
  14718. }
  14719. tmp = me.document.createElement('span');
  14720. startParent.insertBefore(tmp, end);
  14721. if (!domUtils.isBlockElm(end.firstChild)) {
  14722. p = me.document.createElement('p');
  14723. while (end.firstChild) {
  14724. p.appendChild(end.firstChild);
  14725. }
  14726. end.appendChild(p);
  14727. }
  14728. frag.appendChild(end);
  14729. domUtils.breakParent(tmp, startParent);
  14730. if (domUtils.isEmptyNode(tmp.previousSibling)) {
  14731. domUtils.remove(tmp.previousSibling);
  14732. }
  14733. if (domUtils.isEmptyNode(tmp.nextSibling)) {
  14734. domUtils.remove(tmp.nextSibling)
  14735. }
  14736. var nodeStyle = getStyle(startParent) || domUtils.getComputedStyle(startParent, 'list-style-type') || (command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc');
  14737. if (startParent.tagName.toLowerCase() == tag && nodeStyle == style) {
  14738. for (var i = 0, ci, tmpFrag = me.document.createDocumentFragment(); ci = frag.firstChild;) {
  14739. if (domUtils.isTagNode(ci, 'ol ul')) {
  14740. // 删除时,子列表不处理
  14741. // utils.each(domUtils.getElementsByTagName(ci,'li'),function(li){
  14742. // while(li.firstChild){
  14743. // tmpFrag.appendChild(li.firstChild);
  14744. // }
  14745. //
  14746. // });
  14747. tmpFrag.appendChild(ci);
  14748. } else {
  14749. while (ci.firstChild) {
  14750. tmpFrag.appendChild(ci.firstChild);
  14751. domUtils.remove(ci);
  14752. }
  14753. }
  14754. }
  14755. tmp.parentNode.insertBefore(tmpFrag, tmp);
  14756. } else {
  14757. list = me.document.createElement(tag);
  14758. setListStyle(list, style);
  14759. list.appendChild(frag);
  14760. tmp.parentNode.insertBefore(list, tmp);
  14761. }
  14762. domUtils.remove(tmp);
  14763. list && adjustList(list, tag, style);
  14764. range.moveToBookmark(bko).select();
  14765. return;
  14766. }
  14767. //开始
  14768. if (start) {
  14769. while (start) {
  14770. tmp = start.nextSibling;
  14771. if (domUtils.isTagNode(start, 'ol ul')) {
  14772. frag.appendChild(start);
  14773. } else {
  14774. var tmpfrag = me.document.createDocumentFragment(),
  14775. hasBlock = 0;
  14776. while (start.firstChild) {
  14777. if (domUtils.isBlockElm(start.firstChild)) {
  14778. hasBlock = 1;
  14779. }
  14780. tmpfrag.appendChild(start.firstChild);
  14781. }
  14782. if (!hasBlock) {
  14783. var tmpP = me.document.createElement('p');
  14784. tmpP.appendChild(tmpfrag);
  14785. frag.appendChild(tmpP);
  14786. } else {
  14787. frag.appendChild(tmpfrag);
  14788. }
  14789. domUtils.remove(start);
  14790. }
  14791. start = tmp;
  14792. }
  14793. startParent.parentNode.insertBefore(frag, startParent.nextSibling);
  14794. if (domUtils.isEmptyNode(startParent)) {
  14795. range.setStartBefore(startParent);
  14796. domUtils.remove(startParent);
  14797. } else {
  14798. range.setStartAfter(startParent);
  14799. }
  14800. modifyStart = 1;
  14801. }
  14802. if (end && domUtils.inDoc(endParent, me.document)) {
  14803. //结束
  14804. start = endParent.firstChild;
  14805. while (start && start !== end) {
  14806. tmp = start.nextSibling;
  14807. if (domUtils.isTagNode(start, 'ol ul')) {
  14808. frag.appendChild(start);
  14809. } else {
  14810. tmpfrag = me.document.createDocumentFragment();
  14811. hasBlock = 0;
  14812. while (start.firstChild) {
  14813. if (domUtils.isBlockElm(start.firstChild)) {
  14814. hasBlock = 1;
  14815. }
  14816. tmpfrag.appendChild(start.firstChild);
  14817. }
  14818. if (!hasBlock) {
  14819. tmpP = me.document.createElement('p');
  14820. tmpP.appendChild(tmpfrag);
  14821. frag.appendChild(tmpP);
  14822. } else {
  14823. frag.appendChild(tmpfrag);
  14824. }
  14825. domUtils.remove(start);
  14826. }
  14827. start = tmp;
  14828. }
  14829. var tmpDiv = domUtils.createElement(me.document, 'div', {
  14830. 'tmpDiv': 1
  14831. });
  14832. domUtils.moveChild(end, tmpDiv);
  14833. frag.appendChild(tmpDiv);
  14834. domUtils.remove(end);
  14835. endParent.parentNode.insertBefore(frag, endParent);
  14836. range.setEndBefore(endParent);
  14837. if (domUtils.isEmptyNode(endParent)) {
  14838. domUtils.remove(endParent);
  14839. }
  14840. modifyEnd = 1;
  14841. }
  14842. }
  14843. if (!modifyStart) {
  14844. range.setStartBefore(me.document.getElementById(bko.start));
  14845. }
  14846. if (bko.end && !modifyEnd) {
  14847. range.setEndAfter(me.document.getElementById(bko.end));
  14848. }
  14849. range.enlarge(true, function (node) {
  14850. return notExchange[node.tagName];
  14851. });
  14852. frag = me.document.createDocumentFragment();
  14853. var bk = range.createBookmark(),
  14854. current = domUtils.getNextDomNode(bk.start, false, filterFn),
  14855. tmpRange = range.cloneRange(),
  14856. tmpNode,
  14857. block = domUtils.isBlockElm;
  14858. while (current && current !== bk.end && (domUtils.getPosition(current, bk.end) & domUtils.POSITION_PRECEDING)) {
  14859. if (current.nodeType == 3 || dtd.li[current.tagName]) {
  14860. if (current.nodeType == 1 && dtd.$list[current.tagName]) {
  14861. while (current.firstChild) {
  14862. frag.appendChild(current.firstChild);
  14863. }
  14864. tmpNode = domUtils.getNextDomNode(current, false, filterFn);
  14865. domUtils.remove(current);
  14866. current = tmpNode;
  14867. continue;
  14868. }
  14869. tmpNode = current;
  14870. tmpRange.setStartBefore(current);
  14871. while (current && current !== bk.end && (!block(current) || domUtils.isBookmarkNode(current))) {
  14872. tmpNode = current;
  14873. current = domUtils.getNextDomNode(current, false, null, function (node) {
  14874. return !notExchange[node.tagName];
  14875. });
  14876. }
  14877. if (current && block(current)) {
  14878. tmp = domUtils.getNextDomNode(tmpNode, false, filterFn);
  14879. if (tmp && domUtils.isBookmarkNode(tmp)) {
  14880. current = domUtils.getNextDomNode(tmp, false, filterFn);
  14881. tmpNode = tmp;
  14882. }
  14883. }
  14884. tmpRange.setEndAfter(tmpNode);
  14885. current = domUtils.getNextDomNode(tmpNode, false, filterFn);
  14886. var li = range.document.createElement('li');
  14887. li.appendChild(tmpRange.extractContents());
  14888. if (domUtils.isEmptyNode(li)) {
  14889. var tmpNode = range.document.createElement('p');
  14890. while (li.firstChild) {
  14891. tmpNode.appendChild(li.firstChild)
  14892. }
  14893. li.appendChild(tmpNode);
  14894. }
  14895. frag.appendChild(li);
  14896. } else {
  14897. current = domUtils.getNextDomNode(current, true, filterFn);
  14898. }
  14899. }
  14900. range.moveToBookmark(bk).collapse(true);
  14901. list = me.document.createElement(tag);
  14902. setListStyle(list, style);
  14903. list.appendChild(frag);
  14904. range.insertNode(list);
  14905. //当前list上下看能否合并
  14906. adjustList(list, tag, style);
  14907. //去掉冗余的tmpDiv
  14908. for (var i = 0, ci, tmpDivs = domUtils.getElementsByTagName(list, 'div'); ci = tmpDivs[i++];) {
  14909. if (ci.getAttribute('tmpDiv')) {
  14910. domUtils.remove(ci, true)
  14911. }
  14912. }
  14913. range.moveToBookmark(bko).select();
  14914. },
  14915. queryCommandState: function (command) {
  14916. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  14917. var path = this.selection.getStartElementPath();
  14918. for (var i = 0, ci; ci = path[i++];) {
  14919. if (ci.nodeName == 'TABLE') {
  14920. return 0
  14921. }
  14922. if (tag == ci.nodeName.toLowerCase()) {
  14923. return 1
  14924. };
  14925. }
  14926. return 0;
  14927. },
  14928. queryCommandValue: function (command) {
  14929. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  14930. var path = this.selection.getStartElementPath(),
  14931. node;
  14932. for (var i = 0, ci; ci = path[i++];) {
  14933. if (ci.nodeName == 'TABLE') {
  14934. node = null;
  14935. break;
  14936. }
  14937. if (tag == ci.nodeName.toLowerCase()) {
  14938. node = ci;
  14939. break;
  14940. };
  14941. }
  14942. return node ? getStyle(node) || domUtils.getComputedStyle(node, 'list-style-type') : null;
  14943. }
  14944. };
  14945. };
  14946. // plugins/source.js
  14947. /**
  14948. * 源码编辑插件
  14949. * @file
  14950. * @since 1.2.6.1
  14951. */
  14952. (function () {
  14953. var sourceEditors = {
  14954. textarea: function (editor, holder) {
  14955. var textarea = holder.ownerDocument.createElement('textarea');
  14956. textarea.style.cssText = 'position:absolute;resize:none;width:100%;height:100%;border:0;padding:0;margin:0;overflow-y:auto;';
  14957. // todo: IE下只有onresize属性可用... 很纠结
  14958. if (browser.ie && browser.version < 8) {
  14959. textarea.style.width = holder.offsetWidth + 'px';
  14960. textarea.style.height = holder.offsetHeight + 'px';
  14961. holder.onresize = function () {
  14962. textarea.style.width = holder.offsetWidth + 'px';
  14963. textarea.style.height = holder.offsetHeight + 'px';
  14964. };
  14965. }
  14966. holder.appendChild(textarea);
  14967. return {
  14968. setContent: function (content) {
  14969. textarea.value = content;
  14970. },
  14971. getContent: function () {
  14972. return textarea.value;
  14973. },
  14974. select: function () {
  14975. var range;
  14976. if (browser.ie) {
  14977. range = textarea.createTextRange();
  14978. range.collapse(true);
  14979. range.select();
  14980. } else {
  14981. //todo: chrome下无法设置焦点
  14982. textarea.setSelectionRange(0, 0);
  14983. textarea.focus();
  14984. }
  14985. },
  14986. dispose: function () {
  14987. holder.removeChild(textarea);
  14988. // todo
  14989. holder.onresize = null;
  14990. textarea = null;
  14991. holder = null;
  14992. }
  14993. };
  14994. },
  14995. codemirror: function (editor, holder) {
  14996. var codeEditor = window.CodeMirror(holder, {
  14997. mode: "text/html",
  14998. tabMode: "indent",
  14999. lineNumbers: true,
  15000. lineWrapping: true
  15001. });
  15002. var dom = codeEditor.getWrapperElement();
  15003. dom.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;font-family:consolas,"Courier new",monospace;font-size:13px;';
  15004. codeEditor.getScrollerElement().style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;';
  15005. codeEditor.refresh();
  15006. return {
  15007. getCodeMirror: function () {
  15008. return codeEditor;
  15009. },
  15010. setContent: function (content) {
  15011. codeEditor.setValue(content);
  15012. },
  15013. getContent: function () {
  15014. return codeEditor.getValue();
  15015. },
  15016. select: function () {
  15017. codeEditor.focus();
  15018. },
  15019. dispose: function () {
  15020. holder.removeChild(dom);
  15021. dom = null;
  15022. codeEditor = null;
  15023. }
  15024. };
  15025. }
  15026. };
  15027. UE.plugins['source'] = function () {
  15028. var me = this;
  15029. var opt = this.options;
  15030. var sourceMode = false;
  15031. var sourceEditor;
  15032. var orgSetContent;
  15033. opt.sourceEditor = browser.ie ? 'textarea' : (opt.sourceEditor || 'codemirror');
  15034. me.setOpt({
  15035. sourceEditorFirst: false
  15036. });
  15037. function createSourceEditor(holder) {
  15038. return sourceEditors[opt.sourceEditor == 'codemirror' && window.CodeMirror ? 'codemirror' : 'textarea'](me, holder);
  15039. }
  15040. var bakCssText;
  15041. //解决在源码模式下getContent不能得到最新的内容问题
  15042. var oldGetContent,
  15043. bakAddress;
  15044. /**
  15045. * 切换源码模式和编辑模式
  15046. * @command source
  15047. * @method execCommand
  15048. * @param { String } cmd 命令字符串
  15049. * @example
  15050. * ```javascript
  15051. * editor.execCommand( 'source');
  15052. * ```
  15053. */
  15054. /**
  15055. * 查询当前编辑区域的状态是源码模式还是可视化模式
  15056. * @command source
  15057. * @method queryCommandState
  15058. * @param { String } cmd 命令字符串
  15059. * @return { int } 如果当前是源码编辑模式,返回1,否则返回0
  15060. * @example
  15061. * ```javascript
  15062. * editor.queryCommandState( 'source' );
  15063. * ```
  15064. */
  15065. me.commands['source'] = {
  15066. execCommand: function () {
  15067. sourceMode = !sourceMode;
  15068. if (sourceMode) {
  15069. bakAddress = me.selection.getRange().createAddress(false, true);
  15070. me.undoManger && me.undoManger.save(true);
  15071. if (browser.gecko) {
  15072. me.body.contentEditable = false;
  15073. }
  15074. bakCssText = me.iframe.style.cssText;
  15075. me.iframe.style.cssText += 'position:absolute;left:-32768px;top:-32768px;';
  15076. me.fireEvent('beforegetcontent');
  15077. var root = UE.htmlparser(me.body.innerHTML);
  15078. me.filterOutputRule(root);
  15079. root.traversal(function (node) {
  15080. if (node.type == 'element') {
  15081. switch (node.tagName) {
  15082. case 'td':
  15083. case 'th':
  15084. case 'caption':
  15085. if (node.children && node.children.length == 1) {
  15086. if (node.firstChild().tagName == 'br') {
  15087. node.removeChild(node.firstChild())
  15088. }
  15089. };
  15090. break;
  15091. case 'pre':
  15092. node.innerText(node.innerText().replace(/&nbsp;/g, ' '))
  15093. }
  15094. }
  15095. });
  15096. me.fireEvent('aftergetcontent');
  15097. var content = root.toHtml(true);
  15098. sourceEditor = createSourceEditor(me.iframe.parentNode);
  15099. sourceEditor.setContent(content);
  15100. orgSetContent = me.setContent;
  15101. me.setContent = function (html) {
  15102. //这里暂时不触发事件,防止报错
  15103. var root = UE.htmlparser(html);
  15104. me.filterInputRule(root);
  15105. html = root.toHtml();
  15106. sourceEditor.setContent(html);
  15107. };
  15108. setTimeout(function () {
  15109. sourceEditor.select();
  15110. me.addListener('fullscreenchanged', function () {
  15111. try {
  15112. sourceEditor.getCodeMirror().refresh()
  15113. } catch (e) { }
  15114. });
  15115. });
  15116. //重置getContent,源码模式下取值也能是最新的数据
  15117. oldGetContent = me.getContent;
  15118. me.getContent = function () {
  15119. return sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  15120. };
  15121. } else {
  15122. me.iframe.style.cssText = bakCssText;
  15123. var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  15124. //处理掉block节点前后的空格,有可能会误命中,暂时不考虑
  15125. cont = cont.replace(new RegExp('[\\r\\t\\n ]*<\/?(\\w+)\\s*(?:[^>]*)>', 'g'), function (a, b) {
  15126. if (b && !dtd.$inlineWithA[b.toLowerCase()]) {
  15127. return a.replace(/(^[\n\r\t ]*)|([\n\r\t ]*$)/g, '');
  15128. }
  15129. return a.replace(/(^[\n\r\t]*)|([\n\r\t]*$)/g, '')
  15130. });
  15131. me.setContent = orgSetContent;
  15132. me.setContent(cont);
  15133. sourceEditor.dispose();
  15134. sourceEditor = null;
  15135. //还原getContent方法
  15136. me.getContent = oldGetContent;
  15137. var first = me.body.firstChild;
  15138. //trace:1106 都删除空了,下边会报错,所以补充一个p占位
  15139. if (!first) {
  15140. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  15141. first = me.body.firstChild;
  15142. }
  15143. //要在ifm为显示时ff才能取到selection,否则报错
  15144. //这里不能比较位置了
  15145. me.undoManger && me.undoManger.save(true);
  15146. if (browser.gecko) {
  15147. var input = document.createElement('input');
  15148. input.style.cssText = 'position:absolute;left:0;top:-32768px';
  15149. document.body.appendChild(input);
  15150. me.body.contentEditable = false;
  15151. setTimeout(function () {
  15152. domUtils.setViewportOffset(input, { left: -32768, top: 0 });
  15153. input.focus();
  15154. setTimeout(function () {
  15155. me.body.contentEditable = true;
  15156. me.selection.getRange().moveToAddress(bakAddress).select(true);
  15157. domUtils.remove(input);
  15158. });
  15159. });
  15160. } else {
  15161. //ie下有可能报错,比如在代码顶头的情况
  15162. try {
  15163. me.selection.getRange().moveToAddress(bakAddress).select(true);
  15164. } catch (e) { }
  15165. }
  15166. }
  15167. this.fireEvent('sourcemodechanged', sourceMode);
  15168. },
  15169. queryCommandState: function () {
  15170. return sourceMode | 0;
  15171. },
  15172. notNeedUndo: 1
  15173. };
  15174. var oldQueryCommandState = me.queryCommandState;
  15175. me.queryCommandState = function (cmdName) {
  15176. cmdName = cmdName.toLowerCase();
  15177. if (sourceMode) {
  15178. //源码模式下可以开启的命令
  15179. return cmdName in {
  15180. 'source': 1,
  15181. 'fullscreen': 1
  15182. } ? 1 : -1
  15183. }
  15184. return oldQueryCommandState.apply(this, arguments);
  15185. };
  15186. if (opt.sourceEditor == "codemirror") {
  15187. me.addListener("ready", function () {
  15188. utils.loadFile(document, {
  15189. src: opt.codeMirrorJsUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.js",
  15190. tag: "script",
  15191. type: "text/javascript",
  15192. defer: "defer"
  15193. }, function () {
  15194. if (opt.sourceEditorFirst) {
  15195. setTimeout(function () {
  15196. me.execCommand("source");
  15197. }, 0);
  15198. }
  15199. });
  15200. utils.loadFile(document, {
  15201. tag: "link",
  15202. rel: "stylesheet",
  15203. type: "text/css",
  15204. href: opt.codeMirrorCssUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.css"
  15205. });
  15206. });
  15207. }
  15208. };
  15209. })();
  15210. // plugins/enterkey.js
  15211. ///import core
  15212. ///import plugins/undo.js
  15213. ///commands 设置回车标签p或br
  15214. ///commandsName EnterKey
  15215. ///commandsTitle 设置回车标签p或br
  15216. /**
  15217. * @description 处理回车
  15218. * @author zhanyi
  15219. */
  15220. UE.plugins['enterkey'] = function () {
  15221. var hTag,
  15222. me = this,
  15223. tag = me.options.enterTag;
  15224. me.addListener('keyup', function (type, evt) {
  15225. var keyCode = evt.keyCode || evt.which;
  15226. if (keyCode == 13) {
  15227. var range = me.selection.getRange(),
  15228. start = range.startContainer,
  15229. doSave;
  15230. //修正在h1-h6里边回车后不能嵌套p的问题
  15231. if (!browser.ie) {
  15232. if (/h\d/i.test(hTag)) {
  15233. if (browser.gecko) {
  15234. var h = domUtils.findParentByTagName(start, ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'caption', 'table'], true);
  15235. if (!h) {
  15236. me.document.execCommand('formatBlock', false, '<p>');
  15237. doSave = 1;
  15238. }
  15239. } else {
  15240. //chrome remove div
  15241. if (start.nodeType == 1) {
  15242. var tmp = me.document.createTextNode(''), div;
  15243. range.insertNode(tmp);
  15244. div = domUtils.findParentByTagName(tmp, 'div', true);
  15245. if (div) {
  15246. var p = me.document.createElement('p');
  15247. while (div.firstChild) {
  15248. p.appendChild(div.firstChild);
  15249. }
  15250. div.parentNode.insertBefore(p, div);
  15251. domUtils.remove(div);
  15252. range.setStartBefore(tmp).setCursor();
  15253. doSave = 1;
  15254. }
  15255. domUtils.remove(tmp);
  15256. }
  15257. }
  15258. if (me.undoManger && doSave) {
  15259. me.undoManger.save();
  15260. }
  15261. }
  15262. //没有站位符,会出现多行的问题
  15263. browser.opera && range.select();
  15264. } else {
  15265. me.fireEvent('saveScene', true, true)
  15266. }
  15267. }
  15268. });
  15269. me.addListener('keydown', function (type, evt) {
  15270. var keyCode = evt.keyCode || evt.which;
  15271. if (keyCode == 13) {//回车
  15272. if (me.fireEvent('beforeenterkeydown')) {
  15273. domUtils.preventDefault(evt);
  15274. return;
  15275. }
  15276. me.fireEvent('saveScene', true, true);
  15277. hTag = '';
  15278. var range = me.selection.getRange();
  15279. if (!range.collapsed) {
  15280. //跨td不能删
  15281. var start = range.startContainer,
  15282. end = range.endContainer,
  15283. startTd = domUtils.findParentByTagName(start, 'td', true),
  15284. endTd = domUtils.findParentByTagName(end, 'td', true);
  15285. if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) {
  15286. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  15287. return;
  15288. }
  15289. }
  15290. if (tag == 'p') {
  15291. if (!browser.ie) {
  15292. start = domUtils.findParentByTagName(range.startContainer, ['ol', 'ul', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'caption'], true);
  15293. //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command
  15294. //trace:2431
  15295. if (!start && !browser.opera) {
  15296. me.document.execCommand('formatBlock', false, '<p>');
  15297. if (browser.gecko) {
  15298. range = me.selection.getRange();
  15299. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  15300. start && domUtils.removeDirtyAttr(start);
  15301. }
  15302. } else {
  15303. hTag = start.tagName;
  15304. start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start);
  15305. }
  15306. }
  15307. } else {
  15308. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  15309. if (!range.collapsed) {
  15310. range.deleteContents();
  15311. start = range.startContainer;
  15312. if (start.nodeType == 1 && (start = start.childNodes[range.startOffset])) {
  15313. while (start.nodeType == 1) {
  15314. if (dtd.$empty[start.tagName]) {
  15315. range.setStartBefore(start).setCursor();
  15316. if (me.undoManger) {
  15317. me.undoManger.save();
  15318. }
  15319. return false;
  15320. }
  15321. if (!start.firstChild) {
  15322. var br = range.document.createElement('br');
  15323. start.appendChild(br);
  15324. range.setStart(start, 0).setCursor();
  15325. if (me.undoManger) {
  15326. me.undoManger.save();
  15327. }
  15328. return false;
  15329. }
  15330. start = start.firstChild;
  15331. }
  15332. if (start === range.startContainer.childNodes[range.startOffset]) {
  15333. br = range.document.createElement('br');
  15334. range.insertNode(br).setCursor();
  15335. } else {
  15336. range.setStart(start, 0).setCursor();
  15337. }
  15338. } else {
  15339. br = range.document.createElement('br');
  15340. range.insertNode(br).setStartAfter(br).setCursor();
  15341. }
  15342. } else {
  15343. br = range.document.createElement('br');
  15344. range.insertNode(br);
  15345. var parent = br.parentNode;
  15346. if (parent.lastChild === br) {
  15347. br.parentNode.insertBefore(br.cloneNode(true), br);
  15348. range.setStartBefore(br);
  15349. } else {
  15350. range.setStartAfter(br);
  15351. }
  15352. range.setCursor();
  15353. }
  15354. }
  15355. }
  15356. });
  15357. };
  15358. // plugins/keystrokes.js
  15359. /* 处理特殊键的兼容性问题 */
  15360. UE.plugins['keystrokes'] = function () {
  15361. var me = this;
  15362. var collapsed = true;
  15363. me.addListener('keydown', function (type, evt) {
  15364. var keyCode = evt.keyCode || evt.which,
  15365. rng = me.selection.getRange();
  15366. //处理全选的情况
  15367. if (!rng.collapsed && !(evt.ctrlKey || evt.shiftKey || evt.altKey || evt.metaKey) && (keyCode >= 65 && keyCode <= 90
  15368. || keyCode >= 48 && keyCode <= 57 ||
  15369. keyCode >= 96 && keyCode <= 111 || {
  15370. 13: 1,
  15371. 8: 1,
  15372. 46: 1
  15373. }[keyCode])
  15374. ) {
  15375. var tmpNode = rng.startContainer;
  15376. if (domUtils.isFillChar(tmpNode)) {
  15377. rng.setStartBefore(tmpNode)
  15378. }
  15379. tmpNode = rng.endContainer;
  15380. if (domUtils.isFillChar(tmpNode)) {
  15381. rng.setEndAfter(tmpNode)
  15382. }
  15383. rng.txtToElmBoundary();
  15384. //结束边界可能放到了br的前边,要把br包含进来
  15385. // x[xxx]<br/>
  15386. if (rng.endContainer && rng.endContainer.nodeType == 1) {
  15387. tmpNode = rng.endContainer.childNodes[rng.endOffset];
  15388. if (tmpNode && domUtils.isBr(tmpNode)) {
  15389. rng.setEndAfter(tmpNode);
  15390. }
  15391. }
  15392. if (rng.startOffset == 0) {
  15393. tmpNode = rng.startContainer;
  15394. if (domUtils.isBoundaryNode(tmpNode, 'firstChild')) {
  15395. tmpNode = rng.endContainer;
  15396. if (rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode, 'lastChild')) {
  15397. me.fireEvent('saveScene');
  15398. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  15399. rng.setStart(me.body.firstChild, 0).setCursor(false, true);
  15400. me._selectionChange();
  15401. return;
  15402. }
  15403. }
  15404. }
  15405. }
  15406. //处理backspace
  15407. if (keyCode == keymap.Backspace) {
  15408. rng = me.selection.getRange();
  15409. collapsed = rng.collapsed;
  15410. if (me.fireEvent('delkeydown', evt)) {
  15411. return;
  15412. }
  15413. var start, end;
  15414. //避免按两次删除才能生效的问题
  15415. if (rng.collapsed && rng.inFillChar()) {
  15416. start = rng.startContainer;
  15417. if (domUtils.isFillChar(start)) {
  15418. rng.setStartBefore(start).shrinkBoundary(true).collapse(true);
  15419. domUtils.remove(start)
  15420. } else {
  15421. start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar), '');
  15422. rng.startOffset--;
  15423. rng.collapse(true).select(true)
  15424. }
  15425. }
  15426. //解决选中control元素不能删除的问题
  15427. if (start = rng.getClosedNode()) {
  15428. me.fireEvent('saveScene');
  15429. rng.setStartBefore(start);
  15430. domUtils.remove(start);
  15431. rng.setCursor();
  15432. me.fireEvent('saveScene');
  15433. domUtils.preventDefault(evt);
  15434. return;
  15435. }
  15436. //阻止在table上的删除
  15437. if (!browser.ie) {
  15438. start = domUtils.findParentByTagName(rng.startContainer, 'table', true);
  15439. end = domUtils.findParentByTagName(rng.endContainer, 'table', true);
  15440. if (start && !end || !start && end || start !== end) {
  15441. evt.preventDefault();
  15442. return;
  15443. }
  15444. }
  15445. }
  15446. //处理tab键的逻辑
  15447. if (keyCode == keymap.Tab) {
  15448. //不处理以下标签
  15449. var excludeTagNameForTabKey = {
  15450. 'ol': 1,
  15451. 'ul': 1,
  15452. 'table': 1
  15453. };
  15454. //处理组件里的tab按下事件
  15455. if (me.fireEvent('tabkeydown', evt)) {
  15456. domUtils.preventDefault(evt);
  15457. return;
  15458. }
  15459. var range = me.selection.getRange();
  15460. me.fireEvent('saveScene');
  15461. for (var i = 0, txt = '', tabSize = me.options.tabSize || 4, tabNode = me.options.tabNode || '&nbsp;'; i < tabSize; i++) {
  15462. txt += tabNode;
  15463. }
  15464. var span = me.document.createElement('span');
  15465. span.innerHTML = txt + domUtils.fillChar;
  15466. if (range.collapsed) {
  15467. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  15468. } else {
  15469. var filterFn = function (node) {
  15470. return domUtils.isBlockElm(node) && !excludeTagNameForTabKey[node.tagName.toLowerCase()]
  15471. };
  15472. //普通的情况
  15473. start = domUtils.findParent(range.startContainer, filterFn, true);
  15474. end = domUtils.findParent(range.endContainer, filterFn, true);
  15475. if (start && end && start === end) {
  15476. range.deleteContents();
  15477. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  15478. } else {
  15479. var bookmark = range.createBookmark();
  15480. range.enlarge(true);
  15481. var bookmark2 = range.createBookmark(),
  15482. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn);
  15483. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  15484. current.insertBefore(span.cloneNode(true).firstChild, current.firstChild);
  15485. current = domUtils.getNextDomNode(current, false, filterFn);
  15486. }
  15487. range.moveToBookmark(bookmark2).moveToBookmark(bookmark).select();
  15488. }
  15489. }
  15490. domUtils.preventDefault(evt)
  15491. }
  15492. //trace:1634
  15493. //ff的del键在容器空的时候,也会删除
  15494. if (browser.gecko && keyCode == 46) {
  15495. range = me.selection.getRange();
  15496. if (range.collapsed) {
  15497. start = range.startContainer;
  15498. if (domUtils.isEmptyBlock(start)) {
  15499. var parent = start.parentNode;
  15500. while (domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)) {
  15501. start = parent;
  15502. parent = parent.parentNode;
  15503. }
  15504. if (start === parent.lastChild)
  15505. evt.preventDefault();
  15506. return;
  15507. }
  15508. }
  15509. }
  15510. });
  15511. me.addListener('keyup', function (type, evt) {
  15512. var keyCode = evt.keyCode || evt.which,
  15513. rng, me = this;
  15514. if (keyCode == keymap.Backspace) {
  15515. if (me.fireEvent('delkeyup')) {
  15516. return;
  15517. }
  15518. rng = me.selection.getRange();
  15519. if (rng.collapsed) {
  15520. var tmpNode,
  15521. autoClearTagName = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  15522. if (tmpNode = domUtils.findParentByTagName(rng.startContainer, autoClearTagName, true)) {
  15523. if (domUtils.isEmptyBlock(tmpNode)) {
  15524. var pre = tmpNode.previousSibling;
  15525. if (pre && pre.nodeName != 'TABLE') {
  15526. domUtils.remove(tmpNode);
  15527. rng.setStartAtLast(pre).setCursor(false, true);
  15528. return;
  15529. } else {
  15530. var next = tmpNode.nextSibling;
  15531. if (next && next.nodeName != 'TABLE') {
  15532. domUtils.remove(tmpNode);
  15533. rng.setStartAtFirst(next).setCursor(false, true);
  15534. return;
  15535. }
  15536. }
  15537. }
  15538. }
  15539. //处理当删除到body时,要重新给p标签展位
  15540. if (domUtils.isBody(rng.startContainer)) {
  15541. var tmpNode = domUtils.createElement(me.document, 'p', {
  15542. 'innerHTML': browser.ie ? domUtils.fillChar : '<br/>'
  15543. });
  15544. rng.insertNode(tmpNode).setStart(tmpNode, 0).setCursor(false, true);
  15545. }
  15546. }
  15547. //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了
  15548. if (!collapsed && (rng.startContainer.nodeType == 3 || rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer))) {
  15549. if (browser.ie) {
  15550. var span = rng.document.createElement('span');
  15551. rng.insertNode(span).setStartBefore(span).collapse(true);
  15552. rng.select();
  15553. domUtils.remove(span)
  15554. } else {
  15555. rng.select()
  15556. }
  15557. }
  15558. }
  15559. })
  15560. };
  15561. // plugins/fiximgclick.js
  15562. ///import core
  15563. ///commands 修复chrome下图片不能点击的问题,出现八个角可改变大小
  15564. ///commandsName FixImgClick
  15565. ///commandsTitle 修复chrome下图片不能点击的问题,出现八个角可改变大小
  15566. //修复chrome下图片不能点击的问题,出现八个角可改变大小
  15567. UE.plugins['fiximgclick'] = (function () {
  15568. var elementUpdated = false;
  15569. function Scale() {
  15570. this.editor = null;
  15571. this.resizer = null;
  15572. this.cover = null;
  15573. this.doc = document;
  15574. this.prePos = { x: 0, y: 0 };
  15575. this.startPos = { x: 0, y: 0 };
  15576. }
  15577. (function () {
  15578. var rect = [
  15579. //[left, top, width, height]
  15580. [0, 0, -1, -1],
  15581. [0, 0, 0, -1],
  15582. [0, 0, 1, -1],
  15583. [0, 0, -1, 0],
  15584. [0, 0, 1, 0],
  15585. [0, 0, -1, 1],
  15586. [0, 0, 0, 1],
  15587. [0, 0, 1, 1]
  15588. ];
  15589. Scale.prototype = {
  15590. init: function (editor) {
  15591. var me = this;
  15592. me.editor = editor;
  15593. me.startPos = this.prePos = { x: 0, y: 0 };
  15594. me.dragId = -1;
  15595. var hands = [],
  15596. cover = me.cover = document.createElement('div'),
  15597. resizer = me.resizer = document.createElement('div');
  15598. cover.id = me.editor.ui.id + '_imagescale_cover';
  15599. cover.style.cssText = 'position:absolute;display:none;z-index:' + (me.editor.options.zIndex) + ';filter:alpha(opacity=0); opacity:0;background:#CCC;';
  15600. domUtils.on(cover, 'mousedown click', function () {
  15601. me.hide();
  15602. });
  15603. for (i = 0; i < 8; i++) {
  15604. hands.push('<span class="edui-editor-imagescale-hand' + i + '"></span>');
  15605. }
  15606. resizer.id = me.editor.ui.id + '_imagescale';
  15607. resizer.className = 'edui-editor-imagescale';
  15608. resizer.innerHTML = hands.join('');
  15609. resizer.style.cssText += ';display:none;border:1px solid #3b77ff;z-index:' + (me.editor.options.zIndex) + ';';
  15610. me.editor.ui.getDom().appendChild(cover);
  15611. me.editor.ui.getDom().appendChild(resizer);
  15612. me.initStyle();
  15613. me.initEvents();
  15614. },
  15615. initStyle: function () {
  15616. utils.cssRule('imagescale', '.edui-editor-imagescale{display:none;position:absolute;border:1px solid #38B2CE;cursor:hand;-webkit-box-sizing: content-box;-moz-box-sizing: content-box;box-sizing: content-box;}' +
  15617. '.edui-editor-imagescale span{position:absolute;width:6px;height:6px;overflow:hidden;font-size:0px;display:block;background-color:#3C9DD0;}'
  15618. + '.edui-editor-imagescale .edui-editor-imagescale-hand0{cursor:nw-resize;top:0;margin-top:-4px;left:0;margin-left:-4px;}'
  15619. + '.edui-editor-imagescale .edui-editor-imagescale-hand1{cursor:n-resize;top:0;margin-top:-4px;left:50%;margin-left:-4px;}'
  15620. + '.edui-editor-imagescale .edui-editor-imagescale-hand2{cursor:ne-resize;top:0;margin-top:-4px;left:100%;margin-left:-3px;}'
  15621. + '.edui-editor-imagescale .edui-editor-imagescale-hand3{cursor:w-resize;top:50%;margin-top:-4px;left:0;margin-left:-4px;}'
  15622. + '.edui-editor-imagescale .edui-editor-imagescale-hand4{cursor:e-resize;top:50%;margin-top:-4px;left:100%;margin-left:-3px;}'
  15623. + '.edui-editor-imagescale .edui-editor-imagescale-hand5{cursor:sw-resize;top:100%;margin-top:-3px;left:0;margin-left:-4px;}'
  15624. + '.edui-editor-imagescale .edui-editor-imagescale-hand6{cursor:s-resize;top:100%;margin-top:-3px;left:50%;margin-left:-4px;}'
  15625. + '.edui-editor-imagescale .edui-editor-imagescale-hand7{cursor:se-resize;top:100%;margin-top:-3px;left:100%;margin-left:-3px;}');
  15626. },
  15627. initEvents: function () {
  15628. var me = this;
  15629. me.startPos.x = me.startPos.y = 0;
  15630. me.isDraging = false;
  15631. },
  15632. _eventHandler: function (e) {
  15633. var me = this;
  15634. switch (e.type) {
  15635. case 'mousedown':
  15636. var hand = e.target || e.srcElement, hand;
  15637. if (hand.className.indexOf('edui-editor-imagescale-hand') != -1 && me.dragId == -1) {
  15638. me.dragId = hand.className.slice(-1);
  15639. me.startPos.x = me.prePos.x = e.clientX;
  15640. me.startPos.y = me.prePos.y = e.clientY;
  15641. domUtils.on(me.doc, 'mousemove', me.proxy(me._eventHandler, me));
  15642. }
  15643. break;
  15644. case 'mousemove':
  15645. if (me.dragId != -1) {
  15646. me.updateContainerStyle(me.dragId, { x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y });
  15647. me.prePos.x = e.clientX;
  15648. me.prePos.y = e.clientY;
  15649. elementUpdated = true;
  15650. me.updateTargetElement();
  15651. }
  15652. break;
  15653. case 'mouseup':
  15654. if (me.dragId != -1) {
  15655. me.updateContainerStyle(me.dragId, { x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y });
  15656. me.updateTargetElement();
  15657. if (me.target.parentNode) me.attachTo(me.target);
  15658. me.dragId = -1;
  15659. }
  15660. domUtils.un(me.doc, 'mousemove', me.proxy(me._eventHandler, me));
  15661. //修复只是点击挪动点,但没有改变大小,不应该触发contentchange
  15662. if (elementUpdated) {
  15663. elementUpdated = false;
  15664. me.editor.fireEvent('contentchange');
  15665. }
  15666. break;
  15667. default:
  15668. break;
  15669. }
  15670. },
  15671. updateTargetElement: function () {
  15672. var me = this;
  15673. domUtils.setStyles(me.target, {
  15674. 'width': me.resizer.style.width,
  15675. 'height': me.resizer.style.height
  15676. });
  15677. me.target.width = parseInt(me.resizer.style.width);
  15678. me.target.height = parseInt(me.resizer.style.height);
  15679. me.attachTo(me.target);
  15680. },
  15681. updateContainerStyle: function (dir, offset) {
  15682. var me = this,
  15683. dom = me.resizer, tmp;
  15684. if (rect[dir][0] != 0) {
  15685. tmp = parseInt(dom.style.left) + offset.x;
  15686. dom.style.left = me._validScaledProp('left', tmp) + 'px';
  15687. }
  15688. if (rect[dir][1] != 0) {
  15689. tmp = parseInt(dom.style.top) + offset.y;
  15690. dom.style.top = me._validScaledProp('top', tmp) + 'px';
  15691. }
  15692. if (rect[dir][2] != 0) {
  15693. tmp = dom.clientWidth + rect[dir][2] * offset.x;
  15694. dom.style.width = me._validScaledProp('width', tmp) + 'px';
  15695. }
  15696. if (rect[dir][3] != 0) {
  15697. tmp = dom.clientHeight + rect[dir][3] * offset.y;
  15698. dom.style.height = me._validScaledProp('height', tmp) + 'px';
  15699. }
  15700. },
  15701. _validScaledProp: function (prop, value) {
  15702. var ele = this.resizer,
  15703. wrap = document;
  15704. value = isNaN(value) ? 0 : value;
  15705. switch (prop) {
  15706. case 'left':
  15707. return value < 0 ? 0 : (value + ele.clientWidth) > wrap.clientWidth ? wrap.clientWidth - ele.clientWidth : value;
  15708. case 'top':
  15709. return value < 0 ? 0 : (value + ele.clientHeight) > wrap.clientHeight ? wrap.clientHeight - ele.clientHeight : value;
  15710. case 'width':
  15711. return value <= 0 ? 1 : (value + ele.offsetLeft) > wrap.clientWidth ? wrap.clientWidth - ele.offsetLeft : value;
  15712. case 'height':
  15713. return value <= 0 ? 1 : (value + ele.offsetTop) > wrap.clientHeight ? wrap.clientHeight - ele.offsetTop : value;
  15714. }
  15715. },
  15716. hideCover: function () {
  15717. this.cover.style.display = 'none';
  15718. },
  15719. showCover: function () {
  15720. var me = this,
  15721. editorPos = domUtils.getXY(me.editor.ui.getDom()),
  15722. iframePos = domUtils.getXY(me.editor.iframe);
  15723. domUtils.setStyles(me.cover, {
  15724. 'width': me.editor.iframe.offsetWidth + 'px',
  15725. 'height': me.editor.iframe.offsetHeight + 'px',
  15726. 'top': iframePos.y - editorPos.y + 'px',
  15727. 'left': iframePos.x - editorPos.x + 'px',
  15728. 'position': 'absolute',
  15729. 'display': ''
  15730. })
  15731. },
  15732. show: function (targetObj) {
  15733. var me = this;
  15734. me.resizer.style.display = 'block';
  15735. if (targetObj) me.attachTo(targetObj);
  15736. domUtils.on(this.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  15737. domUtils.on(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  15738. me.showCover();
  15739. me.editor.fireEvent('afterscaleshow', me);
  15740. me.editor.fireEvent('saveScene');
  15741. },
  15742. hide: function () {
  15743. var me = this;
  15744. me.hideCover();
  15745. me.resizer.style.display = 'none';
  15746. domUtils.un(me.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  15747. domUtils.un(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  15748. me.editor.fireEvent('afterscalehide', me);
  15749. },
  15750. proxy: function (fn, context) {
  15751. return function (e) {
  15752. return fn.apply(context || this, arguments);
  15753. };
  15754. },
  15755. attachTo: function (targetObj) {
  15756. var me = this,
  15757. target = me.target = targetObj,
  15758. resizer = this.resizer,
  15759. imgPos = domUtils.getXY(target),
  15760. iframePos = domUtils.getXY(me.editor.iframe),
  15761. editorPos = domUtils.getXY(resizer.parentNode);
  15762. domUtils.setStyles(resizer, {
  15763. 'width': target.width + 'px',
  15764. 'height': target.height + 'px',
  15765. 'left': iframePos.x + imgPos.x - me.editor.document.body.scrollLeft - editorPos.x - parseInt(resizer.style.borderLeftWidth) + 'px',
  15766. 'top': iframePos.y + imgPos.y - me.editor.document.body.scrollTop - editorPos.y - parseInt(resizer.style.borderTopWidth) + 'px'
  15767. });
  15768. }
  15769. }
  15770. })();
  15771. return function () {
  15772. var me = this,
  15773. imageScale;
  15774. me.setOpt('imageScaleEnabled', true);
  15775. if (!browser.ie && me.options.imageScaleEnabled) {
  15776. me.addListener('click', function (type, e) {
  15777. var range = me.selection.getRange(),
  15778. img = range.getClosedNode();
  15779. if (img && img.tagName == 'IMG' && me.body.contentEditable != "false") {
  15780. if (img.className.indexOf("edui-faked-music") != -1 ||
  15781. img.getAttribute("anchorname") ||
  15782. domUtils.hasClass(img, 'loadingclass') ||
  15783. domUtils.hasClass(img, 'loaderrorclass')) { return }
  15784. if (!imageScale) {
  15785. imageScale = new Scale();
  15786. imageScale.init(me);
  15787. me.ui.getDom().appendChild(imageScale.resizer);
  15788. var _keyDownHandler = function (e) {
  15789. imageScale.hide();
  15790. if (imageScale.target) me.selection.getRange().selectNode(imageScale.target).select();
  15791. }, _mouseDownHandler = function (e) {
  15792. var ele = e.target || e.srcElement;
  15793. if (ele && (ele.className === undefined || ele.className.indexOf('edui-editor-imagescale') == -1)) {
  15794. _keyDownHandler(e);
  15795. }
  15796. }, timer;
  15797. me.addListener('afterscaleshow', function (e) {
  15798. me.addListener('beforekeydown', _keyDownHandler);
  15799. me.addListener('beforemousedown', _mouseDownHandler);
  15800. domUtils.on(document, 'keydown', _keyDownHandler);
  15801. domUtils.on(document, 'mousedown', _mouseDownHandler);
  15802. me.selection.getNative().removeAllRanges();
  15803. });
  15804. me.addListener('afterscalehide', function (e) {
  15805. me.removeListener('beforekeydown', _keyDownHandler);
  15806. me.removeListener('beforemousedown', _mouseDownHandler);
  15807. domUtils.un(document, 'keydown', _keyDownHandler);
  15808. domUtils.un(document, 'mousedown', _mouseDownHandler);
  15809. var target = imageScale.target;
  15810. if (target.parentNode) {
  15811. me.selection.getRange().selectNode(target).select();
  15812. }
  15813. });
  15814. //TODO 有iframe的情况,mousedown不能往下传。。
  15815. domUtils.on(imageScale.resizer, 'mousedown', function (e) {
  15816. me.selection.getNative().removeAllRanges();
  15817. var ele = e.target || e.srcElement;
  15818. if (ele && ele.className.indexOf('edui-editor-imagescale-hand') == -1) {
  15819. timer = setTimeout(function () {
  15820. imageScale.hide();
  15821. if (imageScale.target) me.selection.getRange().selectNode(ele).select();
  15822. }, 200);
  15823. }
  15824. });
  15825. domUtils.on(imageScale.resizer, 'mouseup', function (e) {
  15826. var ele = e.target || e.srcElement;
  15827. if (ele && ele.className.indexOf('edui-editor-imagescale-hand') == -1) {
  15828. clearTimeout(timer);
  15829. }
  15830. });
  15831. }
  15832. imageScale.show(img);
  15833. } else {
  15834. if (imageScale && imageScale.resizer.style.display != 'none') imageScale.hide();
  15835. }
  15836. });
  15837. }
  15838. if (browser.webkit) {
  15839. me.addListener('click', function (type, e) {
  15840. if (e.target.tagName == 'IMG' && me.body.contentEditable != "false") {
  15841. var range = new dom.Range(me.document);
  15842. range.selectNode(e.target).select();
  15843. }
  15844. });
  15845. }
  15846. }
  15847. })();
  15848. // plugins/autolink.js
  15849. ///import core
  15850. ///commands 为非ie浏览器自动添加a标签
  15851. ///commandsName AutoLink
  15852. ///commandsTitle 自动增加链接
  15853. /**
  15854. * @description 为非ie浏览器自动添加a标签
  15855. * @author zhanyi
  15856. */
  15857. UE.plugin.register('autolink', function () {
  15858. var cont = 0;
  15859. return !browser.ie ? {
  15860. bindEvents: {
  15861. 'reset': function () {
  15862. cont = 0;
  15863. },
  15864. 'keydown': function (type, evt) {
  15865. var me = this;
  15866. var keyCode = evt.keyCode || evt.which;
  15867. if (keyCode == 32 || keyCode == 13) {
  15868. var sel = me.selection.getNative(),
  15869. range = sel.getRangeAt(0).cloneRange(),
  15870. offset,
  15871. charCode;
  15872. var start = range.startContainer;
  15873. while (start.nodeType == 1 && range.startOffset > 0) {
  15874. start = range.startContainer.childNodes[range.startOffset - 1];
  15875. if (!start) {
  15876. break;
  15877. }
  15878. range.setStart(start, start.nodeType == 1 ? start.childNodes.length : start.nodeValue.length);
  15879. range.collapse(true);
  15880. start = range.startContainer;
  15881. }
  15882. do {
  15883. if (range.startOffset == 0) {
  15884. start = range.startContainer.previousSibling;
  15885. while (start && start.nodeType == 1) {
  15886. start = start.lastChild;
  15887. }
  15888. if (!start || domUtils.isFillChar(start)) {
  15889. break;
  15890. }
  15891. offset = start.nodeValue.length;
  15892. } else {
  15893. start = range.startContainer;
  15894. offset = range.startOffset;
  15895. }
  15896. range.setStart(start, offset - 1);
  15897. charCode = range.toString().charCodeAt(0);
  15898. } while (charCode != 160 && charCode != 32);
  15899. if (range.toString().replace(new RegExp(domUtils.fillChar, 'g'), '').match(/(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i)) {
  15900. while (range.toString().length) {
  15901. if (/^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i.test(range.toString())) {
  15902. break;
  15903. }
  15904. try {
  15905. range.setStart(range.startContainer, range.startOffset + 1);
  15906. } catch (e) {
  15907. //trace:2121
  15908. var start = range.startContainer;
  15909. while (!(next = start.nextSibling)) {
  15910. if (domUtils.isBody(start)) {
  15911. return;
  15912. }
  15913. start = start.parentNode;
  15914. }
  15915. range.setStart(next, 0);
  15916. }
  15917. }
  15918. //range的开始边界已经在a标签里的不再处理
  15919. if (domUtils.findParentByTagName(range.startContainer, 'a', true)) {
  15920. return;
  15921. }
  15922. var a = me.document.createElement('a'), text = me.document.createTextNode(' '), href;
  15923. me.undoManger && me.undoManger.save();
  15924. a.appendChild(range.extractContents());
  15925. a.href = a.innerHTML = a.innerHTML.replace(/<[^>]+>/g, '');
  15926. href = a.getAttribute("href").replace(new RegExp(domUtils.fillChar, 'g'), '');
  15927. href = /^(?:https?:\/\/)/ig.test(href) ? href : "http://" + href;
  15928. a.setAttribute('_src', utils.html(href));
  15929. a.href = utils.html(href);
  15930. range.insertNode(a);
  15931. a.parentNode.insertBefore(text, a.nextSibling);
  15932. range.setStart(text, 0);
  15933. range.collapse(true);
  15934. sel.removeAllRanges();
  15935. sel.addRange(range);
  15936. me.undoManger && me.undoManger.save();
  15937. }
  15938. }
  15939. }
  15940. }
  15941. } : {}
  15942. }, function () {
  15943. var keyCodes = {
  15944. 37: 1, 38: 1, 39: 1, 40: 1,
  15945. 13: 1, 32: 1
  15946. };
  15947. function checkIsCludeLink(node) {
  15948. if (node.nodeType == 3) {
  15949. return null
  15950. }
  15951. if (node.nodeName == 'A') {
  15952. return node;
  15953. }
  15954. var lastChild = node.lastChild;
  15955. while (lastChild) {
  15956. if (lastChild.nodeName == 'A') {
  15957. return lastChild;
  15958. }
  15959. if (lastChild.nodeType == 3) {
  15960. if (domUtils.isWhitespace(lastChild)) {
  15961. lastChild = lastChild.previousSibling;
  15962. continue;
  15963. }
  15964. return null
  15965. }
  15966. lastChild = lastChild.lastChild;
  15967. }
  15968. }
  15969. browser.ie && this.addListener('keyup', function (cmd, evt) {
  15970. var me = this, keyCode = evt.keyCode;
  15971. if (keyCodes[keyCode]) {
  15972. var rng = me.selection.getRange();
  15973. var start = rng.startContainer;
  15974. if (keyCode == 13) {
  15975. while (start && !domUtils.isBody(start) && !domUtils.isBlockElm(start)) {
  15976. start = start.parentNode;
  15977. }
  15978. if (start && !domUtils.isBody(start) && start.nodeName == 'P') {
  15979. var pre = start.previousSibling;
  15980. if (pre && pre.nodeType == 1) {
  15981. var pre = checkIsCludeLink(pre);
  15982. if (pre && !pre.getAttribute('_href')) {
  15983. domUtils.remove(pre, true);
  15984. }
  15985. }
  15986. }
  15987. } else if (keyCode == 32) {
  15988. if (start.nodeType == 3 && /^\s$/.test(start.nodeValue)) {
  15989. start = start.previousSibling;
  15990. if (start && start.nodeName == 'A' && !start.getAttribute('_href')) {
  15991. domUtils.remove(start, true);
  15992. }
  15993. }
  15994. } else {
  15995. start = domUtils.findParentByTagName(start, 'a', true);
  15996. if (start && !start.getAttribute('_href')) {
  15997. var bk = rng.createBookmark();
  15998. domUtils.remove(start, true);
  15999. rng.moveToBookmark(bk).select(true)
  16000. }
  16001. }
  16002. }
  16003. });
  16004. }
  16005. );
  16006. // plugins/autoheight.js
  16007. ///import core
  16008. ///commands 当输入内容超过编辑器高度时,编辑器自动增高
  16009. ///commandsName AutoHeight,autoHeightEnabled
  16010. ///commandsTitle 自动增高
  16011. /**
  16012. * @description 自动伸展
  16013. * @author zhanyi
  16014. */
  16015. UE.plugins['autoheight'] = function () {
  16016. var me = this;
  16017. //提供开关,就算加载也可以关闭
  16018. me.autoHeightEnabled = me.options.autoHeightEnabled !== false;
  16019. if (!me.autoHeightEnabled) {
  16020. return;
  16021. }
  16022. var bakOverflow,
  16023. lastHeight = 0,
  16024. options = me.options,
  16025. currentHeight,
  16026. timer;
  16027. function adjustHeight() {
  16028. var me = this;
  16029. clearTimeout(timer);
  16030. if (isFullscreen) return;
  16031. if (!me.queryCommandState || me.queryCommandState && me.queryCommandState('source') != 1) {
  16032. timer = setTimeout(function () {
  16033. var node = me.body.lastChild;
  16034. while (node && node.nodeType != 1) {
  16035. node = node.previousSibling;
  16036. }
  16037. if (node && node.nodeType == 1) {
  16038. node.style.clear = 'both';
  16039. currentHeight = Math.max(domUtils.getXY(node).y + node.offsetHeight + 25, Math.max(options.minFrameHeight, options.initialFrameHeight));
  16040. if (currentHeight != lastHeight) {
  16041. if (currentHeight !== parseInt(me.iframe.parentNode.style.height)) {
  16042. me.iframe.parentNode.style.height = currentHeight + 'px';
  16043. }
  16044. me.body.style.height = currentHeight + 'px';
  16045. lastHeight = currentHeight;
  16046. }
  16047. domUtils.removeStyle(node, 'clear');
  16048. }
  16049. }, 50)
  16050. }
  16051. }
  16052. var isFullscreen;
  16053. me.addListener('fullscreenchanged', function (cmd, f) {
  16054. isFullscreen = f
  16055. });
  16056. me.addListener('destroy', function () {
  16057. me.removeListener('contentchange afterinserthtml keyup mouseup', adjustHeight)
  16058. });
  16059. me.enableAutoHeight = function () {
  16060. var me = this;
  16061. if (!me.autoHeightEnabled) {
  16062. return;
  16063. }
  16064. var doc = me.document;
  16065. me.autoHeightEnabled = true;
  16066. bakOverflow = doc.body.style.overflowY;
  16067. doc.body.style.overflowY = 'hidden';
  16068. me.addListener('contentchange afterinserthtml keyup mouseup', adjustHeight);
  16069. //ff不给事件算得不对
  16070. setTimeout(function () {
  16071. adjustHeight.call(me);
  16072. }, browser.gecko ? 100 : 0);
  16073. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  16074. };
  16075. me.disableAutoHeight = function () {
  16076. me.body.style.overflowY = bakOverflow || '';
  16077. me.removeListener('contentchange', adjustHeight);
  16078. me.removeListener('keyup', adjustHeight);
  16079. me.removeListener('mouseup', adjustHeight);
  16080. me.autoHeightEnabled = false;
  16081. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  16082. };
  16083. me.on('setHeight', function () {
  16084. me.disableAutoHeight()
  16085. });
  16086. me.addListener('ready', function () {
  16087. me.enableAutoHeight();
  16088. //trace:1764
  16089. var timer;
  16090. domUtils.on(browser.ie ? me.body : me.document, browser.webkit ? 'dragover' : 'drop', function () {
  16091. clearTimeout(timer);
  16092. timer = setTimeout(function () {
  16093. //trace:3681
  16094. adjustHeight.call(me);
  16095. }, 100);
  16096. });
  16097. //修复内容过多时,回到顶部,顶部内容被工具栏遮挡问题
  16098. var lastScrollY;
  16099. window.onscroll = function () {
  16100. if (lastScrollY === null) {
  16101. lastScrollY = this.scrollY
  16102. } else if (this.scrollY == 0 && lastScrollY != 0) {
  16103. me.window.scrollTo(0, 0);
  16104. lastScrollY = null;
  16105. }
  16106. }
  16107. });
  16108. };
  16109. // plugins/autofloat.js
  16110. ///import core
  16111. ///commands 悬浮工具栏
  16112. ///commandsName AutoFloat,autoFloatEnabled
  16113. ///commandsTitle 悬浮工具栏
  16114. /**
  16115. * modified by chengchao01
  16116. * 注意: 引入此功能后,在IE6下会将body的背景图片覆盖掉!
  16117. */
  16118. UE.plugins['autofloat'] = function () {
  16119. var me = this,
  16120. lang = me.getLang();
  16121. me.setOpt({
  16122. topOffset: 0
  16123. });
  16124. var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false,
  16125. topOffset = me.options.topOffset;
  16126. //如果不固定toolbar的位置,则直接退出
  16127. if (!optsAutoFloatEnabled) {
  16128. return;
  16129. }
  16130. var uiUtils = UE.ui.uiUtils,
  16131. LteIE6 = browser.ie && browser.version <= 6,
  16132. quirks = browser.quirks;
  16133. function checkHasUI() {
  16134. if (!UE.ui) {
  16135. alert(lang.autofloatMsg);
  16136. return 0;
  16137. }
  16138. return 1;
  16139. }
  16140. function fixIE6FixedPos() {
  16141. var docStyle = document.body.style;
  16142. docStyle.backgroundImage = 'url("about:blank")';
  16143. docStyle.backgroundAttachment = 'fixed';
  16144. }
  16145. var bakCssText,
  16146. placeHolder = document.createElement('div'),
  16147. toolbarBox, orgTop,
  16148. getPosition,
  16149. flag = true; //ie7模式下需要偏移
  16150. function setFloating() {
  16151. var toobarBoxPos = domUtils.getXY(toolbarBox),
  16152. origalFloat = domUtils.getComputedStyle(toolbarBox, 'position'),
  16153. origalLeft = domUtils.getComputedStyle(toolbarBox, 'left');
  16154. toolbarBox.style.width = toolbarBox.offsetWidth + 'px';
  16155. toolbarBox.style.zIndex = me.options.zIndex * 1 + 1;
  16156. toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox);
  16157. if (LteIE6 || (quirks && browser.ie)) {
  16158. if (toolbarBox.style.position != 'absolute') {
  16159. toolbarBox.style.position = 'absolute';
  16160. }
  16161. toolbarBox.style.top = (document.body.scrollTop || document.documentElement.scrollTop) - orgTop + topOffset + 'px';
  16162. } else {
  16163. if (browser.ie7Compat && flag) {
  16164. flag = false;
  16165. toolbarBox.style.left = domUtils.getXY(toolbarBox).x - document.documentElement.getBoundingClientRect().left + 2 + 'px';
  16166. }
  16167. // if(toolbarBox.style.position != 'fixed'){
  16168. // toolbarBox.style.position = 'fixed';
  16169. // toolbarBox.style.top = topOffset +"px";
  16170. // ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px');
  16171. // }
  16172. }
  16173. }
  16174. function unsetFloating() {
  16175. flag = true;
  16176. if (placeHolder.parentNode) {
  16177. placeHolder.parentNode.removeChild(placeHolder);
  16178. }
  16179. toolbarBox.style.cssText = bakCssText;
  16180. }
  16181. function updateFloating() {
  16182. var rect3 = getPosition(me.container);
  16183. var offset = me.options.toolbarTopOffset || 0;
  16184. if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > offset) {
  16185. setFloating();
  16186. } else {
  16187. unsetFloating();
  16188. }
  16189. }
  16190. var defer_updateFloating = utils.defer(function () {
  16191. updateFloating();
  16192. }, browser.ie ? 200 : 100, true);
  16193. me.addListener('destroy', function () {
  16194. domUtils.un(window, ['scroll', 'resize'], updateFloating);
  16195. me.removeListener('keydown', defer_updateFloating);
  16196. });
  16197. me.addListener('ready', function () {
  16198. if (checkHasUI(me)) {
  16199. //加载了ui组件,但在new时,没有加载ui,导致编辑器实例上没有ui类,所以这里做判断
  16200. if (!me.ui) {
  16201. return;
  16202. }
  16203. getPosition = uiUtils.getClientRect;
  16204. toolbarBox = me.ui.getDom('toolbarbox');
  16205. orgTop = getPosition(toolbarBox).top;
  16206. bakCssText = toolbarBox.style.cssText;
  16207. // placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  16208. if (LteIE6) {
  16209. fixIE6FixedPos();
  16210. }
  16211. domUtils.on(window, ['scroll', 'resize'], updateFloating);
  16212. me.addListener('keydown', defer_updateFloating);
  16213. me.addListener('beforefullscreenchange', function (t, enabled) {
  16214. if (enabled) {
  16215. unsetFloating();
  16216. }
  16217. });
  16218. me.addListener('fullscreenchanged', function (t, enabled) {
  16219. if (!enabled) {
  16220. updateFloating();
  16221. }
  16222. });
  16223. me.addListener('sourcemodechanged', function (t, enabled) {
  16224. setTimeout(function () {
  16225. updateFloating();
  16226. }, 0);
  16227. });
  16228. me.addListener("clearDoc", function () {
  16229. setTimeout(function () {
  16230. updateFloating();
  16231. }, 0);
  16232. })
  16233. }
  16234. });
  16235. };
  16236. // plugins/video.js
  16237. /**
  16238. * video插件, 为UEditor提供视频插入支持
  16239. * @file
  16240. * @since 1.2.6.1
  16241. */
  16242. UE.plugins['video'] = function () {
  16243. var me = this;
  16244. /**
  16245. * 创建插入视频字符窜
  16246. * @param url 视频地址
  16247. * @param width 视频宽度
  16248. * @param height 视频高度
  16249. * @param align 视频对齐
  16250. * @param toEmbed 是否以flash代替显示
  16251. * @param addParagraph 是否需要添加P 标签
  16252. */
  16253. function creatInsertStr(url, width, height, id, align, classname, type) {
  16254. url = utils.unhtmlForUrl(url);
  16255. align = utils.unhtml(align);
  16256. classname = utils.unhtml(classname);
  16257. width = parseInt(width, 10) || 0;
  16258. height = parseInt(height, 10) || 0;
  16259. var str;
  16260. switch (type) {
  16261. case 'image':
  16262. str = '<img ' + (id ? 'id="' + id + '"' : '') + ' width="' + width + '" height="' + height + '" _url="' + url + '" class="' + classname.replace(/\bvideo-js\b/, '') + '"' +
  16263. ' src="' + me.options.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif" style="background:url(' + me.options.UEDITOR_HOME_URL + 'themes/default/images/videologo.gif) no-repeat center center; border:1px solid gray;' + (align ? 'float:' + align + ';' : '') + '" />'
  16264. break;
  16265. case 'embed':
  16266. str = '<embed type="application/x-shockwave-flash" class="' + classname + '" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  16267. ' src="' + utils.html(url) + '" width="' + width + '" height="' + height + '"' + (align ? ' style="float:' + align + '"' : '') +
  16268. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  16269. break;
  16270. case 'video':
  16271. var ext = url.substr(url.lastIndexOf('.') + 1);
  16272. if (ext == 'ogv') ext = 'ogg';
  16273. str = '<video' + (id ? ' id="' + id + '"' : '') + ' class="' + classname + ' video-js" ' + (align ? ' style="float:' + align + '"' : '') +
  16274. ' controls preload="none" width="' + width + '" height="' + height + '" src="' + url + '" data-setup="{}">' +
  16275. '<source src="' + url + '" type="video/' + ext + '" /></video>';
  16276. break;
  16277. }
  16278. return str;
  16279. }
  16280. function switchImgAndVideo(root, img2video) {
  16281. utils.each(root.getNodesByTagName(img2video ? 'img' : 'embed video'), function (node) {
  16282. var className = node.getAttr('class');
  16283. if (className && className.indexOf('edui-faked-video') != -1) {
  16284. var html = creatInsertStr(img2video ? node.getAttr('_url') : node.getAttr('src'), node.getAttr('width'), node.getAttr('height'), null, node.getStyle('float') || '', className, img2video ? 'embed' : 'image');
  16285. node.parentNode.replaceChild(UE.uNode.createElement(html), node);
  16286. }
  16287. if (className && className.indexOf('edui-upload-video') != -1) {
  16288. var html = creatInsertStr(img2video ? node.getAttr('_url') : node.getAttr('src'), node.getAttr('width'), node.getAttr('height'), null, node.getStyle('float') || '', className, img2video ? 'video' : 'image');
  16289. node.parentNode.replaceChild(UE.uNode.createElement(html), node);
  16290. }
  16291. })
  16292. }
  16293. me.addOutputRule(function (root) {
  16294. switchImgAndVideo(root, true)
  16295. });
  16296. me.addInputRule(function (root) {
  16297. switchImgAndVideo(root)
  16298. });
  16299. /**
  16300. * 插入视频
  16301. * @command insertvideo
  16302. * @method execCommand
  16303. * @param { String } cmd 命令字符串
  16304. * @param { Object } videoAttr 键值对对象, 描述一个视频的所有属性
  16305. * @example
  16306. * ```javascript
  16307. *
  16308. * var videoAttr = {
  16309. * //视频地址
  16310. * url: 'http://www.youku.com/xxx',
  16311. * //视频宽高值, 单位px
  16312. * width: 200,
  16313. * height: 100
  16314. * };
  16315. *
  16316. * //editor 是编辑器实例
  16317. * //向编辑器插入单个视频
  16318. * editor.execCommand( 'insertvideo', videoAttr );
  16319. * ```
  16320. */
  16321. /**
  16322. * 插入视频
  16323. * @command insertvideo
  16324. * @method execCommand
  16325. * @param { String } cmd 命令字符串
  16326. * @param { Array } videoArr 需要插入的视频的数组, 其中的每一个元素都是一个键值对对象, 描述了一个视频的所有属性
  16327. * @example
  16328. * ```javascript
  16329. *
  16330. * var videoAttr1 = {
  16331. * //视频地址
  16332. * url: 'http://www.youku.com/xxx',
  16333. * //视频宽高值, 单位px
  16334. * width: 200,
  16335. * height: 100
  16336. * },
  16337. * videoAttr2 = {
  16338. * //视频地址
  16339. * url: 'http://www.youku.com/xxx',
  16340. * //视频宽高值, 单位px
  16341. * width: 200,
  16342. * height: 100
  16343. * }
  16344. *
  16345. * //editor 是编辑器实例
  16346. * //该方法将会向编辑器内插入两个视频
  16347. * editor.execCommand( 'insertvideo', [ videoAttr1, videoAttr2 ] );
  16348. * ```
  16349. */
  16350. /**
  16351. * 查询当前光标所在处是否是一个视频
  16352. * @command insertvideo
  16353. * @method queryCommandState
  16354. * @param { String } cmd 需要查询的命令字符串
  16355. * @return { int } 如果当前光标所在处的元素是一个视频对象, 则返回1,否则返回0
  16356. * @example
  16357. * ```javascript
  16358. *
  16359. * //editor 是编辑器实例
  16360. * editor.queryCommandState( 'insertvideo' );
  16361. * ```
  16362. */
  16363. me.commands["insertvideo"] = {
  16364. execCommand: function (cmd, videoObjs, type) {
  16365. videoObjs = utils.isArray(videoObjs) ? videoObjs : [videoObjs];
  16366. var html = [], id = 'tmpVedio', cl;
  16367. for (var i = 0, vi, len = videoObjs.length; i < len; i++) {
  16368. vi = videoObjs[i];
  16369. cl = (type == 'upload' ? 'edui-upload-video video-js vjs-default-skin' : 'edui-faked-video');
  16370. html.push(creatInsertStr(vi.url, vi.width || 420, vi.height || 280, id + i, null, cl, 'image'));
  16371. }
  16372. me.execCommand("inserthtml", html.join(""), true);
  16373. var rng = this.selection.getRange();
  16374. for (var i = 0, len = videoObjs.length; i < len; i++) {
  16375. var img = this.document.getElementById('tmpVedio' + i);
  16376. domUtils.removeAttributes(img, 'id');
  16377. rng.selectNode(img).select();
  16378. me.execCommand('imagefloat', videoObjs[i].align)
  16379. }
  16380. },
  16381. queryCommandState: function () {
  16382. var img = me.selection.getRange().getClosedNode(),
  16383. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video") != -1);
  16384. return flag ? 1 : 0;
  16385. }
  16386. };
  16387. };
  16388. // plugins/table.core.js
  16389. /**
  16390. * Created with JetBrains WebStorm.
  16391. * User: taoqili
  16392. * Date: 13-1-18
  16393. * Time: 上午11:09
  16394. * To change this template use File | Settings | File Templates.
  16395. */
  16396. /**
  16397. * UE表格操作类
  16398. * @param table
  16399. * @constructor
  16400. */
  16401. (function () {
  16402. var UETable = UE.UETable = function (table) {
  16403. this.table = table;
  16404. this.indexTable = [];
  16405. this.selectedTds = [];
  16406. this.cellsRange = {};
  16407. this.update(table);
  16408. };
  16409. //===以下为静态工具方法===
  16410. UETable.removeSelectedClass = function (cells) {
  16411. utils.each(cells, function (cell) {
  16412. domUtils.removeClasses(cell, "selectTdClass");
  16413. })
  16414. };
  16415. UETable.addSelectedClass = function (cells) {
  16416. utils.each(cells, function (cell) {
  16417. domUtils.addClass(cell, "selectTdClass");
  16418. })
  16419. };
  16420. UETable.isEmptyBlock = function (node) {
  16421. var reg = new RegExp(domUtils.fillChar, 'g');
  16422. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  16423. return 0;
  16424. }
  16425. for (var i in dtd.$isNotEmpty) if (dtd.$isNotEmpty.hasOwnProperty(i)) {
  16426. if (node.getElementsByTagName(i).length) {
  16427. return 0;
  16428. }
  16429. }
  16430. return 1;
  16431. };
  16432. UETable.getWidth = function (cell) {
  16433. if (!cell) return 0;
  16434. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  16435. };
  16436. /**
  16437. * 获取单元格或者单元格组的“对齐”状态。 如果当前的检测对象是一个单元格组, 只有在满足所有单元格的 水平和竖直 对齐属性都相同的
  16438. * 条件时才会返回其状态值,否则将返回null; 如果当前只检测了一个单元格, 则直接返回当前单元格的对齐状态;
  16439. * @param table cell or table cells , 支持单个单元格dom对象 或者 单元格dom对象数组
  16440. * @return { align: 'left' || 'right' || 'center', valign: 'top' || 'middle' || 'bottom' } 或者 null
  16441. */
  16442. UETable.getTableCellAlignState = function (cells) {
  16443. !utils.isArray(cells) && (cells = [cells]);
  16444. var result = {},
  16445. status = ['align', 'valign'],
  16446. tempStatus = null,
  16447. isSame = true;//状态是否相同
  16448. utils.each(cells, function (cellNode) {
  16449. utils.each(status, function (currentState) {
  16450. tempStatus = cellNode.getAttribute(currentState);
  16451. if (!result[currentState] && tempStatus) {
  16452. result[currentState] = tempStatus;
  16453. } else if (!result[currentState] || (tempStatus !== result[currentState])) {
  16454. isSame = false;
  16455. return false;
  16456. }
  16457. });
  16458. return isSame;
  16459. });
  16460. return isSame ? result : null;
  16461. };
  16462. /**
  16463. * 根据当前选区获取相关的table信息
  16464. * @return {Object}
  16465. */
  16466. UETable.getTableItemsByRange = function (editor) {
  16467. var start = editor.selection.getStart();
  16468. //ff下会选中bookmark
  16469. if (start && start.id && start.id.indexOf('_baidu_bookmark_start_') === 0 && start.nextSibling) {
  16470. start = start.nextSibling;
  16471. }
  16472. //在table或者td边缘有可能存在选中tr的情况
  16473. var cell = start && domUtils.findParentByTagName(start, ["td", "th"], true),
  16474. tr = cell && cell.parentNode,
  16475. caption = start && domUtils.findParentByTagName(start, 'caption', true),
  16476. table = caption ? caption.parentNode : tr && tr.parentNode.parentNode;
  16477. return {
  16478. cell: cell,
  16479. tr: tr,
  16480. table: table,
  16481. caption: caption
  16482. }
  16483. };
  16484. UETable.getUETableBySelected = function (editor) {
  16485. var table = UETable.getTableItemsByRange(editor).table;
  16486. if (table && table.ueTable && table.ueTable.selectedTds.length) {
  16487. return table.ueTable;
  16488. }
  16489. return null;
  16490. };
  16491. UETable.getDefaultValue = function (editor, table) {
  16492. var borderMap = {
  16493. thin: '0px',
  16494. medium: '1px',
  16495. thick: '2px'
  16496. },
  16497. tableBorder, tdPadding, tdBorder, tmpValue;
  16498. if (!table) {
  16499. table = editor.document.createElement('table');
  16500. table.insertRow(0).insertCell(0).innerHTML = 'xxx';
  16501. editor.body.appendChild(table);
  16502. var td = table.getElementsByTagName('td')[0];
  16503. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  16504. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16505. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  16506. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16507. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  16508. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16509. domUtils.remove(table);
  16510. return {
  16511. tableBorder: tableBorder,
  16512. tdPadding: tdPadding,
  16513. tdBorder: tdBorder
  16514. };
  16515. } else {
  16516. td = table.getElementsByTagName('td')[0];
  16517. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  16518. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16519. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  16520. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16521. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  16522. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16523. return {
  16524. tableBorder: tableBorder,
  16525. tdPadding: tdPadding,
  16526. tdBorder: tdBorder
  16527. };
  16528. }
  16529. };
  16530. /**
  16531. * 根据当前点击的td或者table获取索引对象
  16532. * @param tdOrTable
  16533. */
  16534. UETable.getUETable = function (tdOrTable) {
  16535. var tag = tdOrTable.tagName.toLowerCase();
  16536. tdOrTable = (tag == "td" || tag == "th" || tag == 'caption') ? domUtils.findParentByTagName(tdOrTable, "table", true) : tdOrTable;
  16537. if (!tdOrTable.ueTable) {
  16538. tdOrTable.ueTable = new UETable(tdOrTable);
  16539. }
  16540. return tdOrTable.ueTable;
  16541. };
  16542. UETable.cloneCell = function (cell, ignoreMerge, keepPro) {
  16543. if (!cell || utils.isString(cell)) {
  16544. return this.table.ownerDocument.createElement(cell || 'td');
  16545. }
  16546. var flag = domUtils.hasClass(cell, "selectTdClass");
  16547. flag && domUtils.removeClasses(cell, "selectTdClass");
  16548. var tmpCell = cell.cloneNode(true);
  16549. if (ignoreMerge) {
  16550. tmpCell.rowSpan = tmpCell.colSpan = 1;
  16551. }
  16552. //去掉宽高
  16553. !keepPro && domUtils.removeAttributes(tmpCell, 'width height');
  16554. !keepPro && domUtils.removeAttributes(tmpCell, 'style');
  16555. tmpCell.style.borderLeftStyle = "";
  16556. tmpCell.style.borderTopStyle = "";
  16557. tmpCell.style.borderLeftColor = cell.style.borderRightColor;
  16558. tmpCell.style.borderLeftWidth = cell.style.borderRightWidth;
  16559. tmpCell.style.borderTopColor = cell.style.borderBottomColor;
  16560. tmpCell.style.borderTopWidth = cell.style.borderBottomWidth;
  16561. flag && domUtils.addClass(cell, "selectTdClass");
  16562. return tmpCell;
  16563. }
  16564. UETable.prototype = {
  16565. getMaxRows: function () {
  16566. var rows = this.table.rows, maxLen = 1;
  16567. for (var i = 0, row; row = rows[i]; i++) {
  16568. var currentMax = 1;
  16569. for (var j = 0, cj; cj = row.cells[j++];) {
  16570. currentMax = Math.max(cj.rowSpan || 1, currentMax);
  16571. }
  16572. maxLen = Math.max(currentMax + i, maxLen);
  16573. }
  16574. return maxLen;
  16575. },
  16576. /**
  16577. * 获取当前表格的最大列数
  16578. */
  16579. getMaxCols: function () {
  16580. var rows = this.table.rows, maxLen = 0, cellRows = {};
  16581. for (var i = 0, row; row = rows[i]; i++) {
  16582. var cellsNum = 0;
  16583. for (var j = 0, cj; cj = row.cells[j++];) {
  16584. cellsNum += (cj.colSpan || 1);
  16585. if (cj.rowSpan && cj.rowSpan > 1) {
  16586. for (var k = 1; k < cj.rowSpan; k++) {
  16587. if (!cellRows['row_' + (i + k)]) {
  16588. cellRows['row_' + (i + k)] = (cj.colSpan || 1);
  16589. } else {
  16590. cellRows['row_' + (i + k)]++
  16591. }
  16592. }
  16593. }
  16594. }
  16595. cellsNum += cellRows['row_' + i] || 0;
  16596. maxLen = Math.max(cellsNum, maxLen);
  16597. }
  16598. return maxLen;
  16599. },
  16600. getCellColIndex: function (cell) {
  16601. },
  16602. /**
  16603. * 获取当前cell旁边的单元格,
  16604. * @param cell
  16605. * @param right
  16606. */
  16607. getHSideCell: function (cell, right) {
  16608. try {
  16609. var cellInfo = this.getCellInfo(cell),
  16610. previewRowIndex, previewColIndex;
  16611. var len = this.selectedTds.length,
  16612. range = this.cellsRange;
  16613. //首行或者首列没有前置单元格
  16614. if ((!right && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (right && (!len ? (cellInfo.colIndex == (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  16615. previewRowIndex = !len ? cellInfo.rowIndex : range.beginRowIndex;
  16616. previewColIndex = !right ? (!len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  16617. : (!len ? cellInfo.colIndex + 1 : range.endColIndex + 1);
  16618. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  16619. } catch (e) {
  16620. showError(e);
  16621. }
  16622. },
  16623. getTabNextCell: function (cell, preRowIndex) {
  16624. var cellInfo = this.getCellInfo(cell),
  16625. rowIndex = preRowIndex || cellInfo.rowIndex,
  16626. colIndex = cellInfo.colIndex + 1 + (cellInfo.colSpan - 1),
  16627. nextCell;
  16628. try {
  16629. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  16630. } catch (e) {
  16631. try {
  16632. rowIndex = rowIndex * 1 + 1;
  16633. colIndex = 0;
  16634. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  16635. } catch (e) {
  16636. }
  16637. }
  16638. return nextCell;
  16639. },
  16640. /**
  16641. * 获取视觉上的后置单元格
  16642. * @param cell
  16643. * @param bottom
  16644. */
  16645. getVSideCell: function (cell, bottom, ignoreRange) {
  16646. try {
  16647. var cellInfo = this.getCellInfo(cell),
  16648. nextRowIndex, nextColIndex;
  16649. var len = this.selectedTds.length && !ignoreRange,
  16650. range = this.cellsRange;
  16651. //末行或者末列没有后置单元格
  16652. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  16653. nextRowIndex = !bottom ? (!len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  16654. : (!len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  16655. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  16656. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  16657. } catch (e) {
  16658. showError(e);
  16659. }
  16660. },
  16661. /**
  16662. * 获取相同结束位置的单元格,xOrY指代了是获取x轴相同还是y轴相同
  16663. */
  16664. getSameEndPosCells: function (cell, xOrY) {
  16665. try {
  16666. var flag = (xOrY.toLowerCase() === "x"),
  16667. end = domUtils.getXY(cell)[flag ? 'x' : 'y'] + cell["offset" + (flag ? 'Width' : 'Height')],
  16668. rows = this.table.rows,
  16669. cells = null, returns = [];
  16670. for (var i = 0; i < this.rowsNum; i++) {
  16671. cells = rows[i].cells;
  16672. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  16673. var tmpEnd = domUtils.getXY(tmpCell)[flag ? 'x' : 'y'] + tmpCell["offset" + (flag ? 'Width' : 'Height')];
  16674. //对应行的td已经被上面行rowSpan了
  16675. if (tmpEnd > end && flag) break;
  16676. if (cell == tmpCell || end == tmpEnd) {
  16677. //只获取单一的单元格
  16678. //todo 仅获取单一单元格在特定情况下会造成returns为空,从而影响后续的拖拽实现,修正这个。需考虑性能
  16679. if (tmpCell[flag ? "colSpan" : "rowSpan"] == 1) {
  16680. returns.push(tmpCell);
  16681. }
  16682. if (flag) break;
  16683. }
  16684. }
  16685. }
  16686. return returns;
  16687. } catch (e) {
  16688. showError(e);
  16689. }
  16690. },
  16691. setCellContent: function (cell, content) {
  16692. cell.innerHTML = content || (browser.ie ? domUtils.fillChar : "<br />");
  16693. },
  16694. cloneCell: UETable.cloneCell,
  16695. /**
  16696. * 获取跟当前单元格的右边竖线为左边的所有未合并单元格
  16697. */
  16698. getSameStartPosXCells: function (cell) {
  16699. try {
  16700. var start = domUtils.getXY(cell).x + cell.offsetWidth,
  16701. rows = this.table.rows, cells, returns = [];
  16702. for (var i = 0; i < this.rowsNum; i++) {
  16703. cells = rows[i].cells;
  16704. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  16705. var tmpStart = domUtils.getXY(tmpCell).x;
  16706. if (tmpStart > start) break;
  16707. if (tmpStart == start && tmpCell.colSpan == 1) {
  16708. returns.push(tmpCell);
  16709. break;
  16710. }
  16711. }
  16712. }
  16713. return returns;
  16714. } catch (e) {
  16715. showError(e);
  16716. }
  16717. },
  16718. /**
  16719. * 更新table对应的索引表
  16720. */
  16721. update: function (table) {
  16722. this.table = table || this.table;
  16723. this.selectedTds = [];
  16724. this.cellsRange = {};
  16725. this.indexTable = [];
  16726. var rows = this.table.rows,
  16727. rowsNum = this.getMaxRows(),
  16728. dNum = rowsNum - rows.length,
  16729. colsNum = this.getMaxCols();
  16730. while (dNum--) {
  16731. this.table.insertRow(rows.length);
  16732. }
  16733. this.rowsNum = rowsNum;
  16734. this.colsNum = colsNum;
  16735. for (var i = 0, len = rows.length; i < len; i++) {
  16736. this.indexTable[i] = new Array(colsNum);
  16737. }
  16738. //填充索引表
  16739. for (var rowIndex = 0, row; row = rows[rowIndex]; rowIndex++) {
  16740. for (var cellIndex = 0, cell, cells = row.cells; cell = cells[cellIndex]; cellIndex++) {
  16741. //修正整行被rowSpan时导致的行数计算错误
  16742. if (cell.rowSpan > rowsNum) {
  16743. cell.rowSpan = rowsNum;
  16744. }
  16745. var colIndex = cellIndex,
  16746. rowSpan = cell.rowSpan || 1,
  16747. colSpan = cell.colSpan || 1;
  16748. //当已经被上一行rowSpan或者被前一列colSpan了,则跳到下一个单元格进行
  16749. while (this.indexTable[rowIndex][colIndex]) colIndex++;
  16750. for (var j = 0; j < rowSpan; j++) {
  16751. for (var k = 0; k < colSpan; k++) {
  16752. this.indexTable[rowIndex + j][colIndex + k] = {
  16753. rowIndex: rowIndex,
  16754. cellIndex: cellIndex,
  16755. colIndex: colIndex,
  16756. rowSpan: rowSpan,
  16757. colSpan: colSpan
  16758. }
  16759. }
  16760. }
  16761. }
  16762. }
  16763. //修复残缺td
  16764. for (j = 0; j < rowsNum; j++) {
  16765. for (k = 0; k < colsNum; k++) {
  16766. if (this.indexTable[j][k] === undefined) {
  16767. row = rows[j];
  16768. cell = row.cells[row.cells.length - 1];
  16769. cell = cell ? cell.cloneNode(true) : this.table.ownerDocument.createElement("td");
  16770. this.setCellContent(cell);
  16771. if (cell.colSpan !== 1) cell.colSpan = 1;
  16772. if (cell.rowSpan !== 1) cell.rowSpan = 1;
  16773. row.appendChild(cell);
  16774. this.indexTable[j][k] = {
  16775. rowIndex: j,
  16776. cellIndex: cell.cellIndex,
  16777. colIndex: k,
  16778. rowSpan: 1,
  16779. colSpan: 1
  16780. }
  16781. }
  16782. }
  16783. }
  16784. //当框选后删除行或者列后撤销,需要重建选区。
  16785. var tds = domUtils.getElementsByTagName(this.table, "td"),
  16786. selectTds = [];
  16787. utils.each(tds, function (td) {
  16788. if (domUtils.hasClass(td, "selectTdClass")) {
  16789. selectTds.push(td);
  16790. }
  16791. });
  16792. if (selectTds.length) {
  16793. var start = selectTds[0],
  16794. end = selectTds[selectTds.length - 1],
  16795. startInfo = this.getCellInfo(start),
  16796. endInfo = this.getCellInfo(end);
  16797. this.selectedTds = selectTds;
  16798. this.cellsRange = {
  16799. beginRowIndex: startInfo.rowIndex,
  16800. beginColIndex: startInfo.colIndex,
  16801. endRowIndex: endInfo.rowIndex + endInfo.rowSpan - 1,
  16802. endColIndex: endInfo.colIndex + endInfo.colSpan - 1
  16803. };
  16804. }
  16805. //给第一行设置firstRow的样式名称,在排序图标的样式上使用到
  16806. if (!domUtils.hasClass(this.table.rows[0], "firstRow")) {
  16807. domUtils.addClass(this.table.rows[0], "firstRow");
  16808. for (var i = 1; i < this.table.rows.length; i++) {
  16809. domUtils.removeClasses(this.table.rows[i], "firstRow");
  16810. }
  16811. }
  16812. },
  16813. /**
  16814. * 获取单元格的索引信息
  16815. */
  16816. getCellInfo: function (cell) {
  16817. if (!cell) return;
  16818. var cellIndex = cell.cellIndex,
  16819. rowIndex = cell.parentNode.rowIndex,
  16820. rowInfo = this.indexTable[rowIndex],
  16821. numCols = this.colsNum;
  16822. for (var colIndex = cellIndex; colIndex < numCols; colIndex++) {
  16823. var cellInfo = rowInfo[colIndex];
  16824. if (cellInfo.rowIndex === rowIndex && cellInfo.cellIndex === cellIndex) {
  16825. return cellInfo;
  16826. }
  16827. }
  16828. },
  16829. /**
  16830. * 根据行列号获取单元格
  16831. */
  16832. getCell: function (rowIndex, cellIndex) {
  16833. return rowIndex < this.rowsNum && this.table.rows[rowIndex].cells[cellIndex] || null;
  16834. },
  16835. /**
  16836. * 删除单元格
  16837. */
  16838. deleteCell: function (cell, rowIndex) {
  16839. rowIndex = typeof rowIndex == 'number' ? rowIndex : cell.parentNode.rowIndex;
  16840. var row = this.table.rows[rowIndex];
  16841. row.deleteCell(cell.cellIndex);
  16842. },
  16843. /**
  16844. * 根据始末两个单元格获取被框选的所有单元格范围
  16845. */
  16846. getCellsRange: function (cellA, cellB) {
  16847. function checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex) {
  16848. var tmpBeginRowIndex = beginRowIndex,
  16849. tmpBeginColIndex = beginColIndex,
  16850. tmpEndRowIndex = endRowIndex,
  16851. tmpEndColIndex = endColIndex,
  16852. cellInfo, colIndex, rowIndex;
  16853. // 通过indexTable检查是否存在超出TableRange上边界的情况
  16854. if (beginRowIndex > 0) {
  16855. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  16856. cellInfo = me.indexTable[beginRowIndex][colIndex];
  16857. rowIndex = cellInfo.rowIndex;
  16858. if (rowIndex < beginRowIndex) {
  16859. tmpBeginRowIndex = Math.min(rowIndex, tmpBeginRowIndex);
  16860. }
  16861. }
  16862. }
  16863. // 通过indexTable检查是否存在超出TableRange右边界的情况
  16864. if (endColIndex < me.colsNum) {
  16865. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  16866. cellInfo = me.indexTable[rowIndex][endColIndex];
  16867. colIndex = cellInfo.colIndex + cellInfo.colSpan - 1;
  16868. if (colIndex > endColIndex) {
  16869. tmpEndColIndex = Math.max(colIndex, tmpEndColIndex);
  16870. }
  16871. }
  16872. }
  16873. // 检查是否有超出TableRange下边界的情况
  16874. if (endRowIndex < me.rowsNum) {
  16875. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  16876. cellInfo = me.indexTable[endRowIndex][colIndex];
  16877. rowIndex = cellInfo.rowIndex + cellInfo.rowSpan - 1;
  16878. if (rowIndex > endRowIndex) {
  16879. tmpEndRowIndex = Math.max(rowIndex, tmpEndRowIndex);
  16880. }
  16881. }
  16882. }
  16883. // 检查是否有超出TableRange左边界的情况
  16884. if (beginColIndex > 0) {
  16885. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  16886. cellInfo = me.indexTable[rowIndex][beginColIndex];
  16887. colIndex = cellInfo.colIndex;
  16888. if (colIndex < beginColIndex) {
  16889. tmpBeginColIndex = Math.min(cellInfo.colIndex, tmpBeginColIndex);
  16890. }
  16891. }
  16892. }
  16893. //递归调用直至所有完成所有框选单元格的扩展
  16894. if (tmpBeginRowIndex != beginRowIndex || tmpBeginColIndex != beginColIndex || tmpEndRowIndex != endRowIndex || tmpEndColIndex != endColIndex) {
  16895. return checkRange(tmpBeginRowIndex, tmpBeginColIndex, tmpEndRowIndex, tmpEndColIndex);
  16896. } else {
  16897. // 不需要扩展TableRange的情况
  16898. return {
  16899. beginRowIndex: beginRowIndex,
  16900. beginColIndex: beginColIndex,
  16901. endRowIndex: endRowIndex,
  16902. endColIndex: endColIndex
  16903. };
  16904. }
  16905. }
  16906. try {
  16907. var me = this,
  16908. cellAInfo = me.getCellInfo(cellA);
  16909. if (cellA === cellB) {
  16910. return {
  16911. beginRowIndex: cellAInfo.rowIndex,
  16912. beginColIndex: cellAInfo.colIndex,
  16913. endRowIndex: cellAInfo.rowIndex + cellAInfo.rowSpan - 1,
  16914. endColIndex: cellAInfo.colIndex + cellAInfo.colSpan - 1
  16915. };
  16916. }
  16917. var cellBInfo = me.getCellInfo(cellB);
  16918. // 计算TableRange的四个边
  16919. var beginRowIndex = Math.min(cellAInfo.rowIndex, cellBInfo.rowIndex),
  16920. beginColIndex = Math.min(cellAInfo.colIndex, cellBInfo.colIndex),
  16921. endRowIndex = Math.max(cellAInfo.rowIndex + cellAInfo.rowSpan - 1, cellBInfo.rowIndex + cellBInfo.rowSpan - 1),
  16922. endColIndex = Math.max(cellAInfo.colIndex + cellAInfo.colSpan - 1, cellBInfo.colIndex + cellBInfo.colSpan - 1);
  16923. return checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex);
  16924. } catch (e) {
  16925. //throw e;
  16926. }
  16927. },
  16928. /**
  16929. * 依据cellsRange获取对应的单元格集合
  16930. */
  16931. getCells: function (range) {
  16932. //每次获取cells之前必须先清除上次的选择,否则会对后续获取操作造成影响
  16933. this.clearSelected();
  16934. var beginRowIndex = range.beginRowIndex,
  16935. beginColIndex = range.beginColIndex,
  16936. endRowIndex = range.endRowIndex,
  16937. endColIndex = range.endColIndex,
  16938. cellInfo, rowIndex, colIndex, tdHash = {}, returnTds = [];
  16939. for (var i = beginRowIndex; i <= endRowIndex; i++) {
  16940. for (var j = beginColIndex; j <= endColIndex; j++) {
  16941. cellInfo = this.indexTable[i][j];
  16942. rowIndex = cellInfo.rowIndex;
  16943. colIndex = cellInfo.colIndex;
  16944. // 如果Cells里已经包含了此Cell则跳过
  16945. var key = rowIndex + '|' + colIndex;
  16946. if (tdHash[key]) continue;
  16947. tdHash[key] = 1;
  16948. if (rowIndex < i || colIndex < j || rowIndex + cellInfo.rowSpan - 1 > endRowIndex || colIndex + cellInfo.colSpan - 1 > endColIndex) {
  16949. return null;
  16950. }
  16951. returnTds.push(this.getCell(rowIndex, cellInfo.cellIndex));
  16952. }
  16953. }
  16954. return returnTds;
  16955. },
  16956. /**
  16957. * 清理已经选中的单元格
  16958. */
  16959. clearSelected: function () {
  16960. UETable.removeSelectedClass(this.selectedTds);
  16961. this.selectedTds = [];
  16962. this.cellsRange = {};
  16963. },
  16964. /**
  16965. * 根据range设置已经选中的单元格
  16966. */
  16967. setSelected: function (range) {
  16968. var cells = this.getCells(range);
  16969. UETable.addSelectedClass(cells);
  16970. this.selectedTds = cells;
  16971. this.cellsRange = range;
  16972. },
  16973. isFullRow: function () {
  16974. var range = this.cellsRange;
  16975. return (range.endColIndex - range.beginColIndex + 1) == this.colsNum;
  16976. },
  16977. isFullCol: function () {
  16978. var range = this.cellsRange,
  16979. table = this.table,
  16980. ths = table.getElementsByTagName("th"),
  16981. rows = range.endRowIndex - range.beginRowIndex + 1;
  16982. return !ths.length ? rows == this.rowsNum : rows == this.rowsNum || (rows == this.rowsNum - 1);
  16983. },
  16984. /**
  16985. * 获取视觉上的前置单元格,默认是左边,top传入时
  16986. * @param cell
  16987. * @param top
  16988. */
  16989. getNextCell: function (cell, bottom, ignoreRange) {
  16990. try {
  16991. var cellInfo = this.getCellInfo(cell),
  16992. nextRowIndex, nextColIndex;
  16993. var len = this.selectedTds.length && !ignoreRange,
  16994. range = this.cellsRange;
  16995. //末行或者末列没有后置单元格
  16996. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  16997. nextRowIndex = !bottom ? (!len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  16998. : (!len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  16999. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  17000. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  17001. } catch (e) {
  17002. showError(e);
  17003. }
  17004. },
  17005. getPreviewCell: function (cell, top) {
  17006. try {
  17007. var cellInfo = this.getCellInfo(cell),
  17008. previewRowIndex, previewColIndex;
  17009. var len = this.selectedTds.length,
  17010. range = this.cellsRange;
  17011. //首行或者首列没有前置单元格
  17012. if ((!top && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (top && (!len ? (cellInfo.rowIndex > (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  17013. previewRowIndex = !top ? (!len ? cellInfo.rowIndex : range.beginRowIndex)
  17014. : (!len ? (cellInfo.rowIndex < 1 ? 0 : (cellInfo.rowIndex - 1)) : range.beginRowIndex);
  17015. previewColIndex = !top ? (!len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  17016. : (!len ? cellInfo.colIndex : range.endColIndex + 1);
  17017. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  17018. } catch (e) {
  17019. showError(e);
  17020. }
  17021. },
  17022. /**
  17023. * 移动单元格中的内容
  17024. */
  17025. moveContent: function (cellTo, cellFrom) {
  17026. if (UETable.isEmptyBlock(cellFrom)) return;
  17027. if (UETable.isEmptyBlock(cellTo)) {
  17028. cellTo.innerHTML = cellFrom.innerHTML;
  17029. return;
  17030. }
  17031. var child = cellTo.lastChild;
  17032. if (child.nodeType == 3 || !dtd.$block[child.tagName]) {
  17033. cellTo.appendChild(cellTo.ownerDocument.createElement('br'))
  17034. }
  17035. while (child = cellFrom.firstChild) {
  17036. cellTo.appendChild(child);
  17037. }
  17038. },
  17039. /**
  17040. * 向右合并单元格
  17041. */
  17042. mergeRight: function (cell) {
  17043. var cellInfo = this.getCellInfo(cell),
  17044. rightColIndex = cellInfo.colIndex + cellInfo.colSpan,
  17045. rightCellInfo = this.indexTable[cellInfo.rowIndex][rightColIndex],
  17046. rightCell = this.getCell(rightCellInfo.rowIndex, rightCellInfo.cellIndex);
  17047. //合并
  17048. cell.colSpan = cellInfo.colSpan + rightCellInfo.colSpan;
  17049. //被合并的单元格不应存在宽度属性
  17050. cell.removeAttribute("width");
  17051. //移动内容
  17052. this.moveContent(cell, rightCell);
  17053. //删掉被合并的Cell
  17054. this.deleteCell(rightCell, rightCellInfo.rowIndex);
  17055. this.update();
  17056. },
  17057. /**
  17058. * 向下合并单元格
  17059. */
  17060. mergeDown: function (cell) {
  17061. var cellInfo = this.getCellInfo(cell),
  17062. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan,
  17063. downCellInfo = this.indexTable[downRowIndex][cellInfo.colIndex],
  17064. downCell = this.getCell(downCellInfo.rowIndex, downCellInfo.cellIndex);
  17065. cell.rowSpan = cellInfo.rowSpan + downCellInfo.rowSpan;
  17066. cell.removeAttribute("height");
  17067. this.moveContent(cell, downCell);
  17068. this.deleteCell(downCell, downCellInfo.rowIndex);
  17069. this.update();
  17070. },
  17071. /**
  17072. * 合并整个range中的内容
  17073. */
  17074. mergeRange: function () {
  17075. //由于合并操作可以在任意时刻进行,所以无法通过鼠标位置等信息实时生成range,只能通过缓存实例中的cellsRange对象来访问
  17076. var range = this.cellsRange,
  17077. leftTopCell = this.getCell(range.beginRowIndex, this.indexTable[range.beginRowIndex][range.beginColIndex].cellIndex);
  17078. if (leftTopCell.tagName == "TH" && range.endRowIndex !== range.beginRowIndex) {
  17079. var index = this.indexTable,
  17080. info = this.getCellInfo(leftTopCell);
  17081. leftTopCell = this.getCell(1, index[1][info.colIndex].cellIndex);
  17082. range = this.getCellsRange(leftTopCell, this.getCell(index[this.rowsNum - 1][info.colIndex].rowIndex, index[this.rowsNum - 1][info.colIndex].cellIndex));
  17083. }
  17084. // 删除剩余的Cells
  17085. var cells = this.getCells(range);
  17086. for (var i = 0, ci; ci = cells[i++];) {
  17087. if (ci !== leftTopCell) {
  17088. this.moveContent(leftTopCell, ci);
  17089. this.deleteCell(ci);
  17090. }
  17091. }
  17092. // 修改左上角Cell的rowSpan和colSpan,并调整宽度属性设置
  17093. leftTopCell.rowSpan = range.endRowIndex - range.beginRowIndex + 1;
  17094. leftTopCell.rowSpan > 1 && leftTopCell.removeAttribute("height");
  17095. leftTopCell.colSpan = range.endColIndex - range.beginColIndex + 1;
  17096. leftTopCell.colSpan > 1 && leftTopCell.removeAttribute("width");
  17097. if (leftTopCell.rowSpan == this.rowsNum && leftTopCell.colSpan != 1) {
  17098. leftTopCell.colSpan = 1;
  17099. }
  17100. if (leftTopCell.colSpan == this.colsNum && leftTopCell.rowSpan != 1) {
  17101. var rowIndex = leftTopCell.parentNode.rowIndex;
  17102. //解决IE下的表格操作问题
  17103. if (this.table.deleteRow) {
  17104. for (var i = rowIndex + 1, curIndex = rowIndex + 1, len = leftTopCell.rowSpan; i < len; i++) {
  17105. this.table.deleteRow(curIndex);
  17106. }
  17107. } else {
  17108. for (var i = 0, len = leftTopCell.rowSpan - 1; i < len; i++) {
  17109. var row = this.table.rows[rowIndex + 1];
  17110. row.parentNode.removeChild(row);
  17111. }
  17112. }
  17113. leftTopCell.rowSpan = 1;
  17114. }
  17115. this.update();
  17116. },
  17117. /**
  17118. * 插入一行单元格
  17119. */
  17120. insertRow: function (rowIndex, sourceCell) {
  17121. var numCols = this.colsNum,
  17122. table = this.table,
  17123. row = table.insertRow(rowIndex), cell,
  17124. isInsertTitle = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  17125. function replaceTdToTh(colIndex, cell, tableRow) {
  17126. if (colIndex == 0) {
  17127. var tr = tableRow.nextSibling || tableRow.previousSibling,
  17128. th = tr.cells[colIndex];
  17129. if (th.tagName == 'TH') {
  17130. th = cell.ownerDocument.createElement("th");
  17131. th.appendChild(cell.firstChild);
  17132. tableRow.insertBefore(th, cell);
  17133. domUtils.remove(cell)
  17134. }
  17135. } else {
  17136. if (cell.tagName == 'TH') {
  17137. var td = cell.ownerDocument.createElement("td");
  17138. td.appendChild(cell.firstChild);
  17139. tableRow.insertBefore(td, cell);
  17140. domUtils.remove(cell)
  17141. }
  17142. }
  17143. }
  17144. //首行直接插入,无需考虑部分单元格被rowspan的情况
  17145. if (rowIndex == 0 || rowIndex == this.rowsNum) {
  17146. for (var colIndex = 0; colIndex < numCols; colIndex++) {
  17147. cell = this.cloneCell(sourceCell, true);
  17148. this.setCellContent(cell);
  17149. cell.getAttribute('vAlign') && cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17150. row.appendChild(cell);
  17151. if (!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  17152. }
  17153. } else {
  17154. var infoRow = this.indexTable[rowIndex],
  17155. cellIndex = 0;
  17156. for (colIndex = 0; colIndex < numCols; colIndex++) {
  17157. var cellInfo = infoRow[colIndex];
  17158. //如果存在某个单元格的rowspan穿过待插入行的位置,则修改该单元格的rowspan即可,无需插入单元格
  17159. if (cellInfo.rowIndex < rowIndex) {
  17160. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17161. cell.rowSpan = cellInfo.rowSpan + 1;
  17162. } else {
  17163. cell = this.cloneCell(sourceCell, true);
  17164. this.setCellContent(cell);
  17165. row.appendChild(cell);
  17166. }
  17167. if (!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  17168. }
  17169. }
  17170. //框选时插入不触发contentchange,需要手动更新索引。
  17171. this.update();
  17172. return row;
  17173. },
  17174. /**
  17175. * 删除一行单元格
  17176. * @param rowIndex
  17177. */
  17178. deleteRow: function (rowIndex) {
  17179. var row = this.table.rows[rowIndex],
  17180. infoRow = this.indexTable[rowIndex],
  17181. colsNum = this.colsNum,
  17182. count = 0; //处理计数
  17183. for (var colIndex = 0; colIndex < colsNum;) {
  17184. var cellInfo = infoRow[colIndex],
  17185. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17186. if (cell.rowSpan > 1) {
  17187. if (cellInfo.rowIndex == rowIndex) {
  17188. var clone = cell.cloneNode(true);
  17189. clone.rowSpan = cell.rowSpan - 1;
  17190. clone.innerHTML = "";
  17191. cell.rowSpan = 1;
  17192. var nextRowIndex = rowIndex + 1,
  17193. nextRow = this.table.rows[nextRowIndex],
  17194. insertCellIndex,
  17195. preMerged = this.getPreviewMergedCellsNum(nextRowIndex, colIndex) - count;
  17196. if (preMerged < colIndex) {
  17197. insertCellIndex = colIndex - preMerged - 1;
  17198. //nextRow.insertCell(insertCellIndex);
  17199. domUtils.insertAfter(nextRow.cells[insertCellIndex], clone);
  17200. } else {
  17201. if (nextRow.cells.length) nextRow.insertBefore(clone, nextRow.cells[0])
  17202. }
  17203. count += 1;
  17204. //cell.parentNode.removeChild(cell);
  17205. }
  17206. }
  17207. colIndex += cell.colSpan || 1;
  17208. }
  17209. var deleteTds = [], cacheMap = {};
  17210. for (colIndex = 0; colIndex < colsNum; colIndex++) {
  17211. var tmpRowIndex = infoRow[colIndex].rowIndex,
  17212. tmpCellIndex = infoRow[colIndex].cellIndex,
  17213. key = tmpRowIndex + "_" + tmpCellIndex;
  17214. if (cacheMap[key]) continue;
  17215. cacheMap[key] = 1;
  17216. cell = this.getCell(tmpRowIndex, tmpCellIndex);
  17217. deleteTds.push(cell);
  17218. }
  17219. var mergeTds = [];
  17220. utils.each(deleteTds, function (td) {
  17221. if (td.rowSpan == 1) {
  17222. td.parentNode.removeChild(td);
  17223. } else {
  17224. mergeTds.push(td);
  17225. }
  17226. });
  17227. utils.each(mergeTds, function (td) {
  17228. td.rowSpan--;
  17229. });
  17230. row.parentNode.removeChild(row);
  17231. //浏览器方法本身存在bug,采用自定义方法删除
  17232. //this.table.deleteRow(rowIndex);
  17233. this.update();
  17234. },
  17235. insertCol: function (colIndex, sourceCell, defaultValue) {
  17236. var rowsNum = this.rowsNum,
  17237. rowIndex = 0,
  17238. tableRow, cell,
  17239. backWidth = parseInt((this.table.offsetWidth - (this.colsNum + 1) * 20 - (this.colsNum + 1)) / (this.colsNum + 1), 10),
  17240. isInsertTitleCol = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  17241. function replaceTdToTh(rowIndex, cell, tableRow) {
  17242. if (rowIndex == 0) {
  17243. var th = cell.nextSibling || cell.previousSibling;
  17244. if (th.tagName == 'TH') {
  17245. th = cell.ownerDocument.createElement("th");
  17246. th.appendChild(cell.firstChild);
  17247. tableRow.insertBefore(th, cell);
  17248. domUtils.remove(cell)
  17249. }
  17250. } else {
  17251. if (cell.tagName == 'TH') {
  17252. var td = cell.ownerDocument.createElement("td");
  17253. td.appendChild(cell.firstChild);
  17254. tableRow.insertBefore(td, cell);
  17255. domUtils.remove(cell)
  17256. }
  17257. }
  17258. }
  17259. var preCell;
  17260. if (colIndex == 0 || colIndex == this.colsNum) {
  17261. for (; rowIndex < rowsNum; rowIndex++) {
  17262. tableRow = this.table.rows[rowIndex];
  17263. preCell = tableRow.cells[colIndex == 0 ? colIndex : tableRow.cells.length];
  17264. cell = this.cloneCell(sourceCell, true); //tableRow.insertCell(colIndex == 0 ? colIndex : tableRow.cells.length);
  17265. this.setCellContent(cell);
  17266. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17267. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  17268. if (!colIndex) {
  17269. tableRow.insertBefore(cell, tableRow.cells[0]);
  17270. } else {
  17271. domUtils.insertAfter(tableRow.cells[tableRow.cells.length - 1], cell);
  17272. }
  17273. if (!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow)
  17274. }
  17275. } else {
  17276. for (; rowIndex < rowsNum; rowIndex++) {
  17277. var cellInfo = this.indexTable[rowIndex][colIndex];
  17278. if (cellInfo.colIndex < colIndex) {
  17279. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17280. cell.colSpan = cellInfo.colSpan + 1;
  17281. } else {
  17282. tableRow = this.table.rows[rowIndex];
  17283. preCell = tableRow.cells[cellInfo.cellIndex];
  17284. cell = this.cloneCell(sourceCell, true);//tableRow.insertCell(cellInfo.cellIndex);
  17285. this.setCellContent(cell);
  17286. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17287. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  17288. //防止IE下报错
  17289. preCell ? tableRow.insertBefore(cell, preCell) : tableRow.appendChild(cell);
  17290. }
  17291. if (!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow);
  17292. }
  17293. }
  17294. //框选时插入不触发contentchange,需要手动更新索引
  17295. this.update();
  17296. this.updateWidth(backWidth, defaultValue || { tdPadding: 10, tdBorder: 1 });
  17297. },
  17298. updateWidth: function (width, defaultValue) {
  17299. var table = this.table,
  17300. tmpWidth = UETable.getWidth(table) - defaultValue.tdPadding * 2 - defaultValue.tdBorder + width;
  17301. if (tmpWidth < table.ownerDocument.body.offsetWidth) {
  17302. table.setAttribute("width", tmpWidth);
  17303. return;
  17304. }
  17305. var tds = domUtils.getElementsByTagName(this.table, "td th");
  17306. utils.each(tds, function (td) {
  17307. td.setAttribute("width", width);
  17308. })
  17309. },
  17310. deleteCol: function (colIndex) {
  17311. var indexTable = this.indexTable,
  17312. tableRows = this.table.rows,
  17313. backTableWidth = this.table.getAttribute("width"),
  17314. backTdWidth = 0,
  17315. rowsNum = this.rowsNum,
  17316. cacheMap = {};
  17317. for (var rowIndex = 0; rowIndex < rowsNum;) {
  17318. var infoRow = indexTable[rowIndex],
  17319. cellInfo = infoRow[colIndex],
  17320. key = cellInfo.rowIndex + '_' + cellInfo.colIndex;
  17321. // 跳过已经处理过的Cell
  17322. if (cacheMap[key]) continue;
  17323. cacheMap[key] = 1;
  17324. var cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17325. if (!backTdWidth) backTdWidth = cell && parseInt(cell.offsetWidth / cell.colSpan, 10).toFixed(0);
  17326. // 如果Cell的colSpan大于1, 就修改colSpan, 否则就删掉这个Cell
  17327. if (cell.colSpan > 1) {
  17328. cell.colSpan--;
  17329. } else {
  17330. tableRows[rowIndex].deleteCell(cellInfo.cellIndex);
  17331. }
  17332. rowIndex += cellInfo.rowSpan || 1;
  17333. }
  17334. this.table.setAttribute("width", backTableWidth - backTdWidth);
  17335. this.update();
  17336. },
  17337. splitToCells: function (cell) {
  17338. var me = this,
  17339. cells = this.splitToRows(cell);
  17340. utils.each(cells, function (cell) {
  17341. me.splitToCols(cell);
  17342. })
  17343. },
  17344. splitToRows: function (cell) {
  17345. var cellInfo = this.getCellInfo(cell),
  17346. rowIndex = cellInfo.rowIndex,
  17347. colIndex = cellInfo.colIndex,
  17348. results = [];
  17349. // 修改Cell的rowSpan
  17350. cell.rowSpan = 1;
  17351. results.push(cell);
  17352. // 补齐单元格
  17353. for (var i = rowIndex, endRow = rowIndex + cellInfo.rowSpan; i < endRow; i++) {
  17354. if (i == rowIndex) continue;
  17355. var tableRow = this.table.rows[i],
  17356. tmpCell = tableRow.insertCell(colIndex - this.getPreviewMergedCellsNum(i, colIndex));
  17357. tmpCell.colSpan = cellInfo.colSpan;
  17358. this.setCellContent(tmpCell);
  17359. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17360. tmpCell.setAttribute('align', cell.getAttribute('align'));
  17361. if (cell.style.cssText) {
  17362. tmpCell.style.cssText = cell.style.cssText;
  17363. }
  17364. results.push(tmpCell);
  17365. }
  17366. this.update();
  17367. return results;
  17368. },
  17369. getPreviewMergedCellsNum: function (rowIndex, colIndex) {
  17370. var indexRow = this.indexTable[rowIndex],
  17371. num = 0;
  17372. for (var i = 0; i < colIndex;) {
  17373. var colSpan = indexRow[i].colSpan,
  17374. tmpRowIndex = indexRow[i].rowIndex;
  17375. num += (colSpan - (tmpRowIndex == rowIndex ? 1 : 0));
  17376. i += colSpan;
  17377. }
  17378. return num;
  17379. },
  17380. splitToCols: function (cell) {
  17381. var backWidth = (cell.offsetWidth / cell.colSpan - 22).toFixed(0),
  17382. cellInfo = this.getCellInfo(cell),
  17383. rowIndex = cellInfo.rowIndex,
  17384. colIndex = cellInfo.colIndex,
  17385. results = [];
  17386. // 修改Cell的rowSpan
  17387. cell.colSpan = 1;
  17388. cell.setAttribute("width", backWidth);
  17389. results.push(cell);
  17390. // 补齐单元格
  17391. for (var j = colIndex, endCol = colIndex + cellInfo.colSpan; j < endCol; j++) {
  17392. if (j == colIndex) continue;
  17393. var tableRow = this.table.rows[rowIndex],
  17394. tmpCell = tableRow.insertCell(this.indexTable[rowIndex][j].cellIndex + 1);
  17395. tmpCell.rowSpan = cellInfo.rowSpan;
  17396. this.setCellContent(tmpCell);
  17397. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17398. tmpCell.setAttribute('align', cell.getAttribute('align'));
  17399. tmpCell.setAttribute('width', backWidth);
  17400. if (cell.style.cssText) {
  17401. tmpCell.style.cssText = cell.style.cssText;
  17402. }
  17403. //处理th的情况
  17404. if (cell.tagName == 'TH') {
  17405. var th = cell.ownerDocument.createElement('th');
  17406. th.appendChild(tmpCell.firstChild);
  17407. th.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17408. th.rowSpan = tmpCell.rowSpan;
  17409. tableRow.insertBefore(th, tmpCell);
  17410. domUtils.remove(tmpCell);
  17411. }
  17412. results.push(tmpCell);
  17413. }
  17414. this.update();
  17415. return results;
  17416. },
  17417. isLastCell: function (cell, rowsNum, colsNum) {
  17418. rowsNum = rowsNum || this.rowsNum;
  17419. colsNum = colsNum || this.colsNum;
  17420. var cellInfo = this.getCellInfo(cell);
  17421. return ((cellInfo.rowIndex + cellInfo.rowSpan) == rowsNum) &&
  17422. ((cellInfo.colIndex + cellInfo.colSpan) == colsNum);
  17423. },
  17424. getLastCell: function (cells) {
  17425. cells = cells || this.table.getElementsByTagName("td");
  17426. var firstInfo = this.getCellInfo(cells[0]);
  17427. var me = this, last = cells[0],
  17428. tr = last.parentNode,
  17429. cellsNum = 0, cols = 0, rows;
  17430. utils.each(cells, function (cell) {
  17431. if (cell.parentNode == tr) cols += cell.colSpan || 1;
  17432. cellsNum += cell.rowSpan * cell.colSpan || 1;
  17433. });
  17434. rows = cellsNum / cols;
  17435. utils.each(cells, function (cell) {
  17436. if (me.isLastCell(cell, rows, cols)) {
  17437. last = cell;
  17438. return false;
  17439. }
  17440. });
  17441. return last;
  17442. },
  17443. selectRow: function (rowIndex) {
  17444. var indexRow = this.indexTable[rowIndex],
  17445. start = this.getCell(indexRow[0].rowIndex, indexRow[0].cellIndex),
  17446. end = this.getCell(indexRow[this.colsNum - 1].rowIndex, indexRow[this.colsNum - 1].cellIndex),
  17447. range = this.getCellsRange(start, end);
  17448. this.setSelected(range);
  17449. },
  17450. selectTable: function () {
  17451. var tds = this.table.getElementsByTagName("td"),
  17452. range = this.getCellsRange(tds[0], tds[tds.length - 1]);
  17453. this.setSelected(range);
  17454. },
  17455. setBackground: function (cells, value) {
  17456. if (typeof value === "string") {
  17457. utils.each(cells, function (cell) {
  17458. cell.style.backgroundColor = value;
  17459. })
  17460. } else if (typeof value === "object") {
  17461. value = utils.extend({
  17462. repeat: true,
  17463. colorList: ["#ddd", "#fff"]
  17464. }, value);
  17465. var rowIndex = this.getCellInfo(cells[0]).rowIndex,
  17466. count = 0,
  17467. colors = value.colorList,
  17468. getColor = function (list, index, repeat) {
  17469. return list[index] ? list[index] : repeat ? list[index % list.length] : "";
  17470. };
  17471. for (var i = 0, cell; cell = cells[i++];) {
  17472. var cellInfo = this.getCellInfo(cell);
  17473. cell.style.backgroundColor = getColor(colors, ((rowIndex + count) == cellInfo.rowIndex) ? count : ++count, value.repeat);
  17474. }
  17475. }
  17476. },
  17477. removeBackground: function (cells) {
  17478. utils.each(cells, function (cell) {
  17479. cell.style.backgroundColor = "";
  17480. })
  17481. }
  17482. };
  17483. function showError(e) {
  17484. }
  17485. })();
  17486. // plugins/table.cmds.js
  17487. /**
  17488. * Created with JetBrains PhpStorm.
  17489. * User: taoqili
  17490. * Date: 13-2-20
  17491. * Time: 下午6:25
  17492. * To change this template use File | Settings | File Templates.
  17493. */
  17494. ;
  17495. (function () {
  17496. var UT = UE.UETable,
  17497. getTableItemsByRange = function (editor) {
  17498. return UT.getTableItemsByRange(editor);
  17499. },
  17500. getUETableBySelected = function (editor) {
  17501. return UT.getUETableBySelected(editor)
  17502. },
  17503. getDefaultValue = function (editor, table) {
  17504. return UT.getDefaultValue(editor, table);
  17505. },
  17506. getUETable = function (tdOrTable) {
  17507. return UT.getUETable(tdOrTable);
  17508. };
  17509. UE.commands['inserttable'] = {
  17510. queryCommandState: function () {
  17511. return getTableItemsByRange(this).table ? -1 : 0;
  17512. },
  17513. execCommand: function (cmd, opt) {
  17514. function createTable(opt, tdWidth) {
  17515. var html = [],
  17516. rowsNum = opt.numRows,
  17517. colsNum = opt.numCols;
  17518. for (var r = 0; r < rowsNum; r++) {
  17519. html.push('<tr' + (r == 0 ? ' class="firstRow"' : '') + '>');
  17520. for (var c = 0; c < colsNum; c++) {
  17521. html.push('<td width="' + tdWidth + '" vAlign="' + opt.tdvalign + '" >' + (browser.ie && browser.version < 11 ? domUtils.fillChar : '<br/>') + '</td>')
  17522. }
  17523. html.push('</tr>')
  17524. }
  17525. //禁止指定table-width
  17526. return '<table><tbody>' + html.join('') + '</tbody></table>'
  17527. }
  17528. if (!opt) {
  17529. opt = utils.extend({}, {
  17530. numCols: this.options.defaultCols,
  17531. numRows: this.options.defaultRows,
  17532. tdvalign: this.options.tdvalign
  17533. })
  17534. }
  17535. var me = this;
  17536. var range = this.selection.getRange(),
  17537. start = range.startContainer,
  17538. firstParentBlock = domUtils.findParent(start, function (node) {
  17539. return domUtils.isBlockElm(node);
  17540. }, true) || me.body;
  17541. var defaultValue = getDefaultValue(me),
  17542. tableWidth = firstParentBlock.offsetWidth,
  17543. tdWidth = Math.floor(tableWidth / opt.numCols - defaultValue.tdPadding * 2 - defaultValue.tdBorder);
  17544. //todo其他属性
  17545. !opt.tdvalign && (opt.tdvalign = me.options.tdvalign);
  17546. me.execCommand("inserthtml", createTable(opt, tdWidth));
  17547. }
  17548. };
  17549. UE.commands['insertparagraphbeforetable'] = {
  17550. queryCommandState: function () {
  17551. return getTableItemsByRange(this).cell ? 0 : -1;
  17552. },
  17553. execCommand: function () {
  17554. var table = getTableItemsByRange(this).table;
  17555. if (table) {
  17556. var p = this.document.createElement("p");
  17557. p.innerHTML = browser.ie ? '&nbsp;' : '<br />';
  17558. table.parentNode.insertBefore(p, table);
  17559. this.selection.getRange().setStart(p, 0).setCursor();
  17560. }
  17561. }
  17562. };
  17563. UE.commands['deletetable'] = {
  17564. queryCommandState: function () {
  17565. var rng = this.selection.getRange();
  17566. return domUtils.findParentByTagName(rng.startContainer, 'table', true) ? 0 : -1;
  17567. },
  17568. execCommand: function (cmd, table) {
  17569. var rng = this.selection.getRange();
  17570. table = table || domUtils.findParentByTagName(rng.startContainer, 'table', true);
  17571. if (table) {
  17572. var next = table.nextSibling;
  17573. if (!next) {
  17574. next = domUtils.createElement(this.document, 'p', {
  17575. 'innerHTML': browser.ie ? domUtils.fillChar : '<br/>'
  17576. });
  17577. table.parentNode.insertBefore(next, table);
  17578. }
  17579. domUtils.remove(table);
  17580. rng = this.selection.getRange();
  17581. if (next.nodeType == 3) {
  17582. rng.setStartBefore(next)
  17583. } else {
  17584. rng.setStart(next, 0)
  17585. }
  17586. rng.setCursor(false, true)
  17587. this.fireEvent("tablehasdeleted")
  17588. }
  17589. }
  17590. };
  17591. UE.commands['cellalign'] = {
  17592. queryCommandState: function () {
  17593. return getSelectedArr(this).length ? 0 : -1
  17594. },
  17595. execCommand: function (cmd, align) {
  17596. var selectedTds = getSelectedArr(this);
  17597. if (selectedTds.length) {
  17598. for (var i = 0, ci; ci = selectedTds[i++];) {
  17599. ci.setAttribute('align', align);
  17600. }
  17601. }
  17602. }
  17603. };
  17604. UE.commands['cellvalign'] = {
  17605. queryCommandState: function () {
  17606. return getSelectedArr(this).length ? 0 : -1;
  17607. },
  17608. execCommand: function (cmd, valign) {
  17609. var selectedTds = getSelectedArr(this);
  17610. if (selectedTds.length) {
  17611. for (var i = 0, ci; ci = selectedTds[i++];) {
  17612. ci.setAttribute('vAlign', valign);
  17613. }
  17614. }
  17615. }
  17616. };
  17617. UE.commands['insertcaption'] = {
  17618. queryCommandState: function () {
  17619. var table = getTableItemsByRange(this).table;
  17620. if (table) {
  17621. return table.getElementsByTagName('caption').length == 0 ? 1 : -1;
  17622. }
  17623. return -1;
  17624. },
  17625. execCommand: function () {
  17626. var table = getTableItemsByRange(this).table;
  17627. if (table) {
  17628. var caption = this.document.createElement('caption');
  17629. caption.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  17630. table.insertBefore(caption, table.firstChild);
  17631. var range = this.selection.getRange();
  17632. range.setStart(caption, 0).setCursor();
  17633. }
  17634. }
  17635. };
  17636. UE.commands['deletecaption'] = {
  17637. queryCommandState: function () {
  17638. var rng = this.selection.getRange(),
  17639. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  17640. if (table) {
  17641. return table.getElementsByTagName('caption').length == 0 ? -1 : 1;
  17642. }
  17643. return -1;
  17644. },
  17645. execCommand: function () {
  17646. var rng = this.selection.getRange(),
  17647. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  17648. if (table) {
  17649. domUtils.remove(table.getElementsByTagName('caption')[0]);
  17650. var range = this.selection.getRange();
  17651. range.setStart(table.rows[0].cells[0], 0).setCursor();
  17652. }
  17653. }
  17654. };
  17655. UE.commands['inserttitle'] = {
  17656. queryCommandState: function () {
  17657. var table = getTableItemsByRange(this).table;
  17658. if (table) {
  17659. var firstRow = table.rows[0];
  17660. return firstRow.cells[firstRow.cells.length - 1].tagName.toLowerCase() != 'th' ? 0 : -1
  17661. }
  17662. return -1;
  17663. },
  17664. execCommand: function () {
  17665. var table = getTableItemsByRange(this).table;
  17666. if (table) {
  17667. getUETable(table).insertRow(0, 'th');
  17668. }
  17669. var th = table.getElementsByTagName('th')[0];
  17670. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  17671. }
  17672. };
  17673. UE.commands['deletetitle'] = {
  17674. queryCommandState: function () {
  17675. var table = getTableItemsByRange(this).table;
  17676. if (table) {
  17677. var firstRow = table.rows[0];
  17678. return firstRow.cells[firstRow.cells.length - 1].tagName.toLowerCase() == 'th' ? 0 : -1
  17679. }
  17680. return -1;
  17681. },
  17682. execCommand: function () {
  17683. var table = getTableItemsByRange(this).table;
  17684. if (table) {
  17685. domUtils.remove(table.rows[0])
  17686. }
  17687. var td = table.getElementsByTagName('td')[0];
  17688. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  17689. }
  17690. };
  17691. UE.commands['inserttitlecol'] = {
  17692. queryCommandState: function () {
  17693. var table = getTableItemsByRange(this).table;
  17694. if (table) {
  17695. var lastRow = table.rows[table.rows.length - 1];
  17696. return lastRow.getElementsByTagName('th').length ? -1 : 0;
  17697. }
  17698. return -1;
  17699. },
  17700. execCommand: function (cmd) {
  17701. var table = getTableItemsByRange(this).table;
  17702. if (table) {
  17703. getUETable(table).insertCol(0, 'th');
  17704. }
  17705. resetTdWidth(table, this);
  17706. var th = table.getElementsByTagName('th')[0];
  17707. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  17708. }
  17709. };
  17710. UE.commands['deletetitlecol'] = {
  17711. queryCommandState: function () {
  17712. var table = getTableItemsByRange(this).table;
  17713. if (table) {
  17714. var lastRow = table.rows[table.rows.length - 1];
  17715. return lastRow.getElementsByTagName('th').length ? 0 : -1;
  17716. }
  17717. return -1;
  17718. },
  17719. execCommand: function () {
  17720. var table = getTableItemsByRange(this).table;
  17721. if (table) {
  17722. for (var i = 0; i < table.rows.length; i++) {
  17723. domUtils.remove(table.rows[i].children[0])
  17724. }
  17725. }
  17726. resetTdWidth(table, this);
  17727. var td = table.getElementsByTagName('td')[0];
  17728. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  17729. }
  17730. };
  17731. UE.commands["mergeright"] = {
  17732. queryCommandState: function (cmd) {
  17733. var tableItems = getTableItemsByRange(this),
  17734. table = tableItems.table,
  17735. cell = tableItems.cell;
  17736. if (!table || !cell) return -1;
  17737. var ut = getUETable(table);
  17738. if (ut.selectedTds.length) return -1;
  17739. var cellInfo = ut.getCellInfo(cell),
  17740. rightColIndex = cellInfo.colIndex + cellInfo.colSpan;
  17741. if (rightColIndex >= ut.colsNum) return -1; // 如果处于最右边则不能向右合并
  17742. var rightCellInfo = ut.indexTable[cellInfo.rowIndex][rightColIndex],
  17743. rightCell = table.rows[rightCellInfo.rowIndex].cells[rightCellInfo.cellIndex];
  17744. if (!rightCell || cell.tagName != rightCell.tagName) return -1; // TH和TD不能相互合并
  17745. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  17746. return (rightCellInfo.rowIndex == cellInfo.rowIndex && rightCellInfo.rowSpan == cellInfo.rowSpan) ? 0 : -1;
  17747. },
  17748. execCommand: function (cmd) {
  17749. var rng = this.selection.getRange(),
  17750. bk = rng.createBookmark(true);
  17751. var cell = getTableItemsByRange(this).cell,
  17752. ut = getUETable(cell);
  17753. ut.mergeRight(cell);
  17754. rng.moveToBookmark(bk).select();
  17755. }
  17756. };
  17757. UE.commands["mergedown"] = {
  17758. queryCommandState: function (cmd) {
  17759. var tableItems = getTableItemsByRange(this),
  17760. table = tableItems.table,
  17761. cell = tableItems.cell;
  17762. if (!table || !cell) return -1;
  17763. var ut = getUETable(table);
  17764. if (ut.selectedTds.length) return -1;
  17765. var cellInfo = ut.getCellInfo(cell),
  17766. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan;
  17767. if (downRowIndex >= ut.rowsNum) return -1; // 如果处于最下边则不能向下合并
  17768. var downCellInfo = ut.indexTable[downRowIndex][cellInfo.colIndex],
  17769. downCell = table.rows[downCellInfo.rowIndex].cells[downCellInfo.cellIndex];
  17770. if (!downCell || cell.tagName != downCell.tagName) return -1; // TH和TD不能相互合并
  17771. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  17772. return (downCellInfo.colIndex == cellInfo.colIndex && downCellInfo.colSpan == cellInfo.colSpan) ? 0 : -1;
  17773. },
  17774. execCommand: function () {
  17775. var rng = this.selection.getRange(),
  17776. bk = rng.createBookmark(true);
  17777. var cell = getTableItemsByRange(this).cell,
  17778. ut = getUETable(cell);
  17779. ut.mergeDown(cell);
  17780. rng.moveToBookmark(bk).select();
  17781. }
  17782. };
  17783. UE.commands["mergecells"] = {
  17784. queryCommandState: function () {
  17785. return getUETableBySelected(this) ? 0 : -1;
  17786. },
  17787. execCommand: function () {
  17788. var ut = getUETableBySelected(this);
  17789. if (ut && ut.selectedTds.length) {
  17790. var cell = ut.selectedTds[0];
  17791. ut.mergeRange();
  17792. var rng = this.selection.getRange();
  17793. if (domUtils.isEmptyBlock(cell)) {
  17794. rng.setStart(cell, 0).collapse(true)
  17795. } else {
  17796. rng.selectNodeContents(cell)
  17797. }
  17798. rng.select();
  17799. }
  17800. }
  17801. };
  17802. UE.commands["insertrow"] = {
  17803. queryCommandState: function () {
  17804. var tableItems = getTableItemsByRange(this),
  17805. cell = tableItems.cell;
  17806. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && tableItems.tr !== tableItems.table.rows[0])) &&
  17807. getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  17808. },
  17809. execCommand: function () {
  17810. var rng = this.selection.getRange(),
  17811. bk = rng.createBookmark(true);
  17812. var tableItems = getTableItemsByRange(this),
  17813. cell = tableItems.cell,
  17814. table = tableItems.table,
  17815. ut = getUETable(table),
  17816. cellInfo = ut.getCellInfo(cell);
  17817. //ut.insertRow(!ut.selectedTds.length ? cellInfo.rowIndex:ut.cellsRange.beginRowIndex,'');
  17818. if (!ut.selectedTds.length) {
  17819. ut.insertRow(cellInfo.rowIndex, cell);
  17820. } else {
  17821. var range = ut.cellsRange;
  17822. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  17823. ut.insertRow(range.beginRowIndex, cell);
  17824. }
  17825. }
  17826. rng.moveToBookmark(bk).select();
  17827. if (table.getAttribute("interlaced") === "enabled") this.fireEvent("interlacetable", table);
  17828. }
  17829. };
  17830. //后插入行
  17831. UE.commands["insertrownext"] = {
  17832. queryCommandState: function () {
  17833. var tableItems = getTableItemsByRange(this),
  17834. cell = tableItems.cell;
  17835. return cell && (cell.tagName == "TD") && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  17836. },
  17837. execCommand: function () {
  17838. var rng = this.selection.getRange(),
  17839. bk = rng.createBookmark(true);
  17840. var tableItems = getTableItemsByRange(this),
  17841. cell = tableItems.cell,
  17842. table = tableItems.table,
  17843. ut = getUETable(table),
  17844. cellInfo = ut.getCellInfo(cell);
  17845. //ut.insertRow(!ut.selectedTds.length? cellInfo.rowIndex + cellInfo.rowSpan : ut.cellsRange.endRowIndex + 1,'');
  17846. if (!ut.selectedTds.length) {
  17847. ut.insertRow(cellInfo.rowIndex + cellInfo.rowSpan, cell);
  17848. } else {
  17849. var range = ut.cellsRange;
  17850. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  17851. ut.insertRow(range.endRowIndex + 1, cell);
  17852. }
  17853. }
  17854. rng.moveToBookmark(bk).select();
  17855. if (table.getAttribute("interlaced") === "enabled") this.fireEvent("interlacetable", table);
  17856. }
  17857. };
  17858. UE.commands["deleterow"] = {
  17859. queryCommandState: function () {
  17860. var tableItems = getTableItemsByRange(this);
  17861. return tableItems.cell ? 0 : -1;
  17862. },
  17863. execCommand: function () {
  17864. var cell = getTableItemsByRange(this).cell,
  17865. ut = getUETable(cell),
  17866. cellsRange = ut.cellsRange,
  17867. cellInfo = ut.getCellInfo(cell),
  17868. preCell = ut.getVSideCell(cell),
  17869. nextCell = ut.getVSideCell(cell, true),
  17870. rng = this.selection.getRange();
  17871. if (utils.isEmptyObject(cellsRange)) {
  17872. ut.deleteRow(cellInfo.rowIndex);
  17873. } else {
  17874. for (var i = cellsRange.beginRowIndex; i < cellsRange.endRowIndex + 1; i++) {
  17875. ut.deleteRow(cellsRange.beginRowIndex);
  17876. }
  17877. }
  17878. var table = ut.table;
  17879. if (!table.getElementsByTagName('td').length) {
  17880. var nextSibling = table.nextSibling;
  17881. domUtils.remove(table);
  17882. if (nextSibling) {
  17883. rng.setStart(nextSibling, 0).setCursor(false, true);
  17884. }
  17885. } else {
  17886. if (cellInfo.rowSpan == 1 || cellInfo.rowSpan == cellsRange.endRowIndex - cellsRange.beginRowIndex + 1) {
  17887. if (nextCell || preCell) rng.selectNodeContents(nextCell || preCell).setCursor(false, true);
  17888. } else {
  17889. var newCell = ut.getCell(cellInfo.rowIndex, ut.indexTable[cellInfo.rowIndex][cellInfo.colIndex].cellIndex);
  17890. if (newCell) rng.selectNodeContents(newCell).setCursor(false, true);
  17891. }
  17892. }
  17893. if (table.getAttribute("interlaced") === "enabled") this.fireEvent("interlacetable", table);
  17894. }
  17895. };
  17896. UE.commands["insertcol"] = {
  17897. queryCommandState: function (cmd) {
  17898. var tableItems = getTableItemsByRange(this),
  17899. cell = tableItems.cell;
  17900. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && cell !== tableItems.tr.cells[0])) &&
  17901. getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  17902. },
  17903. execCommand: function (cmd) {
  17904. var rng = this.selection.getRange(),
  17905. bk = rng.createBookmark(true);
  17906. if (this.queryCommandState(cmd) == -1) return;
  17907. var cell = getTableItemsByRange(this).cell,
  17908. ut = getUETable(cell),
  17909. cellInfo = ut.getCellInfo(cell);
  17910. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex:ut.cellsRange.beginColIndex);
  17911. if (!ut.selectedTds.length) {
  17912. ut.insertCol(cellInfo.colIndex, cell);
  17913. } else {
  17914. var range = ut.cellsRange;
  17915. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  17916. ut.insertCol(range.beginColIndex, cell);
  17917. }
  17918. }
  17919. rng.moveToBookmark(bk).select(true);
  17920. }
  17921. };
  17922. UE.commands["insertcolnext"] = {
  17923. queryCommandState: function () {
  17924. var tableItems = getTableItemsByRange(this),
  17925. cell = tableItems.cell;
  17926. return cell && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  17927. },
  17928. execCommand: function () {
  17929. var rng = this.selection.getRange(),
  17930. bk = rng.createBookmark(true);
  17931. var cell = getTableItemsByRange(this).cell,
  17932. ut = getUETable(cell),
  17933. cellInfo = ut.getCellInfo(cell);
  17934. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex + cellInfo.colSpan:ut.cellsRange.endColIndex +1);
  17935. if (!ut.selectedTds.length) {
  17936. ut.insertCol(cellInfo.colIndex + cellInfo.colSpan, cell);
  17937. } else {
  17938. var range = ut.cellsRange;
  17939. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  17940. ut.insertCol(range.endColIndex + 1, cell);
  17941. }
  17942. }
  17943. rng.moveToBookmark(bk).select();
  17944. }
  17945. };
  17946. UE.commands["deletecol"] = {
  17947. queryCommandState: function () {
  17948. var tableItems = getTableItemsByRange(this);
  17949. return tableItems.cell ? 0 : -1;
  17950. },
  17951. execCommand: function () {
  17952. var cell = getTableItemsByRange(this).cell,
  17953. ut = getUETable(cell),
  17954. range = ut.cellsRange,
  17955. cellInfo = ut.getCellInfo(cell),
  17956. preCell = ut.getHSideCell(cell),
  17957. nextCell = ut.getHSideCell(cell, true);
  17958. if (utils.isEmptyObject(range)) {
  17959. ut.deleteCol(cellInfo.colIndex);
  17960. } else {
  17961. for (var i = range.beginColIndex; i < range.endColIndex + 1; i++) {
  17962. ut.deleteCol(range.beginColIndex);
  17963. }
  17964. }
  17965. var table = ut.table,
  17966. rng = this.selection.getRange();
  17967. if (!table.getElementsByTagName('td').length) {
  17968. var nextSibling = table.nextSibling;
  17969. domUtils.remove(table);
  17970. if (nextSibling) {
  17971. rng.setStart(nextSibling, 0).setCursor(false, true);
  17972. }
  17973. } else {
  17974. if (domUtils.inDoc(cell, this.document)) {
  17975. rng.setStart(cell, 0).setCursor(false, true);
  17976. } else {
  17977. if (nextCell && domUtils.inDoc(nextCell, this.document)) {
  17978. rng.selectNodeContents(nextCell).setCursor(false, true);
  17979. } else {
  17980. if (preCell && domUtils.inDoc(preCell, this.document)) {
  17981. rng.selectNodeContents(preCell).setCursor(true, true);
  17982. }
  17983. }
  17984. }
  17985. }
  17986. }
  17987. };
  17988. UE.commands["splittocells"] = {
  17989. queryCommandState: function () {
  17990. var tableItems = getTableItemsByRange(this),
  17991. cell = tableItems.cell;
  17992. if (!cell) return -1;
  17993. var ut = getUETable(tableItems.table);
  17994. if (ut.selectedTds.length > 0) return -1;
  17995. return cell && (cell.colSpan > 1 || cell.rowSpan > 1) ? 0 : -1;
  17996. },
  17997. execCommand: function () {
  17998. var rng = this.selection.getRange(),
  17999. bk = rng.createBookmark(true);
  18000. var cell = getTableItemsByRange(this).cell,
  18001. ut = getUETable(cell);
  18002. ut.splitToCells(cell);
  18003. rng.moveToBookmark(bk).select();
  18004. }
  18005. };
  18006. UE.commands["splittorows"] = {
  18007. queryCommandState: function () {
  18008. var tableItems = getTableItemsByRange(this),
  18009. cell = tableItems.cell;
  18010. if (!cell) return -1;
  18011. var ut = getUETable(tableItems.table);
  18012. if (ut.selectedTds.length > 0) return -1;
  18013. return cell && cell.rowSpan > 1 ? 0 : -1;
  18014. },
  18015. execCommand: function () {
  18016. var rng = this.selection.getRange(),
  18017. bk = rng.createBookmark(true);
  18018. var cell = getTableItemsByRange(this).cell,
  18019. ut = getUETable(cell);
  18020. ut.splitToRows(cell);
  18021. rng.moveToBookmark(bk).select();
  18022. }
  18023. };
  18024. UE.commands["splittocols"] = {
  18025. queryCommandState: function () {
  18026. var tableItems = getTableItemsByRange(this),
  18027. cell = tableItems.cell;
  18028. if (!cell) return -1;
  18029. var ut = getUETable(tableItems.table);
  18030. if (ut.selectedTds.length > 0) return -1;
  18031. return cell && cell.colSpan > 1 ? 0 : -1;
  18032. },
  18033. execCommand: function () {
  18034. var rng = this.selection.getRange(),
  18035. bk = rng.createBookmark(true);
  18036. var cell = getTableItemsByRange(this).cell,
  18037. ut = getUETable(cell);
  18038. ut.splitToCols(cell);
  18039. rng.moveToBookmark(bk).select();
  18040. }
  18041. };
  18042. UE.commands["adaptbytext"] =
  18043. UE.commands["adaptbywindow"] = {
  18044. queryCommandState: function () {
  18045. return getTableItemsByRange(this).table ? 0 : -1
  18046. },
  18047. execCommand: function (cmd) {
  18048. var tableItems = getTableItemsByRange(this),
  18049. table = tableItems.table;
  18050. if (table) {
  18051. if (cmd == 'adaptbywindow') {
  18052. resetTdWidth(table, this);
  18053. } else {
  18054. var cells = domUtils.getElementsByTagName(table, "td th");
  18055. utils.each(cells, function (cell) {
  18056. cell.removeAttribute("width");
  18057. });
  18058. table.removeAttribute("width");
  18059. }
  18060. }
  18061. }
  18062. };
  18063. //平均分配各列
  18064. UE.commands['averagedistributecol'] = {
  18065. queryCommandState: function () {
  18066. var ut = getUETableBySelected(this);
  18067. if (!ut) return -1;
  18068. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  18069. },
  18070. execCommand: function (cmd) {
  18071. var me = this,
  18072. ut = getUETableBySelected(me);
  18073. function getAverageWidth() {
  18074. var tb = ut.table,
  18075. averageWidth, sumWidth = 0, colsNum = 0,
  18076. tbAttr = getDefaultValue(me, tb);
  18077. if (ut.isFullRow()) {
  18078. sumWidth = tb.offsetWidth;
  18079. colsNum = ut.colsNum;
  18080. } else {
  18081. var begin = ut.cellsRange.beginColIndex,
  18082. end = ut.cellsRange.endColIndex,
  18083. node;
  18084. for (var i = begin; i <= end;) {
  18085. node = ut.selectedTds[i];
  18086. sumWidth += node.offsetWidth;
  18087. i += node.colSpan;
  18088. colsNum += 1;
  18089. }
  18090. }
  18091. averageWidth = Math.ceil(sumWidth / colsNum) - tbAttr.tdBorder * 2 - tbAttr.tdPadding * 2;
  18092. return averageWidth;
  18093. }
  18094. function setAverageWidth(averageWidth) {
  18095. utils.each(domUtils.getElementsByTagName(ut.table, "th"), function (node) {
  18096. node.setAttribute("width", "");
  18097. });
  18098. var cells = ut.isFullRow() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  18099. utils.each(cells, function (node) {
  18100. if (node.colSpan == 1) {
  18101. node.setAttribute("width", averageWidth);
  18102. }
  18103. });
  18104. }
  18105. if (ut && ut.selectedTds.length) {
  18106. setAverageWidth(getAverageWidth());
  18107. }
  18108. }
  18109. };
  18110. //平均分配各行
  18111. UE.commands['averagedistributerow'] = {
  18112. queryCommandState: function () {
  18113. var ut = getUETableBySelected(this);
  18114. if (!ut) return -1;
  18115. if (ut.selectedTds && /th/ig.test(ut.selectedTds[0].tagName)) return -1;
  18116. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  18117. },
  18118. execCommand: function (cmd) {
  18119. var me = this,
  18120. ut = getUETableBySelected(me);
  18121. function getAverageHeight() {
  18122. var averageHeight, rowNum, sumHeight = 0,
  18123. tb = ut.table,
  18124. tbAttr = getDefaultValue(me, tb),
  18125. tdpadding = parseInt(domUtils.getComputedStyle(tb.getElementsByTagName('td')[0], "padding-top"));
  18126. if (ut.isFullCol()) {
  18127. var captionArr = domUtils.getElementsByTagName(tb, "caption"),
  18128. thArr = domUtils.getElementsByTagName(tb, "th"),
  18129. captionHeight, thHeight;
  18130. if (captionArr.length > 0) {
  18131. captionHeight = captionArr[0].offsetHeight;
  18132. }
  18133. if (thArr.length > 0) {
  18134. thHeight = thArr[0].offsetHeight;
  18135. }
  18136. sumHeight = tb.offsetHeight - (captionHeight || 0) - (thHeight || 0);
  18137. rowNum = thArr.length == 0 ? ut.rowsNum : (ut.rowsNum - 1);
  18138. } else {
  18139. var begin = ut.cellsRange.beginRowIndex,
  18140. end = ut.cellsRange.endRowIndex,
  18141. count = 0,
  18142. trs = domUtils.getElementsByTagName(tb, "tr");
  18143. for (var i = begin; i <= end; i++) {
  18144. sumHeight += trs[i].offsetHeight;
  18145. count += 1;
  18146. }
  18147. rowNum = count;
  18148. }
  18149. //ie8下是混杂模式
  18150. if (browser.ie && browser.version < 9) {
  18151. averageHeight = Math.ceil(sumHeight / rowNum);
  18152. } else {
  18153. averageHeight = Math.ceil(sumHeight / rowNum) - tbAttr.tdBorder * 2 - tdpadding * 2;
  18154. }
  18155. return averageHeight;
  18156. }
  18157. function setAverageHeight(averageHeight) {
  18158. var cells = ut.isFullCol() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  18159. utils.each(cells, function (node) {
  18160. if (node.rowSpan == 1) {
  18161. node.setAttribute("height", averageHeight);
  18162. }
  18163. });
  18164. }
  18165. if (ut && ut.selectedTds.length) {
  18166. setAverageHeight(getAverageHeight());
  18167. }
  18168. }
  18169. };
  18170. //单元格对齐方式
  18171. UE.commands['cellalignment'] = {
  18172. queryCommandState: function () {
  18173. return getTableItemsByRange(this).table ? 0 : -1
  18174. },
  18175. execCommand: function (cmd, data) {
  18176. var me = this,
  18177. ut = getUETableBySelected(me);
  18178. if (!ut) {
  18179. var start = me.selection.getStart(),
  18180. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  18181. if (!/caption/ig.test(cell.tagName)) {
  18182. domUtils.setAttributes(cell, data);
  18183. } else {
  18184. cell.style.textAlign = data.align;
  18185. cell.style.verticalAlign = data.vAlign;
  18186. }
  18187. me.selection.getRange().setCursor(true);
  18188. } else {
  18189. utils.each(ut.selectedTds, function (cell) {
  18190. domUtils.setAttributes(cell, data);
  18191. });
  18192. }
  18193. },
  18194. /**
  18195. * 查询当前点击的单元格的对齐状态, 如果当前已经选择了多个单元格, 则会返回所有单元格经过统一协调过后的状态
  18196. * @see UE.UETable.getTableCellAlignState
  18197. */
  18198. queryCommandValue: function (cmd) {
  18199. var activeMenuCell = getTableItemsByRange(this).cell;
  18200. if (!activeMenuCell) {
  18201. activeMenuCell = getSelectedArr(this)[0];
  18202. }
  18203. if (!activeMenuCell) {
  18204. return null;
  18205. } else {
  18206. //获取同时选中的其他单元格
  18207. var cells = UE.UETable.getUETable(activeMenuCell).selectedTds;
  18208. !cells.length && (cells = activeMenuCell);
  18209. return UE.UETable.getTableCellAlignState(cells);
  18210. }
  18211. }
  18212. };
  18213. //表格对齐方式
  18214. UE.commands['tablealignment'] = {
  18215. queryCommandState: function () {
  18216. if (browser.ie && browser.version < 8) {
  18217. return -1;
  18218. }
  18219. return getTableItemsByRange(this).table ? 0 : -1
  18220. },
  18221. execCommand: function (cmd, value) {
  18222. var me = this,
  18223. start = me.selection.getStart(),
  18224. table = start && domUtils.findParentByTagName(start, ["table"], true);
  18225. if (table) {
  18226. table.setAttribute("align", value);
  18227. }
  18228. }
  18229. };
  18230. //表格属性
  18231. UE.commands['edittable'] = {
  18232. queryCommandState: function () {
  18233. return getTableItemsByRange(this).table ? 0 : -1
  18234. },
  18235. execCommand: function (cmd, color) {
  18236. var rng = this.selection.getRange(),
  18237. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  18238. if (table) {
  18239. var arr = domUtils.getElementsByTagName(table, "td").concat(
  18240. domUtils.getElementsByTagName(table, "th"),
  18241. domUtils.getElementsByTagName(table, "caption")
  18242. );
  18243. utils.each(arr, function (node) {
  18244. node.style.borderColor = color;
  18245. });
  18246. }
  18247. }
  18248. };
  18249. //单元格属性
  18250. UE.commands['edittd'] = {
  18251. queryCommandState: function () {
  18252. return getTableItemsByRange(this).table ? 0 : -1
  18253. },
  18254. execCommand: function (cmd, bkColor) {
  18255. var me = this,
  18256. ut = getUETableBySelected(me);
  18257. if (!ut) {
  18258. var start = me.selection.getStart(),
  18259. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  18260. if (cell) {
  18261. cell.style.backgroundColor = bkColor;
  18262. }
  18263. } else {
  18264. utils.each(ut.selectedTds, function (cell) {
  18265. cell.style.backgroundColor = bkColor;
  18266. });
  18267. }
  18268. }
  18269. };
  18270. UE.commands["settablebackground"] = {
  18271. queryCommandState: function () {
  18272. return getSelectedArr(this).length > 1 ? 0 : -1;
  18273. },
  18274. execCommand: function (cmd, value) {
  18275. var cells, ut;
  18276. cells = getSelectedArr(this);
  18277. ut = getUETable(cells[0]);
  18278. ut.setBackground(cells, value);
  18279. }
  18280. };
  18281. UE.commands["cleartablebackground"] = {
  18282. queryCommandState: function () {
  18283. var cells = getSelectedArr(this);
  18284. if (!cells.length) return -1;
  18285. for (var i = 0, cell; cell = cells[i++];) {
  18286. if (cell.style.backgroundColor !== "") return 0;
  18287. }
  18288. return -1;
  18289. },
  18290. execCommand: function () {
  18291. var cells = getSelectedArr(this),
  18292. ut = getUETable(cells[0]);
  18293. ut.removeBackground(cells);
  18294. }
  18295. };
  18296. UE.commands["interlacetable"] = UE.commands["uninterlacetable"] = {
  18297. queryCommandState: function (cmd) {
  18298. var table = getTableItemsByRange(this).table;
  18299. if (!table) return -1;
  18300. var interlaced = table.getAttribute("interlaced");
  18301. if (cmd == "interlacetable") {
  18302. //TODO 待定
  18303. //是否需要待定,如果设置,则命令只能单次执行成功,但反射具备toggle效果;否则可以覆盖前次命令,但反射将不存在toggle效果
  18304. return (interlaced === "enabled") ? -1 : 0;
  18305. } else {
  18306. return (!interlaced || interlaced === "disabled") ? -1 : 0;
  18307. }
  18308. },
  18309. execCommand: function (cmd, classList) {
  18310. var table = getTableItemsByRange(this).table;
  18311. if (cmd == "interlacetable") {
  18312. table.setAttribute("interlaced", "enabled");
  18313. this.fireEvent("interlacetable", table, classList);
  18314. } else {
  18315. table.setAttribute("interlaced", "disabled");
  18316. this.fireEvent("uninterlacetable", table);
  18317. }
  18318. }
  18319. };
  18320. UE.commands["setbordervisible"] = {
  18321. queryCommandState: function (cmd) {
  18322. var table = getTableItemsByRange(this).table;
  18323. if (!table) return -1;
  18324. return 0;
  18325. },
  18326. execCommand: function () {
  18327. var table = getTableItemsByRange(this).table;
  18328. utils.each(domUtils.getElementsByTagName(table, 'td'), function (td) {
  18329. td.style.borderWidth = '1px';
  18330. td.style.borderStyle = 'solid';
  18331. })
  18332. }
  18333. };
  18334. function resetTdWidth(table, editor) {
  18335. var tds = domUtils.getElementsByTagName(table, 'td th');
  18336. utils.each(tds, function (td) {
  18337. td.removeAttribute("width");
  18338. });
  18339. table.setAttribute('width', getTableWidth(editor, true, getDefaultValue(editor, table)));
  18340. var tdsWidths = [];
  18341. setTimeout(function () {
  18342. utils.each(tds, function (td) {
  18343. (td.colSpan == 1) && tdsWidths.push(td.offsetWidth)
  18344. })
  18345. utils.each(tds, function (td, i) {
  18346. (td.colSpan == 1) && td.setAttribute("width", tdsWidths[i] + "");
  18347. })
  18348. }, 0);
  18349. }
  18350. function getTableWidth(editor, needIEHack, defaultValue) {
  18351. var body = editor.body;
  18352. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  18353. }
  18354. function getSelectedArr(editor) {
  18355. var cell = getTableItemsByRange(editor).cell;
  18356. if (cell) {
  18357. var ut = getUETable(cell);
  18358. return ut.selectedTds.length ? ut.selectedTds : [cell];
  18359. } else {
  18360. return [];
  18361. }
  18362. }
  18363. })();
  18364. // plugins/table.action.js
  18365. /**
  18366. * Created with JetBrains PhpStorm.
  18367. * User: taoqili
  18368. * Date: 12-10-12
  18369. * Time: 上午10:05
  18370. * To change this template use File | Settings | File Templates.
  18371. */
  18372. UE.plugins['table'] = function () {
  18373. var me = this,
  18374. tabTimer = null,
  18375. //拖动计时器
  18376. tableDragTimer = null,
  18377. //双击计时器
  18378. tableResizeTimer = null,
  18379. //单元格最小宽度
  18380. cellMinWidth = 5,
  18381. isInResizeBuffer = false,
  18382. //单元格边框大小
  18383. cellBorderWidth = 5,
  18384. //鼠标偏移距离
  18385. offsetOfTableCell = 10,
  18386. //记录在有限时间内的点击状态, 共有3个取值, 0, 1, 2。 0代表未初始化, 1代表单击了1次,2代表2次
  18387. singleClickState = 0,
  18388. userActionStatus = null,
  18389. //双击允许的时间范围
  18390. dblclickTime = 360,
  18391. UT = UE.UETable,
  18392. getUETable = function (tdOrTable) {
  18393. return UT.getUETable(tdOrTable);
  18394. },
  18395. getUETableBySelected = function (editor) {
  18396. return UT.getUETableBySelected(editor);
  18397. },
  18398. getDefaultValue = function (editor, table) {
  18399. return UT.getDefaultValue(editor, table);
  18400. },
  18401. removeSelectedClass = function (cells) {
  18402. return UT.removeSelectedClass(cells);
  18403. };
  18404. function showError(e) {
  18405. // throw e;
  18406. }
  18407. me.ready(function () {
  18408. var me = this;
  18409. var orgGetText = me.selection.getText;
  18410. me.selection.getText = function () {
  18411. var table = getUETableBySelected(me);
  18412. if (table) {
  18413. var str = '';
  18414. utils.each(table.selectedTds, function (td) {
  18415. str += td[browser.ie ? 'innerText' : 'textContent'];
  18416. })
  18417. return str;
  18418. } else {
  18419. return orgGetText.call(me.selection)
  18420. }
  18421. }
  18422. })
  18423. //处理拖动及框选相关方法
  18424. var startTd = null, //鼠标按下时的锚点td
  18425. currentTd = null, //当前鼠标经过时的td
  18426. onDrag = "", //指示当前拖动状态,其值可为"","h","v" ,分别表示未拖动状态,横向拖动状态,纵向拖动状态,用于鼠标移动过程中的判断
  18427. onBorder = false, //检测鼠标按下时是否处在单元格边缘位置
  18428. dragButton = null,
  18429. dragOver = false,
  18430. dragLine = null, //模拟的拖动线
  18431. dragTd = null; //发生拖动的目标td
  18432. var mousedown = false,
  18433. //todo 判断混乱模式
  18434. needIEHack = true;
  18435. me.setOpt({
  18436. 'maxColNum': 20,
  18437. 'maxRowNum': 100,
  18438. 'defaultCols': 5,
  18439. 'defaultRows': 5,
  18440. 'tdvalign': 'top',
  18441. 'cursorpath': me.options.UEDITOR_HOME_URL + "themes/default/images/cursor_",
  18442. 'tableDragable': false,
  18443. 'classList': ["ue-table-interlace-color-single", "ue-table-interlace-color-double"]
  18444. });
  18445. me.getUETable = getUETable;
  18446. var commands = {
  18447. 'deletetable': 1,
  18448. 'inserttable': 1,
  18449. 'cellvalign': 1,
  18450. 'insertcaption': 1,
  18451. 'deletecaption': 1,
  18452. 'inserttitle': 1,
  18453. 'deletetitle': 1,
  18454. "mergeright": 1,
  18455. "mergedown": 1,
  18456. "mergecells": 1,
  18457. "insertrow": 1,
  18458. "insertrownext": 1,
  18459. "deleterow": 1,
  18460. "insertcol": 1,
  18461. "insertcolnext": 1,
  18462. "deletecol": 1,
  18463. "splittocells": 1,
  18464. "splittorows": 1,
  18465. "splittocols": 1,
  18466. "adaptbytext": 1,
  18467. "adaptbywindow": 1,
  18468. "adaptbycustomer": 1,
  18469. "insertparagraph": 1,
  18470. "insertparagraphbeforetable": 1,
  18471. "averagedistributecol": 1,
  18472. "averagedistributerow": 1
  18473. };
  18474. me.ready(function () {
  18475. utils.cssRule('table',
  18476. //选中的td上的样式
  18477. '.selectTdClass{background-color:#edf5fa !important}' +
  18478. 'table.noBorderTable td,table.noBorderTable th,table.noBorderTable caption{border:1px dashed #ddd !important}' +
  18479. //插入的表格的默认样式
  18480. 'table{margin-bottom:10px;border-collapse:collapse;display:table;}' +
  18481. 'td,th{padding: 5px 10px;border: 1px solid #DDD;}' +
  18482. 'caption{border:1px dashed #DDD;border-bottom:0;padding:3px;text-align:center;}' +
  18483. 'th{border-top:1px solid #BBB;background-color:#F7F7F7;}' +
  18484. 'table tr.firstRow th{border-top-width:2px;}' +
  18485. '.ue-table-interlace-color-single{ background-color: #fcfcfc; } .ue-table-interlace-color-double{ background-color: #f7faff; }' +
  18486. 'td p{margin:0;padding:0;}', me.document);
  18487. var tableCopyList, isFullCol, isFullRow;
  18488. //注册del/backspace事件
  18489. me.addListener('keydown', function (cmd, evt) {
  18490. var me = this;
  18491. var keyCode = evt.keyCode || evt.which;
  18492. if (keyCode == 8) {
  18493. var ut = getUETableBySelected(me);
  18494. if (ut && ut.selectedTds.length) {
  18495. if (ut.isFullCol()) {
  18496. me.execCommand('deletecol')
  18497. } else if (ut.isFullRow()) {
  18498. me.execCommand('deleterow')
  18499. } else {
  18500. me.fireEvent('delcells');
  18501. }
  18502. domUtils.preventDefault(evt);
  18503. }
  18504. var caption = domUtils.findParentByTagName(me.selection.getStart(), 'caption', true),
  18505. range = me.selection.getRange();
  18506. if (range.collapsed && caption && isEmptyBlock(caption)) {
  18507. me.fireEvent('saveScene');
  18508. var table = caption.parentNode;
  18509. domUtils.remove(caption);
  18510. if (table) {
  18511. range.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  18512. }
  18513. me.fireEvent('saveScene');
  18514. }
  18515. }
  18516. if (keyCode == 46) {
  18517. ut = getUETableBySelected(me);
  18518. if (ut) {
  18519. me.fireEvent('saveScene');
  18520. for (var i = 0, ci; ci = ut.selectedTds[i++];) {
  18521. domUtils.fillNode(me.document, ci)
  18522. }
  18523. me.fireEvent('saveScene');
  18524. domUtils.preventDefault(evt);
  18525. }
  18526. }
  18527. if (keyCode == 13) {
  18528. var rng = me.selection.getRange(),
  18529. caption = domUtils.findParentByTagName(rng.startContainer, 'caption', true);
  18530. if (caption) {
  18531. var table = domUtils.findParentByTagName(caption, 'table');
  18532. if (!rng.collapsed) {
  18533. rng.deleteContents();
  18534. me.fireEvent('saveScene');
  18535. } else {
  18536. if (caption) {
  18537. rng.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  18538. }
  18539. }
  18540. domUtils.preventDefault(evt);
  18541. return;
  18542. }
  18543. if (rng.collapsed) {
  18544. var table = domUtils.findParentByTagName(rng.startContainer, 'table');
  18545. if (table) {
  18546. var cell = table.rows[0].cells[0],
  18547. start = domUtils.findParentByTagName(me.selection.getStart(), ['td', 'th'], true),
  18548. preNode = table.previousSibling;
  18549. if (cell === start && (!preNode || preNode.nodeType == 1 && preNode.tagName == 'TABLE') && domUtils.isStartInblock(rng)) {
  18550. var first = domUtils.findParent(me.selection.getStart(), function (n) { return domUtils.isBlockElm(n) }, true);
  18551. if (first && (/t(h|d)/i.test(first.tagName) || first === start.firstChild)) {
  18552. me.execCommand('insertparagraphbeforetable');
  18553. domUtils.preventDefault(evt);
  18554. }
  18555. }
  18556. }
  18557. }
  18558. }
  18559. if ((evt.ctrlKey || evt.metaKey) && evt.keyCode == '67') {
  18560. tableCopyList = null;
  18561. var ut = getUETableBySelected(me);
  18562. if (ut) {
  18563. var tds = ut.selectedTds;
  18564. isFullCol = ut.isFullCol();
  18565. isFullRow = ut.isFullRow();
  18566. tableCopyList = [
  18567. [ut.cloneCell(tds[0], null, true)]
  18568. ];
  18569. for (var i = 1, ci; ci = tds[i]; i++) {
  18570. if (ci.parentNode !== tds[i - 1].parentNode) {
  18571. tableCopyList.push([ut.cloneCell(ci, null, true)]);
  18572. } else {
  18573. tableCopyList[tableCopyList.length - 1].push(ut.cloneCell(ci, null, true));
  18574. }
  18575. }
  18576. }
  18577. }
  18578. });
  18579. me.addListener("tablehasdeleted", function () {
  18580. toggleDraggableState(this, false, "", null);
  18581. if (dragButton) domUtils.remove(dragButton);
  18582. });
  18583. me.addListener('beforepaste', function (cmd, html) {
  18584. var me = this;
  18585. var rng = me.selection.getRange();
  18586. if (domUtils.findParentByTagName(rng.startContainer, 'caption', true)) {
  18587. var div = me.document.createElement("div");
  18588. div.innerHTML = html.html;
  18589. //trace:3729
  18590. html.html = div[browser.ie9below ? 'innerText' : 'textContent'];
  18591. return;
  18592. }
  18593. var table = getUETableBySelected(me);
  18594. if (tableCopyList) {
  18595. me.fireEvent('saveScene');
  18596. var rng = me.selection.getRange();
  18597. var td = domUtils.findParentByTagName(rng.startContainer, ['td', 'th'], true), tmpNode, preNode;
  18598. if (td) {
  18599. var ut = getUETable(td);
  18600. if (isFullRow) {
  18601. var rowIndex = ut.getCellInfo(td).rowIndex;
  18602. if (td.tagName == 'TH') {
  18603. rowIndex++;
  18604. }
  18605. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18606. var tr = ut.insertRow(rowIndex++, "td");
  18607. for (var j = 0, cj; cj = ci[j]; j++) {
  18608. var cell = tr.cells[j];
  18609. if (!cell) {
  18610. cell = tr.insertCell(j)
  18611. }
  18612. cell.innerHTML = cj.innerHTML;
  18613. cj.getAttribute('width') && cell.setAttribute('width', cj.getAttribute('width'));
  18614. cj.getAttribute('vAlign') && cell.setAttribute('vAlign', cj.getAttribute('vAlign'));
  18615. cj.getAttribute('align') && cell.setAttribute('align', cj.getAttribute('align'));
  18616. cj.style.cssText && (cell.style.cssText = cj.style.cssText)
  18617. }
  18618. for (var j = 0, cj; cj = tr.cells[j]; j++) {
  18619. if (!ci[j])
  18620. break;
  18621. cj.innerHTML = ci[j].innerHTML;
  18622. ci[j].getAttribute('width') && cj.setAttribute('width', ci[j].getAttribute('width'));
  18623. ci[j].getAttribute('vAlign') && cj.setAttribute('vAlign', ci[j].getAttribute('vAlign'));
  18624. ci[j].getAttribute('align') && cj.setAttribute('align', ci[j].getAttribute('align'));
  18625. ci[j].style.cssText && (cj.style.cssText = ci[j].style.cssText)
  18626. }
  18627. }
  18628. } else {
  18629. if (isFullCol) {
  18630. cellInfo = ut.getCellInfo(td);
  18631. var maxColNum = 0;
  18632. for (var j = 0, ci = tableCopyList[0], cj; cj = ci[j++];) {
  18633. maxColNum += cj.colSpan || 1;
  18634. }
  18635. me.__hasEnterExecCommand = true;
  18636. for (i = 0; i < maxColNum; i++) {
  18637. me.execCommand('insertcol');
  18638. }
  18639. me.__hasEnterExecCommand = false;
  18640. td = ut.table.rows[0].cells[cellInfo.cellIndex];
  18641. if (td.tagName == 'TH') {
  18642. td = ut.table.rows[1].cells[cellInfo.cellIndex];
  18643. }
  18644. }
  18645. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18646. tmpNode = td;
  18647. for (var j = 0, cj; cj = ci[j++];) {
  18648. if (td) {
  18649. td.innerHTML = cj.innerHTML;
  18650. //todo 定制处理
  18651. cj.getAttribute('width') && td.setAttribute('width', cj.getAttribute('width'));
  18652. cj.getAttribute('vAlign') && td.setAttribute('vAlign', cj.getAttribute('vAlign'));
  18653. cj.getAttribute('align') && td.setAttribute('align', cj.getAttribute('align'));
  18654. cj.style.cssText && (td.style.cssText = cj.style.cssText);
  18655. preNode = td;
  18656. td = td.nextSibling;
  18657. } else {
  18658. var cloneTd = cj.cloneNode(true);
  18659. domUtils.removeAttributes(cloneTd, ['class', 'rowSpan', 'colSpan']);
  18660. preNode.parentNode.appendChild(cloneTd)
  18661. }
  18662. }
  18663. td = ut.getNextCell(tmpNode, true, true);
  18664. if (!tableCopyList[i])
  18665. break;
  18666. if (!td) {
  18667. var cellInfo = ut.getCellInfo(tmpNode);
  18668. ut.table.insertRow(ut.table.rows.length);
  18669. ut.update();
  18670. td = ut.getVSideCell(tmpNode, true);
  18671. }
  18672. }
  18673. }
  18674. ut.update();
  18675. } else {
  18676. table = me.document.createElement('table');
  18677. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18678. var tr = table.insertRow(table.rows.length);
  18679. for (var j = 0, cj; cj = ci[j++];) {
  18680. cloneTd = UT.cloneCell(cj, null, true);
  18681. domUtils.removeAttributes(cloneTd, ['class']);
  18682. tr.appendChild(cloneTd)
  18683. }
  18684. if (j == 2 && cloneTd.rowSpan > 1) {
  18685. cloneTd.rowSpan = 1;
  18686. }
  18687. }
  18688. var defaultValue = getDefaultValue(me),
  18689. width = me.body.offsetWidth -
  18690. (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0);
  18691. me.execCommand('insertHTML', '<table ' +
  18692. (isFullCol && isFullRow ? 'width="' + width + '"' : '') +
  18693. '>' + table.innerHTML.replace(/>\s*</g, '><').replace(/\bth\b/gi, "td") + '</table>')
  18694. }
  18695. me.fireEvent('contentchange');
  18696. me.fireEvent('saveScene');
  18697. html.html = '';
  18698. return true;
  18699. } else {
  18700. var div = me.document.createElement("div"), tables;
  18701. div.innerHTML = html.html;
  18702. tables = div.getElementsByTagName("table");
  18703. if (domUtils.findParentByTagName(me.selection.getStart(), 'table')) {
  18704. utils.each(tables, function (t) {
  18705. domUtils.remove(t)
  18706. });
  18707. if (domUtils.findParentByTagName(me.selection.getStart(), 'caption', true)) {
  18708. div.innerHTML = div[browser.ie ? 'innerText' : 'textContent'];
  18709. }
  18710. } else {
  18711. utils.each(tables, function (table) {
  18712. removeStyleSize(table, true);
  18713. domUtils.removeAttributes(table, ['style', 'border']);
  18714. utils.each(domUtils.getElementsByTagName(table, "td"), function (td) {
  18715. if (isEmptyBlock(td)) {
  18716. domUtils.fillNode(me.document, td);
  18717. }
  18718. removeStyleSize(td, true);
  18719. // domUtils.removeAttributes(td, ['style'])
  18720. });
  18721. });
  18722. }
  18723. html.html = div.innerHTML;
  18724. }
  18725. });
  18726. me.addListener('afterpaste', function () {
  18727. utils.each(domUtils.getElementsByTagName(me.body, "table"), function (table) {
  18728. if (table.offsetWidth > me.body.offsetWidth) {
  18729. var defaultValue = getDefaultValue(me, table);
  18730. table.style.width = me.body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0) + 'px'
  18731. }
  18732. })
  18733. });
  18734. me.addListener('blur', function () {
  18735. tableCopyList = null;
  18736. });
  18737. var timer;
  18738. me.addListener('keydown', function () {
  18739. clearTimeout(timer);
  18740. timer = setTimeout(function () {
  18741. var rng = me.selection.getRange(),
  18742. cell = domUtils.findParentByTagName(rng.startContainer, ['th', 'td'], true);
  18743. if (cell) {
  18744. var table = cell.parentNode.parentNode.parentNode;
  18745. if (table.offsetWidth > table.getAttribute("width")) {
  18746. cell.style.wordBreak = "break-all";
  18747. }
  18748. }
  18749. }, 100);
  18750. });
  18751. me.addListener("selectionchange", function () {
  18752. toggleDraggableState(me, false, "", null);
  18753. });
  18754. //内容变化时触发索引更新
  18755. //todo 可否考虑标记检测,如果不涉及表格的变化就不进行索引重建和更新
  18756. me.addListener("contentchange", function () {
  18757. var me = this;
  18758. //尽可能排除一些不需要更新的状况
  18759. hideDragLine(me);
  18760. if (getUETableBySelected(me)) return;
  18761. var rng = me.selection.getRange();
  18762. var start = rng.startContainer;
  18763. start = domUtils.findParentByTagName(start, ['td', 'th'], true);
  18764. utils.each(domUtils.getElementsByTagName(me.document, 'table'), function (table) {
  18765. if (me.fireEvent("excludetable", table) === true) return;
  18766. table.ueTable = new UT(table);
  18767. //trace:3742
  18768. // utils.each(domUtils.getElementsByTagName(me.document, 'td'), function (td) {
  18769. //
  18770. // if (domUtils.isEmptyBlock(td) && td !== start) {
  18771. // domUtils.fillNode(me.document, td);
  18772. // if (browser.ie && browser.version == 6) {
  18773. // td.innerHTML = '&nbsp;'
  18774. // }
  18775. // }
  18776. // });
  18777. // utils.each(domUtils.getElementsByTagName(me.document, 'th'), function (th) {
  18778. // if (domUtils.isEmptyBlock(th) && th !== start) {
  18779. // domUtils.fillNode(me.document, th);
  18780. // if (browser.ie && browser.version == 6) {
  18781. // th.innerHTML = '&nbsp;'
  18782. // }
  18783. // }
  18784. // });
  18785. table.onmouseover = function () {
  18786. me.fireEvent('tablemouseover', table);
  18787. };
  18788. table.onmousemove = function () {
  18789. me.fireEvent('tablemousemove', table);
  18790. me.options.tableDragable && toggleDragButton(true, this, me);
  18791. utils.defer(function () {
  18792. me.fireEvent('contentchange', 50)
  18793. }, true)
  18794. };
  18795. table.onmouseout = function () {
  18796. me.fireEvent('tablemouseout', table);
  18797. toggleDraggableState(me, false, "", null);
  18798. hideDragLine(me);
  18799. };
  18800. table.onclick = function (evt) {
  18801. evt = me.window.event || evt;
  18802. var target = getParentTdOrTh(evt.target || evt.srcElement);
  18803. if (!target) return;
  18804. var ut = getUETable(target),
  18805. table = ut.table,
  18806. cellInfo = ut.getCellInfo(target),
  18807. cellsRange,
  18808. rng = me.selection.getRange();
  18809. // if ("topLeft" == inPosition(table, mouseCoords(evt))) {
  18810. // cellsRange = ut.getCellsRange(ut.table.rows[0].cells[0], ut.getLastCell());
  18811. // ut.setSelected(cellsRange);
  18812. // return;
  18813. // }
  18814. // if ("bottomRight" == inPosition(table, mouseCoords(evt))) {
  18815. //
  18816. // return;
  18817. // }
  18818. if (inTableSide(table, target, evt, true)) {
  18819. var endTdCol = ut.getCell(ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].rowIndex, ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].cellIndex);
  18820. if (evt.shiftKey && ut.selectedTds.length) {
  18821. if (ut.selectedTds[0] !== endTdCol) {
  18822. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdCol);
  18823. ut.setSelected(cellsRange);
  18824. } else {
  18825. rng && rng.selectNodeContents(endTdCol).select();
  18826. }
  18827. } else {
  18828. if (target !== endTdCol) {
  18829. cellsRange = ut.getCellsRange(target, endTdCol);
  18830. ut.setSelected(cellsRange);
  18831. } else {
  18832. rng && rng.selectNodeContents(endTdCol).select();
  18833. }
  18834. }
  18835. return;
  18836. }
  18837. if (inTableSide(table, target, evt)) {
  18838. var endTdRow = ut.getCell(ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].rowIndex, ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].cellIndex);
  18839. if (evt.shiftKey && ut.selectedTds.length) {
  18840. if (ut.selectedTds[0] !== endTdRow) {
  18841. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdRow);
  18842. ut.setSelected(cellsRange);
  18843. } else {
  18844. rng && rng.selectNodeContents(endTdRow).select();
  18845. }
  18846. } else {
  18847. if (target !== endTdRow) {
  18848. cellsRange = ut.getCellsRange(target, endTdRow);
  18849. ut.setSelected(cellsRange);
  18850. } else {
  18851. rng && rng.selectNodeContents(endTdRow).select();
  18852. }
  18853. }
  18854. }
  18855. };
  18856. });
  18857. switchBorderColor(me, true);
  18858. });
  18859. domUtils.on(me.document, "mousemove", mouseMoveEvent);
  18860. domUtils.on(me.document, "mouseout", function (evt) {
  18861. var target = evt.target || evt.srcElement;
  18862. if (target.tagName == "TABLE") {
  18863. toggleDraggableState(me, false, "", null);
  18864. }
  18865. });
  18866. /**
  18867. * 表格隔行变色
  18868. */
  18869. me.addListener("interlacetable", function (type, table, classList) {
  18870. if (!table) return;
  18871. var me = this,
  18872. rows = table.rows,
  18873. len = rows.length,
  18874. getClass = function (list, index, repeat) {
  18875. return list[index] ? list[index] : repeat ? list[index % list.length] : "";
  18876. };
  18877. for (var i = 0; i < len; i++) {
  18878. rows[i].className = getClass(classList || me.options.classList, i, true);
  18879. }
  18880. });
  18881. me.addListener("uninterlacetable", function (type, table) {
  18882. if (!table) return;
  18883. var me = this,
  18884. rows = table.rows,
  18885. classList = me.options.classList,
  18886. len = rows.length;
  18887. for (var i = 0; i < len; i++) {
  18888. domUtils.removeClasses(rows[i], classList);
  18889. }
  18890. });
  18891. me.addListener("mousedown", mouseDownEvent);
  18892. me.addListener("mouseup", mouseUpEvent);
  18893. //拖动的时候触发mouseup
  18894. domUtils.on(me.body, 'dragstart', function (evt) {
  18895. mouseUpEvent.call(me, 'dragstart', evt);
  18896. });
  18897. me.addOutputRule(function (root) {
  18898. utils.each(root.getNodesByTagName('div'), function (n) {
  18899. if (n.getAttr('id') == 'ue_tableDragLine') {
  18900. n.parentNode.removeChild(n);
  18901. }
  18902. });
  18903. });
  18904. var currentRowIndex = 0;
  18905. me.addListener("mousedown", function () {
  18906. currentRowIndex = 0;
  18907. });
  18908. me.addListener('tabkeydown', function () {
  18909. var range = this.selection.getRange(),
  18910. common = range.getCommonAncestor(true, true),
  18911. table = domUtils.findParentByTagName(common, 'table');
  18912. if (table) {
  18913. if (domUtils.findParentByTagName(common, 'caption', true)) {
  18914. var cell = domUtils.getElementsByTagName(table, 'th td');
  18915. if (cell && cell.length) {
  18916. range.setStart(cell[0], 0).setCursor(false, true)
  18917. }
  18918. } else {
  18919. var cell = domUtils.findParentByTagName(common, ['td', 'th'], true),
  18920. ua = getUETable(cell);
  18921. currentRowIndex = cell.rowSpan > 1 ? currentRowIndex : ua.getCellInfo(cell).rowIndex;
  18922. var nextCell = ua.getTabNextCell(cell, currentRowIndex);
  18923. if (nextCell) {
  18924. if (isEmptyBlock(nextCell)) {
  18925. range.setStart(nextCell, 0).setCursor(false, true)
  18926. } else {
  18927. range.selectNodeContents(nextCell).select()
  18928. }
  18929. } else {
  18930. me.fireEvent('saveScene');
  18931. me.__hasEnterExecCommand = true;
  18932. this.execCommand('insertrownext');
  18933. me.__hasEnterExecCommand = false;
  18934. range = this.selection.getRange();
  18935. range.setStart(table.rows[table.rows.length - 1].cells[0], 0).setCursor();
  18936. me.fireEvent('saveScene');
  18937. }
  18938. }
  18939. return true;
  18940. }
  18941. });
  18942. browser.ie && me.addListener('selectionchange', function () {
  18943. toggleDraggableState(this, false, "", null);
  18944. });
  18945. me.addListener("keydown", function (type, evt) {
  18946. var me = this;
  18947. //处理在表格的最后一个输入tab产生新的表格
  18948. var keyCode = evt.keyCode || evt.which;
  18949. if (keyCode == 8 || keyCode == 46) {
  18950. return;
  18951. }
  18952. var notCtrlKey = !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey;
  18953. notCtrlKey && removeSelectedClass(domUtils.getElementsByTagName(me.body, "td"));
  18954. var ut = getUETableBySelected(me);
  18955. if (!ut) return;
  18956. notCtrlKey && ut.clearSelected();
  18957. });
  18958. me.addListener("beforegetcontent", function () {
  18959. switchBorderColor(this, false);
  18960. browser.ie && utils.each(this.document.getElementsByTagName('caption'), function (ci) {
  18961. if (domUtils.isEmptyNode(ci)) {
  18962. ci.innerHTML = '&nbsp;'
  18963. }
  18964. });
  18965. });
  18966. me.addListener("aftergetcontent", function () {
  18967. switchBorderColor(this, true);
  18968. });
  18969. me.addListener("getAllHtml", function () {
  18970. removeSelectedClass(me.document.getElementsByTagName("td"));
  18971. });
  18972. //修正全屏状态下插入的表格宽度在非全屏状态下撑开编辑器的情况
  18973. me.addListener("fullscreenchanged", function (type, fullscreen) {
  18974. if (!fullscreen) {
  18975. var ratio = this.body.offsetWidth / document.body.offsetWidth,
  18976. tables = domUtils.getElementsByTagName(this.body, "table");
  18977. utils.each(tables, function (table) {
  18978. if (table.offsetWidth < me.body.offsetWidth) return false;
  18979. var tds = domUtils.getElementsByTagName(table, "td"),
  18980. backWidths = [];
  18981. utils.each(tds, function (td) {
  18982. backWidths.push(td.offsetWidth);
  18983. });
  18984. for (var i = 0, td; td = tds[i]; i++) {
  18985. td.setAttribute("width", Math.floor(backWidths[i] * ratio));
  18986. }
  18987. table.setAttribute("width", Math.floor(getTableWidth(me, needIEHack, getDefaultValue(me))))
  18988. });
  18989. }
  18990. });
  18991. //重写execCommand命令,用于处理框选时的处理
  18992. var oldExecCommand = me.execCommand;
  18993. me.execCommand = function (cmd, datatat) {
  18994. var me = this,
  18995. args = arguments;
  18996. cmd = cmd.toLowerCase();
  18997. var ut = getUETableBySelected(me), tds,
  18998. range = new dom.Range(me.document),
  18999. cmdFun = me.commands[cmd] || UE.commands[cmd],
  19000. result;
  19001. if (!cmdFun) return;
  19002. if (ut && !commands[cmd] && !cmdFun.notNeedUndo && !me.__hasEnterExecCommand) {
  19003. me.__hasEnterExecCommand = true;
  19004. me.fireEvent("beforeexeccommand", cmd);
  19005. tds = ut.selectedTds;
  19006. var lastState = -2, lastValue = -2, value, state;
  19007. for (var i = 0, td; td = tds[i]; i++) {
  19008. if (isEmptyBlock(td)) {
  19009. range.setStart(td, 0).setCursor(false, true)
  19010. } else {
  19011. range.selectNode(td).select(true);
  19012. }
  19013. state = me.queryCommandState(cmd);
  19014. value = me.queryCommandValue(cmd);
  19015. if (state != -1) {
  19016. if (lastState !== state || lastValue !== value) {
  19017. me._ignoreContentChange = true;
  19018. result = oldExecCommand.apply(me, arguments);
  19019. me._ignoreContentChange = false;
  19020. }
  19021. lastState = me.queryCommandState(cmd);
  19022. lastValue = me.queryCommandValue(cmd);
  19023. if (domUtils.isEmptyBlock(td)) {
  19024. domUtils.fillNode(me.document, td)
  19025. }
  19026. }
  19027. }
  19028. range.setStart(tds[0], 0).shrinkBoundary(true).setCursor(false, true);
  19029. me.fireEvent('contentchange');
  19030. me.fireEvent("afterexeccommand", cmd);
  19031. me.__hasEnterExecCommand = false;
  19032. me._selectionChange();
  19033. } else {
  19034. result = oldExecCommand.apply(me, arguments);
  19035. }
  19036. return result;
  19037. };
  19038. });
  19039. /**
  19040. * 删除obj的宽高style,改成属性宽高
  19041. * @param obj
  19042. * @param replaceToProperty
  19043. */
  19044. function removeStyleSize(obj, replaceToProperty) {
  19045. removeStyle(obj, "width", true);
  19046. removeStyle(obj, "height", true);
  19047. }
  19048. function removeStyle(obj, styleName, replaceToProperty) {
  19049. if (obj.style[styleName]) {
  19050. replaceToProperty && obj.setAttribute(styleName, parseInt(obj.style[styleName], 10));
  19051. obj.style[styleName] = "";
  19052. }
  19053. }
  19054. function getParentTdOrTh(ele) {
  19055. if (ele.tagName == "TD" || ele.tagName == "TH") return ele;
  19056. var td;
  19057. if (td = domUtils.findParentByTagName(ele, "td", true) || domUtils.findParentByTagName(ele, "th", true)) return td;
  19058. return null;
  19059. }
  19060. function isEmptyBlock(node) {
  19061. var reg = new RegExp(domUtils.fillChar, 'g');
  19062. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  19063. return 0;
  19064. }
  19065. for (var n in dtd.$isNotEmpty) {
  19066. if (node.getElementsByTagName(n).length) {
  19067. return 0;
  19068. }
  19069. }
  19070. return 1;
  19071. }
  19072. function mouseCoords(evt) {
  19073. if (evt.pageX || evt.pageY) {
  19074. return { x: evt.pageX, y: evt.pageY };
  19075. }
  19076. return {
  19077. x: evt.clientX + me.document.body.scrollLeft - me.document.body.clientLeft,
  19078. y: evt.clientY + me.document.body.scrollTop - me.document.body.clientTop
  19079. };
  19080. }
  19081. function mouseMoveEvent(evt) {
  19082. if (isEditorDisabled()) {
  19083. return;
  19084. }
  19085. try {
  19086. //普通状态下鼠标移动
  19087. var target = getParentTdOrTh(evt.target || evt.srcElement),
  19088. pos;
  19089. //区分用户的行为是拖动还是双击
  19090. if (isInResizeBuffer) {
  19091. me.body.style.webkitUserSelect = 'none';
  19092. if (Math.abs(userActionStatus.x - evt.clientX) > offsetOfTableCell || Math.abs(userActionStatus.y - evt.clientY) > offsetOfTableCell) {
  19093. clearTableDragTimer();
  19094. isInResizeBuffer = false;
  19095. singleClickState = 0;
  19096. //drag action
  19097. tableBorderDrag(evt);
  19098. }
  19099. }
  19100. //修改单元格大小时的鼠标移动
  19101. if (onDrag && dragTd) {
  19102. singleClickState = 0;
  19103. me.body.style.webkitUserSelect = 'none';
  19104. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19105. pos = mouseCoords(evt);
  19106. toggleDraggableState(me, true, onDrag, pos, target);
  19107. if (onDrag == "h") {
  19108. dragLine.style.left = getPermissionX(dragTd, evt) + "px";
  19109. } else if (onDrag == "v") {
  19110. dragLine.style.top = getPermissionY(dragTd, evt) + "px";
  19111. }
  19112. return;
  19113. }
  19114. //当鼠标处于table上时,修改移动过程中的光标状态
  19115. if (target) {
  19116. //针对使用table作为容器的组件不触发拖拽效果
  19117. if (me.fireEvent('excludetable', target) === true)
  19118. return;
  19119. pos = mouseCoords(evt);
  19120. var state = getRelation(target, pos),
  19121. table = domUtils.findParentByTagName(target, "table", true);
  19122. if (inTableSide(table, target, evt, true)) {
  19123. if (me.fireEvent("excludetable", table) === true) return;
  19124. me.body.style.cursor = "url(" + me.options.cursorpath + "h.png),pointer";
  19125. } else if (inTableSide(table, target, evt)) {
  19126. if (me.fireEvent("excludetable", table) === true) return;
  19127. me.body.style.cursor = "url(" + me.options.cursorpath + "v.png),pointer";
  19128. } else {
  19129. me.body.style.cursor = "text";
  19130. var curCell = target;
  19131. if (/\d/.test(state)) {
  19132. state = state.replace(/\d/, '');
  19133. target = getUETable(target).getPreviewCell(target, state == "v");
  19134. }
  19135. //位于第一行的顶部或者第一列的左边时不可拖动
  19136. toggleDraggableState(me, target ? !!state : false, target ? state : '', pos, target);
  19137. }
  19138. } else {
  19139. toggleDragButton(false, table, me);
  19140. }
  19141. } catch (e) {
  19142. showError(e);
  19143. }
  19144. }
  19145. var dragButtonTimer;
  19146. function toggleDragButton(show, table, editor) {
  19147. if (!show) {
  19148. if (dragOver) return;
  19149. dragButtonTimer = setTimeout(function () {
  19150. !dragOver && dragButton && dragButton.parentNode && dragButton.parentNode.removeChild(dragButton);
  19151. }, 2000);
  19152. } else {
  19153. createDragButton(table, editor);
  19154. }
  19155. }
  19156. function createDragButton(table, editor) {
  19157. var pos = domUtils.getXY(table),
  19158. doc = table.ownerDocument;
  19159. if (dragButton && dragButton.parentNode) return dragButton;
  19160. dragButton = doc.createElement("div");
  19161. dragButton.contentEditable = false;
  19162. dragButton.innerHTML = "";
  19163. dragButton.style.cssText = "width:15px;height:15px;background-image:url(" + editor.options.UEDITOR_HOME_URL + "dialogs/table/dragicon.png);position: absolute;cursor:move;top:" + (pos.y - 15) + "px;left:" + (pos.x) + "px;";
  19164. domUtils.unSelectable(dragButton);
  19165. dragButton.onmouseover = function (evt) {
  19166. dragOver = true;
  19167. };
  19168. dragButton.onmouseout = function (evt) {
  19169. dragOver = false;
  19170. };
  19171. domUtils.on(dragButton, 'click', function (type, evt) {
  19172. doClick(evt, this);
  19173. });
  19174. domUtils.on(dragButton, 'dblclick', function (type, evt) {
  19175. doDblClick(evt);
  19176. });
  19177. domUtils.on(dragButton, 'dragstart', function (type, evt) {
  19178. domUtils.preventDefault(evt);
  19179. });
  19180. var timer;
  19181. function doClick(evt, button) {
  19182. // 部分浏览器下需要清理
  19183. clearTimeout(timer);
  19184. timer = setTimeout(function () {
  19185. editor.fireEvent("tableClicked", table, button);
  19186. }, 300);
  19187. }
  19188. function doDblClick(evt) {
  19189. clearTimeout(timer);
  19190. var ut = getUETable(table),
  19191. start = table.rows[0].cells[0],
  19192. end = ut.getLastCell(),
  19193. range = ut.getCellsRange(start, end);
  19194. editor.selection.getRange().setStart(start, 0).setCursor(false, true);
  19195. ut.setSelected(range);
  19196. }
  19197. doc.body.appendChild(dragButton);
  19198. }
  19199. // function inPosition(table, pos) {
  19200. // var tablePos = domUtils.getXY(table),
  19201. // width = table.offsetWidth,
  19202. // height = table.offsetHeight;
  19203. // if (pos.x - tablePos.x < 5 && pos.y - tablePos.y < 5) {
  19204. // return "topLeft";
  19205. // } else if (tablePos.x + width - pos.x < 5 && tablePos.y + height - pos.y < 5) {
  19206. // return "bottomRight";
  19207. // }
  19208. // }
  19209. function inTableSide(table, cell, evt, top) {
  19210. var pos = mouseCoords(evt),
  19211. state = getRelation(cell, pos);
  19212. if (top) {
  19213. var caption = table.getElementsByTagName("caption")[0],
  19214. capHeight = caption ? caption.offsetHeight : 0;
  19215. return (state == "v1") && ((pos.y - domUtils.getXY(table).y - capHeight) < 8);
  19216. } else {
  19217. return (state == "h1") && ((pos.x - domUtils.getXY(table).x) < 8);
  19218. }
  19219. }
  19220. /**
  19221. * 获取拖动时允许的X轴坐标
  19222. * @param dragTd
  19223. * @param evt
  19224. */
  19225. function getPermissionX(dragTd, evt) {
  19226. var ut = getUETable(dragTd);
  19227. if (ut) {
  19228. var preTd = ut.getSameEndPosCells(dragTd, "x")[0],
  19229. nextTd = ut.getSameStartPosXCells(dragTd)[0],
  19230. mouseX = mouseCoords(evt).x,
  19231. left = (preTd ? domUtils.getXY(preTd).x : domUtils.getXY(ut.table).x) + 20,
  19232. right = nextTd ? domUtils.getXY(nextTd).x + nextTd.offsetWidth - 20 : (me.body.offsetWidth + 5 || parseInt(domUtils.getComputedStyle(me.body, "width"), 10));
  19233. left += cellMinWidth;
  19234. right -= cellMinWidth;
  19235. return mouseX < left ? left : mouseX > right ? right : mouseX;
  19236. }
  19237. }
  19238. /**
  19239. * 获取拖动时允许的Y轴坐标
  19240. */
  19241. function getPermissionY(dragTd, evt) {
  19242. try {
  19243. var top = domUtils.getXY(dragTd).y,
  19244. mousePosY = mouseCoords(evt).y;
  19245. return mousePosY < top ? top : mousePosY;
  19246. } catch (e) {
  19247. showError(e);
  19248. }
  19249. }
  19250. /**
  19251. * 移动状态切换
  19252. */
  19253. function toggleDraggableState(editor, draggable, dir, mousePos, cell) {
  19254. try {
  19255. editor.body.style.cursor = dir == "h" ? "col-resize" : dir == "v" ? "row-resize" : "text";
  19256. if (browser.ie) {
  19257. if (dir && !mousedown && !getUETableBySelected(editor)) {
  19258. getDragLine(editor, editor.document);
  19259. showDragLineAt(dir, cell);
  19260. } else {
  19261. hideDragLine(editor)
  19262. }
  19263. }
  19264. onBorder = draggable;
  19265. } catch (e) {
  19266. showError(e);
  19267. }
  19268. }
  19269. /**
  19270. * 获取与UETable相关的resize line
  19271. * @param uetable UETable对象
  19272. */
  19273. function getResizeLineByUETable() {
  19274. var lineId = '_UETableResizeLine',
  19275. line = this.document.getElementById(lineId);
  19276. if (!line) {
  19277. line = this.document.createElement("div");
  19278. line.id = lineId;
  19279. line.contnetEditable = false;
  19280. line.setAttribute("unselectable", "on");
  19281. var styles = {
  19282. width: 2 * cellBorderWidth + 1 + 'px',
  19283. position: 'absolute',
  19284. 'z-index': 100000,
  19285. cursor: 'col-resize',
  19286. background: 'red',
  19287. display: 'none'
  19288. };
  19289. //切换状态
  19290. line.onmouseout = function () {
  19291. this.style.display = 'none';
  19292. };
  19293. utils.extend(line.style, styles);
  19294. this.document.body.appendChild(line);
  19295. }
  19296. return line;
  19297. }
  19298. /**
  19299. * 更新resize-line
  19300. */
  19301. function updateResizeLine(cell, uetable) {
  19302. var line = getResizeLineByUETable.call(this),
  19303. table = uetable.table,
  19304. styles = {
  19305. top: domUtils.getXY(table).y + 'px',
  19306. left: domUtils.getXY(cell).x + cell.offsetWidth - cellBorderWidth + 'px',
  19307. display: 'block',
  19308. height: table.offsetHeight + 'px'
  19309. };
  19310. utils.extend(line.style, styles);
  19311. }
  19312. /**
  19313. * 显示resize-line
  19314. */
  19315. function showResizeLine(cell) {
  19316. var uetable = getUETable(cell);
  19317. updateResizeLine.call(this, cell, uetable);
  19318. }
  19319. /**
  19320. * 获取鼠标与当前单元格的相对位置
  19321. * @param ele
  19322. * @param mousePos
  19323. */
  19324. function getRelation(ele, mousePos) {
  19325. var elePos = domUtils.getXY(ele);
  19326. if (!elePos) {
  19327. return '';
  19328. }
  19329. if (elePos.x + ele.offsetWidth - mousePos.x < cellBorderWidth) {
  19330. return "h";
  19331. }
  19332. if (mousePos.x - elePos.x < cellBorderWidth) {
  19333. return 'h1'
  19334. }
  19335. if (elePos.y + ele.offsetHeight - mousePos.y < cellBorderWidth) {
  19336. return "v";
  19337. }
  19338. if (mousePos.y - elePos.y < cellBorderWidth) {
  19339. return 'v1'
  19340. }
  19341. return '';
  19342. }
  19343. function mouseDownEvent(type, evt) {
  19344. if (isEditorDisabled()) {
  19345. return;
  19346. }
  19347. userActionStatus = {
  19348. x: evt.clientX,
  19349. y: evt.clientY
  19350. };
  19351. //右键菜单单独处理
  19352. if (evt.button == 2) {
  19353. var ut = getUETableBySelected(me),
  19354. flag = false;
  19355. if (ut) {
  19356. var td = getTargetTd(me, evt);
  19357. utils.each(ut.selectedTds, function (ti) {
  19358. if (ti === td) {
  19359. flag = true;
  19360. }
  19361. });
  19362. if (!flag) {
  19363. removeSelectedClass(domUtils.getElementsByTagName(me.body, "th td"));
  19364. ut.clearSelected()
  19365. } else {
  19366. td = ut.selectedTds[0];
  19367. setTimeout(function () {
  19368. me.selection.getRange().setStart(td, 0).setCursor(false, true);
  19369. }, 0);
  19370. }
  19371. }
  19372. } else {
  19373. tableClickHander(evt);
  19374. }
  19375. }
  19376. //清除表格的计时器
  19377. function clearTableTimer() {
  19378. tabTimer && clearTimeout(tabTimer);
  19379. tabTimer = null;
  19380. }
  19381. //双击收缩
  19382. function tableDbclickHandler(evt) {
  19383. singleClickState = 0;
  19384. evt = evt || me.window.event;
  19385. var target = getParentTdOrTh(evt.target || evt.srcElement);
  19386. if (target) {
  19387. var h;
  19388. if (h = getRelation(target, mouseCoords(evt))) {
  19389. hideDragLine(me);
  19390. if (h == 'h1') {
  19391. h = 'h';
  19392. if (inTableSide(domUtils.findParentByTagName(target, "table"), target, evt)) {
  19393. me.execCommand('adaptbywindow');
  19394. } else {
  19395. target = getUETable(target).getPreviewCell(target);
  19396. if (target) {
  19397. var rng = me.selection.getRange();
  19398. rng.selectNodeContents(target).setCursor(true, true)
  19399. }
  19400. }
  19401. }
  19402. if (h == 'h') {
  19403. var ut = getUETable(target),
  19404. table = ut.table,
  19405. cells = getCellsByMoveBorder(target, table, true);
  19406. cells = extractArray(cells, 'left');
  19407. ut.width = ut.offsetWidth;
  19408. var oldWidth = [],
  19409. newWidth = [];
  19410. utils.each(cells, function (cell) {
  19411. oldWidth.push(cell.offsetWidth);
  19412. });
  19413. utils.each(cells, function (cell) {
  19414. cell.removeAttribute("width");
  19415. });
  19416. window.setTimeout(function () {
  19417. //是否允许改变
  19418. var changeable = true;
  19419. utils.each(cells, function (cell, index) {
  19420. var width = cell.offsetWidth;
  19421. if (width > oldWidth[index]) {
  19422. changeable = false;
  19423. return false;
  19424. }
  19425. newWidth.push(width);
  19426. });
  19427. var change = changeable ? newWidth : oldWidth;
  19428. utils.each(cells, function (cell, index) {
  19429. cell.width = change[index] - getTabcellSpace();
  19430. });
  19431. }, 0);
  19432. // minWidth -= cellMinWidth;
  19433. //
  19434. // table.removeAttribute("width");
  19435. // utils.each(cells, function (cell) {
  19436. // cell.style.width = "";
  19437. // cell.width -= minWidth;
  19438. // });
  19439. }
  19440. }
  19441. }
  19442. }
  19443. function tableClickHander(evt) {
  19444. removeSelectedClass(domUtils.getElementsByTagName(me.body, "td th"));
  19445. //trace:3113
  19446. //选中单元格,点击table外部,不会清掉table上挂的ueTable,会引起getUETableBySelected方法返回值
  19447. utils.each(me.document.getElementsByTagName('table'), function (t) {
  19448. t.ueTable = null;
  19449. });
  19450. startTd = getTargetTd(me, evt);
  19451. if (!startTd) return;
  19452. var table = domUtils.findParentByTagName(startTd, "table", true);
  19453. ut = getUETable(table);
  19454. ut && ut.clearSelected();
  19455. //判断当前鼠标状态
  19456. if (!onBorder) {
  19457. me.document.body.style.webkitUserSelect = '';
  19458. mousedown = true;
  19459. me.addListener('mouseover', mouseOverEvent);
  19460. } else {
  19461. //边框上的动作处理
  19462. borderActionHandler(evt);
  19463. }
  19464. }
  19465. //处理表格边框上的动作, 这里做延时处理,避免两种动作互相影响
  19466. function borderActionHandler(evt) {
  19467. if (browser.ie) {
  19468. evt = reconstruct(evt);
  19469. }
  19470. clearTableDragTimer();
  19471. //是否正在等待resize的缓冲中
  19472. isInResizeBuffer = true;
  19473. tableDragTimer = setTimeout(function () {
  19474. tableBorderDrag(evt);
  19475. }, dblclickTime);
  19476. }
  19477. function extractArray(originArr, key) {
  19478. var result = [],
  19479. tmp = null;
  19480. for (var i = 0, len = originArr.length; i < len; i++) {
  19481. tmp = originArr[i][key];
  19482. if (tmp) {
  19483. result.push(tmp);
  19484. }
  19485. }
  19486. return result;
  19487. }
  19488. function clearTableDragTimer() {
  19489. tableDragTimer && clearTimeout(tableDragTimer);
  19490. tableDragTimer = null;
  19491. }
  19492. function reconstruct(obj) {
  19493. var attrs = ['pageX', 'pageY', 'clientX', 'clientY', 'srcElement', 'target'],
  19494. newObj = {};
  19495. if (obj) {
  19496. for (var i = 0, key, val; key = attrs[i]; i++) {
  19497. val = obj[key];
  19498. val && (newObj[key] = val);
  19499. }
  19500. }
  19501. return newObj;
  19502. }
  19503. //边框拖动
  19504. function tableBorderDrag(evt) {
  19505. isInResizeBuffer = false;
  19506. startTd = evt.target || evt.srcElement;
  19507. if (!startTd) return;
  19508. var state = getRelation(startTd, mouseCoords(evt));
  19509. if (/\d/.test(state)) {
  19510. state = state.replace(/\d/, '');
  19511. startTd = getUETable(startTd).getPreviewCell(startTd, state == 'v');
  19512. }
  19513. hideDragLine(me);
  19514. getDragLine(me, me.document);
  19515. me.fireEvent('saveScene');
  19516. showDragLineAt(state, startTd);
  19517. mousedown = true;
  19518. //拖动开始
  19519. onDrag = state;
  19520. dragTd = startTd;
  19521. }
  19522. function mouseUpEvent(type, evt) {
  19523. if (isEditorDisabled()) {
  19524. return;
  19525. }
  19526. clearTableDragTimer();
  19527. isInResizeBuffer = false;
  19528. if (onBorder) {
  19529. singleClickState = ++singleClickState % 3;
  19530. userActionStatus = {
  19531. x: evt.clientX,
  19532. y: evt.clientY
  19533. };
  19534. tableResizeTimer = setTimeout(function () {
  19535. singleClickState > 0 && singleClickState--;
  19536. }, dblclickTime);
  19537. if (singleClickState === 2) {
  19538. singleClickState = 0;
  19539. tableDbclickHandler(evt);
  19540. return;
  19541. }
  19542. }
  19543. if (evt.button == 2) return;
  19544. var me = this;
  19545. //清除表格上原生跨选问题
  19546. var range = me.selection.getRange(),
  19547. start = domUtils.findParentByTagName(range.startContainer, 'table', true),
  19548. end = domUtils.findParentByTagName(range.endContainer, 'table', true);
  19549. if (start || end) {
  19550. if (start === end) {
  19551. start = domUtils.findParentByTagName(range.startContainer, ['td', 'th', 'caption'], true);
  19552. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th', 'caption'], true);
  19553. if (start !== end) {
  19554. me.selection.clearRange()
  19555. }
  19556. } else {
  19557. me.selection.clearRange()
  19558. }
  19559. }
  19560. mousedown = false;
  19561. me.document.body.style.webkitUserSelect = '';
  19562. //拖拽状态下的mouseUP
  19563. if (onDrag && dragTd) {
  19564. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19565. singleClickState = 0;
  19566. dragLine = me.document.getElementById('ue_tableDragLine');
  19567. // trace 3973
  19568. if (dragLine) {
  19569. var dragTdPos = domUtils.getXY(dragTd),
  19570. dragLinePos = domUtils.getXY(dragLine);
  19571. switch (onDrag) {
  19572. case "h":
  19573. changeColWidth(dragTd, dragLinePos.x - dragTdPos.x);
  19574. break;
  19575. case "v":
  19576. changeRowHeight(dragTd, dragLinePos.y - dragTdPos.y - dragTd.offsetHeight);
  19577. break;
  19578. default:
  19579. }
  19580. onDrag = "";
  19581. dragTd = null;
  19582. hideDragLine(me);
  19583. me.fireEvent('saveScene');
  19584. return;
  19585. }
  19586. }
  19587. //正常状态下的mouseup
  19588. if (!startTd) {
  19589. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, "td", true);
  19590. if (!target) target = domUtils.findParentByTagName(evt.target || evt.srcElement, "th", true);
  19591. if (target && (target.tagName == "TD" || target.tagName == "TH")) {
  19592. if (me.fireEvent("excludetable", target) === true) return;
  19593. range = new dom.Range(me.document);
  19594. range.setStart(target, 0).setCursor(false, true);
  19595. }
  19596. } else {
  19597. var ut = getUETable(startTd),
  19598. cell = ut ? ut.selectedTds[0] : null;
  19599. if (cell) {
  19600. range = new dom.Range(me.document);
  19601. if (domUtils.isEmptyBlock(cell)) {
  19602. range.setStart(cell, 0).setCursor(false, true);
  19603. } else {
  19604. range.selectNodeContents(cell).shrinkBoundary().setCursor(false, true);
  19605. }
  19606. } else {
  19607. range = me.selection.getRange().shrinkBoundary();
  19608. if (!range.collapsed) {
  19609. var start = domUtils.findParentByTagName(range.startContainer, ['td', 'th'], true),
  19610. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th'], true);
  19611. //在table里边的不能清除
  19612. if (start && !end || !start && end || start && end && start !== end) {
  19613. range.setCursor(false, true);
  19614. }
  19615. }
  19616. }
  19617. startTd = null;
  19618. me.removeListener('mouseover', mouseOverEvent);
  19619. }
  19620. me._selectionChange(250, evt);
  19621. }
  19622. function mouseOverEvent(type, evt) {
  19623. if (isEditorDisabled()) {
  19624. return;
  19625. }
  19626. var me = this,
  19627. tar = evt.target || evt.srcElement;
  19628. currentTd = domUtils.findParentByTagName(tar, "td", true) || domUtils.findParentByTagName(tar, "th", true);
  19629. //需要判断两个TD是否位于同一个表格内
  19630. if (startTd && currentTd &&
  19631. ((startTd.tagName == "TD" && currentTd.tagName == "TD") || (startTd.tagName == "TH" && currentTd.tagName == "TH")) &&
  19632. domUtils.findParentByTagName(startTd, 'table') == domUtils.findParentByTagName(currentTd, 'table')) {
  19633. var ut = getUETable(currentTd);
  19634. if (startTd != currentTd) {
  19635. me.document.body.style.webkitUserSelect = 'none';
  19636. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19637. var range = ut.getCellsRange(startTd, currentTd);
  19638. ut.setSelected(range);
  19639. } else {
  19640. me.document.body.style.webkitUserSelect = '';
  19641. ut.clearSelected();
  19642. }
  19643. }
  19644. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  19645. }
  19646. function setCellHeight(cell, height, backHeight) {
  19647. var lineHight = parseInt(domUtils.getComputedStyle(cell, "line-height"), 10),
  19648. tmpHeight = backHeight + height;
  19649. height = tmpHeight < lineHight ? lineHight : tmpHeight;
  19650. if (cell.style.height) cell.style.height = "";
  19651. cell.rowSpan == 1 ? cell.setAttribute("height", height) : (cell.removeAttribute && cell.removeAttribute("height"));
  19652. }
  19653. function getWidth(cell) {
  19654. if (!cell) return 0;
  19655. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  19656. }
  19657. function changeColWidth(cell, changeValue) {
  19658. var ut = getUETable(cell);
  19659. if (ut) {
  19660. //根据当前移动的边框获取相关的单元格
  19661. var table = ut.table,
  19662. cells = getCellsByMoveBorder(cell, table);
  19663. table.style.width = "";
  19664. table.removeAttribute("width");
  19665. //修正改变量
  19666. changeValue = correctChangeValue(changeValue, cell, cells);
  19667. if (cell.nextSibling) {
  19668. var i = 0;
  19669. utils.each(cells, function (cellGroup) {
  19670. cellGroup.left.width = (+cellGroup.left.width) + changeValue;
  19671. cellGroup.right && (cellGroup.right.width = (+cellGroup.right.width) - changeValue);
  19672. });
  19673. } else {
  19674. utils.each(cells, function (cellGroup) {
  19675. cellGroup.left.width -= -changeValue;
  19676. });
  19677. }
  19678. }
  19679. }
  19680. function isEditorDisabled() {
  19681. return me.body.contentEditable === "false";
  19682. }
  19683. function changeRowHeight(td, changeValue) {
  19684. if (Math.abs(changeValue) < 10) return;
  19685. var ut = getUETable(td);
  19686. if (ut) {
  19687. var cells = ut.getSameEndPosCells(td, "y"),
  19688. //备份需要连带变化的td的原始高度,否则后期无法获取正确的值
  19689. backHeight = cells[0] ? cells[0].offsetHeight : 0;
  19690. for (var i = 0, cell; cell = cells[i++];) {
  19691. setCellHeight(cell, changeValue, backHeight);
  19692. }
  19693. }
  19694. }
  19695. /**
  19696. * 获取调整单元格大小的相关单元格
  19697. * @isContainMergeCell 返回的结果中是否包含发生合并后的单元格
  19698. */
  19699. function getCellsByMoveBorder(cell, table, isContainMergeCell) {
  19700. if (!table) {
  19701. table = domUtils.findParentByTagName(cell, 'table');
  19702. }
  19703. if (!table) {
  19704. return null;
  19705. }
  19706. //获取到该单元格所在行的序列号
  19707. var index = domUtils.getNodeIndex(cell),
  19708. temp = cell,
  19709. rows = table.rows,
  19710. colIndex = 0;
  19711. while (temp) {
  19712. //获取到当前单元格在未发生单元格合并时的序列
  19713. if (temp.nodeType === 1) {
  19714. colIndex += (temp.colSpan || 1);
  19715. }
  19716. temp = temp.previousSibling;
  19717. }
  19718. temp = null;
  19719. //记录想关的单元格
  19720. var borderCells = [];
  19721. utils.each(rows, function (tabRow) {
  19722. var cells = tabRow.cells,
  19723. currIndex = 0;
  19724. utils.each(cells, function (tabCell) {
  19725. currIndex += (tabCell.colSpan || 1);
  19726. if (currIndex === colIndex) {
  19727. borderCells.push({
  19728. left: tabCell,
  19729. right: tabCell.nextSibling || null
  19730. });
  19731. return false;
  19732. } else if (currIndex > colIndex) {
  19733. if (isContainMergeCell) {
  19734. borderCells.push({
  19735. left: tabCell
  19736. });
  19737. }
  19738. return false;
  19739. }
  19740. });
  19741. });
  19742. return borderCells;
  19743. }
  19744. /**
  19745. * 通过给定的单元格集合获取最小的单元格width
  19746. */
  19747. function getMinWidthByTableCells(cells) {
  19748. var minWidth = Number.MAX_VALUE;
  19749. for (var i = 0, curCell; curCell = cells[i]; i++) {
  19750. minWidth = Math.min(minWidth, curCell.width || getTableCellWidth(curCell));
  19751. }
  19752. return minWidth;
  19753. }
  19754. function correctChangeValue(changeValue, relatedCell, cells) {
  19755. //为单元格的paading预留空间
  19756. changeValue -= getTabcellSpace();
  19757. if (changeValue < 0) {
  19758. return 0;
  19759. }
  19760. changeValue -= getTableCellWidth(relatedCell);
  19761. //确定方向
  19762. var direction = changeValue < 0 ? 'left' : 'right';
  19763. changeValue = Math.abs(changeValue);
  19764. //只关心非最后一个单元格就可以
  19765. utils.each(cells, function (cellGroup) {
  19766. var curCell = cellGroup[direction];
  19767. //为单元格保留最小空间
  19768. if (curCell) {
  19769. changeValue = Math.min(changeValue, getTableCellWidth(curCell) - cellMinWidth);
  19770. }
  19771. });
  19772. //修正越界
  19773. changeValue = changeValue < 0 ? 0 : changeValue;
  19774. return direction === 'left' ? -changeValue : changeValue;
  19775. }
  19776. function getTableCellWidth(cell) {
  19777. var width = 0,
  19778. //偏移纠正量
  19779. offset = 0,
  19780. width = cell.offsetWidth - getTabcellSpace();
  19781. //最后一个节点纠正一下
  19782. if (!cell.nextSibling) {
  19783. width -= getTableCellOffset(cell);
  19784. }
  19785. width = width < 0 ? 0 : width;
  19786. try {
  19787. cell.width = width;
  19788. } catch (e) {
  19789. }
  19790. return width;
  19791. }
  19792. /**
  19793. * 获取单元格所在表格的最末单元格的偏移量
  19794. */
  19795. function getTableCellOffset(cell) {
  19796. tab = domUtils.findParentByTagName(cell, "table", false);
  19797. if (tab.offsetVal === undefined) {
  19798. var prev = cell.previousSibling;
  19799. if (prev) {
  19800. //最后一个单元格和前一个单元格的width diff结果 如果恰好为一个border width, 则条件成立
  19801. tab.offsetVal = cell.offsetWidth - prev.offsetWidth === UT.borderWidth ? UT.borderWidth : 0;
  19802. } else {
  19803. tab.offsetVal = 0;
  19804. }
  19805. }
  19806. return tab.offsetVal;
  19807. }
  19808. function getTabcellSpace() {
  19809. if (UT.tabcellSpace === undefined) {
  19810. var cell = null,
  19811. tab = me.document.createElement("table"),
  19812. tbody = me.document.createElement("tbody"),
  19813. trow = me.document.createElement("tr"),
  19814. tabcell = me.document.createElement("td"),
  19815. mirror = null;
  19816. tabcell.style.cssText = 'border: 0;';
  19817. tabcell.width = 1;
  19818. trow.appendChild(tabcell);
  19819. trow.appendChild(mirror = tabcell.cloneNode(false));
  19820. tbody.appendChild(trow);
  19821. tab.appendChild(tbody);
  19822. tab.style.cssText = "visibility: hidden;";
  19823. me.body.appendChild(tab);
  19824. UT.paddingSpace = tabcell.offsetWidth - 1;
  19825. var tmpTabWidth = tab.offsetWidth;
  19826. tabcell.style.cssText = '';
  19827. mirror.style.cssText = '';
  19828. UT.borderWidth = (tab.offsetWidth - tmpTabWidth) / 3;
  19829. UT.tabcellSpace = UT.paddingSpace + UT.borderWidth;
  19830. me.body.removeChild(tab);
  19831. }
  19832. getTabcellSpace = function () { return UT.tabcellSpace; };
  19833. return UT.tabcellSpace;
  19834. }
  19835. function getDragLine(editor, doc) {
  19836. if (mousedown) return;
  19837. dragLine = editor.document.createElement("div");
  19838. domUtils.setAttributes(dragLine, {
  19839. id: "ue_tableDragLine",
  19840. unselectable: 'on',
  19841. contenteditable: false,
  19842. 'onresizestart': 'return false',
  19843. 'ondragstart': 'return false',
  19844. 'onselectstart': 'return false',
  19845. style: "background-color:blue;position:absolute;padding:0;margin:0;background-image:none;border:0px none;opacity:0;filter:alpha(opacity=0)"
  19846. });
  19847. editor.body.appendChild(dragLine);
  19848. }
  19849. function hideDragLine(editor) {
  19850. if (mousedown) return;
  19851. var line;
  19852. while (line = editor.document.getElementById('ue_tableDragLine')) {
  19853. domUtils.remove(line)
  19854. }
  19855. }
  19856. /**
  19857. * 依据state(v|h)在cell位置显示横线
  19858. * @param state
  19859. * @param cell
  19860. */
  19861. function showDragLineAt(state, cell) {
  19862. if (!cell) return;
  19863. var table = domUtils.findParentByTagName(cell, "table"),
  19864. caption = table.getElementsByTagName('caption'),
  19865. width = table.offsetWidth,
  19866. height = table.offsetHeight - (caption.length > 0 ? caption[0].offsetHeight : 0),
  19867. tablePos = domUtils.getXY(table),
  19868. cellPos = domUtils.getXY(cell), css;
  19869. switch (state) {
  19870. case "h":
  19871. css = 'height:' + height + 'px;top:' + (tablePos.y + (caption.length > 0 ? caption[0].offsetHeight : 0)) + 'px;left:' + (cellPos.x + cell.offsetWidth);
  19872. dragLine.style.cssText = css + 'px;position: absolute;display:block;background-color:blue;width:1px;border:0; color:blue;opacity:.3;filter:alpha(opacity=30)';
  19873. break;
  19874. case "v":
  19875. css = 'width:' + width + 'px;left:' + tablePos.x + 'px;top:' + (cellPos.y + cell.offsetHeight);
  19876. //必须加上border:0和color:blue,否则低版ie不支持背景色显示
  19877. dragLine.style.cssText = css + 'px;overflow:hidden;position: absolute;display:block;background-color:blue;height:1px;border:0;color:blue;opacity:.2;filter:alpha(opacity=20)';
  19878. break;
  19879. default:
  19880. }
  19881. }
  19882. /**
  19883. * 当表格边框颜色为白色时设置为虚线,true为添加虚线
  19884. * @param editor
  19885. * @param flag
  19886. */
  19887. function switchBorderColor(editor, flag) {
  19888. var tableArr = domUtils.getElementsByTagName(editor.body, "table"), color;
  19889. for (var i = 0, node; node = tableArr[i++];) {
  19890. var td = domUtils.getElementsByTagName(node, "td");
  19891. if (td[0]) {
  19892. if (flag) {
  19893. color = (td[0].style.borderColor).replace(/\s/g, "");
  19894. if (/(#ffffff)|(rgb\(255,255,255\))/ig.test(color))
  19895. domUtils.addClass(node, "noBorderTable")
  19896. } else {
  19897. domUtils.removeClasses(node, "noBorderTable")
  19898. }
  19899. }
  19900. }
  19901. }
  19902. function getTableWidth(editor, needIEHack, defaultValue) {
  19903. var body = editor.body;
  19904. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  19905. }
  19906. /**
  19907. * 获取当前拖动的单元格
  19908. */
  19909. function getTargetTd(editor, evt) {
  19910. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, ["td", "th"], true),
  19911. dir = null;
  19912. if (!target) {
  19913. return null;
  19914. }
  19915. dir = getRelation(target, mouseCoords(evt));
  19916. //如果有前一个节点, 需要做一个修正, 否则可能会得到一个错误的td
  19917. if (!target) {
  19918. return null;
  19919. }
  19920. if (dir === 'h1' && target.previousSibling) {
  19921. var position = domUtils.getXY(target),
  19922. cellWidth = target.offsetWidth;
  19923. if (Math.abs(position.x + cellWidth - evt.clientX) > cellWidth / 3) {
  19924. target = target.previousSibling;
  19925. }
  19926. } else if (dir === 'v1' && target.parentNode.previousSibling) {
  19927. var position = domUtils.getXY(target),
  19928. cellHeight = target.offsetHeight;
  19929. if (Math.abs(position.y + cellHeight - evt.clientY) > cellHeight / 3) {
  19930. target = target.parentNode.previousSibling.firstChild;
  19931. }
  19932. }
  19933. //排除了非td内部以及用于代码高亮部分的td
  19934. return target && !(editor.fireEvent("excludetable", target) === true) ? target : null;
  19935. }
  19936. };
  19937. // plugins/table.sort.js
  19938. /**
  19939. * Created with JetBrains PhpStorm.
  19940. * User: Jinqn
  19941. * Date: 13-10-12
  19942. * Time: 上午10:20
  19943. * To change this template use File | Settings | File Templates.
  19944. */
  19945. UE.UETable.prototype.sortTable = function (sortByCellIndex, compareFn) {
  19946. var table = this.table,
  19947. rows = table.rows,
  19948. trArray = [],
  19949. flag = rows[0].cells[0].tagName === "TH",
  19950. lastRowIndex = 0;
  19951. if (this.selectedTds.length) {
  19952. var range = this.cellsRange,
  19953. len = range.endRowIndex + 1;
  19954. for (var i = range.beginRowIndex; i < len; i++) {
  19955. trArray[i] = rows[i];
  19956. }
  19957. trArray.splice(0, range.beginRowIndex);
  19958. lastRowIndex = (range.endRowIndex + 1) === this.rowsNum ? 0 : range.endRowIndex + 1;
  19959. } else {
  19960. for (var i = 0, len = rows.length; i < len; i++) {
  19961. trArray[i] = rows[i];
  19962. }
  19963. }
  19964. var Fn = {
  19965. 'reversecurrent': function (td1, td2) {
  19966. return 1;
  19967. },
  19968. 'orderbyasc': function (td1, td2) {
  19969. var value1 = td1.innerText || td1.textContent,
  19970. value2 = td2.innerText || td2.textContent;
  19971. return value1.localeCompare(value2);
  19972. },
  19973. 'reversebyasc': function (td1, td2) {
  19974. var value1 = td1.innerHTML,
  19975. value2 = td2.innerHTML;
  19976. return value2.localeCompare(value1);
  19977. },
  19978. 'orderbynum': function (td1, td2) {
  19979. var value1 = td1[browser.ie ? 'innerText' : 'textContent'].match(/\d+/),
  19980. value2 = td2[browser.ie ? 'innerText' : 'textContent'].match(/\d+/);
  19981. if (value1) value1 = +value1[0];
  19982. if (value2) value2 = +value2[0];
  19983. return (value1 || 0) - (value2 || 0);
  19984. },
  19985. 'reversebynum': function (td1, td2) {
  19986. var value1 = td1[browser.ie ? 'innerText' : 'textContent'].match(/\d+/),
  19987. value2 = td2[browser.ie ? 'innerText' : 'textContent'].match(/\d+/);
  19988. if (value1) value1 = +value1[0];
  19989. if (value2) value2 = +value2[0];
  19990. return (value2 || 0) - (value1 || 0);
  19991. }
  19992. };
  19993. //对表格设置排序的标记data-sort-type
  19994. table.setAttribute('data-sort-type', compareFn && typeof compareFn === "string" && Fn[compareFn] ? compareFn : '');
  19995. //th不参与排序
  19996. flag && trArray.splice(0, 1);
  19997. trArray = utils.sort(trArray, function (tr1, tr2) {
  19998. var result;
  19999. if (compareFn && typeof compareFn === "function") {
  20000. result = compareFn.call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  20001. } else if (compareFn && typeof compareFn === "number") {
  20002. result = 1;
  20003. } else if (compareFn && typeof compareFn === "string" && Fn[compareFn]) {
  20004. result = Fn[compareFn].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  20005. } else {
  20006. result = Fn['orderbyasc'].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  20007. }
  20008. return result;
  20009. });
  20010. var fragment = table.ownerDocument.createDocumentFragment();
  20011. for (var j = 0, len = trArray.length; j < len; j++) {
  20012. fragment.appendChild(trArray[j]);
  20013. }
  20014. var tbody = table.getElementsByTagName("tbody")[0];
  20015. if (!lastRowIndex) {
  20016. tbody.appendChild(fragment);
  20017. } else {
  20018. tbody.insertBefore(fragment, rows[lastRowIndex - range.endRowIndex + range.beginRowIndex - 1])
  20019. }
  20020. };
  20021. UE.plugins['tablesort'] = function () {
  20022. var me = this,
  20023. UT = UE.UETable,
  20024. getUETable = function (tdOrTable) {
  20025. return UT.getUETable(tdOrTable);
  20026. },
  20027. getTableItemsByRange = function (editor) {
  20028. return UT.getTableItemsByRange(editor);
  20029. };
  20030. me.ready(function () {
  20031. //添加表格可排序的样式
  20032. utils.cssRule('tablesort',
  20033. 'table.sortEnabled tr.firstRow th,table.sortEnabled tr.firstRow td{padding-right:20px;background-repeat: no-repeat;background-position: center right;' +
  20034. ' background-image:url(' + me.options.themePath + me.options.theme + '/images/sortable.png);}',
  20035. me.document);
  20036. //做单元格合并操作时,清除可排序标识
  20037. me.addListener("afterexeccommand", function (type, cmd) {
  20038. if (cmd == 'mergeright' || cmd == 'mergedown' || cmd == 'mergecells') {
  20039. this.execCommand('disablesort');
  20040. }
  20041. });
  20042. });
  20043. //表格排序
  20044. UE.commands['sorttable'] = {
  20045. queryCommandState: function () {
  20046. var me = this,
  20047. tableItems = getTableItemsByRange(me);
  20048. if (!tableItems.cell) return -1;
  20049. var table = tableItems.table,
  20050. cells = table.getElementsByTagName("td");
  20051. for (var i = 0, cell; cell = cells[i++];) {
  20052. if (cell.rowSpan != 1 || cell.colSpan != 1) return -1;
  20053. }
  20054. return 0;
  20055. },
  20056. execCommand: function (cmd, fn) {
  20057. var me = this,
  20058. range = me.selection.getRange(),
  20059. bk = range.createBookmark(true),
  20060. tableItems = getTableItemsByRange(me),
  20061. cell = tableItems.cell,
  20062. ut = getUETable(tableItems.table),
  20063. cellInfo = ut.getCellInfo(cell);
  20064. ut.sortTable(cellInfo.cellIndex, fn);
  20065. range.moveToBookmark(bk);
  20066. try {
  20067. range.select();
  20068. } catch (e) { }
  20069. }
  20070. };
  20071. //设置表格可排序,清除表格可排序
  20072. UE.commands["enablesort"] = UE.commands["disablesort"] = {
  20073. queryCommandState: function (cmd) {
  20074. var table = getTableItemsByRange(this).table;
  20075. if (table && cmd == 'enablesort') {
  20076. var cells = domUtils.getElementsByTagName(table, 'th td');
  20077. for (var i = 0; i < cells.length; i++) {
  20078. if (cells[i].getAttribute('colspan') > 1 || cells[i].getAttribute('rowspan') > 1) return -1;
  20079. }
  20080. }
  20081. return !table ? -1 : cmd == 'enablesort' ^ table.getAttribute('data-sort') != 'sortEnabled' ? -1 : 0;
  20082. },
  20083. execCommand: function (cmd) {
  20084. var table = getTableItemsByRange(this).table;
  20085. table.setAttribute("data-sort", cmd == "enablesort" ? "sortEnabled" : "sortDisabled");
  20086. cmd == "enablesort" ? domUtils.addClass(table, "sortEnabled") : domUtils.removeClasses(table, "sortEnabled");
  20087. }
  20088. };
  20089. };
  20090. // plugins/contextmenu.js
  20091. ///import core
  20092. ///commands 右键菜单
  20093. ///commandsName ContextMenu
  20094. ///commandsTitle 右键菜单
  20095. /**
  20096. * 右键菜单
  20097. * @function
  20098. * @name baidu.editor.plugins.contextmenu
  20099. * @author zhanyi
  20100. */
  20101. UE.plugins['contextmenu'] = function () {
  20102. var me = this;
  20103. me.setOpt('enableContextMenu', true);
  20104. if (me.getOpt('enableContextMenu') === false) {
  20105. return;
  20106. }
  20107. var lang = me.getLang("contextMenu"),
  20108. menu,
  20109. items = me.options.contextMenu || [
  20110. { label: lang['selectall'], cmdName: 'selectall' },
  20111. {
  20112. label: lang.cleardoc,
  20113. cmdName: 'cleardoc',
  20114. exec: function () {
  20115. if (confirm(lang.confirmclear)) {
  20116. this.execCommand('cleardoc');
  20117. }
  20118. }
  20119. },
  20120. '-',
  20121. {
  20122. label: lang.unlink,
  20123. cmdName: 'unlink'
  20124. },
  20125. '-',
  20126. {
  20127. group: lang.paragraph,
  20128. icon: 'justifyjustify',
  20129. subMenu: [
  20130. {
  20131. label: lang.justifyleft,
  20132. cmdName: 'justify',
  20133. value: 'left'
  20134. },
  20135. {
  20136. label: lang.justifyright,
  20137. cmdName: 'justify',
  20138. value: 'right'
  20139. },
  20140. {
  20141. label: lang.justifycenter,
  20142. cmdName: 'justify',
  20143. value: 'center'
  20144. },
  20145. {
  20146. label: lang.justifyjustify,
  20147. cmdName: 'justify',
  20148. value: 'justify'
  20149. }
  20150. ]
  20151. },
  20152. '-',
  20153. {
  20154. group: lang.table,
  20155. icon: 'table',
  20156. subMenu: [
  20157. {
  20158. label: lang.inserttable,
  20159. cmdName: 'inserttable'
  20160. },
  20161. {
  20162. label: lang.deletetable,
  20163. cmdName: 'deletetable'
  20164. },
  20165. '-',
  20166. {
  20167. label: lang.deleterow,
  20168. cmdName: 'deleterow'
  20169. },
  20170. {
  20171. label: lang.deletecol,
  20172. cmdName: 'deletecol'
  20173. },
  20174. {
  20175. label: lang.insertcol,
  20176. cmdName: 'insertcol'
  20177. },
  20178. {
  20179. label: lang.insertcolnext,
  20180. cmdName: 'insertcolnext'
  20181. },
  20182. {
  20183. label: lang.insertrow,
  20184. cmdName: 'insertrow'
  20185. },
  20186. {
  20187. label: lang.insertrownext,
  20188. cmdName: 'insertrownext'
  20189. },
  20190. '-',
  20191. {
  20192. label: lang.insertcaption,
  20193. cmdName: 'insertcaption'
  20194. },
  20195. {
  20196. label: lang.deletecaption,
  20197. cmdName: 'deletecaption'
  20198. },
  20199. {
  20200. label: lang.inserttitle,
  20201. cmdName: 'inserttitle'
  20202. },
  20203. {
  20204. label: lang.deletetitle,
  20205. cmdName: 'deletetitle'
  20206. },
  20207. {
  20208. label: lang.inserttitlecol,
  20209. cmdName: 'inserttitlecol'
  20210. },
  20211. {
  20212. label: lang.deletetitlecol,
  20213. cmdName: 'deletetitlecol'
  20214. },
  20215. '-',
  20216. {
  20217. label: lang.mergecells,
  20218. cmdName: 'mergecells'
  20219. },
  20220. {
  20221. label: lang.mergeright,
  20222. cmdName: 'mergeright'
  20223. },
  20224. {
  20225. label: lang.mergedown,
  20226. cmdName: 'mergedown'
  20227. },
  20228. '-',
  20229. {
  20230. label: lang.splittorows,
  20231. cmdName: 'splittorows'
  20232. },
  20233. {
  20234. label: lang.splittocols,
  20235. cmdName: 'splittocols'
  20236. },
  20237. {
  20238. label: lang.splittocells,
  20239. cmdName: 'splittocells'
  20240. },
  20241. '-',
  20242. {
  20243. label: lang.averageDiseRow,
  20244. cmdName: 'averagedistributerow'
  20245. },
  20246. {
  20247. label: lang.averageDisCol,
  20248. cmdName: 'averagedistributecol'
  20249. },
  20250. '-',
  20251. {
  20252. label: lang.edittd,
  20253. cmdName: 'edittd',
  20254. exec: function () {
  20255. if (UE.ui['edittd']) {
  20256. new UE.ui['edittd'](this);
  20257. }
  20258. this.getDialog('edittd').open();
  20259. }
  20260. },
  20261. {
  20262. label: lang.edittable,
  20263. cmdName: 'edittable',
  20264. exec: function () {
  20265. if (UE.ui['edittable']) {
  20266. new UE.ui['edittable'](this);
  20267. }
  20268. this.getDialog('edittable').open();
  20269. }
  20270. },
  20271. {
  20272. label: lang.setbordervisible,
  20273. cmdName: 'setbordervisible'
  20274. }
  20275. ]
  20276. },
  20277. {
  20278. group: lang.tablesort,
  20279. icon: 'tablesort',
  20280. subMenu: [
  20281. {
  20282. label: lang.enablesort,
  20283. cmdName: 'enablesort'
  20284. },
  20285. {
  20286. label: lang.disablesort,
  20287. cmdName: 'disablesort'
  20288. },
  20289. '-',
  20290. {
  20291. label: lang.reversecurrent,
  20292. cmdName: 'sorttable',
  20293. value: 'reversecurrent'
  20294. },
  20295. {
  20296. label: lang.orderbyasc,
  20297. cmdName: 'sorttable',
  20298. value: 'orderbyasc'
  20299. },
  20300. {
  20301. label: lang.reversebyasc,
  20302. cmdName: 'sorttable',
  20303. value: 'reversebyasc'
  20304. },
  20305. {
  20306. label: lang.orderbynum,
  20307. cmdName: 'sorttable',
  20308. value: 'orderbynum'
  20309. },
  20310. {
  20311. label: lang.reversebynum,
  20312. cmdName: 'sorttable',
  20313. value: 'reversebynum'
  20314. }
  20315. ]
  20316. },
  20317. {
  20318. group: lang.borderbk,
  20319. icon: 'borderBack',
  20320. subMenu: [
  20321. {
  20322. label: lang.setcolor,
  20323. cmdName: "interlacetable",
  20324. exec: function () {
  20325. this.execCommand("interlacetable");
  20326. }
  20327. },
  20328. {
  20329. label: lang.unsetcolor,
  20330. cmdName: "uninterlacetable",
  20331. exec: function () {
  20332. this.execCommand("uninterlacetable");
  20333. }
  20334. },
  20335. {
  20336. label: lang.setbackground,
  20337. cmdName: "settablebackground",
  20338. exec: function () {
  20339. this.execCommand("settablebackground", { repeat: true, colorList: ["#bbb", "#ccc"] });
  20340. }
  20341. },
  20342. {
  20343. label: lang.unsetbackground,
  20344. cmdName: "cleartablebackground",
  20345. exec: function () {
  20346. this.execCommand("cleartablebackground");
  20347. }
  20348. },
  20349. {
  20350. label: lang.redandblue,
  20351. cmdName: "settablebackground",
  20352. exec: function () {
  20353. this.execCommand("settablebackground", { repeat: true, colorList: ["red", "blue"] });
  20354. }
  20355. },
  20356. {
  20357. label: lang.threecolorgradient,
  20358. cmdName: "settablebackground",
  20359. exec: function () {
  20360. this.execCommand("settablebackground", { repeat: true, colorList: ["#aaa", "#bbb", "#ccc"] });
  20361. }
  20362. }
  20363. ]
  20364. },
  20365. {
  20366. group: lang.aligntd,
  20367. icon: 'aligntd',
  20368. subMenu: [
  20369. {
  20370. cmdName: 'cellalignment',
  20371. value: { align: 'left', vAlign: 'top' }
  20372. },
  20373. {
  20374. cmdName: 'cellalignment',
  20375. value: { align: 'center', vAlign: 'top' }
  20376. },
  20377. {
  20378. cmdName: 'cellalignment',
  20379. value: { align: 'right', vAlign: 'top' }
  20380. },
  20381. {
  20382. cmdName: 'cellalignment',
  20383. value: { align: 'left', vAlign: 'middle' }
  20384. },
  20385. {
  20386. cmdName: 'cellalignment',
  20387. value: { align: 'center', vAlign: 'middle' }
  20388. },
  20389. {
  20390. cmdName: 'cellalignment',
  20391. value: { align: 'right', vAlign: 'middle' }
  20392. },
  20393. {
  20394. cmdName: 'cellalignment',
  20395. value: { align: 'left', vAlign: 'bottom' }
  20396. },
  20397. {
  20398. cmdName: 'cellalignment',
  20399. value: { align: 'center', vAlign: 'bottom' }
  20400. },
  20401. {
  20402. cmdName: 'cellalignment',
  20403. value: { align: 'right', vAlign: 'bottom' }
  20404. }
  20405. ]
  20406. },
  20407. {
  20408. group: lang.aligntable,
  20409. icon: 'aligntable',
  20410. subMenu: [
  20411. {
  20412. cmdName: 'tablealignment',
  20413. className: 'left',
  20414. label: lang.tableleft,
  20415. value: "left"
  20416. },
  20417. {
  20418. cmdName: 'tablealignment',
  20419. className: 'center',
  20420. label: lang.tablecenter,
  20421. value: "center"
  20422. },
  20423. {
  20424. cmdName: 'tablealignment',
  20425. className: 'right',
  20426. label: lang.tableright,
  20427. value: "right"
  20428. }
  20429. ]
  20430. },
  20431. '-',
  20432. {
  20433. label: lang.insertparagraphbefore,
  20434. cmdName: 'insertparagraph',
  20435. value: true
  20436. },
  20437. {
  20438. label: lang.insertparagraphafter,
  20439. cmdName: 'insertparagraph'
  20440. },
  20441. {
  20442. label: lang['copy'],
  20443. cmdName: 'copy'
  20444. },
  20445. {
  20446. label: lang['paste'],
  20447. cmdName: 'paste'
  20448. }
  20449. ];
  20450. if (!items.length) {
  20451. return;
  20452. }
  20453. var uiUtils = UE.ui.uiUtils;
  20454. me.addListener('contextmenu', function (type, evt) {
  20455. var offset = uiUtils.getViewportOffsetByEvent(evt);
  20456. me.fireEvent('beforeselectionchange');
  20457. if (menu) {
  20458. menu.destroy();
  20459. }
  20460. for (var i = 0, ti, contextItems = []; ti = items[i]; i++) {
  20461. var last;
  20462. (function (item) {
  20463. if (item == '-') {
  20464. if ((last = contextItems[contextItems.length - 1]) && last !== '-') {
  20465. contextItems.push('-');
  20466. }
  20467. } else if (item.hasOwnProperty("group")) {
  20468. for (var j = 0, cj, subMenu = []; cj = item.subMenu[j]; j++) {
  20469. (function (subItem) {
  20470. if (subItem == '-') {
  20471. if ((last = subMenu[subMenu.length - 1]) && last !== '-') {
  20472. subMenu.push('-');
  20473. } else {
  20474. subMenu.splice(subMenu.length - 1);
  20475. }
  20476. } else {
  20477. if ((me.commands[subItem.cmdName] || UE.commands[subItem.cmdName] || subItem.query) &&
  20478. (subItem.query ? subItem.query() : me.queryCommandState(subItem.cmdName)) > -1) {
  20479. subMenu.push({
  20480. 'label': subItem.label || me.getLang("contextMenu." + subItem.cmdName + (subItem.value || '')) || "",
  20481. 'className': 'edui-for-' + subItem.cmdName + (subItem.className ? (' edui-for-' + subItem.cmdName + '-' + subItem.className) : ''),
  20482. onclick: subItem.exec ? function () {
  20483. subItem.exec.call(me);
  20484. } : function () {
  20485. me.execCommand(subItem.cmdName, subItem.value);
  20486. }
  20487. });
  20488. }
  20489. }
  20490. })(cj);
  20491. }
  20492. if (subMenu.length) {
  20493. function getLabel() {
  20494. switch (item.icon) {
  20495. case "table":
  20496. return me.getLang("contextMenu.table");
  20497. case "justifyjustify":
  20498. return me.getLang("contextMenu.paragraph");
  20499. case "aligntd":
  20500. return me.getLang("contextMenu.aligntd");
  20501. case "aligntable":
  20502. return me.getLang("contextMenu.aligntable");
  20503. case "tablesort":
  20504. return lang.tablesort;
  20505. case "borderBack":
  20506. return lang.borderbk;
  20507. default:
  20508. return '';
  20509. }
  20510. }
  20511. contextItems.push({
  20512. //todo 修正成自动获取方式
  20513. 'label': getLabel(),
  20514. className: 'edui-for-' + item.icon,
  20515. 'subMenu': {
  20516. items: subMenu,
  20517. editor: me
  20518. }
  20519. });
  20520. }
  20521. } else {
  20522. //有可能commmand没有加载右键不能出来,或者没有command也想能展示出来添加query方法
  20523. if ((me.commands[item.cmdName] || UE.commands[item.cmdName] || item.query) &&
  20524. (item.query ? item.query.call(me) : me.queryCommandState(item.cmdName)) > -1) {
  20525. contextItems.push({
  20526. 'label': item.label || me.getLang("contextMenu." + item.cmdName),
  20527. className: 'edui-for-' + (item.icon ? item.icon : item.cmdName + (item.value || '')),
  20528. onclick: item.exec ? function () {
  20529. item.exec.call(me);
  20530. } : function () {
  20531. me.execCommand(item.cmdName, item.value);
  20532. }
  20533. });
  20534. }
  20535. }
  20536. })(ti);
  20537. }
  20538. if (contextItems[contextItems.length - 1] == '-') {
  20539. contextItems.pop();
  20540. }
  20541. menu = new UE.ui.Menu({
  20542. items: contextItems,
  20543. className: "edui-contextmenu",
  20544. editor: me
  20545. });
  20546. menu.render();
  20547. menu.showAt(offset);
  20548. me.fireEvent("aftershowcontextmenu", menu);
  20549. domUtils.preventDefault(evt);
  20550. if (browser.ie) {
  20551. var ieRange;
  20552. try {
  20553. ieRange = me.selection.getNative().createRange();
  20554. } catch (e) {
  20555. return;
  20556. }
  20557. if (ieRange.item) {
  20558. var range = new dom.Range(me.document);
  20559. range.selectNode(ieRange.item(0)).select(true, true);
  20560. }
  20561. }
  20562. });
  20563. // 添加复制的flash按钮
  20564. me.addListener('aftershowcontextmenu', function (type, menu) {
  20565. if (me.zeroclipboard) {
  20566. var items = menu.items;
  20567. for (var key in items) {
  20568. if (items[key].className == 'edui-for-copy') {
  20569. me.zeroclipboard.clip(items[key].getDom());
  20570. }
  20571. }
  20572. }
  20573. });
  20574. };
  20575. // plugins/shortcutmenu.js
  20576. ///import core
  20577. ///commands 弹出菜单
  20578. // commandsName popupmenu
  20579. ///commandsTitle 弹出菜单
  20580. /**
  20581. * 弹出菜单
  20582. * @function
  20583. * @name baidu.editor.plugins.popupmenu
  20584. * @author xuheng
  20585. */
  20586. UE.plugins['shortcutmenu'] = function () {
  20587. var me = this,
  20588. menu,
  20589. items = me.options.shortcutMenu || [];
  20590. if (!items.length) {
  20591. return;
  20592. }
  20593. me.addListener('contextmenu mouseup', function (type, e) {
  20594. var me = this,
  20595. customEvt = {
  20596. type: type,
  20597. target: e.target || e.srcElement,
  20598. screenX: e.screenX,
  20599. screenY: e.screenY,
  20600. clientX: e.clientX,
  20601. clientY: e.clientY
  20602. };
  20603. setTimeout(function () {
  20604. var rng = me.selection.getRange();
  20605. if (rng.collapsed === false || type == "contextmenu") {
  20606. if (!menu) {
  20607. menu = new baidu.editor.ui.ShortCutMenu({
  20608. editor: me,
  20609. items: items,
  20610. theme: me.options.theme,
  20611. className: 'edui-shortcutmenu'
  20612. });
  20613. menu.render();
  20614. me.fireEvent("afterrendershortcutmenu", menu);
  20615. }
  20616. menu.show(customEvt, !!UE.plugins['contextmenu']);
  20617. }
  20618. });
  20619. if (type == 'contextmenu') {
  20620. domUtils.preventDefault(e);
  20621. if (browser.ie9below) {
  20622. var ieRange;
  20623. try {
  20624. ieRange = me.selection.getNative().createRange();
  20625. } catch (e) {
  20626. return;
  20627. }
  20628. if (ieRange.item) {
  20629. var range = new dom.Range(me.document);
  20630. range.selectNode(ieRange.item(0)).select(true, true);
  20631. }
  20632. }
  20633. }
  20634. });
  20635. me.addListener('keydown', function (type) {
  20636. if (type == "keydown") {
  20637. menu && !menu.isHidden && menu.hide();
  20638. }
  20639. });
  20640. };
  20641. // plugins/basestyle.js
  20642. /**
  20643. * B、I、sub、super命令支持
  20644. * @file
  20645. * @since 1.2.6.1
  20646. */
  20647. UE.plugins['basestyle'] = function () {
  20648. /**
  20649. * 字体加粗
  20650. * @command bold
  20651. * @param { String } cmd 命令字符串
  20652. * @remind 对已加粗的文本内容执行该命令, 将取消加粗
  20653. * @method execCommand
  20654. * @example
  20655. * ```javascript
  20656. * //editor是编辑器实例
  20657. * //对当前选中的文本内容执行加粗操作
  20658. * //第一次执行, 文本内容加粗
  20659. * editor.execCommand( 'bold' );
  20660. *
  20661. * //第二次执行, 文本内容取消加粗
  20662. * editor.execCommand( 'bold' );
  20663. * ```
  20664. */
  20665. /**
  20666. * 字体倾斜
  20667. * @command italic
  20668. * @method execCommand
  20669. * @param { String } cmd 命令字符串
  20670. * @remind 对已倾斜的文本内容执行该命令, 将取消倾斜
  20671. * @example
  20672. * ```javascript
  20673. * //editor是编辑器实例
  20674. * //对当前选中的文本内容执行斜体操作
  20675. * //第一次操作, 文本内容将变成斜体
  20676. * editor.execCommand( 'italic' );
  20677. *
  20678. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20679. * editor.execCommand( 'italic' );
  20680. * ```
  20681. */
  20682. /**
  20683. * 下标文本,与“superscript”命令互斥
  20684. * @command subscript
  20685. * @method execCommand
  20686. * @remind 把选中的文本内容切换成下标文本, 如果当前选中的文本已经是下标, 则该操作会把文本内容还原成正常文本
  20687. * @param { String } cmd 命令字符串
  20688. * @example
  20689. * ```javascript
  20690. * //editor是编辑器实例
  20691. * //对当前选中的文本内容执行下标操作
  20692. * //第一次操作, 文本内容将变成下标文本
  20693. * editor.execCommand( 'subscript' );
  20694. *
  20695. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20696. * editor.execCommand( 'subscript' );
  20697. * ```
  20698. */
  20699. /**
  20700. * 上标文本,与“subscript”命令互斥
  20701. * @command superscript
  20702. * @method execCommand
  20703. * @remind 把选中的文本内容切换成上标文本, 如果当前选中的文本已经是上标, 则该操作会把文本内容还原成正常文本
  20704. * @param { String } cmd 命令字符串
  20705. * @example
  20706. * ```javascript
  20707. * //editor是编辑器实例
  20708. * //对当前选中的文本内容执行上标操作
  20709. * //第一次操作, 文本内容将变成上标文本
  20710. * editor.execCommand( 'superscript' );
  20711. *
  20712. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20713. * editor.execCommand( 'superscript' );
  20714. * ```
  20715. */
  20716. var basestyles = {
  20717. 'bold': ['strong', 'b'],
  20718. 'italic': ['em', 'i'],
  20719. 'subscript': ['sub'],
  20720. 'superscript': ['sup']
  20721. },
  20722. getObj = function (editor, tagNames) {
  20723. return domUtils.filterNodeList(editor.selection.getStartElementPath(), tagNames);
  20724. },
  20725. me = this;
  20726. //添加快捷键
  20727. me.addshortcutkey({
  20728. "Bold": "ctrl+66",//^B
  20729. "Italic": "ctrl+73", //^I
  20730. "Underline": "ctrl+85"//^U
  20731. });
  20732. me.addInputRule(function (root) {
  20733. utils.each(root.getNodesByTagName('b i'), function (node) {
  20734. switch (node.tagName) {
  20735. case 'b':
  20736. node.tagName = 'strong';
  20737. break;
  20738. case 'i':
  20739. node.tagName = 'em';
  20740. }
  20741. });
  20742. });
  20743. for (var style in basestyles) {
  20744. (function (cmd, tagNames) {
  20745. me.commands[cmd] = {
  20746. execCommand: function (cmdName) {
  20747. var range = me.selection.getRange(), obj = getObj(this, tagNames);
  20748. if (range.collapsed) {
  20749. if (obj) {
  20750. var tmpText = me.document.createTextNode('');
  20751. range.insertNode(tmpText).removeInlineStyle(tagNames);
  20752. range.setStartBefore(tmpText);
  20753. domUtils.remove(tmpText);
  20754. } else {
  20755. var tmpNode = range.document.createElement(tagNames[0]);
  20756. if (cmdName == 'superscript' || cmdName == 'subscript') {
  20757. tmpText = me.document.createTextNode('');
  20758. range.insertNode(tmpText)
  20759. .removeInlineStyle(['sub', 'sup'])
  20760. .setStartBefore(tmpText)
  20761. .collapse(true);
  20762. }
  20763. range.insertNode(tmpNode).setStart(tmpNode, 0);
  20764. }
  20765. range.collapse(true);
  20766. } else {
  20767. if (cmdName == 'superscript' || cmdName == 'subscript') {
  20768. if (!obj || obj.tagName.toLowerCase() != cmdName) {
  20769. range.removeInlineStyle(['sub', 'sup']);
  20770. }
  20771. }
  20772. obj ? range.removeInlineStyle(tagNames) : range.applyInlineStyle(tagNames[0]);
  20773. }
  20774. range.select();
  20775. },
  20776. queryCommandState: function () {
  20777. return getObj(this, tagNames) ? 1 : 0;
  20778. }
  20779. };
  20780. })(style, basestyles[style]);
  20781. }
  20782. };
  20783. // plugins/elementpath.js
  20784. /**
  20785. * 选取路径命令
  20786. * @file
  20787. */
  20788. UE.plugins['elementpath'] = function () {
  20789. var currentLevel,
  20790. tagNames,
  20791. me = this;
  20792. me.setOpt('elementPathEnabled', true);
  20793. if (!me.options.elementPathEnabled) {
  20794. return;
  20795. }
  20796. me.commands['elementpath'] = {
  20797. execCommand: function (cmdName, level) {
  20798. var start = tagNames[level],
  20799. range = me.selection.getRange();
  20800. currentLevel = level * 1;
  20801. range.selectNode(start).select();
  20802. },
  20803. queryCommandValue: function () {
  20804. //产生一个副本,不能修改原来的startElementPath;
  20805. var parents = [].concat(this.selection.getStartElementPath()).reverse(),
  20806. names = [];
  20807. tagNames = parents;
  20808. for (var i = 0, ci; ci = parents[i]; i++) {
  20809. if (ci.nodeType == 3) {
  20810. continue;
  20811. }
  20812. var name = ci.tagName.toLowerCase();
  20813. if (name == 'img' && ci.getAttribute('anchorname')) {
  20814. name = 'anchor';
  20815. }
  20816. names[i] = name;
  20817. if (currentLevel == i) {
  20818. currentLevel = -1;
  20819. break;
  20820. }
  20821. }
  20822. return names;
  20823. }
  20824. };
  20825. };
  20826. // plugins/formatmatch.js
  20827. /**
  20828. * 格式刷,只格式inline的
  20829. * @file
  20830. * @since 1.2.6.1
  20831. */
  20832. /**
  20833. * 格式刷
  20834. * @command formatmatch
  20835. * @method execCommand
  20836. * @remind 该操作不能复制段落格式
  20837. * @param { String } cmd 命令字符串
  20838. * @example
  20839. * ```javascript
  20840. * //editor是编辑器实例
  20841. * //获取格式刷
  20842. * editor.execCommand( 'formatmatch' );
  20843. * ```
  20844. */
  20845. UE.plugins['formatmatch'] = function () {
  20846. var me = this,
  20847. list = [], img,
  20848. flag = 0;
  20849. me.addListener('reset', function () {
  20850. list = [];
  20851. flag = 0;
  20852. });
  20853. function addList(type, evt) {
  20854. if (browser.webkit) {
  20855. var target = evt.target.tagName == 'IMG' ? evt.target : null;
  20856. }
  20857. function addFormat(range) {
  20858. if (text) {
  20859. range.selectNode(text);
  20860. }
  20861. return range.applyInlineStyle(list[list.length - 1].tagName, null, list);
  20862. }
  20863. me.undoManger && me.undoManger.save();
  20864. var range = me.selection.getRange(),
  20865. imgT = target || range.getClosedNode();
  20866. if (img && imgT && imgT.tagName == 'IMG') {
  20867. //trace:964
  20868. imgT.style.cssText += ';float:' + (img.style.cssFloat || img.style.styleFloat || 'none') + ';display:' + (img.style.display || 'inline');
  20869. img = null;
  20870. } else {
  20871. if (!img) {
  20872. var collapsed = range.collapsed;
  20873. if (collapsed) {
  20874. var text = me.document.createTextNode('match');
  20875. range.insertNode(text).select();
  20876. }
  20877. me.__hasEnterExecCommand = true;
  20878. //不能把block上的属性干掉
  20879. //trace:1553
  20880. var removeFormatAttributes = me.options.removeFormatAttributes;
  20881. me.options.removeFormatAttributes = '';
  20882. me.execCommand('removeformat');
  20883. me.options.removeFormatAttributes = removeFormatAttributes;
  20884. me.__hasEnterExecCommand = false;
  20885. //trace:969
  20886. range = me.selection.getRange();
  20887. if (list.length) {
  20888. addFormat(range);
  20889. }
  20890. if (text) {
  20891. range.setStartBefore(text).collapse(true);
  20892. }
  20893. range.select();
  20894. text && domUtils.remove(text);
  20895. }
  20896. }
  20897. me.undoManger && me.undoManger.save();
  20898. me.removeListener('mouseup', addList);
  20899. flag = 0;
  20900. }
  20901. me.commands['formatmatch'] = {
  20902. execCommand: function (cmdName) {
  20903. if (flag) {
  20904. flag = 0;
  20905. list = [];
  20906. me.removeListener('mouseup', addList);
  20907. return;
  20908. }
  20909. var range = me.selection.getRange();
  20910. img = range.getClosedNode();
  20911. if (!img || img.tagName != 'IMG') {
  20912. range.collapse(true).shrinkBoundary();
  20913. var start = range.startContainer;
  20914. list = domUtils.findParents(start, true, function (node) {
  20915. return !domUtils.isBlockElm(node) && node.nodeType == 1;
  20916. });
  20917. //a不能加入格式刷, 并且克隆节点
  20918. for (var i = 0, ci; ci = list[i]; i++) {
  20919. if (ci.tagName == 'A') {
  20920. list.splice(i, 1);
  20921. break;
  20922. }
  20923. }
  20924. }
  20925. me.addListener('mouseup', addList);
  20926. flag = 1;
  20927. },
  20928. queryCommandState: function () {
  20929. return flag;
  20930. },
  20931. notNeedUndo: 1
  20932. };
  20933. };
  20934. // plugins/searchreplace.js
  20935. ///import core
  20936. ///commands 查找替换
  20937. ///commandsName SearchReplace
  20938. ///commandsTitle 查询替换
  20939. ///commandsDialog dialogs\searchreplace
  20940. /**
  20941. * @description 查找替换
  20942. * @author zhanyi
  20943. */
  20944. UE.plugin.register('searchreplace', function () {
  20945. var me = this;
  20946. var _blockElm = { 'table': 1, 'tbody': 1, 'tr': 1, 'ol': 1, 'ul': 1 };
  20947. function findTextInString(textContent, opt, currentIndex) {
  20948. var str = opt.searchStr;
  20949. if (opt.dir == -1) {
  20950. textContent = textContent.split('').reverse().join('');
  20951. str = str.split('').reverse().join('');
  20952. currentIndex = textContent.length - currentIndex;
  20953. }
  20954. var reg = new RegExp(str, 'g' + (opt.casesensitive ? '' : 'i')), match;
  20955. while (match = reg.exec(textContent)) {
  20956. if (match.index >= currentIndex) {
  20957. return opt.dir == -1 ? textContent.length - match.index - opt.searchStr.length : match.index;
  20958. }
  20959. }
  20960. return -1
  20961. }
  20962. function findTextBlockElm(node, currentIndex, opt) {
  20963. var textContent, index, methodName = opt.all || opt.dir == 1 ? 'getNextDomNode' : 'getPreDomNode';
  20964. if (domUtils.isBody(node)) {
  20965. node = node.firstChild;
  20966. }
  20967. var first = 1;
  20968. while (node) {
  20969. textContent = node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent'];
  20970. index = findTextInString(textContent, opt, currentIndex);
  20971. first = 0;
  20972. if (index != -1) {
  20973. return {
  20974. 'node': node,
  20975. 'index': index
  20976. }
  20977. }
  20978. node = domUtils[methodName](node);
  20979. while (node && _blockElm[node.nodeName.toLowerCase()]) {
  20980. node = domUtils[methodName](node, true);
  20981. }
  20982. if (node) {
  20983. currentIndex = opt.dir == -1 ? (node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent']).length : 0;
  20984. }
  20985. }
  20986. }
  20987. function findNTextInBlockElm(node, index, str) {
  20988. var currentIndex = 0,
  20989. currentNode = node.firstChild,
  20990. currentNodeLength = 0,
  20991. result;
  20992. while (currentNode) {
  20993. if (currentNode.nodeType == 3) {
  20994. currentNodeLength = currentNode.nodeValue.replace(/(^[\t\r\n]+)|([\t\r\n]+$)/, '').length;
  20995. currentIndex += currentNodeLength;
  20996. if (currentIndex >= index) {
  20997. return {
  20998. 'node': currentNode,
  20999. 'index': currentNodeLength - (currentIndex - index)
  21000. }
  21001. }
  21002. } else if (!dtd.$empty[currentNode.tagName]) {
  21003. currentNodeLength = currentNode[browser.ie ? 'innerText' : 'textContent'].replace(/(^[\t\r\n]+)|([\t\r\n]+$)/, '').length
  21004. currentIndex += currentNodeLength;
  21005. if (currentIndex >= index) {
  21006. result = findNTextInBlockElm(currentNode, currentNodeLength - (currentIndex - index), str);
  21007. if (result) {
  21008. return result;
  21009. }
  21010. }
  21011. }
  21012. currentNode = domUtils.getNextDomNode(currentNode);
  21013. }
  21014. }
  21015. function searchReplace(me, opt) {
  21016. var rng = me.selection.getRange(),
  21017. startBlockNode,
  21018. searchStr = opt.searchStr,
  21019. span = me.document.createElement('span');
  21020. span.innerHTML = '$$ueditor_searchreplace_key$$';
  21021. rng.shrinkBoundary(true);
  21022. //判断是不是第一次选中
  21023. if (!rng.collapsed) {
  21024. rng.select();
  21025. var rngText = me.selection.getText();
  21026. if (new RegExp('^' + opt.searchStr + '$', (opt.casesensitive ? '' : 'i')).test(rngText)) {
  21027. if (opt.replaceStr != undefined) {
  21028. replaceText(rng, opt.replaceStr);
  21029. rng.select();
  21030. return true;
  21031. } else {
  21032. rng.collapse(opt.dir == -1)
  21033. }
  21034. }
  21035. }
  21036. rng.insertNode(span);
  21037. rng.enlargeToBlockElm(true);
  21038. startBlockNode = rng.startContainer;
  21039. var currentIndex = startBlockNode[browser.ie ? 'innerText' : 'textContent'].indexOf('$$ueditor_searchreplace_key$$');
  21040. rng.setStartBefore(span);
  21041. domUtils.remove(span);
  21042. var result = findTextBlockElm(startBlockNode, currentIndex, opt);
  21043. if (result) {
  21044. var rngStart = findNTextInBlockElm(result.node, result.index, searchStr);
  21045. var rngEnd = findNTextInBlockElm(result.node, result.index + searchStr.length, searchStr);
  21046. rng.setStart(rngStart.node, rngStart.index).setEnd(rngEnd.node, rngEnd.index);
  21047. if (opt.replaceStr !== undefined) {
  21048. replaceText(rng, opt.replaceStr)
  21049. }
  21050. rng.select();
  21051. return true;
  21052. } else {
  21053. rng.setCursor()
  21054. }
  21055. }
  21056. function replaceText(rng, str) {
  21057. str = me.document.createTextNode(str);
  21058. rng.deleteContents().insertNode(str);
  21059. }
  21060. return {
  21061. commands: {
  21062. 'searchreplace': {
  21063. execCommand: function (cmdName, opt) {
  21064. utils.extend(opt, {
  21065. all: false,
  21066. casesensitive: false,
  21067. dir: 1
  21068. }, true);
  21069. var num = 0;
  21070. if (opt.all) {
  21071. var rng = me.selection.getRange(),
  21072. first = me.body.firstChild;
  21073. if (first && first.nodeType == 1) {
  21074. rng.setStart(first, 0);
  21075. rng.shrinkBoundary(true);
  21076. } else if (first.nodeType == 3) {
  21077. rng.setStartBefore(first)
  21078. }
  21079. rng.collapse(true).select(true);
  21080. if (opt.replaceStr !== undefined) {
  21081. me.fireEvent('saveScene');
  21082. }
  21083. while (searchReplace(this, opt)) {
  21084. num++;
  21085. }
  21086. if (num) {
  21087. me.fireEvent('saveScene');
  21088. }
  21089. } else {
  21090. if (opt.replaceStr !== undefined) {
  21091. me.fireEvent('saveScene');
  21092. }
  21093. if (searchReplace(this, opt)) {
  21094. num++
  21095. }
  21096. if (num) {
  21097. me.fireEvent('saveScene');
  21098. }
  21099. }
  21100. return num;
  21101. },
  21102. notNeedUndo: 1
  21103. }
  21104. }
  21105. }
  21106. });
  21107. // plugins/customstyle.js
  21108. /**
  21109. * 自定义样式
  21110. * @file
  21111. * @since 1.2.6.1
  21112. */
  21113. /**
  21114. * 根据config配置文件里“customstyle”选项的值对匹配的标签执行样式替换。
  21115. * @command customstyle
  21116. * @method execCommand
  21117. * @param { String } cmd 命令字符串
  21118. * @example
  21119. * ```javascript
  21120. * editor.execCommand( 'customstyle' );
  21121. * ```
  21122. */
  21123. UE.plugins['customstyle'] = function () {
  21124. var me = this;
  21125. me.setOpt({
  21126. 'customstyle': [
  21127. { tag: 'h1', name: 'tc', style: 'font-size:32px;font-weight:bold;border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:center;margin:0 0 20px 0;' },
  21128. { tag: 'h1', name: 'tl', style: 'font-size:32px;font-weight:bold;border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:left;margin:0 0 10px 0;' },
  21129. { tag: 'span', name: 'im', style: 'font-size:16px;font-style:italic;font-weight:bold;line-height:18px;' },
  21130. { tag: 'span', name: 'hi', style: 'font-size:16px;font-style:italic;font-weight:bold;color:rgb(51, 153, 204);line-height:18px;' }
  21131. ]
  21132. });
  21133. me.commands['customstyle'] = {
  21134. execCommand: function (cmdName, obj) {
  21135. var me = this,
  21136. tagName = obj.tag,
  21137. node = domUtils.findParent(me.selection.getStart(), function (node) {
  21138. return node.getAttribute('label');
  21139. }, true),
  21140. range, bk, tmpObj = {};
  21141. for (var p in obj) {
  21142. if (obj[p] !== undefined)
  21143. tmpObj[p] = obj[p];
  21144. }
  21145. delete tmpObj.tag;
  21146. if (node && node.getAttribute('label') == obj.label) {
  21147. range = this.selection.getRange();
  21148. bk = range.createBookmark();
  21149. if (range.collapsed) {
  21150. //trace:1732 删掉自定义标签,要有p来回填站位
  21151. if (dtd.$block[node.tagName]) {
  21152. var fillNode = me.document.createElement('p');
  21153. domUtils.moveChild(node, fillNode);
  21154. node.parentNode.insertBefore(fillNode, node);
  21155. domUtils.remove(node);
  21156. } else {
  21157. domUtils.remove(node, true);
  21158. }
  21159. } else {
  21160. var common = domUtils.getCommonAncestor(bk.start, bk.end),
  21161. nodes = domUtils.getElementsByTagName(common, tagName);
  21162. if (new RegExp(tagName, 'i').test(common.tagName)) {
  21163. nodes.push(common);
  21164. }
  21165. for (var i = 0, ni; ni = nodes[i++];) {
  21166. if (ni.getAttribute('label') == obj.label) {
  21167. var ps = domUtils.getPosition(ni, bk.start), pe = domUtils.getPosition(ni, bk.end);
  21168. if ((ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  21169. &&
  21170. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  21171. )
  21172. if (dtd.$block[tagName]) {
  21173. var fillNode = me.document.createElement('p');
  21174. domUtils.moveChild(ni, fillNode);
  21175. ni.parentNode.insertBefore(fillNode, ni);
  21176. }
  21177. domUtils.remove(ni, true);
  21178. }
  21179. }
  21180. node = domUtils.findParent(common, function (node) {
  21181. return node.getAttribute('label') == obj.label;
  21182. }, true);
  21183. if (node) {
  21184. domUtils.remove(node, true);
  21185. }
  21186. }
  21187. range.moveToBookmark(bk).select();
  21188. } else {
  21189. if (dtd.$block[tagName]) {
  21190. this.execCommand('paragraph', tagName, tmpObj, 'customstyle');
  21191. range = me.selection.getRange();
  21192. if (!range.collapsed) {
  21193. range.collapse();
  21194. node = domUtils.findParent(me.selection.getStart(), function (node) {
  21195. return node.getAttribute('label') == obj.label;
  21196. }, true);
  21197. var pNode = me.document.createElement('p');
  21198. domUtils.insertAfter(node, pNode);
  21199. domUtils.fillNode(me.document, pNode);
  21200. range.setStart(pNode, 0).setCursor();
  21201. }
  21202. } else {
  21203. range = me.selection.getRange();
  21204. if (range.collapsed) {
  21205. node = me.document.createElement(tagName);
  21206. domUtils.setAttributes(node, tmpObj);
  21207. range.insertNode(node).setStart(node, 0).setCursor();
  21208. return;
  21209. }
  21210. bk = range.createBookmark();
  21211. range.applyInlineStyle(tagName, tmpObj).moveToBookmark(bk).select();
  21212. }
  21213. }
  21214. },
  21215. queryCommandValue: function () {
  21216. var parent = domUtils.filterNodeList(
  21217. this.selection.getStartElementPath(),
  21218. function (node) { return node.getAttribute('label') }
  21219. );
  21220. return parent ? parent.getAttribute('label') : '';
  21221. }
  21222. };
  21223. //当去掉customstyle是,如果是块元素,用p代替
  21224. me.addListener('keyup', function (type, evt) {
  21225. var keyCode = evt.keyCode || evt.which;
  21226. if (keyCode == 32 || keyCode == 13) {
  21227. var range = me.selection.getRange();
  21228. if (range.collapsed) {
  21229. var node = domUtils.findParent(me.selection.getStart(), function (node) {
  21230. return node.getAttribute('label');
  21231. }, true);
  21232. if (node && dtd.$block[node.tagName] && domUtils.isEmptyNode(node)) {
  21233. var p = me.document.createElement('p');
  21234. domUtils.insertAfter(node, p);
  21235. domUtils.fillNode(me.document, p);
  21236. domUtils.remove(node);
  21237. range.setStart(p, 0).setCursor();
  21238. }
  21239. }
  21240. }
  21241. });
  21242. };
  21243. // plugins/catchremoteimage.js
  21244. ///import core
  21245. ///commands 远程图片抓取
  21246. ///commandsName catchRemoteImage,catchremoteimageenable
  21247. ///commandsTitle 远程图片抓取
  21248. /**
  21249. * 远程图片抓取,当开启本插件时所有不符合本地域名的图片都将被抓取成为本地服务器上的图片
  21250. */
  21251. UE.plugins['catchremoteimage'] = function () {
  21252. var me = this,
  21253. ajax = UE.ajax;
  21254. /* 设置默认值 */
  21255. if (me.options.catchRemoteImageEnable === false) return;
  21256. me.setOpt({
  21257. catchRemoteImageEnable: false
  21258. });
  21259. me.addListener("afterpaste", function () {
  21260. me.fireEvent("catchRemoteImage");
  21261. });
  21262. me.addListener("catchRemoteImage", function () {
  21263. var catcherLocalDomain = me.getOpt('catcherLocalDomain'),
  21264. catcherActionUrl = me.getActionUrl(me.getOpt('catcherActionName')),
  21265. catcherUrlPrefix = me.getOpt('catcherUrlPrefix'),
  21266. catcherFieldName = me.getOpt('catcherFieldName');
  21267. var remoteImages = [],
  21268. imgs = domUtils.getElementsByTagName(me.document, "img"),
  21269. test = function (src, urls) {
  21270. if (src.indexOf(location.host) != -1 || /(^\.)|(^\/)/.test(src)) {
  21271. return true;
  21272. }
  21273. if (urls) {
  21274. for (var j = 0, url; url = urls[j++];) {
  21275. if (src.indexOf(url) !== -1) {
  21276. return true;
  21277. }
  21278. }
  21279. }
  21280. return false;
  21281. };
  21282. for (var i = 0, ci; ci = imgs[i++];) {
  21283. if (ci.getAttribute("word_img")) {
  21284. continue;
  21285. }
  21286. var src = ci.getAttribute("_src") || ci.src || "";
  21287. if (/^(https?|ftp):/i.test(src) && !test(src, catcherLocalDomain)) {
  21288. remoteImages.push(src);
  21289. }
  21290. }
  21291. if (remoteImages.length) {
  21292. catchremoteimage(remoteImages, {
  21293. //成功抓取
  21294. success: function (r) {
  21295. try {
  21296. var info = r.state !== undefined ? r : eval("(" + r.responseText + ")");
  21297. } catch (e) {
  21298. return;
  21299. }
  21300. /* 获取源路径和新路径 */
  21301. var i, j, ci, cj, oldSrc, newSrc, list = info.list;
  21302. for (i = 0; ci = imgs[i++];) {
  21303. oldSrc = ci.getAttribute("_src") || ci.src || "";
  21304. for (j = 0; cj = list[j++];) {
  21305. if (oldSrc == cj.source && cj.state == "SUCCESS") { //抓取失败时不做替换处理
  21306. newSrc = catcherUrlPrefix + cj.url;
  21307. domUtils.setAttributes(ci, {
  21308. "src": newSrc,
  21309. "_src": newSrc
  21310. });
  21311. break;
  21312. }
  21313. }
  21314. }
  21315. me.fireEvent('catchremotesuccess')
  21316. },
  21317. //回调失败,本次请求超时
  21318. error: function () {
  21319. me.fireEvent("catchremoteerror");
  21320. }
  21321. });
  21322. }
  21323. function catchremoteimage(imgs, callbacks) {
  21324. var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '',
  21325. url = utils.formatUrl(catcherActionUrl + (catcherActionUrl.indexOf('?') == -1 ? '?' : '&') + params),
  21326. isJsonp = utils.isCrossDomainUrl(url),
  21327. opt = {
  21328. 'method': 'POST',
  21329. 'dataType': isJsonp ? 'jsonp' : '',
  21330. 'timeout': 60000, //单位:毫秒,回调请求超时设置。目标用户如果网速不是很快的话此处建议设置一个较大的数值
  21331. 'onsuccess': callbacks["success"],
  21332. 'onerror': callbacks["error"]
  21333. };
  21334. opt[catcherFieldName] = imgs;
  21335. ajax.request(url, opt);
  21336. }
  21337. });
  21338. };
  21339. // plugins/snapscreen.js
  21340. /**
  21341. * 截屏插件,为UEditor提供插入支持
  21342. * @file
  21343. * @since 1.4.2
  21344. */
  21345. UE.plugin.register('snapscreen', function () {
  21346. var me = this;
  21347. var snapplugin;
  21348. function getLocation(url) {
  21349. var search,
  21350. a = document.createElement('a'),
  21351. params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
  21352. a.href = url;
  21353. if (browser.ie) {
  21354. a.href = a.href;
  21355. }
  21356. search = a.search;
  21357. if (params) {
  21358. search = search + (search.indexOf('?') == -1 ? '?' : '&') + params;
  21359. search = search.replace(/[&]+/ig, '&');
  21360. }
  21361. return {
  21362. 'port': a.port,
  21363. 'hostname': a.hostname,
  21364. 'path': a.pathname + search || + a.hash
  21365. }
  21366. }
  21367. return {
  21368. commands: {
  21369. /**
  21370. * 字体背景颜色
  21371. * @command snapscreen
  21372. * @method execCommand
  21373. * @param { String } cmd 命令字符串
  21374. * @example
  21375. * ```javascript
  21376. * editor.execCommand('snapscreen');
  21377. * ```
  21378. */
  21379. 'snapscreen': {
  21380. execCommand: function (cmd) {
  21381. var url, local, res;
  21382. var lang = me.getLang("snapScreen_plugin");
  21383. if (!snapplugin) {
  21384. var container = me.container;
  21385. var doc = me.container.ownerDocument || me.container.document;
  21386. snapplugin = doc.createElement("object");
  21387. try { snapplugin.type = "application/x-pluginbaidusnap"; } catch (e) {
  21388. return;
  21389. }
  21390. snapplugin.style.cssText = "position:absolute;left:-9999px;width:0;height:0;";
  21391. snapplugin.setAttribute("width", "0");
  21392. snapplugin.setAttribute("height", "0");
  21393. container.appendChild(snapplugin);
  21394. }
  21395. function onSuccess(rs) {
  21396. try {
  21397. rs = eval("(" + rs + ")");
  21398. if (rs.state == 'SUCCESS') {
  21399. var opt = me.options;
  21400. me.execCommand('insertimage', {
  21401. src: opt.snapscreenUrlPrefix + rs.url,
  21402. _src: opt.snapscreenUrlPrefix + rs.url,
  21403. alt: rs.title || '',
  21404. floatStyle: opt.snapscreenImgAlign
  21405. });
  21406. } else {
  21407. alert(rs.state);
  21408. }
  21409. } catch (e) {
  21410. alert(lang.callBackErrorMsg);
  21411. }
  21412. }
  21413. url = me.getActionUrl(me.getOpt('snapscreenActionName'));
  21414. local = getLocation(url);
  21415. setTimeout(function () {
  21416. try {
  21417. res = snapplugin.saveSnapshot(local.hostname, local.path, local.port);
  21418. } catch (e) {
  21419. me.ui._dialogs['snapscreenDialog'].open();
  21420. return;
  21421. }
  21422. onSuccess(res);
  21423. }, 50);
  21424. },
  21425. queryCommandState: function () {
  21426. return (navigator.userAgent.indexOf("Windows", 0) != -1) ? 0 : -1;
  21427. }
  21428. }
  21429. }
  21430. }
  21431. });
  21432. // plugins/insertparagraph.js
  21433. /**
  21434. * 插入段落
  21435. * @file
  21436. * @since 1.2.6.1
  21437. */
  21438. /**
  21439. * 插入段落
  21440. * @command insertparagraph
  21441. * @method execCommand
  21442. * @param { String } cmd 命令字符串
  21443. * @example
  21444. * ```javascript
  21445. * //editor是编辑器实例
  21446. * editor.execCommand( 'insertparagraph' );
  21447. * ```
  21448. */
  21449. UE.commands['insertparagraph'] = {
  21450. execCommand: function (cmdName, front) {
  21451. var me = this,
  21452. range = me.selection.getRange(),
  21453. start = range.startContainer, tmpNode;
  21454. while (start) {
  21455. if (domUtils.isBody(start)) {
  21456. break;
  21457. }
  21458. tmpNode = start;
  21459. start = start.parentNode;
  21460. }
  21461. if (tmpNode) {
  21462. var p = me.document.createElement('p');
  21463. if (front) {
  21464. tmpNode.parentNode.insertBefore(p, tmpNode)
  21465. } else {
  21466. tmpNode.parentNode.insertBefore(p, tmpNode.nextSibling)
  21467. }
  21468. domUtils.fillNode(me.document, p);
  21469. range.setStart(p, 0).setCursor(false, true);
  21470. }
  21471. }
  21472. };
  21473. // plugins/webapp.js
  21474. /**
  21475. * 百度应用
  21476. * @file
  21477. * @since 1.2.6.1
  21478. */
  21479. /**
  21480. * 插入百度应用
  21481. * @command webapp
  21482. * @method execCommand
  21483. * @remind 需要百度APPKey
  21484. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  21485. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  21486. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  21487. * @example
  21488. * ```javascript
  21489. * //editor是编辑器实例
  21490. * //在编辑器里插入一个“植物大战僵尸”的APP
  21491. * editor.execCommand( 'webapp' , {
  21492. * title: '植物大战僵尸',
  21493. * width: 560,
  21494. * height: 465,
  21495. * logo: '应用展示的图片',
  21496. * url: '百度应用的地址'
  21497. * } );
  21498. * ```
  21499. */
  21500. //UE.plugins['webapp'] = function () {
  21501. // var me = this;
  21502. // function createInsertStr( obj, toIframe, addParagraph ) {
  21503. // return !toIframe ?
  21504. // (addParagraph ? '<p>' : '') + '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  21505. // ' src="' + me.options.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif" style="background:url(' + obj.logo+') no-repeat center center; border:1px solid gray;" class="edui-faked-webapp" _url="' + obj.url + '" />' +
  21506. // (addParagraph ? '</p>' : '')
  21507. // :
  21508. // '<iframe class="edui-faked-webapp" title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '" scrolling="no" frameborder="0" src="' + obj.url + '" logo_url = '+obj.logo+'></iframe>';
  21509. // }
  21510. //
  21511. // function switchImgAndIframe( img2frame ) {
  21512. // var tmpdiv,
  21513. // nodes = domUtils.getElementsByTagName( me.document, !img2frame ? "iframe" : "img" );
  21514. // for ( var i = 0, node; node = nodes[i++]; ) {
  21515. // if ( node.className != "edui-faked-webapp" ){
  21516. // continue;
  21517. // }
  21518. // tmpdiv = me.document.createElement( "div" );
  21519. // tmpdiv.innerHTML = createInsertStr( img2frame ? {url:node.getAttribute( "_url" ), width:node.width, height:node.height,title:node.title,logo:node.style.backgroundImage.replace("url(","").replace(")","")} : {url:node.getAttribute( "src", 2 ),title:node.title, width:node.width, height:node.height,logo:node.getAttribute("logo_url")}, img2frame ? true : false,false );
  21520. // node.parentNode.replaceChild( tmpdiv.firstChild, node );
  21521. // }
  21522. // }
  21523. //
  21524. // me.addListener( "beforegetcontent", function () {
  21525. // switchImgAndIframe( true );
  21526. // } );
  21527. // me.addListener( 'aftersetcontent', function () {
  21528. // switchImgAndIframe( false );
  21529. // } );
  21530. // me.addListener( 'aftergetcontent', function ( cmdName ) {
  21531. // if ( cmdName == 'aftergetcontent' && me.queryCommandState( 'source' ) ){
  21532. // return;
  21533. // }
  21534. // switchImgAndIframe( false );
  21535. // } );
  21536. //
  21537. // me.commands['webapp'] = {
  21538. // execCommand:function ( cmd, obj ) {
  21539. // me.execCommand( "inserthtml", createInsertStr( obj, false,true ) );
  21540. // }
  21541. // };
  21542. //};
  21543. UE.plugin.register('webapp', function () {
  21544. var me = this;
  21545. function createInsertStr(obj, toEmbed) {
  21546. return !toEmbed ?
  21547. '<img title="' + obj.title + '" width="' + obj.width + '" height="' + obj.height + '"' +
  21548. ' src="' + me.options.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif" _logo_url="' + obj.logo + '" style="background:url(' + obj.logo
  21549. + ') no-repeat center center; border:1px solid gray;" class="edui-faked-webapp" _url="' + obj.url + '" ' +
  21550. (obj.align && !obj.cssfloat ? 'align="' + obj.align + '"' : '') +
  21551. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  21552. '/>'
  21553. :
  21554. '<iframe class="edui-faked-webapp" title="' + obj.title + '" ' +
  21555. (obj.align && !obj.cssfloat ? 'align="' + obj.align + '"' : '') +
  21556. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  21557. 'width="' + obj.width + '" height="' + obj.height + '" scrolling="no" frameborder="0" src="' + obj.url + '" logo_url = "' + obj.logo + '"></iframe>'
  21558. }
  21559. return {
  21560. outputRule: function (root) {
  21561. utils.each(root.getNodesByTagName('img'), function (node) {
  21562. var html;
  21563. if (node.getAttr('class') == 'edui-faked-webapp') {
  21564. html = createInsertStr({
  21565. title: node.getAttr('title'),
  21566. 'width': node.getAttr('width'),
  21567. 'height': node.getAttr('height'),
  21568. 'align': node.getAttr('align'),
  21569. 'cssfloat': node.getStyle('float'),
  21570. 'url': node.getAttr("_url"),
  21571. 'logo': node.getAttr('_logo_url')
  21572. }, true);
  21573. var embed = UE.uNode.createElement(html);
  21574. node.parentNode.replaceChild(embed, node);
  21575. }
  21576. })
  21577. },
  21578. inputRule: function (root) {
  21579. utils.each(root.getNodesByTagName('iframe'), function (node) {
  21580. if (node.getAttr('class') == 'edui-faked-webapp') {
  21581. var img = UE.uNode.createElement(createInsertStr({
  21582. title: node.getAttr('title'),
  21583. 'width': node.getAttr('width'),
  21584. 'height': node.getAttr('height'),
  21585. 'align': node.getAttr('align'),
  21586. 'cssfloat': node.getStyle('float'),
  21587. 'url': node.getAttr("src"),
  21588. 'logo': node.getAttr('logo_url')
  21589. }));
  21590. node.parentNode.replaceChild(img, node);
  21591. }
  21592. })
  21593. },
  21594. commands: {
  21595. /**
  21596. * 插入百度应用
  21597. * @command webapp
  21598. * @method execCommand
  21599. * @remind 需要百度APPKey
  21600. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  21601. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  21602. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  21603. * @example
  21604. * ```javascript
  21605. * //editor是编辑器实例
  21606. * //在编辑器里插入一个“植物大战僵尸”的APP
  21607. * editor.execCommand( 'webapp' , {
  21608. * title: '植物大战僵尸',
  21609. * width: 560,
  21610. * height: 465,
  21611. * logo: '应用展示的图片',
  21612. * url: '百度应用的地址'
  21613. * } );
  21614. * ```
  21615. */
  21616. 'webapp': {
  21617. execCommand: function (cmd, obj) {
  21618. var me = this,
  21619. str = createInsertStr(utils.extend(obj, {
  21620. align: 'none'
  21621. }), false);
  21622. me.execCommand("inserthtml", str);
  21623. },
  21624. queryCommandState: function () {
  21625. var me = this,
  21626. img = me.selection.getRange().getClosedNode(),
  21627. flag = img && (img.className == "edui-faked-webapp");
  21628. return flag ? 1 : 0;
  21629. }
  21630. }
  21631. }
  21632. }
  21633. });
  21634. // plugins/template.js
  21635. ///import core
  21636. ///import plugins\inserthtml.js
  21637. ///import plugins\cleardoc.js
  21638. ///commands 模板
  21639. ///commandsName template
  21640. ///commandsTitle 模板
  21641. ///commandsDialog dialogs\template
  21642. UE.plugins['template'] = function () {
  21643. UE.commands['template'] = {
  21644. execCommand: function (cmd, obj) {
  21645. obj.html && this.execCommand("inserthtml", obj.html);
  21646. }
  21647. };
  21648. this.addListener("click", function (type, evt) {
  21649. var el = evt.target || evt.srcElement,
  21650. range = this.selection.getRange();
  21651. var tnode = domUtils.findParent(el, function (node) {
  21652. if (node.className && domUtils.hasClass(node, "ue_t")) {
  21653. return node;
  21654. }
  21655. }, true);
  21656. tnode && range.selectNode(tnode).shrinkBoundary().select();
  21657. });
  21658. this.addListener("keydown", function (type, evt) {
  21659. var range = this.selection.getRange();
  21660. if (!range.collapsed) {
  21661. if (!evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  21662. var tnode = domUtils.findParent(range.startContainer, function (node) {
  21663. if (node.className && domUtils.hasClass(node, "ue_t")) {
  21664. return node;
  21665. }
  21666. }, true);
  21667. if (tnode) {
  21668. domUtils.removeClasses(tnode, ["ue_t"]);
  21669. }
  21670. }
  21671. }
  21672. });
  21673. };
  21674. // plugins/music.js
  21675. /**
  21676. * 插入音乐命令
  21677. * @file
  21678. */
  21679. UE.plugin.register('music', function () {
  21680. var me = this;
  21681. function creatInsertStr(url, width, height, align, cssfloat, toEmbed) {
  21682. return !toEmbed ?
  21683. '<img ' +
  21684. (align && !cssfloat ? 'align="' + align + '"' : '') +
  21685. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  21686. ' width="' + width + '" height="' + height + '" _url="' + url + '" class="edui-faked-music"' +
  21687. ' src="' + me.options.langPath + me.options.lang + '/images/music.png" />'
  21688. :
  21689. '<embed type="application/x-shockwave-flash" class="edui-faked-music" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  21690. ' src="' + url + '" width="' + width + '" height="' + height + '" ' + (align && !cssfloat ? 'align="' + align + '"' : '') +
  21691. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  21692. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  21693. }
  21694. return {
  21695. outputRule: function (root) {
  21696. utils.each(root.getNodesByTagName('img'), function (node) {
  21697. var html;
  21698. if (node.getAttr('class') == 'edui-faked-music') {
  21699. var cssfloat = node.getStyle('float');
  21700. var align = node.getAttr('align');
  21701. html = creatInsertStr(node.getAttr("_url"), node.getAttr('width'), node.getAttr('height'), align, cssfloat, true);
  21702. var embed = UE.uNode.createElement(html);
  21703. node.parentNode.replaceChild(embed, node);
  21704. }
  21705. })
  21706. },
  21707. inputRule: function (root) {
  21708. utils.each(root.getNodesByTagName('embed'), function (node) {
  21709. if (node.getAttr('class') == 'edui-faked-music') {
  21710. var cssfloat = node.getStyle('float');
  21711. var align = node.getAttr('align');
  21712. html = creatInsertStr(node.getAttr("src"), node.getAttr('width'), node.getAttr('height'), align, cssfloat, false);
  21713. var img = UE.uNode.createElement(html);
  21714. node.parentNode.replaceChild(img, node);
  21715. }
  21716. })
  21717. },
  21718. commands: {
  21719. /**
  21720. * 插入音乐
  21721. * @command music
  21722. * @method execCommand
  21723. * @param { Object } musicOptions 插入音乐的参数项, 支持的key有: url=>音乐地址;
  21724. * width=>音乐容器宽度;height=>音乐容器高度;align=>音乐文件的对齐方式, 可选值有: left, center, right, none
  21725. * @example
  21726. * ```javascript
  21727. * //editor是编辑器实例
  21728. * //在编辑器里插入一个“植物大战僵尸”的APP
  21729. * editor.execCommand( 'music' , {
  21730. * width: 400,
  21731. * height: 95,
  21732. * align: "center",
  21733. * url: "音乐地址"
  21734. * } );
  21735. * ```
  21736. */
  21737. 'music': {
  21738. execCommand: function (cmd, musicObj) {
  21739. var me = this,
  21740. str = creatInsertStr(musicObj.url, musicObj.width || 400, musicObj.height || 95, "none", false);
  21741. me.execCommand("inserthtml", str);
  21742. },
  21743. queryCommandState: function () {
  21744. var me = this,
  21745. img = me.selection.getRange().getClosedNode(),
  21746. flag = img && (img.className == "edui-faked-music");
  21747. return flag ? 1 : 0;
  21748. }
  21749. }
  21750. }
  21751. }
  21752. });
  21753. // plugins/autoupload.js
  21754. /**
  21755. * @description
  21756. * 1.拖放文件到编辑区域,自动上传并插入到选区
  21757. * 2.插入粘贴板的图片,自动上传并插入到选区
  21758. * @author Jinqn
  21759. * @date 2013-10-14
  21760. */
  21761. UE.plugin.register('autoupload', function () {
  21762. function sendAndInsertFile(file, editor) {
  21763. var me = editor;
  21764. //模拟数据
  21765. var fieldName, urlPrefix, maxSize, allowFiles, actionUrl,
  21766. loadingHtml, errorHandler, successHandler,
  21767. filetype = /image\/\w+/i.test(file.type) ? 'image' : 'file',
  21768. loadingId = 'loading_' + (+new Date()).toString(36);
  21769. fieldName = me.getOpt(filetype + 'FieldName');
  21770. urlPrefix = me.getOpt(filetype + 'UrlPrefix');
  21771. maxSize = me.getOpt(filetype + 'MaxSize');
  21772. allowFiles = me.getOpt(filetype + 'AllowFiles');
  21773. actionUrl = me.getActionUrl(me.getOpt(filetype + 'ActionName'));
  21774. errorHandler = function (title) {
  21775. var loader = me.document.getElementById(loadingId);
  21776. loader && domUtils.remove(loader);
  21777. me.fireEvent('showmessage', {
  21778. 'id': loadingId,
  21779. 'content': title,
  21780. 'type': 'error',
  21781. 'timeout': 4000
  21782. });
  21783. };
  21784. if (filetype == 'image') {
  21785. loadingHtml = '<img class="loadingclass" id="' + loadingId + '" src="' +
  21786. me.options.themePath + me.options.theme +
  21787. '/images/spacer.gif" title="' + (me.getLang('autoupload.loading') || '') + '" >';
  21788. successHandler = function (data) {
  21789. var link = urlPrefix + data.url,
  21790. loader = me.document.getElementById(loadingId);
  21791. if (loader) {
  21792. loader.setAttribute('src', link);
  21793. loader.setAttribute('_src', link);
  21794. loader.setAttribute('title', data.title || '');
  21795. loader.setAttribute('alt', data.original || '');
  21796. loader.removeAttribute('id');
  21797. domUtils.removeClasses(loader, 'loadingclass');
  21798. }
  21799. };
  21800. } else {
  21801. loadingHtml = '<p>' +
  21802. '<img class="loadingclass" id="' + loadingId + '" src="' +
  21803. me.options.themePath + me.options.theme +
  21804. '/images/spacer.gif" title="' + (me.getLang('autoupload.loading') || '') + '" >' +
  21805. '</p>';
  21806. successHandler = function (data) {
  21807. var link = urlPrefix + data.url,
  21808. loader = me.document.getElementById(loadingId);
  21809. var rng = me.selection.getRange(),
  21810. bk = rng.createBookmark();
  21811. rng.selectNode(loader).select();
  21812. me.execCommand('insertfile', { 'url': link });
  21813. rng.moveToBookmark(bk).select();
  21814. };
  21815. }
  21816. /* 插入loading的占位符 */
  21817. me.execCommand('inserthtml', loadingHtml);
  21818. /* 判断后端配置是否没有加载成功 */
  21819. if (!me.getOpt(filetype + 'ActionName')) {
  21820. errorHandler(me.getLang('autoupload.errorLoadConfig'));
  21821. return;
  21822. }
  21823. /* 判断文件大小是否超出限制 */
  21824. if (file.size > maxSize) {
  21825. errorHandler(me.getLang('autoupload.exceedSizeError'));
  21826. return;
  21827. }
  21828. /* 判断文件格式是否超出允许 */
  21829. var fileext = file.name ? file.name.substr(file.name.lastIndexOf('.')) : '';
  21830. if ((fileext && filetype != 'image') || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
  21831. errorHandler(me.getLang('autoupload.exceedTypeError'));
  21832. return;
  21833. }
  21834. /* 创建Ajax并提交 */
  21835. var xhr = new XMLHttpRequest(),
  21836. fd = new FormData(),
  21837. params = utils.serializeParam(me.queryCommandValue('serverparam')) || '',
  21838. url = utils.formatUrl(actionUrl + (actionUrl.indexOf('?') == -1 ? '?' : '&') + params);
  21839. fd.append(fieldName, file, file.name || ('blob.' + file.type.substr('image/'.length)));
  21840. fd.append('type', 'ajax');
  21841. xhr.open("post", url, true);
  21842. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  21843. xhr.addEventListener('load', function (e) {
  21844. try {
  21845. var json = (new Function("return " + utils.trim(e.target.response)))();
  21846. if (json.state == 'SUCCESS' && json.url) {
  21847. successHandler(json);
  21848. } else {
  21849. errorHandler(json.state);
  21850. }
  21851. } catch (er) {
  21852. errorHandler(me.getLang('autoupload.loadError'));
  21853. }
  21854. });
  21855. xhr.send(fd);
  21856. }
  21857. function getPasteImage(e) {
  21858. return e.clipboardData && e.clipboardData.items && e.clipboardData.items.length == 1 && /^image\//.test(e.clipboardData.items[0].type) ? e.clipboardData.items : null;
  21859. }
  21860. function getDropImage(e) {
  21861. return e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files : null;
  21862. }
  21863. return {
  21864. outputRule: function (root) {
  21865. utils.each(root.getNodesByTagName('img'), function (n) {
  21866. if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
  21867. n.parentNode.removeChild(n);
  21868. }
  21869. });
  21870. utils.each(root.getNodesByTagName('p'), function (n) {
  21871. if (/\bloadpara\b/.test(n.getAttr('class'))) {
  21872. n.parentNode.removeChild(n);
  21873. }
  21874. });
  21875. },
  21876. bindEvents: {
  21877. //插入粘贴板的图片,拖放插入图片
  21878. 'ready': function (e) {
  21879. var me = this;
  21880. if (window.FormData && window.FileReader) {
  21881. domUtils.on(me.body, 'paste drop', function (e) {
  21882. var hasImg = false,
  21883. items;
  21884. //获取粘贴板文件列表或者拖放文件列表
  21885. items = e.type == 'paste' ? getPasteImage(e) : getDropImage(e);
  21886. if (items) {
  21887. var len = items.length,
  21888. file;
  21889. while (len--) {
  21890. file = items[len];
  21891. if (file.getAsFile) file = file.getAsFile();
  21892. if (file && file.size > 0) {
  21893. sendAndInsertFile(file, me);
  21894. hasImg = true;
  21895. }
  21896. }
  21897. hasImg && e.preventDefault();
  21898. }
  21899. });
  21900. //取消拖放图片时出现的文字光标位置提示
  21901. domUtils.on(me.body, 'dragover', function (e) {
  21902. if (e.dataTransfer.types[0] == 'Files') {
  21903. e.preventDefault();
  21904. }
  21905. });
  21906. //设置loading的样式
  21907. utils.cssRule('loading',
  21908. '.loadingclass{display:inline-block;cursor:default;background: url(\''
  21909. + this.options.themePath
  21910. + this.options.theme + '/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-left:1px;height: 22px;width: 22px;}\n' +
  21911. '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
  21912. + this.options.themePath
  21913. + this.options.theme + '/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
  21914. '}',
  21915. this.document);
  21916. }
  21917. }
  21918. }
  21919. }
  21920. });
  21921. // plugins/autosave.js
  21922. UE.plugin.register('autosave', function () {
  21923. var me = this,
  21924. //无限循环保护
  21925. lastSaveTime = new Date(),
  21926. //最小保存间隔时间
  21927. MIN_TIME = 20,
  21928. //auto save key
  21929. saveKey = null;
  21930. function save(editor) {
  21931. var saveData;
  21932. if (new Date() - lastSaveTime < MIN_TIME) {
  21933. return;
  21934. }
  21935. if (!editor.hasContents()) {
  21936. //这里不能调用命令来删除, 会造成事件死循环
  21937. saveKey && me.removePreferences(saveKey);
  21938. return;
  21939. }
  21940. lastSaveTime = new Date();
  21941. editor._saveFlag = null;
  21942. saveData = me.body.innerHTML;
  21943. if (editor.fireEvent("beforeautosave", {
  21944. content: saveData
  21945. }) === false) {
  21946. return;
  21947. }
  21948. me.setPreferences(saveKey, saveData);
  21949. editor.fireEvent("afterautosave", {
  21950. content: saveData
  21951. });
  21952. }
  21953. return {
  21954. defaultOptions: {
  21955. //默认间隔时间
  21956. saveInterval: 500,
  21957. enableAutoSave: true // HaoChuan9421
  21958. },
  21959. bindEvents: {
  21960. 'ready': function () {
  21961. var _suffix = "-drafts-data",
  21962. key = null;
  21963. if (me.key) {
  21964. key = me.key + _suffix;
  21965. } else {
  21966. key = (me.container.parentNode.id || 'ue-common') + _suffix;
  21967. }
  21968. //页面地址+编辑器ID 保持唯一
  21969. saveKey = (location.protocol + location.host + location.pathname).replace(/[.:\/]/g, '_') + key;
  21970. },
  21971. 'contentchange': function () {
  21972. // HaoChuan9421
  21973. if (!me.getOpt('enableAutoSave')) {
  21974. return;
  21975. }
  21976. if (!saveKey) {
  21977. return;
  21978. }
  21979. if (me._saveFlag) {
  21980. window.clearTimeout(me._saveFlag);
  21981. }
  21982. if (me.options.saveInterval > 0) {
  21983. me._saveFlag = window.setTimeout(function () {
  21984. save(me);
  21985. }, me.options.saveInterval);
  21986. } else {
  21987. save(me);
  21988. }
  21989. }
  21990. },
  21991. commands: {
  21992. 'clearlocaldata': {
  21993. execCommand: function (cmd, name) {
  21994. if (saveKey && me.getPreferences(saveKey)) {
  21995. me.removePreferences(saveKey)
  21996. }
  21997. },
  21998. notNeedUndo: true,
  21999. ignoreContentChange: true
  22000. },
  22001. 'getlocaldata': {
  22002. execCommand: function (cmd, name) {
  22003. return saveKey ? me.getPreferences(saveKey) || '' : '';
  22004. },
  22005. notNeedUndo: true,
  22006. ignoreContentChange: true
  22007. },
  22008. 'drafts': {
  22009. execCommand: function (cmd, name) {
  22010. if (saveKey) {
  22011. me.body.innerHTML = me.getPreferences(saveKey) || '<p>' + domUtils.fillHtml + '</p>';
  22012. me.focus(true);
  22013. }
  22014. },
  22015. queryCommandState: function () {
  22016. return saveKey ? (me.getPreferences(saveKey) === null ? -1 : 0) : -1;
  22017. },
  22018. notNeedUndo: true,
  22019. ignoreContentChange: true
  22020. }
  22021. }
  22022. }
  22023. });
  22024. // plugins/charts.js
  22025. UE.plugin.register('charts', function () {
  22026. var me = this;
  22027. return {
  22028. bindEvents: {
  22029. 'chartserror': function () {
  22030. }
  22031. },
  22032. commands: {
  22033. 'charts': {
  22034. execCommand: function (cmd, data) {
  22035. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true),
  22036. flagText = [],
  22037. config = {};
  22038. if (!tableNode) {
  22039. return false;
  22040. }
  22041. if (!validData(tableNode)) {
  22042. me.fireEvent("chartserror");
  22043. return false;
  22044. }
  22045. config.title = data.title || '';
  22046. config.subTitle = data.subTitle || '';
  22047. config.xTitle = data.xTitle || '';
  22048. config.yTitle = data.yTitle || '';
  22049. config.suffix = data.suffix || '';
  22050. config.tip = data.tip || '';
  22051. //数据对齐方式
  22052. config.dataFormat = data.tableDataFormat || '';
  22053. //图表类型
  22054. config.chartType = data.chartType || 0;
  22055. for (var key in config) {
  22056. if (!config.hasOwnProperty(key)) {
  22057. continue;
  22058. }
  22059. flagText.push(key + ":" + config[key]);
  22060. }
  22061. tableNode.setAttribute("data-chart", flagText.join(";"));
  22062. domUtils.addClass(tableNode, "edui-charts-table");
  22063. },
  22064. queryCommandState: function (cmd, name) {
  22065. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true);
  22066. return tableNode && validData(tableNode) ? 0 : -1;
  22067. }
  22068. }
  22069. },
  22070. inputRule: function (root) {
  22071. utils.each(root.getNodesByTagName('table'), function (tableNode) {
  22072. if (tableNode.getAttr("data-chart") !== undefined) {
  22073. tableNode.setAttr("style");
  22074. }
  22075. })
  22076. },
  22077. outputRule: function (root) {
  22078. utils.each(root.getNodesByTagName('table'), function (tableNode) {
  22079. if (tableNode.getAttr("data-chart") !== undefined) {
  22080. tableNode.setAttr("style", "display: none;");
  22081. }
  22082. })
  22083. }
  22084. }
  22085. function validData(table) {
  22086. var firstRows = null,
  22087. cellCount = 0;
  22088. //行数不够
  22089. if (table.rows.length < 2) {
  22090. return false;
  22091. }
  22092. //列数不够
  22093. if (table.rows[0].cells.length < 2) {
  22094. return false;
  22095. }
  22096. //第一行所有cell必须是th
  22097. firstRows = table.rows[0].cells;
  22098. cellCount = firstRows.length;
  22099. for (var i = 0, cell; cell = firstRows[i]; i++) {
  22100. if (cell.tagName.toLowerCase() !== 'th') {
  22101. return false;
  22102. }
  22103. }
  22104. for (var i = 1, row; row = table.rows[i]; i++) {
  22105. //每行单元格数不匹配, 返回false
  22106. if (row.cells.length != cellCount) {
  22107. return false;
  22108. }
  22109. //第一列不是th也返回false
  22110. if (row.cells[0].tagName.toLowerCase() !== 'th') {
  22111. return false;
  22112. }
  22113. for (var j = 1, cell; cell = row.cells[j]; j++) {
  22114. var value = utils.trim((cell.innerText || cell.textContent || ''));
  22115. value = value.replace(new RegExp(UE.dom.domUtils.fillChar, 'g'), '').replace(/^\s+|\s+$/g, '');
  22116. //必须是数字
  22117. if (!/^\d*\.?\d+$/.test(value)) {
  22118. return false;
  22119. }
  22120. }
  22121. }
  22122. return true;
  22123. }
  22124. });
  22125. // plugins/section.js
  22126. /**
  22127. * 目录大纲支持插件
  22128. * @file
  22129. * @since 1.3.0
  22130. */
  22131. UE.plugin.register('section', function () {
  22132. /* 目录节点对象 */
  22133. function Section(option) {
  22134. this.tag = '';
  22135. this.level = -1,
  22136. this.dom = null;
  22137. this.nextSection = null;
  22138. this.previousSection = null;
  22139. this.parentSection = null;
  22140. this.startAddress = [];
  22141. this.endAddress = [];
  22142. this.children = [];
  22143. }
  22144. function getSection(option) {
  22145. var section = new Section();
  22146. return utils.extend(section, option);
  22147. }
  22148. function getNodeFromAddress(startAddress, root) {
  22149. var current = root;
  22150. for (var i = 0; i < startAddress.length; i++) {
  22151. if (!current.childNodes) return null;
  22152. current = current.childNodes[startAddress[i]];
  22153. }
  22154. return current;
  22155. }
  22156. var me = this;
  22157. return {
  22158. bindMultiEvents: {
  22159. type: 'aftersetcontent afterscencerestore',
  22160. handler: function () {
  22161. me.fireEvent('updateSections');
  22162. }
  22163. },
  22164. bindEvents: {
  22165. /* 初始化、拖拽、粘贴、执行setcontent之后 */
  22166. 'ready': function () {
  22167. me.fireEvent('updateSections');
  22168. domUtils.on(me.body, 'drop paste', function () {
  22169. me.fireEvent('updateSections');
  22170. });
  22171. },
  22172. /* 执行paragraph命令之后 */
  22173. 'afterexeccommand': function (type, cmd) {
  22174. if (cmd == 'paragraph') {
  22175. me.fireEvent('updateSections');
  22176. }
  22177. },
  22178. /* 部分键盘操作,触发updateSections事件 */
  22179. 'keyup': function (type, e) {
  22180. var me = this,
  22181. range = me.selection.getRange();
  22182. if (range.collapsed != true) {
  22183. me.fireEvent('updateSections');
  22184. } else {
  22185. var keyCode = e.keyCode || e.which;
  22186. if (keyCode == 13 || keyCode == 8 || keyCode == 46) {
  22187. me.fireEvent('updateSections');
  22188. }
  22189. }
  22190. }
  22191. },
  22192. commands: {
  22193. 'getsections': {
  22194. execCommand: function (cmd, levels) {
  22195. var levelFn = levels || ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  22196. for (var i = 0; i < levelFn.length; i++) {
  22197. if (typeof levelFn[i] == 'string') {
  22198. levelFn[i] = function (fn) {
  22199. return function (node) {
  22200. return node.tagName == fn.toUpperCase()
  22201. };
  22202. }(levelFn[i]);
  22203. } else if (typeof levelFn[i] != 'function') {
  22204. levelFn[i] = function (node) {
  22205. return null;
  22206. }
  22207. }
  22208. }
  22209. function getSectionLevel(node) {
  22210. for (var i = 0; i < levelFn.length; i++) {
  22211. if (levelFn[i](node)) return i;
  22212. }
  22213. return -1;
  22214. }
  22215. var me = this,
  22216. Directory = getSection({ 'level': -1, 'title': 'root' }),
  22217. previous = Directory;
  22218. function traversal(node, Directory) {
  22219. var level,
  22220. tmpSection = null,
  22221. parent,
  22222. child,
  22223. children = node.childNodes;
  22224. for (var i = 0, len = children.length; i < len; i++) {
  22225. child = children[i];
  22226. level = getSectionLevel(child);
  22227. if (level >= 0) {
  22228. var address = me.selection.getRange().selectNode(child).createAddress(true).startAddress,
  22229. current = getSection({
  22230. 'tag': child.tagName,
  22231. 'title': child.innerText || child.textContent || '',
  22232. 'level': level,
  22233. 'dom': child,
  22234. 'startAddress': utils.clone(address, []),
  22235. 'endAddress': utils.clone(address, []),
  22236. 'children': []
  22237. });
  22238. previous.nextSection = current;
  22239. current.previousSection = previous;
  22240. parent = previous;
  22241. while (level <= parent.level) {
  22242. parent = parent.parentSection;
  22243. }
  22244. current.parentSection = parent;
  22245. parent.children.push(current);
  22246. tmpSection = previous = current;
  22247. } else {
  22248. child.nodeType === 1 && traversal(child, Directory);
  22249. tmpSection && tmpSection.endAddress[tmpSection.endAddress.length - 1]++;
  22250. }
  22251. }
  22252. }
  22253. traversal(me.body, Directory);
  22254. return Directory;
  22255. },
  22256. notNeedUndo: true
  22257. },
  22258. 'movesection': {
  22259. execCommand: function (cmd, sourceSection, targetSection, isAfter) {
  22260. var me = this,
  22261. targetAddress,
  22262. target;
  22263. if (!sourceSection || !targetSection || targetSection.level == -1) return;
  22264. targetAddress = isAfter ? targetSection.endAddress : targetSection.startAddress;
  22265. target = getNodeFromAddress(targetAddress, me.body);
  22266. /* 判断目标地址是否被源章节包含 */
  22267. if (!targetAddress || !target || isContainsAddress(sourceSection.startAddress, sourceSection.endAddress, targetAddress)) return;
  22268. var startNode = getNodeFromAddress(sourceSection.startAddress, me.body),
  22269. endNode = getNodeFromAddress(sourceSection.endAddress, me.body),
  22270. current,
  22271. nextNode;
  22272. if (isAfter) {
  22273. current = endNode;
  22274. while (current && !(domUtils.getPosition(startNode, current) & domUtils.POSITION_FOLLOWING)) {
  22275. nextNode = current.previousSibling;
  22276. domUtils.insertAfter(target, current);
  22277. if (current == startNode) break;
  22278. current = nextNode;
  22279. }
  22280. } else {
  22281. current = startNode;
  22282. while (current && !(domUtils.getPosition(current, endNode) & domUtils.POSITION_FOLLOWING)) {
  22283. nextNode = current.nextSibling;
  22284. target.parentNode.insertBefore(current, target);
  22285. if (current == endNode) break;
  22286. current = nextNode;
  22287. }
  22288. }
  22289. me.fireEvent('updateSections');
  22290. /* 获取地址的包含关系 */
  22291. function isContainsAddress(startAddress, endAddress, addressTarget) {
  22292. var isAfterStartAddress = false,
  22293. isBeforeEndAddress = false;
  22294. for (var i = 0; i < startAddress.length; i++) {
  22295. if (i >= addressTarget.length) break;
  22296. if (addressTarget[i] > startAddress[i]) {
  22297. isAfterStartAddress = true;
  22298. break;
  22299. } else if (addressTarget[i] < startAddress[i]) {
  22300. break;
  22301. }
  22302. }
  22303. for (var i = 0; i < endAddress.length; i++) {
  22304. if (i >= addressTarget.length) break;
  22305. if (addressTarget[i] < startAddress[i]) {
  22306. isBeforeEndAddress = true;
  22307. break;
  22308. } else if (addressTarget[i] > startAddress[i]) {
  22309. break;
  22310. }
  22311. }
  22312. return isAfterStartAddress && isBeforeEndAddress;
  22313. }
  22314. }
  22315. },
  22316. 'deletesection': {
  22317. execCommand: function (cmd, section, keepChildren) {
  22318. var me = this;
  22319. if (!section) return;
  22320. function getNodeFromAddress(startAddress) {
  22321. var current = me.body;
  22322. for (var i = 0; i < startAddress.length; i++) {
  22323. if (!current.childNodes) return null;
  22324. current = current.childNodes[startAddress[i]];
  22325. }
  22326. return current;
  22327. }
  22328. var startNode = getNodeFromAddress(section.startAddress),
  22329. endNode = getNodeFromAddress(section.endAddress),
  22330. current = startNode,
  22331. nextNode;
  22332. if (!keepChildren) {
  22333. while (current && domUtils.inDoc(endNode, me.document) && !(domUtils.getPosition(current, endNode) & domUtils.POSITION_FOLLOWING)) {
  22334. nextNode = current.nextSibling;
  22335. domUtils.remove(current);
  22336. current = nextNode;
  22337. }
  22338. } else {
  22339. domUtils.remove(current);
  22340. }
  22341. me.fireEvent('updateSections');
  22342. }
  22343. },
  22344. 'selectsection': {
  22345. execCommand: function (cmd, section) {
  22346. if (!section && !section.dom) return false;
  22347. var me = this,
  22348. range = me.selection.getRange(),
  22349. address = {
  22350. 'startAddress': utils.clone(section.startAddress, []),
  22351. 'endAddress': utils.clone(section.endAddress, [])
  22352. };
  22353. address.endAddress[address.endAddress.length - 1]++;
  22354. range.moveToAddress(address).select().scrollToView();
  22355. return true;
  22356. },
  22357. notNeedUndo: true
  22358. },
  22359. 'scrolltosection': {
  22360. execCommand: function (cmd, section) {
  22361. if (!section && !section.dom) return false;
  22362. var me = this,
  22363. range = me.selection.getRange(),
  22364. address = {
  22365. 'startAddress': section.startAddress,
  22366. 'endAddress': section.endAddress
  22367. };
  22368. address.endAddress[address.endAddress.length - 1]++;
  22369. range.moveToAddress(address).scrollToView();
  22370. return true;
  22371. },
  22372. notNeedUndo: true
  22373. }
  22374. }
  22375. }
  22376. });
  22377. // plugins/simpleupload.js
  22378. /**
  22379. * @description
  22380. * 简单上传:点击按钮,直接选择文件上传
  22381. * @author Jinqn
  22382. * @date 2014-03-31
  22383. */
  22384. UE.plugin.register('simpleupload', function () {
  22385. var me = this,
  22386. isLoaded = false,
  22387. containerBtn;
  22388. function initUploadBtn() {
  22389. var w = containerBtn.offsetWidth || 20,
  22390. h = containerBtn.offsetHeight || 20,
  22391. btnIframe = document.createElement('iframe'),
  22392. btnStyle = 'display:block;width:' + w + 'px;height:' + h + 'px;overflow:hidden;border:0;margin:0;padding:0;position:absolute;top:0;left:0;filter:alpha(opacity=0);-moz-opacity:0;-khtml-opacity: 0;opacity: 0;cursor:pointer;';
  22393. domUtils.on(btnIframe, 'load', function () {
  22394. var timestrap = (+new Date()).toString(36),
  22395. wrapper,
  22396. btnIframeDoc,
  22397. btnIframeBody;
  22398. btnIframeDoc = (btnIframe.contentDocument || btnIframe.contentWindow.document);
  22399. btnIframeBody = btnIframeDoc.body;
  22400. wrapper = btnIframeDoc.createElement('div');
  22401. wrapper.innerHTML = '<form id="edui_form_' + timestrap + '" target="edui_iframe_' + timestrap + '" method="POST" enctype="multipart/form-data" action="' + me.getOpt('serverUrl') + '" ' +
  22402. 'style="' + btnStyle + '">' +
  22403. '<input id="edui_input_' + timestrap + '" type="file" accept="image/*" name="' + me.options.imageFieldName + '" ' +
  22404. 'style="' + btnStyle + '">' +
  22405. '</form>' +
  22406. '<iframe id="edui_iframe_' + timestrap + '" name="edui_iframe_' + timestrap + '" style="display:none;width:0;height:0;border:0;margin:0;padding:0;position:absolute;"></iframe>';
  22407. wrapper.className = 'edui-' + me.options.theme;
  22408. wrapper.id = me.ui.id + '_iframeupload';
  22409. btnIframeBody.style.cssText = btnStyle;
  22410. btnIframeBody.style.width = w + 'px';
  22411. btnIframeBody.style.height = h + 'px';
  22412. btnIframeBody.appendChild(wrapper);
  22413. if (btnIframeBody.parentNode) {
  22414. btnIframeBody.parentNode.style.width = w + 'px';
  22415. btnIframeBody.parentNode.style.height = w + 'px';
  22416. }
  22417. var form = btnIframeDoc.getElementById('edui_form_' + timestrap);
  22418. var input = btnIframeDoc.getElementById('edui_input_' + timestrap);
  22419. var iframe = btnIframeDoc.getElementById('edui_iframe_' + timestrap);
  22420. /**
  22421. * 2017-09-07 改掉了ueditor源码,将本身的单文件上传的方法改为ajax上传,主要目的是为了解决跨域的问题
  22422. * @author Guoqing
  22423. */
  22424. domUtils.on(input, 'change', function () {
  22425. if (!input.value) return;
  22426. var loadingId = 'loading_' + (+new Date()).toString(36);
  22427. var imageActionUrl = me.getActionUrl(me.getOpt('imageActionName'));
  22428. var allowFiles = me.getOpt('imageAllowFiles');
  22429. me.focus();
  22430. me.execCommand('inserthtml', '<img class="loadingclass" id="' + loadingId + '" src="' + me.options.themePath + me.options.theme + '/images/spacer.gif" title="' + (me.getLang('simpleupload.loading') || '') + '" >');
  22431. /!* 判断后端配置是否没有加载成功 *!/
  22432. if (!me.getOpt('imageActionName')) {
  22433. errorHandler(me.getLang('autoupload.errorLoadConfig'));
  22434. return;
  22435. }
  22436. // 判断文件格式是否错误
  22437. var filename = input.value,
  22438. fileext = filename ? filename.substr(filename.lastIndexOf('.')) : '';
  22439. if (!fileext || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
  22440. showErrorLoader(me.getLang('simpleupload.exceedTypeError'));
  22441. return;
  22442. }
  22443. var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
  22444. var action = utils.formatUrl(imageActionUrl + (imageActionUrl.indexOf('?') == -1 ? '?' : '&') + params);
  22445. var formData = new FormData();
  22446. formData.append("upfile", form[0].files[0]);
  22447. $.ajax({
  22448. url: action,
  22449. type: 'POST',
  22450. cache: false,
  22451. data: formData,
  22452. processData: false,
  22453. contentType: false,
  22454. success: function (data) {
  22455. data = JSON.parse(data);
  22456. var link, loader,
  22457. body = (iframe.contentDocument || iframe.contentWindow.document).body,
  22458. result = body.innerText || body.textContent || '';
  22459. link = data.url;//me.options.imageUrlPrefix + data.url;
  22460. if (data.state == 'SUCCESS' && data.url) {
  22461. loader = me.document.getElementById(loadingId);
  22462. loader.setAttribute('src', link);
  22463. loader.setAttribute('_src', link);
  22464. loader.setAttribute('title', data.title || '');
  22465. loader.setAttribute('alt', data.original || '');
  22466. loader.removeAttribute('id');
  22467. domUtils.removeClasses(loader, 'loadingclass');
  22468. } else {
  22469. showErrorLoader && showErrorLoader(data.state);
  22470. }
  22471. form.reset();
  22472. }
  22473. });
  22474. function showErrorLoader(title) {
  22475. if (loadingId) {
  22476. var loader = me.document.getElementById(loadingId);
  22477. loader && domUtils.remove(loader);
  22478. me.fireEvent('showmessage', {
  22479. 'id': loadingId,
  22480. 'content': title,
  22481. 'type': 'error',
  22482. 'timeout': 4000
  22483. });
  22484. }
  22485. }
  22486. });
  22487. // domUtils.on(input, 'change', function(){
  22488. // if(!input.value) return;
  22489. // var loadingId = 'loading_' + (+new Date()).toString(36);
  22490. // var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
  22491. // var imageActionUrl = me.getActionUrl(me.getOpt('imageActionName'));
  22492. // var allowFiles = me.getOpt('imageAllowFiles');
  22493. // me.focus();
  22494. // me.execCommand('inserthtml', '<img class="loadingclass" id="' + loadingId + '" src="' + me.options.themePath + me.options.theme +'/images/spacer.gif" title="' + (me.getLang('simpleupload.loading') || '') + '" >');
  22495. // function callback(){
  22496. // try{
  22497. // var link, json, loader,
  22498. // body = (iframe.contentDocument || iframe.contentWindow.document).body,
  22499. // result = body.innerText || body.textContent || '';
  22500. // json = (new Function("return " + result))();
  22501. // link = me.options.imageUrlPrefix + json.url;
  22502. // if(json.state == 'SUCCESS' && json.url) {
  22503. // loader = me.document.getElementById(loadingId);
  22504. // loader.setAttribute('src', link);
  22505. // loader.setAttribute('_src', link);
  22506. // loader.setAttribute('title', json.title || '');
  22507. // loader.setAttribute('alt', json.original || '');
  22508. // loader.removeAttribute('id');
  22509. // domUtils.removeClasses(loader, 'loadingclass');
  22510. // me.fireEvent("contentchange"); // HaoChuan9421
  22511. // } else {
  22512. // showErrorLoader && showErrorLoader(json.state);
  22513. // }
  22514. // }catch(er){
  22515. // showErrorLoader && showErrorLoader(me.getLang('simpleupload.loadError'));
  22516. // }
  22517. // form.reset();
  22518. // domUtils.un(iframe, 'load', callback);
  22519. // }
  22520. // function showErrorLoader(title){
  22521. // if(loadingId) {
  22522. // var loader = me.document.getElementById(loadingId);
  22523. // loader && domUtils.remove(loader);
  22524. // me.fireEvent('showmessage', {
  22525. // 'id': loadingId,
  22526. // 'content': title,
  22527. // 'type': 'error',
  22528. // 'timeout': 4000
  22529. // });
  22530. // }
  22531. // }
  22532. // /* 判断后端配置是否没有加载成功 */
  22533. // if (!me.getOpt('imageActionName')) {
  22534. // errorHandler(me.getLang('autoupload.errorLoadConfig'));
  22535. // return;
  22536. // }
  22537. // // 判断文件格式是否错误
  22538. // var filename = input.value,
  22539. // fileext = filename ? filename.substr(filename.lastIndexOf('.')):'';
  22540. // if (!fileext || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
  22541. // showErrorLoader(me.getLang('simpleupload.exceedTypeError'));
  22542. // return;
  22543. // }
  22544. // domUtils.on(iframe, 'load', callback);
  22545. // form.action = utils.formatUrl(imageActionUrl + (imageActionUrl.indexOf('?') == -1 ? '?':'&') + params);
  22546. // form.submit();
  22547. // });
  22548. var stateTimer;
  22549. me.addListener('selectionchange', function () {
  22550. clearTimeout(stateTimer);
  22551. stateTimer = setTimeout(function () {
  22552. var state = me.queryCommandState('simpleupload');
  22553. if (state == -1) {
  22554. input.disabled = 'disabled';
  22555. } else {
  22556. input.disabled = false;
  22557. }
  22558. }, 400);
  22559. });
  22560. isLoaded = true;
  22561. });
  22562. btnIframe.style.cssText = btnStyle;
  22563. containerBtn.appendChild(btnIframe);
  22564. }
  22565. return {
  22566. bindEvents: {
  22567. 'ready': function () {
  22568. //设置loading的样式
  22569. utils.cssRule('loading',
  22570. '.loadingclass{display:inline-block;cursor:default;background: url(\''
  22571. + this.options.themePath
  22572. + this.options.theme + '/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;}\n' +
  22573. '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
  22574. + this.options.themePath
  22575. + this.options.theme + '/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
  22576. '}',
  22577. this.document);
  22578. },
  22579. /* 初始化简单上传按钮 */
  22580. 'simpleuploadbtnready': function (type, container) {
  22581. containerBtn = container;
  22582. me.afterConfigReady(initUploadBtn);
  22583. }
  22584. },
  22585. outputRule: function (root) {
  22586. utils.each(root.getNodesByTagName('img'), function (n) {
  22587. if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
  22588. n.parentNode.removeChild(n);
  22589. }
  22590. });
  22591. },
  22592. commands: {
  22593. 'simpleupload': {
  22594. queryCommandState: function () {
  22595. return isLoaded ? 0 : -1;
  22596. }
  22597. }
  22598. }
  22599. }
  22600. });
  22601. // plugins/serverparam.js
  22602. /**
  22603. * 服务器提交的额外参数列表设置插件
  22604. * @file
  22605. * @since 1.2.6.1
  22606. */
  22607. UE.plugin.register('serverparam', function () {
  22608. var me = this,
  22609. serverParam = {};
  22610. return {
  22611. commands: {
  22612. /**
  22613. * 修改服务器提交的额外参数列表,清除所有项
  22614. * @command serverparam
  22615. * @method execCommand
  22616. * @param { String } cmd 命令字符串
  22617. * @example
  22618. * ```javascript
  22619. * editor.execCommand('serverparam');
  22620. * editor.queryCommandValue('serverparam'); //返回空
  22621. * ```
  22622. */
  22623. /**
  22624. * 修改服务器提交的额外参数列表,删除指定项
  22625. * @command serverparam
  22626. * @method execCommand
  22627. * @param { String } cmd 命令字符串
  22628. * @param { String } key 要清除的属性
  22629. * @example
  22630. * ```javascript
  22631. * editor.execCommand('serverparam', 'name'); //删除属性name
  22632. * ```
  22633. */
  22634. /**
  22635. * 修改服务器提交的额外参数列表,使用键值添加项
  22636. * @command serverparam
  22637. * @method execCommand
  22638. * @param { String } cmd 命令字符串
  22639. * @param { String } key 要添加的属性
  22640. * @param { String } value 要添加属性的值
  22641. * @example
  22642. * ```javascript
  22643. * editor.execCommand('serverparam', 'name', 'hello');
  22644. * editor.queryCommandValue('serverparam'); //返回对象 {'name': 'hello'}
  22645. * ```
  22646. */
  22647. /**
  22648. * 修改服务器提交的额外参数列表,传入键值对对象添加多项
  22649. * @command serverparam
  22650. * @method execCommand
  22651. * @param { String } cmd 命令字符串
  22652. * @param { Object } key 传入的键值对对象
  22653. * @example
  22654. * ```javascript
  22655. * editor.execCommand('serverparam', {'name': 'hello'});
  22656. * editor.queryCommandValue('serverparam'); //返回对象 {'name': 'hello'}
  22657. * ```
  22658. */
  22659. /**
  22660. * 修改服务器提交的额外参数列表,使用自定义函数添加多项
  22661. * @command serverparam
  22662. * @method execCommand
  22663. * @param { String } cmd 命令字符串
  22664. * @param { Function } key 自定义获取参数的函数
  22665. * @example
  22666. * ```javascript
  22667. * editor.execCommand('serverparam', function(editor){
  22668. * return {'key': 'value'};
  22669. * });
  22670. * editor.queryCommandValue('serverparam'); //返回对象 {'key': 'value'}
  22671. * ```
  22672. */
  22673. /**
  22674. * 获取服务器提交的额外参数列表
  22675. * @command serverparam
  22676. * @method queryCommandValue
  22677. * @param { String } cmd 命令字符串
  22678. * @example
  22679. * ```javascript
  22680. * editor.queryCommandValue( 'serverparam' ); //返回对象 {'key': 'value'}
  22681. * ```
  22682. */
  22683. 'serverparam': {
  22684. execCommand: function (cmd, key, value) {
  22685. if (key === undefined || key === null) { //不传参数,清空列表
  22686. serverParam = {};
  22687. } else if (utils.isString(key)) { //传入键值
  22688. if (value === undefined || value === null) {
  22689. delete serverParam[key];
  22690. } else {
  22691. serverParam[key] = value;
  22692. }
  22693. } else if (utils.isObject(key)) { //传入对象,覆盖列表项
  22694. utils.extend(serverParam, key, true);
  22695. } else if (utils.isFunction(key)) { //传入函数,添加列表项
  22696. utils.extend(serverParam, key(), true);
  22697. }
  22698. },
  22699. queryCommandValue: function () {
  22700. return serverParam || {};
  22701. }
  22702. }
  22703. }
  22704. }
  22705. });
  22706. // plugins/insertfile.js
  22707. /**
  22708. * 插入附件
  22709. */
  22710. UE.plugin.register('insertfile', function () {
  22711. var me = this;
  22712. function getFileIcon(url) {
  22713. var ext = url.substr(url.lastIndexOf('.') + 1).toLowerCase(),
  22714. maps = {
  22715. "rar": "icon_rar.gif",
  22716. "zip": "icon_rar.gif",
  22717. "tar": "icon_rar.gif",
  22718. "gz": "icon_rar.gif",
  22719. "bz2": "icon_rar.gif",
  22720. "doc": "icon_doc.gif",
  22721. "docx": "icon_doc.gif",
  22722. "pdf": "icon_pdf.gif",
  22723. "mp3": "icon_mp3.gif",
  22724. "xls": "icon_xls.gif",
  22725. "chm": "icon_chm.gif",
  22726. "ppt": "icon_ppt.gif",
  22727. "pptx": "icon_ppt.gif",
  22728. "avi": "icon_mv.gif",
  22729. "rmvb": "icon_mv.gif",
  22730. "wmv": "icon_mv.gif",
  22731. "flv": "icon_mv.gif",
  22732. "swf": "icon_mv.gif",
  22733. "rm": "icon_mv.gif",
  22734. "exe": "icon_exe.gif",
  22735. "psd": "icon_psd.gif",
  22736. "txt": "icon_txt.gif",
  22737. "jpg": "icon_jpg.gif",
  22738. "png": "icon_jpg.gif",
  22739. "jpeg": "icon_jpg.gif",
  22740. "gif": "icon_jpg.gif",
  22741. "ico": "icon_jpg.gif",
  22742. "bmp": "icon_jpg.gif"
  22743. };
  22744. return maps[ext] ? maps[ext] : maps['txt'];
  22745. }
  22746. return {
  22747. commands: {
  22748. 'insertfile': {
  22749. execCommand: function (command, filelist) {
  22750. filelist = utils.isArray(filelist) ? filelist : [filelist];
  22751. var i, item, icon, title,
  22752. html = '',
  22753. URL = me.getOpt('UEDITOR_HOME_URL'),
  22754. iconDir = URL + (URL.substr(URL.length - 1) == '/' ? '' : '/') + 'dialogs/attachment/fileTypeImages/';
  22755. for (i = 0; i < filelist.length; i++) {
  22756. item = filelist[i];
  22757. icon = iconDir + getFileIcon(item.url);
  22758. title = item.title || item.url.substr(item.url.lastIndexOf('/') + 1);
  22759. html += '<p style="line-height: 16px;">' +
  22760. '<img style="vertical-align: middle; margin-right: 2px;" src="' + icon + '" _src="' + icon + '" />' +
  22761. '<a style="font-size:12px; color:#0066cc;" href="' + item.url + '" title="' + title + '">' + title + '</a>' +
  22762. '</p>';
  22763. }
  22764. me.execCommand('insertHtml', html);
  22765. }
  22766. }
  22767. }
  22768. }
  22769. });
  22770. // plugins/xssFilter.js
  22771. /**
  22772. * @file xssFilter.js
  22773. * @desc xss过滤器
  22774. * @author robbenmu
  22775. */
  22776. UE.plugins.xssFilter = function () {
  22777. var config = UEDITOR_CONFIG;
  22778. var whitList = config.whitList;
  22779. function filter(node) {
  22780. var tagName = node.tagName;
  22781. var attrs = node.attrs;
  22782. if (!whitList.hasOwnProperty(tagName)) {
  22783. node.parentNode.removeChild(node);
  22784. return false;
  22785. }
  22786. UE.utils.each(attrs, function (val, key) {
  22787. if (whitList[tagName].indexOf(key) === -1) {
  22788. node.setAttr(key);
  22789. }
  22790. });
  22791. }
  22792. // 添加inserthtml\paste等操作用的过滤规则
  22793. if (whitList && config.xssFilterRules) {
  22794. this.options.filterRules = function () {
  22795. var result = {};
  22796. UE.utils.each(whitList, function (val, key) {
  22797. result[key] = function (node) {
  22798. return filter(node);
  22799. };
  22800. });
  22801. return result;
  22802. }();
  22803. }
  22804. var tagList = [];
  22805. UE.utils.each(whitList, function (val, key) {
  22806. tagList.push(key);
  22807. });
  22808. // 添加input过滤规则
  22809. //
  22810. if (whitList && config.inputXssFilter) {
  22811. this.addInputRule(function (root) {
  22812. root.traversal(function (node) {
  22813. if (node.type !== 'element') {
  22814. return false;
  22815. }
  22816. filter(node);
  22817. });
  22818. });
  22819. }
  22820. // 添加output过滤规则
  22821. //
  22822. if (whitList && config.outputXssFilter) {
  22823. this.addOutputRule(function (root) {
  22824. root.traversal(function (node) {
  22825. if (node.type !== 'element') {
  22826. return false;
  22827. }
  22828. filter(node);
  22829. });
  22830. });
  22831. }
  22832. };
  22833. // ui/ui.js
  22834. var baidu = baidu || {};
  22835. baidu.editor = baidu.editor || {};
  22836. UE.ui = baidu.editor.ui = {};
  22837. // ui/uiutils.js
  22838. (function () {
  22839. var browser = baidu.editor.browser,
  22840. domUtils = baidu.editor.dom.domUtils;
  22841. var magic = '$EDITORUI';
  22842. var root = window[magic] = {};
  22843. var uidMagic = 'ID' + magic;
  22844. var uidCount = 0;
  22845. var uiUtils = baidu.editor.ui.uiUtils = {
  22846. uid: function (obj) {
  22847. return (obj ? obj[uidMagic] || (obj[uidMagic] = ++uidCount) : ++uidCount);
  22848. },
  22849. hook: function (fn, callback) {
  22850. var dg;
  22851. if (fn && fn._callbacks) {
  22852. dg = fn;
  22853. } else {
  22854. dg = function () {
  22855. var q;
  22856. if (fn) {
  22857. q = fn.apply(this, arguments);
  22858. }
  22859. var callbacks = dg._callbacks;
  22860. var k = callbacks.length;
  22861. while (k--) {
  22862. var r = callbacks[k].apply(this, arguments);
  22863. if (q === undefined) {
  22864. q = r;
  22865. }
  22866. }
  22867. return q;
  22868. };
  22869. dg._callbacks = [];
  22870. }
  22871. dg._callbacks.push(callback);
  22872. return dg;
  22873. },
  22874. createElementByHtml: function (html) {
  22875. var el = document.createElement('div');
  22876. el.innerHTML = html;
  22877. el = el.firstChild;
  22878. el.parentNode.removeChild(el);
  22879. return el;
  22880. },
  22881. getViewportElement: function () {
  22882. return (browser.ie && browser.quirks) ?
  22883. document.body : document.documentElement;
  22884. },
  22885. getClientRect: function (element) {
  22886. var bcr;
  22887. //trace IE6下在控制编辑器显隐时可能会报错,catch一下
  22888. try {
  22889. bcr = element.getBoundingClientRect();
  22890. } catch (e) {
  22891. bcr = { left: 0, top: 0, height: 0, width: 0 }
  22892. }
  22893. var rect = {
  22894. left: Math.round(bcr.left),
  22895. top: Math.round(bcr.top),
  22896. height: Math.round(bcr.bottom - bcr.top),
  22897. width: Math.round(bcr.right - bcr.left)
  22898. };
  22899. var doc;
  22900. while ((doc = element.ownerDocument) !== document &&
  22901. (element = domUtils.getWindow(doc).frameElement)) {
  22902. bcr = element.getBoundingClientRect();
  22903. rect.left += bcr.left;
  22904. rect.top += bcr.top;
  22905. }
  22906. rect.bottom = rect.top + rect.height;
  22907. rect.right = rect.left + rect.width;
  22908. return rect;
  22909. },
  22910. getViewportRect: function () {
  22911. var viewportEl = uiUtils.getViewportElement();
  22912. var width = (window.innerWidth || viewportEl.clientWidth) | 0;
  22913. var height = (window.innerHeight || viewportEl.clientHeight) | 0;
  22914. return {
  22915. left: 0,
  22916. top: 0,
  22917. height: height,
  22918. width: width,
  22919. bottom: height,
  22920. right: width
  22921. };
  22922. },
  22923. setViewportOffset: function (element, offset) {
  22924. var rect;
  22925. var fixedLayer = uiUtils.getFixedLayer();
  22926. if (element.parentNode === fixedLayer) {
  22927. element.style.left = offset.left + 'px';
  22928. element.style.top = offset.top + 'px';
  22929. } else {
  22930. domUtils.setViewportOffset(element, offset);
  22931. }
  22932. },
  22933. getEventOffset: function (evt) {
  22934. var el = evt.target || evt.srcElement;
  22935. var rect = uiUtils.getClientRect(el);
  22936. var offset = uiUtils.getViewportOffsetByEvent(evt);
  22937. return {
  22938. left: offset.left - rect.left,
  22939. top: offset.top - rect.top
  22940. };
  22941. },
  22942. getViewportOffsetByEvent: function (evt) {
  22943. var el = evt.target || evt.srcElement;
  22944. var frameEl = domUtils.getWindow(el).frameElement;
  22945. var offset = {
  22946. left: evt.clientX,
  22947. top: evt.clientY
  22948. };
  22949. if (frameEl && el.ownerDocument !== document) {
  22950. var rect = uiUtils.getClientRect(frameEl);
  22951. offset.left += rect.left;
  22952. offset.top += rect.top;
  22953. }
  22954. return offset;
  22955. },
  22956. setGlobal: function (id, obj) {
  22957. root[id] = obj;
  22958. return magic + '["' + id + '"]';
  22959. },
  22960. unsetGlobal: function (id) {
  22961. delete root[id];
  22962. },
  22963. copyAttributes: function (tgt, src) {
  22964. var attributes = src.attributes;
  22965. var k = attributes.length;
  22966. while (k--) {
  22967. var attrNode = attributes[k];
  22968. if (attrNode.nodeName != 'style' && attrNode.nodeName != 'class' && (!browser.ie || attrNode.specified)) {
  22969. tgt.setAttribute(attrNode.nodeName, attrNode.nodeValue);
  22970. }
  22971. }
  22972. if (src.className) {
  22973. domUtils.addClass(tgt, src.className);
  22974. }
  22975. if (src.style.cssText) {
  22976. tgt.style.cssText += ';' + src.style.cssText;
  22977. }
  22978. },
  22979. removeStyle: function (el, styleName) {
  22980. if (el.style.removeProperty) {
  22981. el.style.removeProperty(styleName);
  22982. } else if (el.style.removeAttribute) {
  22983. el.style.removeAttribute(styleName);
  22984. } else throw '';
  22985. },
  22986. contains: function (elA, elB) {
  22987. return elA && elB && (elA === elB ? false : (
  22988. elA.contains ? elA.contains(elB) :
  22989. elA.compareDocumentPosition(elB) & 16
  22990. ));
  22991. },
  22992. startDrag: function (evt, callbacks, doc) {
  22993. var doc = doc || document;
  22994. var startX = evt.clientX;
  22995. var startY = evt.clientY;
  22996. function handleMouseMove(evt) {
  22997. var x = evt.clientX - startX;
  22998. var y = evt.clientY - startY;
  22999. callbacks.ondragmove(x, y, evt);
  23000. if (evt.stopPropagation) {
  23001. evt.stopPropagation();
  23002. } else {
  23003. evt.cancelBubble = true;
  23004. }
  23005. }
  23006. if (doc.addEventListener) {
  23007. function handleMouseUp(evt) {
  23008. doc.removeEventListener('mousemove', handleMouseMove, true);
  23009. doc.removeEventListener('mouseup', handleMouseUp, true);
  23010. window.removeEventListener('mouseup', handleMouseUp, true);
  23011. callbacks.ondragstop();
  23012. }
  23013. doc.addEventListener('mousemove', handleMouseMove, true);
  23014. doc.addEventListener('mouseup', handleMouseUp, true);
  23015. window.addEventListener('mouseup', handleMouseUp, true);
  23016. evt.preventDefault();
  23017. } else {
  23018. var elm = evt.srcElement;
  23019. elm.setCapture();
  23020. function releaseCaptrue() {
  23021. elm.releaseCapture();
  23022. elm.detachEvent('onmousemove', handleMouseMove);
  23023. elm.detachEvent('onmouseup', releaseCaptrue);
  23024. elm.detachEvent('onlosecaptrue', releaseCaptrue);
  23025. callbacks.ondragstop();
  23026. }
  23027. elm.attachEvent('onmousemove', handleMouseMove);
  23028. elm.attachEvent('onmouseup', releaseCaptrue);
  23029. elm.attachEvent('onlosecaptrue', releaseCaptrue);
  23030. evt.returnValue = false;
  23031. }
  23032. callbacks.ondragstart();
  23033. },
  23034. getFixedLayer: function () {
  23035. var layer = document.getElementById('edui_fixedlayer');
  23036. if (layer == null) {
  23037. layer = document.createElement('div');
  23038. layer.id = 'edui_fixedlayer';
  23039. document.body.appendChild(layer);
  23040. if (browser.ie && browser.version <= 8) {
  23041. layer.style.position = 'absolute';
  23042. bindFixedLayer();
  23043. setTimeout(updateFixedOffset);
  23044. } else {
  23045. layer.style.position = 'fixed';
  23046. }
  23047. layer.style.left = '0';
  23048. layer.style.top = '0';
  23049. layer.style.width = '0';
  23050. layer.style.height = '0';
  23051. }
  23052. return layer;
  23053. },
  23054. makeUnselectable: function (element) {
  23055. if (browser.opera || (browser.ie && browser.version < 9)) {
  23056. element.unselectable = 'on';
  23057. if (element.hasChildNodes()) {
  23058. for (var i = 0; i < element.childNodes.length; i++) {
  23059. if (element.childNodes[i].nodeType == 1) {
  23060. uiUtils.makeUnselectable(element.childNodes[i]);
  23061. }
  23062. }
  23063. }
  23064. } else {
  23065. if (element.style.MozUserSelect !== undefined) {
  23066. element.style.MozUserSelect = 'none';
  23067. } else if (element.style.WebkitUserSelect !== undefined) {
  23068. element.style.WebkitUserSelect = 'none';
  23069. } else if (element.style.KhtmlUserSelect !== undefined) {
  23070. element.style.KhtmlUserSelect = 'none';
  23071. }
  23072. }
  23073. }
  23074. };
  23075. function updateFixedOffset() {
  23076. var layer = document.getElementById('edui_fixedlayer');
  23077. uiUtils.setViewportOffset(layer, {
  23078. left: 0,
  23079. top: 0
  23080. });
  23081. // layer.style.display = 'none';
  23082. // layer.style.display = 'block';
  23083. //#trace: 1354
  23084. // setTimeout(updateFixedOffset);
  23085. }
  23086. function bindFixedLayer(adjOffset) {
  23087. domUtils.on(window, 'scroll', updateFixedOffset);
  23088. domUtils.on(window, 'resize', baidu.editor.utils.defer(updateFixedOffset, 0, true));
  23089. }
  23090. })();
  23091. // ui/uibase.js
  23092. (function () {
  23093. var utils = baidu.editor.utils,
  23094. uiUtils = baidu.editor.ui.uiUtils,
  23095. EventBase = baidu.editor.EventBase,
  23096. UIBase = baidu.editor.ui.UIBase = function () {
  23097. };
  23098. UIBase.prototype = {
  23099. className: '',
  23100. uiName: '',
  23101. initOptions: function (options) {
  23102. var me = this;
  23103. for (var k in options) {
  23104. me[k] = options[k];
  23105. }
  23106. this.id = this.id || 'edui' + uiUtils.uid();
  23107. },
  23108. initUIBase: function () {
  23109. this._globalKey = utils.unhtml(uiUtils.setGlobal(this.id, this));
  23110. },
  23111. render: function (holder) {
  23112. var html = this.renderHtml();
  23113. var el = uiUtils.createElementByHtml(html);
  23114. //by xuheng 给每个node添加class
  23115. var list = domUtils.getElementsByTagName(el, "*");
  23116. var theme = "edui-" + (this.theme || this.editor.options.theme);
  23117. var layer = document.getElementById('edui_fixedlayer');
  23118. for (var i = 0, node; node = list[i++];) {
  23119. domUtils.addClass(node, theme);
  23120. }
  23121. domUtils.addClass(el, theme);
  23122. if (layer) {
  23123. layer.className = "";
  23124. domUtils.addClass(layer, theme);
  23125. }
  23126. var seatEl = this.getDom();
  23127. if (seatEl != null) {
  23128. seatEl.parentNode.replaceChild(el, seatEl);
  23129. uiUtils.copyAttributes(el, seatEl);
  23130. } else {
  23131. if (typeof holder == 'string') {
  23132. holder = document.getElementById(holder);
  23133. }
  23134. holder = holder || uiUtils.getFixedLayer();
  23135. domUtils.addClass(holder, theme);
  23136. holder.appendChild(el);
  23137. }
  23138. this.postRender();
  23139. },
  23140. getDom: function (name) {
  23141. if (!name) {
  23142. return document.getElementById(this.id);
  23143. } else {
  23144. return document.getElementById(this.id + '_' + name);
  23145. }
  23146. },
  23147. postRender: function () {
  23148. this.fireEvent('postrender');
  23149. },
  23150. getHtmlTpl: function () {
  23151. return '';
  23152. },
  23153. formatHtml: function (tpl) {
  23154. var prefix = 'edui-' + this.uiName;
  23155. return (tpl
  23156. .replace(/##/g, this.id)
  23157. .replace(/%%-/g, this.uiName ? prefix + '-' : '')
  23158. .replace(/%%/g, (this.uiName ? prefix : '') + ' ' + this.className)
  23159. .replace(/\$\$/g, this._globalKey));
  23160. },
  23161. renderHtml: function () {
  23162. return this.formatHtml(this.getHtmlTpl());
  23163. },
  23164. dispose: function () {
  23165. var box = this.getDom();
  23166. if (box) baidu.editor.dom.domUtils.remove(box);
  23167. uiUtils.unsetGlobal(this.id);
  23168. }
  23169. };
  23170. utils.inherits(UIBase, EventBase);
  23171. })();
  23172. // ui/separator.js
  23173. (function () {
  23174. var utils = baidu.editor.utils,
  23175. UIBase = baidu.editor.ui.UIBase,
  23176. Separator = baidu.editor.ui.Separator = function (options) {
  23177. this.initOptions(options);
  23178. this.initSeparator();
  23179. };
  23180. Separator.prototype = {
  23181. uiName: 'separator',
  23182. initSeparator: function () {
  23183. this.initUIBase();
  23184. },
  23185. getHtmlTpl: function () {
  23186. return '<div id="##" class="edui-box %%"></div>';
  23187. }
  23188. };
  23189. utils.inherits(Separator, UIBase);
  23190. })();
  23191. // ui/mask.js
  23192. ///import core
  23193. ///import uicore
  23194. (function () {
  23195. var utils = baidu.editor.utils,
  23196. domUtils = baidu.editor.dom.domUtils,
  23197. UIBase = baidu.editor.ui.UIBase,
  23198. uiUtils = baidu.editor.ui.uiUtils;
  23199. var Mask = baidu.editor.ui.Mask = function (options) {
  23200. this.initOptions(options);
  23201. this.initUIBase();
  23202. };
  23203. Mask.prototype = {
  23204. getHtmlTpl: function () {
  23205. return '<div id="##" class="edui-mask %%" onclick="return $$._onClick(event, this);" onmousedown="return $$._onMouseDown(event, this);"></div>';
  23206. },
  23207. postRender: function () {
  23208. var me = this;
  23209. domUtils.on(window, 'resize', function () {
  23210. setTimeout(function () {
  23211. if (!me.isHidden()) {
  23212. me._fill();
  23213. }
  23214. });
  23215. });
  23216. },
  23217. show: function (zIndex) {
  23218. this._fill();
  23219. this.getDom().style.display = '';
  23220. this.getDom().style.zIndex = zIndex;
  23221. },
  23222. hide: function () {
  23223. this.getDom().style.display = 'none';
  23224. this.getDom().style.zIndex = '';
  23225. },
  23226. isHidden: function () {
  23227. return this.getDom().style.display == 'none';
  23228. },
  23229. _onMouseDown: function () {
  23230. return false;
  23231. },
  23232. _onClick: function (e, target) {
  23233. this.fireEvent('click', e, target);
  23234. },
  23235. _fill: function () {
  23236. var el = this.getDom();
  23237. var vpRect = uiUtils.getViewportRect();
  23238. el.style.width = vpRect.width + 'px';
  23239. el.style.height = vpRect.height + 'px';
  23240. }
  23241. };
  23242. utils.inherits(Mask, UIBase);
  23243. })();
  23244. // ui/popup.js
  23245. ///import core
  23246. ///import uicore
  23247. (function () {
  23248. var utils = baidu.editor.utils,
  23249. uiUtils = baidu.editor.ui.uiUtils,
  23250. domUtils = baidu.editor.dom.domUtils,
  23251. UIBase = baidu.editor.ui.UIBase,
  23252. Popup = baidu.editor.ui.Popup = function (options) {
  23253. this.initOptions(options);
  23254. this.initPopup();
  23255. };
  23256. var allPopups = [];
  23257. function closeAllPopup(evt, el) {
  23258. for (var i = 0; i < allPopups.length; i++) {
  23259. var pop = allPopups[i];
  23260. if (!pop.isHidden()) {
  23261. if (pop.queryAutoHide(el) !== false) {
  23262. if (evt && /scroll/ig.test(evt.type) && pop.className == "edui-wordpastepop") return;
  23263. pop.hide();
  23264. }
  23265. }
  23266. }
  23267. if (allPopups.length)
  23268. pop.editor.fireEvent("afterhidepop");
  23269. }
  23270. Popup.postHide = closeAllPopup;
  23271. var ANCHOR_CLASSES = ['edui-anchor-topleft', 'edui-anchor-topright',
  23272. 'edui-anchor-bottomleft', 'edui-anchor-bottomright'];
  23273. Popup.prototype = {
  23274. SHADOW_RADIUS: 5,
  23275. content: null,
  23276. _hidden: false,
  23277. autoRender: true,
  23278. canSideLeft: true,
  23279. canSideUp: true,
  23280. initPopup: function () {
  23281. this.initUIBase();
  23282. allPopups.push(this);
  23283. },
  23284. getHtmlTpl: function () {
  23285. return '<div id="##" class="edui-popup %%" onmousedown="return false;">' +
  23286. ' <div id="##_body" class="edui-popup-body">' +
  23287. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  23288. ' <div class="edui-shadow"></div>' +
  23289. ' <div id="##_content" class="edui-popup-content">' +
  23290. this.getContentHtmlTpl() +
  23291. ' </div>' +
  23292. ' </div>' +
  23293. '</div>';
  23294. },
  23295. getContentHtmlTpl: function () {
  23296. if (this.content) {
  23297. if (typeof this.content == 'string') {
  23298. return this.content;
  23299. }
  23300. return this.content.renderHtml();
  23301. } else {
  23302. return ''
  23303. }
  23304. },
  23305. _UIBase_postRender: UIBase.prototype.postRender,
  23306. postRender: function () {
  23307. if (this.content instanceof UIBase) {
  23308. this.content.postRender();
  23309. }
  23310. //捕获鼠标滚轮
  23311. if (this.captureWheel && !this.captured) {
  23312. this.captured = true;
  23313. var winHeight = (document.documentElement.clientHeight || document.body.clientHeight) - 80,
  23314. _height = this.getDom().offsetHeight,
  23315. _top = uiUtils.getClientRect(this.combox.getDom()).top,
  23316. content = this.getDom('content'),
  23317. ifr = this.getDom('body').getElementsByTagName('iframe'),
  23318. me = this;
  23319. ifr.length && (ifr = ifr[0]);
  23320. while (_top + _height > winHeight) {
  23321. _height -= 30;
  23322. }
  23323. content.style.height = _height + 'px';
  23324. //同步更改iframe高度
  23325. ifr && (ifr.style.height = _height + 'px');
  23326. //阻止在combox上的鼠标滚轮事件, 防止用户的正常操作被误解
  23327. if (window.XMLHttpRequest) {
  23328. domUtils.on(content, ('onmousewheel' in document.body) ? 'mousewheel' : 'DOMMouseScroll', function (e) {
  23329. if (e.preventDefault) {
  23330. e.preventDefault();
  23331. } else {
  23332. e.returnValue = false;
  23333. }
  23334. if (e.wheelDelta) {
  23335. content.scrollTop -= (e.wheelDelta / 120) * 60;
  23336. } else {
  23337. content.scrollTop -= (e.detail / -3) * 60;
  23338. }
  23339. });
  23340. } else {
  23341. //ie6
  23342. domUtils.on(this.getDom(), 'mousewheel', function (e) {
  23343. e.returnValue = false;
  23344. me.getDom('content').scrollTop -= (e.wheelDelta / 120) * 60;
  23345. });
  23346. }
  23347. }
  23348. this.fireEvent('postRenderAfter');
  23349. this.hide(true);
  23350. this._UIBase_postRender();
  23351. },
  23352. _doAutoRender: function () {
  23353. if (!this.getDom() && this.autoRender) {
  23354. this.render();
  23355. }
  23356. },
  23357. mesureSize: function () {
  23358. var box = this.getDom('content');
  23359. return uiUtils.getClientRect(box);
  23360. },
  23361. fitSize: function () {
  23362. if (this.captureWheel && this.sized) {
  23363. return this.__size;
  23364. }
  23365. this.sized = true;
  23366. var popBodyEl = this.getDom('body');
  23367. popBodyEl.style.width = '';
  23368. popBodyEl.style.height = '';
  23369. var size = this.mesureSize();
  23370. if (this.captureWheel) {
  23371. popBodyEl.style.width = -(-20 - size.width) + 'px';
  23372. var height = parseInt(this.getDom('content').style.height, 10);
  23373. !window.isNaN(height) && (size.height = height);
  23374. } else {
  23375. popBodyEl.style.width = size.width + 'px';
  23376. }
  23377. popBodyEl.style.height = size.height + 'px';
  23378. this.__size = size;
  23379. this.captureWheel && (this.getDom('content').style.overflow = 'auto');
  23380. return size;
  23381. },
  23382. showAnchor: function (element, hoz) {
  23383. this.showAnchorRect(uiUtils.getClientRect(element), hoz);
  23384. },
  23385. showAnchorRect: function (rect, hoz, adj) {
  23386. this._doAutoRender();
  23387. var vpRect = uiUtils.getViewportRect();
  23388. this.getDom().style.visibility = 'hidden';
  23389. this._show();
  23390. var popSize = this.fitSize();
  23391. var sideLeft, sideUp, left, top;
  23392. if (hoz) {
  23393. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  23394. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  23395. left = (sideLeft ? rect.left - popSize.width : rect.right);
  23396. top = (sideUp ? rect.bottom - popSize.height : rect.top);
  23397. } else {
  23398. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  23399. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  23400. left = (sideLeft ? rect.right - popSize.width : rect.left);
  23401. top = (sideUp ? rect.top - popSize.height : rect.bottom);
  23402. }
  23403. var popEl = this.getDom();
  23404. uiUtils.setViewportOffset(popEl, {
  23405. left: left,
  23406. top: top
  23407. });
  23408. domUtils.removeClasses(popEl, ANCHOR_CLASSES);
  23409. popEl.className += ' ' + ANCHOR_CLASSES[(sideUp ? 1 : 0) * 2 + (sideLeft ? 1 : 0)];
  23410. if (this.editor) {
  23411. popEl.style.zIndex = this.editor.container.style.zIndex * 1 + 10;
  23412. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = popEl.style.zIndex - 1;
  23413. }
  23414. this.getDom().style.visibility = 'visible';
  23415. },
  23416. showAt: function (offset) {
  23417. var left = offset.left;
  23418. var top = offset.top;
  23419. var rect = {
  23420. left: left,
  23421. top: top,
  23422. right: left,
  23423. bottom: top,
  23424. height: 0,
  23425. width: 0
  23426. };
  23427. this.showAnchorRect(rect, false, true);
  23428. },
  23429. _show: function () {
  23430. if (this._hidden) {
  23431. var box = this.getDom();
  23432. box.style.display = '';
  23433. this._hidden = false;
  23434. // if (box.setActive) {
  23435. // box.setActive();
  23436. // }
  23437. this.fireEvent('show');
  23438. }
  23439. },
  23440. isHidden: function () {
  23441. return this._hidden;
  23442. },
  23443. show: function () {
  23444. this._doAutoRender();
  23445. this._show();
  23446. },
  23447. hide: function (notNofity) {
  23448. if (!this._hidden && this.getDom()) {
  23449. this.getDom().style.display = 'none';
  23450. this._hidden = true;
  23451. if (!notNofity) {
  23452. this.fireEvent('hide');
  23453. }
  23454. }
  23455. },
  23456. queryAutoHide: function (el) {
  23457. return !el || !uiUtils.contains(this.getDom(), el);
  23458. }
  23459. };
  23460. utils.inherits(Popup, UIBase);
  23461. domUtils.on(document, 'mousedown', function (evt) {
  23462. var el = evt.target || evt.srcElement;
  23463. closeAllPopup(evt, el);
  23464. });
  23465. domUtils.on(window, 'scroll', function (evt, el) {
  23466. closeAllPopup(evt, el);
  23467. });
  23468. })();
  23469. // ui/colorpicker.js
  23470. ///import core
  23471. ///import uicore
  23472. (function () {
  23473. var utils = baidu.editor.utils,
  23474. UIBase = baidu.editor.ui.UIBase,
  23475. ColorPicker = baidu.editor.ui.ColorPicker = function (options) {
  23476. this.initOptions(options);
  23477. this.noColorText = this.noColorText || this.editor.getLang("clearColor");
  23478. this.initUIBase();
  23479. };
  23480. ColorPicker.prototype = {
  23481. getHtmlTpl: function () {
  23482. return genColorPicker(this.noColorText, this.editor);
  23483. },
  23484. _onTableClick: function (evt) {
  23485. var tgt = evt.target || evt.srcElement;
  23486. var color = tgt.getAttribute('data-color');
  23487. if (color) {
  23488. this.fireEvent('pickcolor', color);
  23489. }
  23490. },
  23491. _onTableOver: function (evt) {
  23492. var tgt = evt.target || evt.srcElement;
  23493. var color = tgt.getAttribute('data-color');
  23494. if (color) {
  23495. this.getDom('preview').style.backgroundColor = color;
  23496. }
  23497. },
  23498. _onTableOut: function () {
  23499. this.getDom('preview').style.backgroundColor = '';
  23500. },
  23501. _onPickNoColor: function () {
  23502. this.fireEvent('picknocolor');
  23503. }
  23504. };
  23505. utils.inherits(ColorPicker, UIBase);
  23506. var COLORS = (
  23507. 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' +
  23508. 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' +
  23509. 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' +
  23510. 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' +
  23511. 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' +
  23512. '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' +
  23513. 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(',');
  23514. function genColorPicker(noColorText, editor) {
  23515. var html = '<div id="##" class="edui-colorpicker %%">' +
  23516. '<div class="edui-colorpicker-topbar edui-clearfix">' +
  23517. '<div unselectable="on" id="##_preview" class="edui-colorpicker-preview"></div>' +
  23518. '<div unselectable="on" class="edui-colorpicker-nocolor" onclick="$$._onPickNoColor(event, this);">' + noColorText + '</div>' +
  23519. '</div>' +
  23520. '<table class="edui-box" style="border-collapse: collapse;" onmouseover="$$._onTableOver(event, this);" onmouseout="$$._onTableOut(event, this);" onclick="return $$._onTableClick(event, this);" cellspacing="0" cellpadding="0">' +
  23521. '<tr style="border-bottom: 1px solid #ddd;font-size: 13px;line-height: 25px;color:#39C;padding-top: 2px"><td colspan="10">' + editor.getLang("themeColor") + '</td> </tr>' +
  23522. '<tr class="edui-colorpicker-tablefirstrow" >';
  23523. for (var i = 0; i < COLORS.length; i++) {
  23524. if (i && i % 10 === 0) {
  23525. html += '</tr>' + (i == 60 ? '<tr style="border-bottom: 1px solid #ddd;font-size: 13px;line-height: 25px;color:#39C;"><td colspan="10">' + editor.getLang("standardColor") + '</td></tr>' : '') + '<tr' + (i == 60 ? ' class="edui-colorpicker-tablefirstrow"' : '') + '>';
  23526. }
  23527. html += i < 70 ? '<td style="padding: 0 2px;"><a hidefocus title="' + COLORS[i] + '" onclick="return false;" href="javascript:" unselectable="on" class="edui-box edui-colorpicker-colorcell"' +
  23528. ' data-color="#' + COLORS[i] + '"' +
  23529. ' style="background-color:#' + COLORS[i] + ';border:solid #ccc;' +
  23530. (i < 10 || i >= 60 ? 'border-width:1px;' :
  23531. i >= 10 && i < 20 ? 'border-width:1px 1px 0 1px;' :
  23532. 'border-width:0 1px 0 1px;') +
  23533. '"' +
  23534. '></a></td>' : '';
  23535. }
  23536. html += '</tr></table></div>';
  23537. return html;
  23538. }
  23539. })();
  23540. // ui/tablepicker.js
  23541. ///import core
  23542. ///import uicore
  23543. (function () {
  23544. var utils = baidu.editor.utils,
  23545. uiUtils = baidu.editor.ui.uiUtils,
  23546. UIBase = baidu.editor.ui.UIBase;
  23547. var TablePicker = baidu.editor.ui.TablePicker = function (options) {
  23548. this.initOptions(options);
  23549. this.initTablePicker();
  23550. };
  23551. TablePicker.prototype = {
  23552. defaultNumRows: 10,
  23553. defaultNumCols: 10,
  23554. maxNumRows: 20,
  23555. maxNumCols: 20,
  23556. numRows: 10,
  23557. numCols: 10,
  23558. lengthOfCellSide: 22,
  23559. initTablePicker: function () {
  23560. this.initUIBase();
  23561. },
  23562. getHtmlTpl: function () {
  23563. var me = this;
  23564. return '<div id="##" class="edui-tablepicker %%">' +
  23565. '<div class="edui-tablepicker-body">' +
  23566. '<div class="edui-infoarea">' +
  23567. '<span id="##_label" class="edui-label"></span>' +
  23568. '</div>' +
  23569. '<div class="edui-pickarea"' +
  23570. ' onmousemove="$$._onMouseMove(event, this);"' +
  23571. ' onmouseover="$$._onMouseOver(event, this);"' +
  23572. ' onmouseout="$$._onMouseOut(event, this);"' +
  23573. ' onclick="$$._onClick(event, this);"' +
  23574. '>' +
  23575. '<div id="##_overlay" class="edui-overlay"></div>' +
  23576. '</div>' +
  23577. '</div>' +
  23578. '</div>';
  23579. },
  23580. _UIBase_render: UIBase.prototype.render,
  23581. render: function (holder) {
  23582. this._UIBase_render(holder);
  23583. this.getDom('label').innerHTML = '0' + this.editor.getLang("t_row") + ' x 0' + this.editor.getLang("t_col");
  23584. },
  23585. _track: function (numCols, numRows) {
  23586. var style = this.getDom('overlay').style;
  23587. var sideLen = this.lengthOfCellSide;
  23588. style.width = numCols * sideLen + 'px';
  23589. style.height = numRows * sideLen + 'px';
  23590. var label = this.getDom('label');
  23591. label.innerHTML = numCols + this.editor.getLang("t_col") + ' x ' + numRows + this.editor.getLang("t_row");
  23592. this.numCols = numCols;
  23593. this.numRows = numRows;
  23594. },
  23595. _onMouseOver: function (evt, el) {
  23596. var rel = evt.relatedTarget || evt.fromElement;
  23597. if (!uiUtils.contains(el, rel) && el !== rel) {
  23598. this.getDom('label').innerHTML = '0' + this.editor.getLang("t_col") + ' x 0' + this.editor.getLang("t_row");
  23599. this.getDom('overlay').style.visibility = '';
  23600. }
  23601. },
  23602. _onMouseOut: function (evt, el) {
  23603. var rel = evt.relatedTarget || evt.toElement;
  23604. if (!uiUtils.contains(el, rel) && el !== rel) {
  23605. this.getDom('label').innerHTML = '0' + this.editor.getLang("t_col") + ' x 0' + this.editor.getLang("t_row");
  23606. this.getDom('overlay').style.visibility = 'hidden';
  23607. }
  23608. },
  23609. _onMouseMove: function (evt, el) {
  23610. var style = this.getDom('overlay').style;
  23611. var offset = uiUtils.getEventOffset(evt);
  23612. var sideLen = this.lengthOfCellSide;
  23613. var numCols = Math.ceil(offset.left / sideLen);
  23614. var numRows = Math.ceil(offset.top / sideLen);
  23615. this._track(numCols, numRows);
  23616. },
  23617. _onClick: function () {
  23618. this.fireEvent('picktable', this.numCols, this.numRows);
  23619. }
  23620. };
  23621. utils.inherits(TablePicker, UIBase);
  23622. })();
  23623. // ui/stateful.js
  23624. (function () {
  23625. var browser = baidu.editor.browser,
  23626. domUtils = baidu.editor.dom.domUtils,
  23627. uiUtils = baidu.editor.ui.uiUtils;
  23628. var TPL_STATEFUL = 'onmousedown="$$.Stateful_onMouseDown(event, this);"' +
  23629. ' onmouseup="$$.Stateful_onMouseUp(event, this);"' +
  23630. (browser.ie ? (
  23631. ' onmouseenter="$$.Stateful_onMouseEnter(event, this);"' +
  23632. ' onmouseleave="$$.Stateful_onMouseLeave(event, this);"')
  23633. : (
  23634. ' onmouseover="$$.Stateful_onMouseOver(event, this);"' +
  23635. ' onmouseout="$$.Stateful_onMouseOut(event, this);"'));
  23636. baidu.editor.ui.Stateful = {
  23637. alwalysHoverable: false,
  23638. target: null,//目标元素和this指向dom不一样
  23639. Stateful_init: function () {
  23640. this._Stateful_dGetHtmlTpl = this.getHtmlTpl;
  23641. this.getHtmlTpl = this.Stateful_getHtmlTpl;
  23642. },
  23643. Stateful_getHtmlTpl: function () {
  23644. var tpl = this._Stateful_dGetHtmlTpl();
  23645. // 使用function避免$转义
  23646. return tpl.replace(/stateful/g, function () { return TPL_STATEFUL; });
  23647. },
  23648. Stateful_onMouseEnter: function (evt, el) {
  23649. this.target = el;
  23650. if (!this.isDisabled() || this.alwalysHoverable) {
  23651. this.addState('hover');
  23652. this.fireEvent('over');
  23653. }
  23654. },
  23655. Stateful_onMouseLeave: function (evt, el) {
  23656. if (!this.isDisabled() || this.alwalysHoverable) {
  23657. this.removeState('hover');
  23658. this.removeState('active');
  23659. this.fireEvent('out');
  23660. }
  23661. },
  23662. Stateful_onMouseOver: function (evt, el) {
  23663. var rel = evt.relatedTarget;
  23664. if (!uiUtils.contains(el, rel) && el !== rel) {
  23665. this.Stateful_onMouseEnter(evt, el);
  23666. }
  23667. },
  23668. Stateful_onMouseOut: function (evt, el) {
  23669. var rel = evt.relatedTarget;
  23670. if (!uiUtils.contains(el, rel) && el !== rel) {
  23671. this.Stateful_onMouseLeave(evt, el);
  23672. }
  23673. },
  23674. Stateful_onMouseDown: function (evt, el) {
  23675. if (!this.isDisabled()) {
  23676. this.addState('active');
  23677. }
  23678. },
  23679. Stateful_onMouseUp: function (evt, el) {
  23680. if (!this.isDisabled()) {
  23681. this.removeState('active');
  23682. }
  23683. },
  23684. Stateful_postRender: function () {
  23685. if (this.disabled && !this.hasState('disabled')) {
  23686. this.addState('disabled');
  23687. }
  23688. },
  23689. hasState: function (state) {
  23690. return domUtils.hasClass(this.getStateDom(), 'edui-state-' + state);
  23691. },
  23692. addState: function (state) {
  23693. if (!this.hasState(state)) {
  23694. this.getStateDom().className += ' edui-state-' + state;
  23695. }
  23696. },
  23697. removeState: function (state) {
  23698. if (this.hasState(state)) {
  23699. domUtils.removeClasses(this.getStateDom(), ['edui-state-' + state]);
  23700. }
  23701. },
  23702. getStateDom: function () {
  23703. return this.getDom('state');
  23704. },
  23705. isChecked: function () {
  23706. return this.hasState('checked');
  23707. },
  23708. setChecked: function (checked) {
  23709. if (!this.isDisabled() && checked) {
  23710. this.addState('checked');
  23711. } else {
  23712. this.removeState('checked');
  23713. }
  23714. },
  23715. isDisabled: function () {
  23716. return this.hasState('disabled');
  23717. },
  23718. setDisabled: function (disabled) {
  23719. if (disabled) {
  23720. this.removeState('hover');
  23721. this.removeState('checked');
  23722. this.removeState('active');
  23723. this.addState('disabled');
  23724. } else {
  23725. this.removeState('disabled');
  23726. }
  23727. }
  23728. };
  23729. })();
  23730. // ui/button.js
  23731. ///import core
  23732. ///import uicore
  23733. ///import ui/stateful.js
  23734. (function () {
  23735. var utils = baidu.editor.utils,
  23736. UIBase = baidu.editor.ui.UIBase,
  23737. Stateful = baidu.editor.ui.Stateful,
  23738. Button = baidu.editor.ui.Button = function (options) {
  23739. if (options.name) {
  23740. var btnName = options.name;
  23741. var cssRules = options.cssRules;
  23742. if (!options.className) {
  23743. options.className = 'edui-for-' + btnName;
  23744. }
  23745. options.cssRules = '.edui-default .edui-for-' + btnName + ' .edui-icon {' + cssRules + '}'
  23746. }
  23747. this.initOptions(options);
  23748. this.initButton();
  23749. };
  23750. Button.prototype = {
  23751. uiName: 'button',
  23752. label: '',
  23753. title: '',
  23754. showIcon: true,
  23755. showText: true,
  23756. cssRules: '',
  23757. initButton: function () {
  23758. this.initUIBase();
  23759. this.Stateful_init();
  23760. if (this.cssRules) {
  23761. utils.cssRule('edui-customize-' + this.name + '-style', this.cssRules);
  23762. }
  23763. },
  23764. getHtmlTpl: function () {
  23765. return '<div id="##" class="edui-box %%">' +
  23766. '<div id="##_state" stateful>' +
  23767. '<div class="%%-wrap"><div id="##_body" unselectable="on" ' + (this.title ? 'title="' + this.title + '"' : '') +
  23768. ' class="%%-body" onmousedown="return $$._onMouseDown(event, this);" onclick="return $$._onClick(event, this);">' +
  23769. (this.showIcon ? '<div class="edui-box edui-icon"></div>' : '') +
  23770. (this.showText ? '<div class="edui-box edui-label">' + this.label + '</div>' : '') +
  23771. '</div>' +
  23772. '</div>' +
  23773. '</div></div>';
  23774. },
  23775. postRender: function () {
  23776. this.Stateful_postRender();
  23777. this.setDisabled(this.disabled)
  23778. },
  23779. _onMouseDown: function (e) {
  23780. var target = e.target || e.srcElement,
  23781. tagName = target && target.tagName && target.tagName.toLowerCase();
  23782. if (tagName == 'input' || tagName == 'object' || tagName == 'object') {
  23783. return false;
  23784. }
  23785. },
  23786. _onClick: function () {
  23787. if (!this.isDisabled()) {
  23788. this.fireEvent('click');
  23789. }
  23790. },
  23791. setTitle: function (text) {
  23792. var label = this.getDom('label');
  23793. label.innerHTML = text;
  23794. }
  23795. };
  23796. utils.inherits(Button, UIBase);
  23797. utils.extend(Button.prototype, Stateful);
  23798. })();
  23799. // ui/splitbutton.js
  23800. ///import core
  23801. ///import uicore
  23802. ///import ui/stateful.js
  23803. (function () {
  23804. var utils = baidu.editor.utils,
  23805. uiUtils = baidu.editor.ui.uiUtils,
  23806. domUtils = baidu.editor.dom.domUtils,
  23807. UIBase = baidu.editor.ui.UIBase,
  23808. Stateful = baidu.editor.ui.Stateful,
  23809. SplitButton = baidu.editor.ui.SplitButton = function (options) {
  23810. this.initOptions(options);
  23811. this.initSplitButton();
  23812. };
  23813. SplitButton.prototype = {
  23814. popup: null,
  23815. uiName: 'splitbutton',
  23816. title: '',
  23817. initSplitButton: function () {
  23818. this.initUIBase();
  23819. this.Stateful_init();
  23820. var me = this;
  23821. if (this.popup != null) {
  23822. var popup = this.popup;
  23823. this.popup = null;
  23824. this.setPopup(popup);
  23825. }
  23826. },
  23827. _UIBase_postRender: UIBase.prototype.postRender,
  23828. postRender: function () {
  23829. this.Stateful_postRender();
  23830. this._UIBase_postRender();
  23831. },
  23832. setPopup: function (popup) {
  23833. if (this.popup === popup) return;
  23834. if (this.popup != null) {
  23835. this.popup.dispose();
  23836. }
  23837. popup.addListener('show', utils.bind(this._onPopupShow, this));
  23838. popup.addListener('hide', utils.bind(this._onPopupHide, this));
  23839. popup.addListener('postrender', utils.bind(function () {
  23840. popup.getDom('body').appendChild(
  23841. uiUtils.createElementByHtml('<div id="' +
  23842. this.popup.id + '_bordereraser" class="edui-bordereraser edui-background" style="width:' +
  23843. (uiUtils.getClientRect(this.getDom()).width + 20) + 'px"></div>')
  23844. );
  23845. popup.getDom().className += ' ' + this.className;
  23846. }, this));
  23847. this.popup = popup;
  23848. },
  23849. _onPopupShow: function () {
  23850. this.addState('opened');
  23851. },
  23852. _onPopupHide: function () {
  23853. this.removeState('opened');
  23854. },
  23855. getHtmlTpl: function () {
  23856. return '<div id="##" class="edui-box %%">' +
  23857. '<div ' + (this.title ? 'title="' + this.title + '"' : '') + ' id="##_state" stateful><div class="%%-body">' +
  23858. '<div id="##_button_body" class="edui-box edui-button-body" onclick="$$._onButtonClick(event, this);">' +
  23859. '<div class="edui-box edui-icon"></div>' +
  23860. '</div>' +
  23861. '<div class="edui-box edui-splitborder"></div>' +
  23862. '<div class="edui-box edui-arrow" onclick="$$._onArrowClick();"></div>' +
  23863. '</div></div></div>';
  23864. },
  23865. showPopup: function () {
  23866. // 当popup往上弹出的时候,做特殊处理
  23867. var rect = uiUtils.getClientRect(this.getDom());
  23868. rect.top -= this.popup.SHADOW_RADIUS;
  23869. rect.height += this.popup.SHADOW_RADIUS;
  23870. this.popup.showAnchorRect(rect);
  23871. },
  23872. _onArrowClick: function (event, el) {
  23873. if (!this.isDisabled()) {
  23874. this.showPopup();
  23875. }
  23876. },
  23877. _onButtonClick: function () {
  23878. if (!this.isDisabled()) {
  23879. this.fireEvent('buttonclick');
  23880. }
  23881. }
  23882. };
  23883. utils.inherits(SplitButton, UIBase);
  23884. utils.extend(SplitButton.prototype, Stateful, true);
  23885. })();
  23886. // ui/colorbutton.js
  23887. ///import core
  23888. ///import uicore
  23889. ///import ui/colorpicker.js
  23890. ///import ui/popup.js
  23891. ///import ui/splitbutton.js
  23892. (function () {
  23893. var utils = baidu.editor.utils,
  23894. uiUtils = baidu.editor.ui.uiUtils,
  23895. ColorPicker = baidu.editor.ui.ColorPicker,
  23896. Popup = baidu.editor.ui.Popup,
  23897. SplitButton = baidu.editor.ui.SplitButton,
  23898. ColorButton = baidu.editor.ui.ColorButton = function (options) {
  23899. this.initOptions(options);
  23900. this.initColorButton();
  23901. };
  23902. ColorButton.prototype = {
  23903. initColorButton: function () {
  23904. var me = this;
  23905. this.popup = new Popup({
  23906. content: new ColorPicker({
  23907. noColorText: me.editor.getLang("clearColor"),
  23908. editor: me.editor,
  23909. onpickcolor: function (t, color) {
  23910. me._onPickColor(color);
  23911. },
  23912. onpicknocolor: function (t, color) {
  23913. me._onPickNoColor(color);
  23914. }
  23915. }),
  23916. editor: me.editor
  23917. });
  23918. this.initSplitButton();
  23919. },
  23920. _SplitButton_postRender: SplitButton.prototype.postRender,
  23921. postRender: function () {
  23922. this._SplitButton_postRender();
  23923. this.getDom('button_body').appendChild(
  23924. uiUtils.createElementByHtml('<div id="' + this.id + '_colorlump" class="edui-colorlump"></div>')
  23925. );
  23926. this.getDom().className += ' edui-colorbutton';
  23927. },
  23928. setColor: function (color) {
  23929. this.getDom('colorlump').style.backgroundColor = color;
  23930. this.color = color;
  23931. },
  23932. _onPickColor: function (color) {
  23933. if (this.fireEvent('pickcolor', color) !== false) {
  23934. this.setColor(color);
  23935. this.popup.hide();
  23936. }
  23937. },
  23938. _onPickNoColor: function (color) {
  23939. if (this.fireEvent('picknocolor') !== false) {
  23940. this.popup.hide();
  23941. }
  23942. }
  23943. };
  23944. utils.inherits(ColorButton, SplitButton);
  23945. })();
  23946. // ui/tablebutton.js
  23947. ///import core
  23948. ///import uicore
  23949. ///import ui/popup.js
  23950. ///import ui/tablepicker.js
  23951. ///import ui/splitbutton.js
  23952. (function () {
  23953. var utils = baidu.editor.utils,
  23954. Popup = baidu.editor.ui.Popup,
  23955. TablePicker = baidu.editor.ui.TablePicker,
  23956. SplitButton = baidu.editor.ui.SplitButton,
  23957. TableButton = baidu.editor.ui.TableButton = function (options) {
  23958. this.initOptions(options);
  23959. this.initTableButton();
  23960. };
  23961. TableButton.prototype = {
  23962. initTableButton: function () {
  23963. var me = this;
  23964. this.popup = new Popup({
  23965. content: new TablePicker({
  23966. editor: me.editor,
  23967. onpicktable: function (t, numCols, numRows) {
  23968. me._onPickTable(numCols, numRows);
  23969. }
  23970. }),
  23971. 'editor': me.editor
  23972. });
  23973. this.initSplitButton();
  23974. },
  23975. _onPickTable: function (numCols, numRows) {
  23976. if (this.fireEvent('picktable', numCols, numRows) !== false) {
  23977. this.popup.hide();
  23978. }
  23979. }
  23980. };
  23981. utils.inherits(TableButton, SplitButton);
  23982. })();
  23983. // ui/autotypesetpicker.js
  23984. ///import core
  23985. ///import uicore
  23986. (function () {
  23987. var utils = baidu.editor.utils,
  23988. UIBase = baidu.editor.ui.UIBase;
  23989. var AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker = function (options) {
  23990. this.initOptions(options);
  23991. this.initAutoTypeSetPicker();
  23992. };
  23993. AutoTypeSetPicker.prototype = {
  23994. initAutoTypeSetPicker: function () {
  23995. this.initUIBase();
  23996. },
  23997. getHtmlTpl: function () {
  23998. var me = this.editor,
  23999. opt = me.options.autotypeset,
  24000. lang = me.getLang("autoTypeSet");
  24001. var textAlignInputName = 'textAlignValue' + me.uid,
  24002. imageBlockInputName = 'imageBlockLineValue' + me.uid,
  24003. symbolConverInputName = 'symbolConverValue' + me.uid;
  24004. return '<div id="##" class="edui-autotypesetpicker %%">' +
  24005. '<div class="edui-autotypesetpicker-body">' +
  24006. '<table >' +
  24007. '<tr><td nowrap><input type="checkbox" name="mergeEmptyline" ' + (opt["mergeEmptyline"] ? "checked" : "") + '>' + lang.mergeLine + '</td><td colspan="2"><input type="checkbox" name="removeEmptyline" ' + (opt["removeEmptyline"] ? "checked" : "") + '>' + lang.delLine + '</td></tr>' +
  24008. '<tr><td nowrap><input type="checkbox" name="removeClass" ' + (opt["removeClass"] ? "checked" : "") + '>' + lang.removeFormat + '</td><td colspan="2"><input type="checkbox" name="indent" ' + (opt["indent"] ? "checked" : "") + '>' + lang.indent + '</td></tr>' +
  24009. '<tr>' +
  24010. '<td nowrap><input type="checkbox" name="textAlign" ' + (opt["textAlign"] ? "checked" : "") + '>' + lang.alignment + '</td>' +
  24011. '<td colspan="2" id="' + textAlignInputName + '">' +
  24012. '<input type="radio" name="' + textAlignInputName + '" value="left" ' + ((opt["textAlign"] && opt["textAlign"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  24013. '<input type="radio" name="' + textAlignInputName + '" value="center" ' + ((opt["textAlign"] && opt["textAlign"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  24014. '<input type="radio" name="' + textAlignInputName + '" value="right" ' + ((opt["textAlign"] && opt["textAlign"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") +
  24015. '</td>' +
  24016. '</tr>' +
  24017. '<tr>' +
  24018. '<td nowrap><input type="checkbox" name="imageBlockLine" ' + (opt["imageBlockLine"] ? "checked" : "") + '>' + lang.imageFloat + '</td>' +
  24019. '<td nowrap id="' + imageBlockInputName + '">' +
  24020. '<input type="radio" name="' + imageBlockInputName + '" value="none" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "none") ? "checked" : "") + '>' + me.getLang("default") +
  24021. '<input type="radio" name="' + imageBlockInputName + '" value="left" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  24022. '<input type="radio" name="' + imageBlockInputName + '" value="center" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  24023. '<input type="radio" name="' + imageBlockInputName + '" value="right" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") +
  24024. '</td>' +
  24025. '</tr>' +
  24026. '<tr><td nowrap><input type="checkbox" name="clearFontSize" ' + (opt["clearFontSize"] ? "checked" : "") + '>' + lang.removeFontsize + '</td><td colspan="2"><input type="checkbox" name="clearFontFamily" ' + (opt["clearFontFamily"] ? "checked" : "") + '>' + lang.removeFontFamily + '</td></tr>' +
  24027. '<tr><td nowrap colspan="3"><input type="checkbox" name="removeEmptyNode" ' + (opt["removeEmptyNode"] ? "checked" : "") + '>' + lang.removeHtml + '</td></tr>' +
  24028. '<tr><td nowrap colspan="3"><input type="checkbox" name="pasteFilter" ' + (opt["pasteFilter"] ? "checked" : "") + '>' + lang.pasteFilter + '</td></tr>' +
  24029. '<tr>' +
  24030. '<td nowrap><input type="checkbox" name="symbolConver" ' + (opt["bdc2sb"] || opt["tobdc"] ? "checked" : "") + '>' + lang.symbol + '</td>' +
  24031. '<td id="' + symbolConverInputName + '">' +
  24032. '<input type="radio" name="bdc" value="bdc2sb" ' + (opt["bdc2sb"] ? "checked" : "") + '>' + lang.bdc2sb +
  24033. '<input type="radio" name="bdc" value="tobdc" ' + (opt["tobdc"] ? "checked" : "") + '>' + lang.tobdc + '' +
  24034. '</td>' +
  24035. '<td nowrap align="right"><button >' + lang.run + '</button></td>' +
  24036. '</tr>' +
  24037. '</table>' +
  24038. '</div>' +
  24039. '</div>';
  24040. },
  24041. _UIBase_render: UIBase.prototype.render
  24042. };
  24043. utils.inherits(AutoTypeSetPicker, UIBase);
  24044. })();
  24045. // ui/autotypesetbutton.js
  24046. ///import core
  24047. ///import uicore
  24048. ///import ui/popup.js
  24049. ///import ui/autotypesetpicker.js
  24050. ///import ui/splitbutton.js
  24051. (function () {
  24052. var utils = baidu.editor.utils,
  24053. Popup = baidu.editor.ui.Popup,
  24054. AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker,
  24055. SplitButton = baidu.editor.ui.SplitButton,
  24056. AutoTypeSetButton = baidu.editor.ui.AutoTypeSetButton = function (options) {
  24057. this.initOptions(options);
  24058. this.initAutoTypeSetButton();
  24059. };
  24060. function getPara(me) {
  24061. var opt = {},
  24062. cont = me.getDom(),
  24063. editorId = me.editor.uid,
  24064. inputType = null,
  24065. attrName = null,
  24066. ipts = domUtils.getElementsByTagName(cont, "input");
  24067. for (var i = ipts.length - 1, ipt; ipt = ipts[i--];) {
  24068. inputType = ipt.getAttribute("type");
  24069. if (inputType == "checkbox") {
  24070. attrName = ipt.getAttribute("name");
  24071. opt[attrName] && delete opt[attrName];
  24072. if (ipt.checked) {
  24073. var attrValue = document.getElementById(attrName + "Value" + editorId);
  24074. if (attrValue) {
  24075. if (/input/ig.test(attrValue.tagName)) {
  24076. opt[attrName] = attrValue.value;
  24077. } else {
  24078. var iptChilds = attrValue.getElementsByTagName("input");
  24079. for (var j = iptChilds.length - 1, iptchild; iptchild = iptChilds[j--];) {
  24080. if (iptchild.checked) {
  24081. opt[attrName] = iptchild.value;
  24082. break;
  24083. }
  24084. }
  24085. }
  24086. } else {
  24087. opt[attrName] = true;
  24088. }
  24089. } else {
  24090. opt[attrName] = false;
  24091. }
  24092. } else {
  24093. opt[ipt.getAttribute("value")] = ipt.checked;
  24094. }
  24095. }
  24096. var selects = domUtils.getElementsByTagName(cont, "select");
  24097. for (var i = 0, si; si = selects[i++];) {
  24098. var attr = si.getAttribute('name');
  24099. opt[attr] = opt[attr] ? si.value : '';
  24100. }
  24101. utils.extend(me.editor.options.autotypeset, opt);
  24102. me.editor.setPreferences('autotypeset', opt);
  24103. }
  24104. AutoTypeSetButton.prototype = {
  24105. initAutoTypeSetButton: function () {
  24106. var me = this;
  24107. this.popup = new Popup({
  24108. //传入配置参数
  24109. content: new AutoTypeSetPicker({ editor: me.editor }),
  24110. 'editor': me.editor,
  24111. hide: function () {
  24112. if (!this._hidden && this.getDom()) {
  24113. getPara(this);
  24114. this.getDom().style.display = 'none';
  24115. this._hidden = true;
  24116. this.fireEvent('hide');
  24117. }
  24118. }
  24119. });
  24120. var flag = 0;
  24121. this.popup.addListener('postRenderAfter', function () {
  24122. var popupUI = this;
  24123. if (flag) return;
  24124. var cont = this.getDom(),
  24125. btn = cont.getElementsByTagName('button')[0];
  24126. btn.onclick = function () {
  24127. getPara(popupUI);
  24128. me.editor.execCommand('autotypeset');
  24129. popupUI.hide()
  24130. };
  24131. domUtils.on(cont, 'click', function (e) {
  24132. var target = e.target || e.srcElement,
  24133. editorId = me.editor.uid;
  24134. if (target && target.tagName == 'INPUT') {
  24135. // 点击图片浮动的checkbox,去除对应的radio
  24136. if (target.name == 'imageBlockLine' || target.name == 'textAlign' || target.name == 'symbolConver') {
  24137. var checked = target.checked,
  24138. radioTd = document.getElementById(target.name + 'Value' + editorId),
  24139. radios = radioTd.getElementsByTagName('input'),
  24140. defalutSelect = {
  24141. 'imageBlockLine': 'none',
  24142. 'textAlign': 'left',
  24143. 'symbolConver': 'tobdc'
  24144. };
  24145. for (var i = 0; i < radios.length; i++) {
  24146. if (checked) {
  24147. if (radios[i].value == defalutSelect[target.name]) {
  24148. radios[i].checked = 'checked';
  24149. }
  24150. } else {
  24151. radios[i].checked = false;
  24152. }
  24153. }
  24154. }
  24155. // 点击radio,选中对应的checkbox
  24156. if (target.name == ('imageBlockLineValue' + editorId) || target.name == ('textAlignValue' + editorId) || target.name == 'bdc') {
  24157. var checkboxs = target.parentNode.previousSibling.getElementsByTagName('input');
  24158. checkboxs && (checkboxs[0].checked = true);
  24159. }
  24160. getPara(popupUI);
  24161. }
  24162. });
  24163. flag = 1;
  24164. });
  24165. this.initSplitButton();
  24166. }
  24167. };
  24168. utils.inherits(AutoTypeSetButton, SplitButton);
  24169. })();
  24170. // ui/cellalignpicker.js
  24171. ///import core
  24172. ///import uicore
  24173. (function () {
  24174. var utils = baidu.editor.utils,
  24175. Popup = baidu.editor.ui.Popup,
  24176. Stateful = baidu.editor.ui.Stateful,
  24177. UIBase = baidu.editor.ui.UIBase;
  24178. /**
  24179. * 该参数将新增一个参数: selected, 参数类型为一个Object, 形如{ 'align': 'center', 'valign': 'top' }, 表示单元格的初始
  24180. * 对齐状态为: 竖直居上,水平居中; 其中 align的取值为:'center', 'left', 'right'; valign的取值为: 'top', 'middle', 'bottom'
  24181. * @update 2013/4/2 hancong03@baidu.com
  24182. */
  24183. var CellAlignPicker = baidu.editor.ui.CellAlignPicker = function (options) {
  24184. this.initOptions(options);
  24185. this.initSelected();
  24186. this.initCellAlignPicker();
  24187. };
  24188. CellAlignPicker.prototype = {
  24189. //初始化选中状态, 该方法将根据传递进来的参数获取到应该选中的对齐方式图标的索引
  24190. initSelected: function () {
  24191. var status = {
  24192. valign: {
  24193. top: 0,
  24194. middle: 1,
  24195. bottom: 2
  24196. },
  24197. align: {
  24198. left: 0,
  24199. center: 1,
  24200. right: 2
  24201. },
  24202. count: 3
  24203. },
  24204. result = -1;
  24205. if (this.selected) {
  24206. this.selectedIndex = status.valign[this.selected.valign] * status.count + status.align[this.selected.align];
  24207. }
  24208. },
  24209. initCellAlignPicker: function () {
  24210. this.initUIBase();
  24211. this.Stateful_init();
  24212. },
  24213. getHtmlTpl: function () {
  24214. var alignType = ['left', 'center', 'right'],
  24215. COUNT = 9,
  24216. tempClassName = null,
  24217. tempIndex = -1,
  24218. tmpl = [];
  24219. for (var i = 0; i < COUNT; i++) {
  24220. tempClassName = this.selectedIndex === i ? ' class="edui-cellalign-selected" ' : '';
  24221. tempIndex = i % 3;
  24222. tempIndex === 0 && tmpl.push('<tr>');
  24223. tmpl.push('<td index="' + i + '" ' + tempClassName + ' stateful><div class="edui-icon edui-' + alignType[tempIndex] + '"></div></td>');
  24224. tempIndex === 2 && tmpl.push('</tr>');
  24225. }
  24226. return '<div id="##" class="edui-cellalignpicker %%">' +
  24227. '<div class="edui-cellalignpicker-body">' +
  24228. '<table onclick="$$._onClick(event);">' +
  24229. tmpl.join('') +
  24230. '</table>' +
  24231. '</div>' +
  24232. '</div>';
  24233. },
  24234. getStateDom: function () {
  24235. return this.target;
  24236. },
  24237. _onClick: function (evt) {
  24238. var target = evt.target || evt.srcElement;
  24239. if (/icon/.test(target.className)) {
  24240. this.items[target.parentNode.getAttribute("index")].onclick();
  24241. Popup.postHide(evt);
  24242. }
  24243. },
  24244. _UIBase_render: UIBase.prototype.render
  24245. };
  24246. utils.inherits(CellAlignPicker, UIBase);
  24247. utils.extend(CellAlignPicker.prototype, Stateful, true);
  24248. })();
  24249. // ui/pastepicker.js
  24250. ///import core
  24251. ///import uicore
  24252. (function () {
  24253. var utils = baidu.editor.utils,
  24254. Stateful = baidu.editor.ui.Stateful,
  24255. uiUtils = baidu.editor.ui.uiUtils,
  24256. UIBase = baidu.editor.ui.UIBase;
  24257. var PastePicker = baidu.editor.ui.PastePicker = function (options) {
  24258. this.initOptions(options);
  24259. this.initPastePicker();
  24260. };
  24261. PastePicker.prototype = {
  24262. initPastePicker: function () {
  24263. this.initUIBase();
  24264. this.Stateful_init();
  24265. },
  24266. getHtmlTpl: function () {
  24267. return '<div class="edui-pasteicon" onclick="$$._onClick(this)"></div>' +
  24268. '<div class="edui-pastecontainer">' +
  24269. '<div class="edui-title">' + this.editor.getLang("pasteOpt") + '</div>' +
  24270. '<div class="edui-button">' +
  24271. '<div title="' + this.editor.getLang("pasteSourceFormat") + '" onclick="$$.format(false)" stateful>' +
  24272. '<div class="edui-richtxticon"></div></div>' +
  24273. '<div title="' + this.editor.getLang("tagFormat") + '" onclick="$$.format(2)" stateful>' +
  24274. '<div class="edui-tagicon"></div></div>' +
  24275. '<div title="' + this.editor.getLang("pasteTextFormat") + '" onclick="$$.format(true)" stateful>' +
  24276. '<div class="edui-plaintxticon"></div></div>' +
  24277. '</div>' +
  24278. '</div>' +
  24279. '</div>'
  24280. },
  24281. getStateDom: function () {
  24282. return this.target;
  24283. },
  24284. format: function (param) {
  24285. this.editor.ui._isTransfer = true;
  24286. this.editor.fireEvent('pasteTransfer', param);
  24287. },
  24288. _onClick: function (cur) {
  24289. var node = domUtils.getNextDomNode(cur),
  24290. screenHt = uiUtils.getViewportRect().height,
  24291. subPop = uiUtils.getClientRect(node);
  24292. if ((subPop.top + subPop.height) > screenHt)
  24293. node.style.top = (-subPop.height - cur.offsetHeight) + "px";
  24294. else
  24295. node.style.top = "";
  24296. if (/hidden/ig.test(domUtils.getComputedStyle(node, "visibility"))) {
  24297. node.style.visibility = "visible";
  24298. domUtils.addClass(cur, "edui-state-opened");
  24299. } else {
  24300. node.style.visibility = "hidden";
  24301. domUtils.removeClasses(cur, "edui-state-opened")
  24302. }
  24303. },
  24304. _UIBase_render: UIBase.prototype.render
  24305. };
  24306. utils.inherits(PastePicker, UIBase);
  24307. utils.extend(PastePicker.prototype, Stateful, true);
  24308. })();
  24309. // ui/toolbar.js
  24310. (function () {
  24311. var utils = baidu.editor.utils,
  24312. uiUtils = baidu.editor.ui.uiUtils,
  24313. UIBase = baidu.editor.ui.UIBase,
  24314. Toolbar = baidu.editor.ui.Toolbar = function (options) {
  24315. this.initOptions(options);
  24316. this.initToolbar();
  24317. };
  24318. Toolbar.prototype = {
  24319. items: null,
  24320. initToolbar: function () {
  24321. this.items = this.items || [];
  24322. this.initUIBase();
  24323. },
  24324. add: function (item, index) {
  24325. if (index === undefined) {
  24326. this.items.push(item);
  24327. } else {
  24328. this.items.splice(index, 0, item)
  24329. }
  24330. },
  24331. getHtmlTpl: function () {
  24332. var buff = [];
  24333. for (var i = 0; i < this.items.length; i++) {
  24334. buff[i] = this.items[i].renderHtml();
  24335. }
  24336. return '<div id="##" class="edui-toolbar %%" onselectstart="return false;" onmousedown="return $$._onMouseDown(event, this);">' +
  24337. buff.join('') +
  24338. '</div>'
  24339. },
  24340. postRender: function () {
  24341. var box = this.getDom();
  24342. for (var i = 0; i < this.items.length; i++) {
  24343. this.items[i].postRender();
  24344. }
  24345. uiUtils.makeUnselectable(box);
  24346. },
  24347. _onMouseDown: function (e) {
  24348. var target = e.target || e.srcElement,
  24349. tagName = target && target.tagName && target.tagName.toLowerCase();
  24350. if (tagName == 'input' || tagName == 'object' || tagName == 'object') {
  24351. return false;
  24352. }
  24353. }
  24354. };
  24355. utils.inherits(Toolbar, UIBase);
  24356. })();
  24357. // ui/menu.js
  24358. ///import core
  24359. ///import uicore
  24360. ///import ui\popup.js
  24361. ///import ui\stateful.js
  24362. (function () {
  24363. var utils = baidu.editor.utils,
  24364. domUtils = baidu.editor.dom.domUtils,
  24365. uiUtils = baidu.editor.ui.uiUtils,
  24366. UIBase = baidu.editor.ui.UIBase,
  24367. Popup = baidu.editor.ui.Popup,
  24368. Stateful = baidu.editor.ui.Stateful,
  24369. CellAlignPicker = baidu.editor.ui.CellAlignPicker,
  24370. Menu = baidu.editor.ui.Menu = function (options) {
  24371. this.initOptions(options);
  24372. this.initMenu();
  24373. };
  24374. var menuSeparator = {
  24375. renderHtml: function () {
  24376. return '<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>';
  24377. },
  24378. postRender: function () {
  24379. },
  24380. queryAutoHide: function () {
  24381. return true;
  24382. }
  24383. };
  24384. Menu.prototype = {
  24385. items: null,
  24386. uiName: 'menu',
  24387. initMenu: function () {
  24388. this.items = this.items || [];
  24389. this.initPopup();
  24390. this.initItems();
  24391. },
  24392. initItems: function () {
  24393. for (var i = 0; i < this.items.length; i++) {
  24394. var item = this.items[i];
  24395. if (item == '-') {
  24396. this.items[i] = this.getSeparator();
  24397. } else if (!(item instanceof MenuItem)) {
  24398. item.editor = this.editor;
  24399. item.theme = this.editor.options.theme;
  24400. this.items[i] = this.createItem(item);
  24401. }
  24402. }
  24403. },
  24404. getSeparator: function () {
  24405. return menuSeparator;
  24406. },
  24407. createItem: function (item) {
  24408. //新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  24409. item.menu = this;
  24410. return new MenuItem(item);
  24411. },
  24412. _Popup_getContentHtmlTpl: Popup.prototype.getContentHtmlTpl,
  24413. getContentHtmlTpl: function () {
  24414. if (this.items.length == 0) {
  24415. return this._Popup_getContentHtmlTpl();
  24416. }
  24417. var buff = [];
  24418. for (var i = 0; i < this.items.length; i++) {
  24419. var item = this.items[i];
  24420. buff[i] = item.renderHtml();
  24421. }
  24422. return ('<div class="%%-body">' + buff.join('') + '</div>');
  24423. },
  24424. _Popup_postRender: Popup.prototype.postRender,
  24425. postRender: function () {
  24426. var me = this;
  24427. for (var i = 0; i < this.items.length; i++) {
  24428. var item = this.items[i];
  24429. item.ownerMenu = this;
  24430. item.postRender();
  24431. }
  24432. domUtils.on(this.getDom(), 'mouseover', function (evt) {
  24433. evt = evt || event;
  24434. var rel = evt.relatedTarget || evt.fromElement;
  24435. var el = me.getDom();
  24436. if (!uiUtils.contains(el, rel) && el !== rel) {
  24437. me.fireEvent('over');
  24438. }
  24439. });
  24440. this._Popup_postRender();
  24441. },
  24442. queryAutoHide: function (el) {
  24443. if (el) {
  24444. if (uiUtils.contains(this.getDom(), el)) {
  24445. return false;
  24446. }
  24447. for (var i = 0; i < this.items.length; i++) {
  24448. var item = this.items[i];
  24449. if (item.queryAutoHide(el) === false) {
  24450. return false;
  24451. }
  24452. }
  24453. }
  24454. },
  24455. clearItems: function () {
  24456. for (var i = 0; i < this.items.length; i++) {
  24457. var item = this.items[i];
  24458. clearTimeout(item._showingTimer);
  24459. clearTimeout(item._closingTimer);
  24460. if (item.subMenu) {
  24461. item.subMenu.destroy();
  24462. }
  24463. }
  24464. this.items = [];
  24465. },
  24466. destroy: function () {
  24467. if (this.getDom()) {
  24468. domUtils.remove(this.getDom());
  24469. }
  24470. this.clearItems();
  24471. },
  24472. dispose: function () {
  24473. this.destroy();
  24474. }
  24475. };
  24476. utils.inherits(Menu, Popup);
  24477. /**
  24478. * @update 2013/04/03 hancong03 新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  24479. * @type {Function}
  24480. */
  24481. var MenuItem = baidu.editor.ui.MenuItem = function (options) {
  24482. this.initOptions(options);
  24483. this.initUIBase();
  24484. this.Stateful_init();
  24485. if (this.subMenu && !(this.subMenu instanceof Menu)) {
  24486. if (options.className && options.className.indexOf("aligntd") != -1) {
  24487. var me = this;
  24488. //获取单元格对齐初始状态
  24489. this.subMenu.selected = this.editor.queryCommandValue('cellalignment');
  24490. this.subMenu = new Popup({
  24491. content: new CellAlignPicker(this.subMenu),
  24492. parentMenu: me,
  24493. editor: me.editor,
  24494. destroy: function () {
  24495. if (this.getDom()) {
  24496. domUtils.remove(this.getDom());
  24497. }
  24498. }
  24499. });
  24500. this.subMenu.addListener("postRenderAfter", function () {
  24501. domUtils.on(this.getDom(), "mouseover", function () {
  24502. me.addState('opened');
  24503. });
  24504. });
  24505. } else {
  24506. this.subMenu = new Menu(this.subMenu);
  24507. }
  24508. }
  24509. };
  24510. MenuItem.prototype = {
  24511. label: '',
  24512. subMenu: null,
  24513. ownerMenu: null,
  24514. uiName: 'menuitem',
  24515. alwalysHoverable: true,
  24516. getHtmlTpl: function () {
  24517. return '<div id="##" class="%%" stateful onclick="$$._onClick(event, this);">' +
  24518. '<div class="%%-body">' +
  24519. this.renderLabelHtml() +
  24520. '</div>' +
  24521. '</div>';
  24522. },
  24523. postRender: function () {
  24524. var me = this;
  24525. this.addListener('over', function () {
  24526. me.ownerMenu.fireEvent('submenuover', me);
  24527. if (me.subMenu) {
  24528. me.delayShowSubMenu();
  24529. }
  24530. });
  24531. if (this.subMenu) {
  24532. this.getDom().className += ' edui-hassubmenu';
  24533. this.subMenu.render();
  24534. this.addListener('out', function () {
  24535. me.delayHideSubMenu();
  24536. });
  24537. this.subMenu.addListener('over', function () {
  24538. clearTimeout(me._closingTimer);
  24539. me._closingTimer = null;
  24540. me.addState('opened');
  24541. });
  24542. this.ownerMenu.addListener('hide', function () {
  24543. me.hideSubMenu();
  24544. });
  24545. this.ownerMenu.addListener('submenuover', function (t, subMenu) {
  24546. if (subMenu !== me) {
  24547. me.delayHideSubMenu();
  24548. }
  24549. });
  24550. this.subMenu._bakQueryAutoHide = this.subMenu.queryAutoHide;
  24551. this.subMenu.queryAutoHide = function (el) {
  24552. if (el && uiUtils.contains(me.getDom(), el)) {
  24553. return false;
  24554. }
  24555. return this._bakQueryAutoHide(el);
  24556. };
  24557. }
  24558. this.getDom().style.tabIndex = '-1';
  24559. uiUtils.makeUnselectable(this.getDom());
  24560. this.Stateful_postRender();
  24561. },
  24562. delayShowSubMenu: function () {
  24563. var me = this;
  24564. if (!me.isDisabled()) {
  24565. me.addState('opened');
  24566. clearTimeout(me._showingTimer);
  24567. clearTimeout(me._closingTimer);
  24568. me._closingTimer = null;
  24569. me._showingTimer = setTimeout(function () {
  24570. me.showSubMenu();
  24571. }, 250);
  24572. }
  24573. },
  24574. delayHideSubMenu: function () {
  24575. var me = this;
  24576. if (!me.isDisabled()) {
  24577. me.removeState('opened');
  24578. clearTimeout(me._showingTimer);
  24579. if (!me._closingTimer) {
  24580. me._closingTimer = setTimeout(function () {
  24581. if (!me.hasState('opened')) {
  24582. me.hideSubMenu();
  24583. }
  24584. me._closingTimer = null;
  24585. }, 400);
  24586. }
  24587. }
  24588. },
  24589. renderLabelHtml: function () {
  24590. return '<div class="edui-arrow"></div>' +
  24591. '<div class="edui-box edui-icon"></div>' +
  24592. '<div class="edui-box edui-label %%-label">' + (this.label || '') + '</div>';
  24593. },
  24594. getStateDom: function () {
  24595. return this.getDom();
  24596. },
  24597. queryAutoHide: function (el) {
  24598. if (this.subMenu && this.hasState('opened')) {
  24599. return this.subMenu.queryAutoHide(el);
  24600. }
  24601. },
  24602. _onClick: function (event, this_) {
  24603. if (this.hasState('disabled')) return;
  24604. if (this.fireEvent('click', event, this_) !== false) {
  24605. if (this.subMenu) {
  24606. this.showSubMenu();
  24607. } else {
  24608. Popup.postHide(event);
  24609. }
  24610. }
  24611. },
  24612. showSubMenu: function () {
  24613. var rect = uiUtils.getClientRect(this.getDom());
  24614. rect.right -= 5;
  24615. rect.left += 2;
  24616. rect.width -= 7;
  24617. rect.top -= 4;
  24618. rect.bottom += 4;
  24619. rect.height += 8;
  24620. this.subMenu.showAnchorRect(rect, true, true);
  24621. },
  24622. hideSubMenu: function () {
  24623. this.subMenu.hide();
  24624. }
  24625. };
  24626. utils.inherits(MenuItem, UIBase);
  24627. utils.extend(MenuItem.prototype, Stateful, true);
  24628. })();
  24629. // ui/combox.js
  24630. ///import core
  24631. ///import uicore
  24632. ///import ui/menu.js
  24633. ///import ui/splitbutton.js
  24634. (function () {
  24635. // todo: menu和item提成通用list
  24636. var utils = baidu.editor.utils,
  24637. uiUtils = baidu.editor.ui.uiUtils,
  24638. Menu = baidu.editor.ui.Menu,
  24639. SplitButton = baidu.editor.ui.SplitButton,
  24640. Combox = baidu.editor.ui.Combox = function (options) {
  24641. this.initOptions(options);
  24642. this.initCombox();
  24643. };
  24644. Combox.prototype = {
  24645. uiName: 'combox',
  24646. onbuttonclick: function () {
  24647. this.showPopup();
  24648. },
  24649. initCombox: function () {
  24650. var me = this;
  24651. this.items = this.items || [];
  24652. for (var i = 0; i < this.items.length; i++) {
  24653. var item = this.items[i];
  24654. item.uiName = 'listitem';
  24655. item.index = i;
  24656. item.onclick = function () {
  24657. me.selectByIndex(this.index);
  24658. };
  24659. }
  24660. this.popup = new Menu({
  24661. items: this.items,
  24662. uiName: 'list',
  24663. editor: this.editor,
  24664. captureWheel: true,
  24665. combox: this
  24666. });
  24667. this.initSplitButton();
  24668. },
  24669. _SplitButton_postRender: SplitButton.prototype.postRender,
  24670. postRender: function () {
  24671. this._SplitButton_postRender();
  24672. this.setLabel(this.label || '');
  24673. this.setValue(this.initValue || '');
  24674. },
  24675. showPopup: function () {
  24676. var rect = uiUtils.getClientRect(this.getDom());
  24677. rect.top += 1;
  24678. rect.bottom -= 1;
  24679. rect.height -= 2;
  24680. this.popup.showAnchorRect(rect);
  24681. },
  24682. getValue: function () {
  24683. return this.value;
  24684. },
  24685. setValue: function (value) {
  24686. var index = this.indexByValue(value);
  24687. if (index != -1) {
  24688. this.selectedIndex = index;
  24689. this.setLabel(this.items[index].label);
  24690. this.value = this.items[index].value;
  24691. } else {
  24692. this.selectedIndex = -1;
  24693. this.setLabel(this.getLabelForUnknowValue(value));
  24694. this.value = value;
  24695. }
  24696. },
  24697. setLabel: function (label) {
  24698. this.getDom('button_body').innerHTML = label;
  24699. this.label = label;
  24700. },
  24701. getLabelForUnknowValue: function (value) {
  24702. return value;
  24703. },
  24704. indexByValue: function (value) {
  24705. for (var i = 0; i < this.items.length; i++) {
  24706. if (value == this.items[i].value) {
  24707. return i;
  24708. }
  24709. }
  24710. return -1;
  24711. },
  24712. getItem: function (index) {
  24713. return this.items[index];
  24714. },
  24715. selectByIndex: function (index) {
  24716. if (index < this.items.length && this.fireEvent('select', index) !== false) {
  24717. this.selectedIndex = index;
  24718. this.value = this.items[index].value;
  24719. this.setLabel(this.items[index].label);
  24720. }
  24721. }
  24722. };
  24723. utils.inherits(Combox, SplitButton);
  24724. })();
  24725. // ui/dialog.js
  24726. ///import core
  24727. ///import uicore
  24728. ///import ui/mask.js
  24729. ///import ui/button.js
  24730. (function () {
  24731. var utils = baidu.editor.utils,
  24732. domUtils = baidu.editor.dom.domUtils,
  24733. uiUtils = baidu.editor.ui.uiUtils,
  24734. Mask = baidu.editor.ui.Mask,
  24735. UIBase = baidu.editor.ui.UIBase,
  24736. Button = baidu.editor.ui.Button,
  24737. Dialog = baidu.editor.ui.Dialog = function (options) {
  24738. if (options.name) {
  24739. var name = options.name;
  24740. var cssRules = options.cssRules;
  24741. if (!options.className) {
  24742. options.className = 'edui-for-' + name;
  24743. }
  24744. if (cssRules) {
  24745. options.cssRules = '.edui-default .edui-for-' + name + ' .edui-dialog-content {' + cssRules + '}'
  24746. }
  24747. }
  24748. this.initOptions(utils.extend({
  24749. autoReset: true,
  24750. draggable: true,
  24751. onok: function () { },
  24752. oncancel: function () { },
  24753. onclose: function (t, ok) {
  24754. return ok ? this.onok() : this.oncancel();
  24755. },
  24756. //是否控制dialog中的scroll事件, 默认为不阻止
  24757. holdScroll: false
  24758. }, options));
  24759. this.initDialog();
  24760. };
  24761. var modalMask;
  24762. var dragMask;
  24763. var activeDialog;
  24764. Dialog.prototype = {
  24765. draggable: false,
  24766. uiName: 'dialog',
  24767. initDialog: function () {
  24768. var me = this,
  24769. theme = this.editor.options.theme;
  24770. if (this.cssRules) {
  24771. utils.cssRule('edui-customize-' + this.name + '-style', this.cssRules);
  24772. }
  24773. this.initUIBase();
  24774. this.modalMask = (modalMask || (modalMask = new Mask({
  24775. className: 'edui-dialog-modalmask',
  24776. theme: theme,
  24777. onclick: function () {
  24778. activeDialog && activeDialog.close(false);
  24779. }
  24780. })));
  24781. this.dragMask = (dragMask || (dragMask = new Mask({
  24782. className: 'edui-dialog-dragmask',
  24783. theme: theme
  24784. })));
  24785. this.closeButton = new Button({
  24786. className: 'edui-dialog-closebutton',
  24787. title: me.closeDialog,
  24788. theme: theme,
  24789. onclick: function () {
  24790. me.close(false);
  24791. }
  24792. });
  24793. this.fullscreen && this.initResizeEvent();
  24794. if (this.buttons) {
  24795. for (var i = 0; i < this.buttons.length; i++) {
  24796. if (!(this.buttons[i] instanceof Button)) {
  24797. this.buttons[i] = new Button(utils.extend(this.buttons[i], {
  24798. editor: this.editor
  24799. }, true));
  24800. }
  24801. }
  24802. }
  24803. },
  24804. initResizeEvent: function () {
  24805. var me = this;
  24806. domUtils.on(window, "resize", function () {
  24807. if (me._hidden || me._hidden === undefined) {
  24808. return;
  24809. }
  24810. if (me.__resizeTimer) {
  24811. window.clearTimeout(me.__resizeTimer);
  24812. }
  24813. me.__resizeTimer = window.setTimeout(function () {
  24814. me.__resizeTimer = null;
  24815. var dialogWrapNode = me.getDom(),
  24816. contentNode = me.getDom('content'),
  24817. wrapRect = UE.ui.uiUtils.getClientRect(dialogWrapNode),
  24818. contentRect = UE.ui.uiUtils.getClientRect(contentNode),
  24819. vpRect = uiUtils.getViewportRect();
  24820. contentNode.style.width = (vpRect.width - wrapRect.width + contentRect.width) + "px";
  24821. contentNode.style.height = (vpRect.height - wrapRect.height + contentRect.height) + "px";
  24822. dialogWrapNode.style.width = vpRect.width + "px";
  24823. dialogWrapNode.style.height = vpRect.height + "px";
  24824. me.fireEvent("resize");
  24825. }, 100);
  24826. });
  24827. },
  24828. fitSize: function () {
  24829. var popBodyEl = this.getDom('body');
  24830. // if (!(baidu.editor.browser.ie && baidu.editor.browser.version == 7)) {
  24831. // uiUtils.removeStyle(popBodyEl, 'width');
  24832. // uiUtils.removeStyle(popBodyEl, 'height');
  24833. // }
  24834. var size = this.mesureSize();
  24835. popBodyEl.style.width = size.width + 'px';
  24836. popBodyEl.style.height = size.height + 'px';
  24837. return size;
  24838. },
  24839. safeSetOffset: function (offset) {
  24840. var me = this;
  24841. var el = me.getDom();
  24842. var vpRect = uiUtils.getViewportRect();
  24843. var rect = uiUtils.getClientRect(el);
  24844. var left = offset.left;
  24845. if (left + rect.width > vpRect.right) {
  24846. left = vpRect.right - rect.width;
  24847. }
  24848. var top = offset.top;
  24849. if (top + rect.height > vpRect.bottom) {
  24850. top = vpRect.bottom - rect.height;
  24851. }
  24852. el.style.left = Math.max(left, 0) + 'px';
  24853. el.style.top = Math.max(top, 0) + 'px';
  24854. },
  24855. showAtCenter: function () {
  24856. var vpRect = uiUtils.getViewportRect();
  24857. if (!this.fullscreen) {
  24858. this.getDom().style.display = '';
  24859. var popSize = this.fitSize();
  24860. var titleHeight = this.getDom('titlebar').offsetHeight | 0;
  24861. var left = vpRect.width / 2 - popSize.width / 2;
  24862. var top = vpRect.height / 2 - (popSize.height - titleHeight) / 2 - titleHeight;
  24863. var popEl = this.getDom();
  24864. this.safeSetOffset({
  24865. left: Math.max(left | 0, 0),
  24866. top: Math.max(top | 0, 0)
  24867. });
  24868. if (!domUtils.hasClass(popEl, 'edui-state-centered')) {
  24869. popEl.className += ' edui-state-centered';
  24870. }
  24871. } else {
  24872. var dialogWrapNode = this.getDom(),
  24873. contentNode = this.getDom('content');
  24874. dialogWrapNode.style.display = "block";
  24875. var wrapRect = UE.ui.uiUtils.getClientRect(dialogWrapNode),
  24876. contentRect = UE.ui.uiUtils.getClientRect(contentNode);
  24877. dialogWrapNode.style.left = "-100000px";
  24878. contentNode.style.width = (vpRect.width - wrapRect.width + contentRect.width) + "px";
  24879. contentNode.style.height = (vpRect.height - wrapRect.height + contentRect.height) + "px";
  24880. dialogWrapNode.style.width = vpRect.width + "px";
  24881. dialogWrapNode.style.height = vpRect.height + "px";
  24882. dialogWrapNode.style.left = 0;
  24883. //保存环境的overflow值
  24884. this._originalContext = {
  24885. html: {
  24886. overflowX: document.documentElement.style.overflowX,
  24887. overflowY: document.documentElement.style.overflowY
  24888. },
  24889. body: {
  24890. overflowX: document.body.style.overflowX,
  24891. overflowY: document.body.style.overflowY
  24892. }
  24893. };
  24894. document.documentElement.style.overflowX = 'hidden';
  24895. document.documentElement.style.overflowY = 'hidden';
  24896. document.body.style.overflowX = 'hidden';
  24897. document.body.style.overflowY = 'hidden';
  24898. }
  24899. this._show();
  24900. },
  24901. getContentHtml: function () {
  24902. var contentHtml = '';
  24903. if (typeof this.content == 'string') {
  24904. contentHtml = this.content;
  24905. } else if (this.iframeUrl) {
  24906. contentHtml = '<span id="' + this.id + '_contmask" class="dialogcontmask"></span><iframe id="' + this.id +
  24907. '_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="' + this.iframeUrl + '"></iframe>';
  24908. }
  24909. return contentHtml;
  24910. },
  24911. getHtmlTpl: function () {
  24912. var footHtml = '';
  24913. if (this.buttons) {
  24914. var buff = [];
  24915. for (var i = 0; i < this.buttons.length; i++) {
  24916. buff[i] = this.buttons[i].renderHtml();
  24917. }
  24918. footHtml = '<div class="%%-foot">' +
  24919. '<div id="##_buttons" class="%%-buttons">' + buff.join('') + '</div>' +
  24920. '</div>';
  24921. }
  24922. return '<div id="##" class="%%"><div ' + (!this.fullscreen ? 'class="%%"' : 'class="%%-wrap edui-dialog-fullscreen-flag"') + '><div id="##_body" class="%%-body">' +
  24923. '<div class="%%-shadow"></div>' +
  24924. '<div id="##_titlebar" class="%%-titlebar">' +
  24925. '<div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);">' +
  24926. '<span class="%%-caption">' + (this.title || '') + '</span>' +
  24927. '</div>' +
  24928. this.closeButton.renderHtml() +
  24929. '</div>' +
  24930. '<div id="##_content" class="%%-content">' + (this.autoReset ? '' : this.getContentHtml()) + '</div>' +
  24931. footHtml +
  24932. '</div></div></div>';
  24933. },
  24934. postRender: function () {
  24935. // todo: 保持居中/记住上次关闭位置选项
  24936. if (!this.modalMask.getDom()) {
  24937. this.modalMask.render();
  24938. this.modalMask.hide();
  24939. }
  24940. if (!this.dragMask.getDom()) {
  24941. this.dragMask.render();
  24942. this.dragMask.hide();
  24943. }
  24944. var me = this;
  24945. this.addListener('show', function () {
  24946. me.modalMask.show(this.getDom().style.zIndex - 2);
  24947. });
  24948. this.addListener('hide', function () {
  24949. me.modalMask.hide();
  24950. });
  24951. if (this.buttons) {
  24952. for (var i = 0; i < this.buttons.length; i++) {
  24953. this.buttons[i].postRender();
  24954. }
  24955. }
  24956. domUtils.on(window, 'resize', function () {
  24957. setTimeout(function () {
  24958. if (!me.isHidden()) {
  24959. me.safeSetOffset(uiUtils.getClientRect(me.getDom()));
  24960. }
  24961. });
  24962. });
  24963. //hold住scroll事件,防止dialog的滚动影响页面
  24964. // if( this.holdScroll ) {
  24965. //
  24966. // if( !me.iframeUrl ) {
  24967. // domUtils.on( document.getElementById( me.id + "_iframe"), !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24968. // domUtils.preventDefault(e);
  24969. // } );
  24970. // } else {
  24971. // me.addListener('dialogafterreset', function(){
  24972. // window.setTimeout(function(){
  24973. // var iframeWindow = document.getElementById( me.id + "_iframe").contentWindow;
  24974. //
  24975. // if( browser.ie ) {
  24976. //
  24977. // var timer = window.setInterval(function(){
  24978. //
  24979. // if( iframeWindow.document && iframeWindow.document.body ) {
  24980. // window.clearInterval( timer );
  24981. // timer = null;
  24982. // domUtils.on( iframeWindow.document.body, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24983. // domUtils.preventDefault(e);
  24984. // } );
  24985. // }
  24986. //
  24987. // }, 100);
  24988. //
  24989. // } else {
  24990. // domUtils.on( iframeWindow, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24991. // domUtils.preventDefault(e);
  24992. // } );
  24993. // }
  24994. //
  24995. // }, 1);
  24996. // });
  24997. // }
  24998. //
  24999. // }
  25000. this._hide();
  25001. },
  25002. mesureSize: function () {
  25003. var body = this.getDom('body');
  25004. var width = uiUtils.getClientRect(this.getDom('content')).width;
  25005. var dialogBodyStyle = body.style;
  25006. dialogBodyStyle.width = width;
  25007. return uiUtils.getClientRect(body);
  25008. },
  25009. _onTitlebarMouseDown: function (evt, el) {
  25010. if (this.draggable) {
  25011. var rect;
  25012. var vpRect = uiUtils.getViewportRect();
  25013. var me = this;
  25014. uiUtils.startDrag(evt, {
  25015. ondragstart: function () {
  25016. rect = uiUtils.getClientRect(me.getDom());
  25017. me.getDom('contmask').style.visibility = 'visible';
  25018. me.dragMask.show(me.getDom().style.zIndex - 1);
  25019. },
  25020. ondragmove: function (x, y) {
  25021. var left = rect.left + x;
  25022. var top = rect.top + y;
  25023. me.safeSetOffset({
  25024. left: left,
  25025. top: top
  25026. });
  25027. },
  25028. ondragstop: function () {
  25029. me.getDom('contmask').style.visibility = 'hidden';
  25030. domUtils.removeClasses(me.getDom(), ['edui-state-centered']);
  25031. me.dragMask.hide();
  25032. }
  25033. });
  25034. }
  25035. },
  25036. reset: function () {
  25037. this.getDom('content').innerHTML = this.getContentHtml();
  25038. this.fireEvent('dialogafterreset');
  25039. },
  25040. _show: function () {
  25041. if (this._hidden) {
  25042. this.getDom().style.display = '';
  25043. //要高过编辑器的zindxe
  25044. this.editor.container.style.zIndex && (this.getDom().style.zIndex = this.editor.container.style.zIndex * 1 + 10);
  25045. this._hidden = false;
  25046. this.fireEvent('show');
  25047. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = this.getDom().style.zIndex - 4;
  25048. }
  25049. },
  25050. isHidden: function () {
  25051. return this._hidden;
  25052. },
  25053. _hide: function () {
  25054. if (!this._hidden) {
  25055. var wrapNode = this.getDom();
  25056. wrapNode.style.display = 'none';
  25057. wrapNode.style.zIndex = '';
  25058. wrapNode.style.width = '';
  25059. wrapNode.style.height = '';
  25060. this._hidden = true;
  25061. this.fireEvent('hide');
  25062. }
  25063. },
  25064. open: function () {
  25065. if (this.autoReset) {
  25066. //有可能还没有渲染
  25067. try {
  25068. this.reset();
  25069. } catch (e) {
  25070. this.render();
  25071. this.open()
  25072. }
  25073. }
  25074. this.showAtCenter();
  25075. if (this.iframeUrl) {
  25076. try {
  25077. this.getDom('iframe').focus();
  25078. } catch (ex) { }
  25079. }
  25080. activeDialog = this;
  25081. },
  25082. _onCloseButtonClick: function (evt, el) {
  25083. this.close(false);
  25084. },
  25085. close: function (ok) {
  25086. if (this.fireEvent('close', ok) !== false) {
  25087. //还原环境
  25088. if (this.fullscreen) {
  25089. document.documentElement.style.overflowX = this._originalContext.html.overflowX;
  25090. document.documentElement.style.overflowY = this._originalContext.html.overflowY;
  25091. document.body.style.overflowX = this._originalContext.body.overflowX;
  25092. document.body.style.overflowY = this._originalContext.body.overflowY;
  25093. delete this._originalContext;
  25094. }
  25095. this._hide();
  25096. //销毁content
  25097. var content = this.getDom('content');
  25098. var iframe = this.getDom('iframe');
  25099. if (content && iframe) {
  25100. var doc = iframe.contentDocument || iframe.contentWindow.document;
  25101. doc && (doc.body.innerHTML = '');
  25102. domUtils.remove(content);
  25103. }
  25104. }
  25105. }
  25106. };
  25107. utils.inherits(Dialog, UIBase);
  25108. })();
  25109. // ui/menubutton.js
  25110. ///import core
  25111. ///import uicore
  25112. ///import ui/menu.js
  25113. ///import ui/splitbutton.js
  25114. (function () {
  25115. var utils = baidu.editor.utils,
  25116. Menu = baidu.editor.ui.Menu,
  25117. SplitButton = baidu.editor.ui.SplitButton,
  25118. MenuButton = baidu.editor.ui.MenuButton = function (options) {
  25119. this.initOptions(options);
  25120. this.initMenuButton();
  25121. };
  25122. MenuButton.prototype = {
  25123. initMenuButton: function () {
  25124. var me = this;
  25125. this.uiName = "menubutton";
  25126. this.popup = new Menu({
  25127. items: me.items,
  25128. className: me.className,
  25129. editor: me.editor
  25130. });
  25131. this.popup.addListener('show', function () {
  25132. var list = this;
  25133. for (var i = 0; i < list.items.length; i++) {
  25134. list.items[i].removeState('checked');
  25135. if (list.items[i].value == me._value) {
  25136. list.items[i].addState('checked');
  25137. this.value = me._value;
  25138. }
  25139. }
  25140. });
  25141. this.initSplitButton();
  25142. },
  25143. setValue: function (value) {
  25144. this._value = value;
  25145. }
  25146. };
  25147. utils.inherits(MenuButton, SplitButton);
  25148. })();
  25149. // ui/multiMenu.js
  25150. ///import core
  25151. ///import uicore
  25152. ///commands 表情
  25153. (function () {
  25154. var utils = baidu.editor.utils,
  25155. Popup = baidu.editor.ui.Popup,
  25156. SplitButton = baidu.editor.ui.SplitButton,
  25157. MultiMenuPop = baidu.editor.ui.MultiMenuPop = function (options) {
  25158. this.initOptions(options);
  25159. this.initMultiMenu();
  25160. };
  25161. MultiMenuPop.prototype = {
  25162. initMultiMenu: function () {
  25163. var me = this;
  25164. this.popup = new Popup({
  25165. content: '',
  25166. editor: me.editor,
  25167. iframe_rendered: false,
  25168. onshow: function () {
  25169. if (!this.iframe_rendered) {
  25170. this.iframe_rendered = true;
  25171. this.getDom('content').innerHTML = '<iframe id="' + me.id + '_iframe" src="' + me.iframeUrl + '" frameborder="0"></iframe>';
  25172. me.editor.container.style.zIndex && (this.getDom().style.zIndex = me.editor.container.style.zIndex * 1 + 1);
  25173. }
  25174. }
  25175. // canSideUp:false,
  25176. // canSideLeft:false
  25177. });
  25178. this.onbuttonclick = function () {
  25179. this.showPopup();
  25180. };
  25181. this.initSplitButton();
  25182. }
  25183. };
  25184. utils.inherits(MultiMenuPop, SplitButton);
  25185. })();
  25186. // ui/shortcutmenu.js
  25187. (function () {
  25188. var UI = baidu.editor.ui,
  25189. UIBase = UI.UIBase,
  25190. uiUtils = UI.uiUtils,
  25191. utils = baidu.editor.utils,
  25192. domUtils = baidu.editor.dom.domUtils;
  25193. var allMenus = [],//存储所有快捷菜单
  25194. timeID,
  25195. isSubMenuShow = false;//是否有子pop显示
  25196. var ShortCutMenu = UI.ShortCutMenu = function (options) {
  25197. this.initOptions(options);
  25198. this.initShortCutMenu();
  25199. };
  25200. ShortCutMenu.postHide = hideAllMenu;
  25201. ShortCutMenu.prototype = {
  25202. isHidden: true,
  25203. SPACE: 5,
  25204. initShortCutMenu: function () {
  25205. this.items = this.items || [];
  25206. this.initUIBase();
  25207. this.initItems();
  25208. this.initEvent();
  25209. allMenus.push(this);
  25210. },
  25211. initEvent: function () {
  25212. var me = this,
  25213. doc = me.editor.document;
  25214. domUtils.on(doc, "mousemove", function (e) {
  25215. if (me.isHidden === false) {
  25216. //有pop显示就不隐藏快捷菜单
  25217. if (me.getSubMenuMark() || me.eventType == "contextmenu") return;
  25218. var flag = true,
  25219. el = me.getDom(),
  25220. wt = el.offsetWidth,
  25221. ht = el.offsetHeight,
  25222. distanceX = wt / 2 + me.SPACE,//距离中心X标准
  25223. distanceY = ht / 2,//距离中心Y标准
  25224. x = Math.abs(e.screenX - me.left),//离中心距离横坐标
  25225. y = Math.abs(e.screenY - me.top);//离中心距离纵坐标
  25226. clearTimeout(timeID);
  25227. timeID = setTimeout(function () {
  25228. if (y > 0 && y < distanceY) {
  25229. me.setOpacity(el, "1");
  25230. } else if (y > distanceY && y < distanceY + 70) {
  25231. me.setOpacity(el, "0.5");
  25232. flag = false;
  25233. } else if (y > distanceY + 70 && y < distanceY + 140) {
  25234. me.hide();
  25235. }
  25236. if (flag && x > 0 && x < distanceX) {
  25237. me.setOpacity(el, "1")
  25238. } else if (x > distanceX && x < distanceX + 70) {
  25239. me.setOpacity(el, "0.5")
  25240. } else if (x > distanceX + 70 && x < distanceX + 140) {
  25241. me.hide();
  25242. }
  25243. });
  25244. }
  25245. });
  25246. //ie\ff下 mouseout不准
  25247. if (browser.chrome) {
  25248. domUtils.on(doc, "mouseout", function (e) {
  25249. var relatedTgt = e.relatedTarget || e.toElement;
  25250. if (relatedTgt == null || relatedTgt.tagName == "HTML") {
  25251. me.hide();
  25252. }
  25253. });
  25254. }
  25255. me.editor.addListener("afterhidepop", function () {
  25256. if (!me.isHidden) {
  25257. isSubMenuShow = true;
  25258. }
  25259. });
  25260. },
  25261. initItems: function () {
  25262. if (utils.isArray(this.items)) {
  25263. for (var i = 0, len = this.items.length; i < len; i++) {
  25264. var item = this.items[i].toLowerCase();
  25265. if (UI[item]) {
  25266. this.items[i] = new UI[item](this.editor);
  25267. this.items[i].className += " edui-shortcutsubmenu ";
  25268. }
  25269. }
  25270. }
  25271. },
  25272. setOpacity: function (el, value) {
  25273. if (browser.ie && browser.version < 9) {
  25274. el.style.filter = "alpha(opacity = " + parseFloat(value) * 100 + ");"
  25275. } else {
  25276. el.style.opacity = value;
  25277. }
  25278. },
  25279. getSubMenuMark: function () {
  25280. isSubMenuShow = false;
  25281. var layerEle = uiUtils.getFixedLayer();
  25282. var list = domUtils.getElementsByTagName(layerEle, "div", function (node) {
  25283. return domUtils.hasClass(node, "edui-shortcutsubmenu edui-popup")
  25284. });
  25285. for (var i = 0, node; node = list[i++];) {
  25286. if (node.style.display != "none") {
  25287. isSubMenuShow = true;
  25288. }
  25289. }
  25290. return isSubMenuShow;
  25291. },
  25292. show: function (e, hasContextmenu) {
  25293. var me = this,
  25294. offset = {},
  25295. el = this.getDom(),
  25296. fixedlayer = uiUtils.getFixedLayer();
  25297. function setPos(offset) {
  25298. if (offset.left < 0) {
  25299. offset.left = 0;
  25300. }
  25301. if (offset.top < 0) {
  25302. offset.top = 0;
  25303. }
  25304. el.style.cssText = "position:absolute;left:" + offset.left + "px;top:" + offset.top + "px;";
  25305. }
  25306. function setPosByCxtMenu(menu) {
  25307. if (!menu.tagName) {
  25308. menu = menu.getDom();
  25309. }
  25310. offset.left = parseInt(menu.style.left);
  25311. offset.top = parseInt(menu.style.top);
  25312. offset.top -= el.offsetHeight + 15;
  25313. setPos(offset);
  25314. }
  25315. me.eventType = e.type;
  25316. el.style.cssText = "display:block;left:-9999px";
  25317. if (e.type == "contextmenu" && hasContextmenu) {
  25318. var menu = domUtils.getElementsByTagName(fixedlayer, "div", "edui-contextmenu")[0];
  25319. if (menu) {
  25320. setPosByCxtMenu(menu)
  25321. } else {
  25322. me.editor.addListener("aftershowcontextmenu", function (type, menu) {
  25323. setPosByCxtMenu(menu);
  25324. });
  25325. }
  25326. } else {
  25327. offset = uiUtils.getViewportOffsetByEvent(e);
  25328. offset.top -= el.offsetHeight + me.SPACE;
  25329. offset.left += me.SPACE + 20;
  25330. setPos(offset);
  25331. me.setOpacity(el, 0.2);
  25332. }
  25333. me.isHidden = false;
  25334. me.left = e.screenX + el.offsetWidth / 2 - me.SPACE;
  25335. me.top = e.screenY - (el.offsetHeight / 2) - me.SPACE;
  25336. if (me.editor) {
  25337. el.style.zIndex = me.editor.container.style.zIndex * 1 + 10;
  25338. fixedlayer.style.zIndex = el.style.zIndex - 1;
  25339. }
  25340. },
  25341. hide: function () {
  25342. if (this.getDom()) {
  25343. this.getDom().style.display = "none";
  25344. }
  25345. this.isHidden = true;
  25346. },
  25347. postRender: function () {
  25348. if (utils.isArray(this.items)) {
  25349. for (var i = 0, item; item = this.items[i++];) {
  25350. item.postRender();
  25351. }
  25352. }
  25353. },
  25354. getHtmlTpl: function () {
  25355. var buff;
  25356. if (utils.isArray(this.items)) {
  25357. buff = [];
  25358. for (var i = 0; i < this.items.length; i++) {
  25359. buff[i] = this.items[i].renderHtml();
  25360. }
  25361. buff = buff.join("");
  25362. } else {
  25363. buff = this.items;
  25364. }
  25365. return '<div id="##" class="%% edui-toolbar" data-src="shortcutmenu" onmousedown="return false;" onselectstart="return false;" >' +
  25366. buff +
  25367. '</div>';
  25368. }
  25369. };
  25370. utils.inherits(ShortCutMenu, UIBase);
  25371. function hideAllMenu(e) {
  25372. var tgt = e.target || e.srcElement,
  25373. cur = domUtils.findParent(tgt, function (node) {
  25374. return domUtils.hasClass(node, "edui-shortcutmenu") || domUtils.hasClass(node, "edui-popup");
  25375. }, true);
  25376. if (!cur) {
  25377. for (var i = 0, menu; menu = allMenus[i++];) {
  25378. menu.hide()
  25379. }
  25380. }
  25381. }
  25382. domUtils.on(document, 'mousedown', function (e) {
  25383. hideAllMenu(e);
  25384. });
  25385. domUtils.on(window, 'scroll', function (e) {
  25386. hideAllMenu(e);
  25387. });
  25388. })();
  25389. // ui/breakline.js
  25390. (function () {
  25391. var utils = baidu.editor.utils,
  25392. UIBase = baidu.editor.ui.UIBase,
  25393. Breakline = baidu.editor.ui.Breakline = function (options) {
  25394. this.initOptions(options);
  25395. this.initSeparator();
  25396. };
  25397. Breakline.prototype = {
  25398. uiName: 'Breakline',
  25399. initSeparator: function () {
  25400. this.initUIBase();
  25401. },
  25402. getHtmlTpl: function () {
  25403. return '<br/>';
  25404. }
  25405. };
  25406. utils.inherits(Breakline, UIBase);
  25407. })();
  25408. // ui/message.js
  25409. ///import core
  25410. ///import uicore
  25411. (function () {
  25412. var utils = baidu.editor.utils,
  25413. domUtils = baidu.editor.dom.domUtils,
  25414. UIBase = baidu.editor.ui.UIBase,
  25415. Message = baidu.editor.ui.Message = function (options) {
  25416. this.initOptions(options);
  25417. this.initMessage();
  25418. };
  25419. Message.prototype = {
  25420. initMessage: function () {
  25421. this.initUIBase();
  25422. },
  25423. getHtmlTpl: function () {
  25424. return '<div id="##" class="edui-message %%">' +
  25425. ' <div id="##_closer" class="edui-message-closer">×</div>' +
  25426. ' <div id="##_body" class="edui-message-body edui-message-type-info">' +
  25427. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  25428. ' <div class="edui-shadow"></div>' +
  25429. ' <div id="##_content" class="edui-message-content">' +
  25430. ' </div>' +
  25431. ' </div>' +
  25432. '</div>';
  25433. },
  25434. reset: function (opt) {
  25435. var me = this;
  25436. if (!opt.keepshow) {
  25437. clearTimeout(this.timer);
  25438. me.timer = setTimeout(function () {
  25439. me.hide();
  25440. }, opt.timeout || 4000);
  25441. }
  25442. opt.content !== undefined && me.setContent(opt.content);
  25443. opt.type !== undefined && me.setType(opt.type);
  25444. me.show();
  25445. },
  25446. postRender: function () {
  25447. var me = this,
  25448. closer = this.getDom('closer');
  25449. closer && domUtils.on(closer, 'click', function () {
  25450. me.hide();
  25451. });
  25452. },
  25453. setContent: function (content) {
  25454. this.getDom('content').innerHTML = content;
  25455. },
  25456. setType: function (type) {
  25457. type = type || 'info';
  25458. var body = this.getDom('body');
  25459. body.className = body.className.replace(/edui-message-type-[\w-]+/, 'edui-message-type-' + type);
  25460. },
  25461. getContent: function () {
  25462. return this.getDom('content').innerHTML;
  25463. },
  25464. getType: function () {
  25465. var arr = this.getDom('body').match(/edui-message-type-([\w-]+)/);
  25466. return arr ? arr[1] : '';
  25467. },
  25468. show: function () {
  25469. this.getDom().style.display = 'block';
  25470. },
  25471. hide: function () {
  25472. var dom = this.getDom();
  25473. if (dom) {
  25474. dom.style.display = 'none';
  25475. dom.parentNode && dom.parentNode.removeChild(dom);
  25476. }
  25477. }
  25478. };
  25479. utils.inherits(Message, UIBase);
  25480. })();
  25481. // adapter/editorui.js
  25482. //ui跟编辑器的适配層
  25483. //那个按钮弹出是dialog,是下拉筐等都是在这个js中配置
  25484. //自己写的ui也要在这里配置,放到baidu.editor.ui下边,当编辑器实例化的时候会根据ueditor.config中的toolbars找到相应的进行实例化
  25485. (function () {
  25486. var utils = baidu.editor.utils;
  25487. var editorui = baidu.editor.ui;
  25488. var _Dialog = editorui.Dialog;
  25489. editorui.buttons = {};
  25490. editorui.Dialog = function (options) {
  25491. var dialog = new _Dialog(options);
  25492. dialog.addListener('hide', function () {
  25493. if (dialog.editor) {
  25494. var editor = dialog.editor;
  25495. try {
  25496. if (browser.gecko) {
  25497. var y = editor.window.scrollY,
  25498. x = editor.window.scrollX;
  25499. editor.body.focus();
  25500. editor.window.scrollTo(x, y);
  25501. } else {
  25502. editor.focus();
  25503. }
  25504. } catch (ex) {
  25505. }
  25506. }
  25507. });
  25508. return dialog;
  25509. };
  25510. var iframeUrlMap = {
  25511. 'anchor': '~/dialogs/anchor/anchor.html',
  25512. 'insertimage': '~/dialogs/image/image.html',
  25513. 'link': '~/dialogs/link/link.html',
  25514. 'spechars': '~/dialogs/spechars/spechars.html',
  25515. 'searchreplace': '~/dialogs/searchreplace/searchreplace.html',
  25516. 'map': '~/dialogs/map/map.html',
  25517. 'gmap': '~/dialogs/gmap/gmap.html',
  25518. 'insertvideo': '~/dialogs/video/video.html',
  25519. 'help': '~/dialogs/help/help.html',
  25520. 'preview': '~/dialogs/preview/preview.html',
  25521. 'emotion': '~/dialogs/emotion/emotion.html',
  25522. 'wordimage': '~/dialogs/wordimage/wordimage.html',
  25523. 'attachment': '~/dialogs/attachment/attachment.html',
  25524. 'insertframe': '~/dialogs/insertframe/insertframe.html',
  25525. 'edittip': '~/dialogs/table/edittip.html',
  25526. 'edittable': '~/dialogs/table/edittable.html',
  25527. 'edittd': '~/dialogs/table/edittd.html',
  25528. 'webapp': '~/dialogs/webapp/webapp.html',
  25529. 'snapscreen': '~/dialogs/snapscreen/snapscreen.html',
  25530. 'scrawl': '~/dialogs/scrawl/scrawl.html',
  25531. 'music': '~/dialogs/music/music.html',
  25532. 'template': '~/dialogs/template/template.html',
  25533. 'background': '~/dialogs/background/background.html',
  25534. 'charts': '~/dialogs/charts/charts.html'
  25535. };
  25536. //为工具栏添加按钮,以下都是统一的按钮触发命令,所以写在一起
  25537. var btnCmds = ['undo', 'redo', 'formatmatch',
  25538. 'bold', 'italic', 'underline', 'fontborder', 'touppercase', 'tolowercase',
  25539. 'strikethrough', 'subscript', 'superscript', 'source', 'indent', 'outdent',
  25540. 'blockquote', 'pasteplain', 'pagebreak',
  25541. 'selectall', 'print', 'horizontal', 'removeformat', 'time', 'date', 'unlink',
  25542. 'insertparagraphbeforetable', 'insertrow', 'insertcol', 'mergeright', 'mergedown', 'deleterow',
  25543. 'deletecol', 'splittorows', 'splittocols', 'splittocells', 'mergecells', 'deletetable', 'drafts'];
  25544. for (var i = 0, ci; ci = btnCmds[i++];) {
  25545. ci = ci.toLowerCase();
  25546. editorui[ci] = function (cmd) {
  25547. return function (editor) {
  25548. var ui = new editorui.Button({
  25549. className: 'edui-for-' + cmd,
  25550. title: editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  25551. onclick: function () {
  25552. editor.execCommand(cmd);
  25553. },
  25554. theme: editor.options.theme,
  25555. showText: false
  25556. });
  25557. editorui.buttons[cmd] = ui;
  25558. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25559. var state = editor.queryCommandState(cmd);
  25560. if (state == -1) {
  25561. ui.setDisabled(true);
  25562. ui.setChecked(false);
  25563. } else {
  25564. if (!uiReady) {
  25565. ui.setDisabled(false);
  25566. ui.setChecked(state);
  25567. }
  25568. }
  25569. });
  25570. return ui;
  25571. };
  25572. }(ci);
  25573. }
  25574. //清除文档
  25575. editorui.cleardoc = function (editor) {
  25576. var ui = new editorui.Button({
  25577. className: 'edui-for-cleardoc',
  25578. title: editor.options.labelMap.cleardoc || editor.getLang("labelMap.cleardoc") || '',
  25579. theme: editor.options.theme,
  25580. onclick: function () {
  25581. if (confirm(editor.getLang("confirmClear"))) {
  25582. editor.execCommand('cleardoc');
  25583. }
  25584. }
  25585. });
  25586. editorui.buttons["cleardoc"] = ui;
  25587. editor.addListener('selectionchange', function () {
  25588. ui.setDisabled(editor.queryCommandState('cleardoc') == -1);
  25589. });
  25590. return ui;
  25591. };
  25592. //排版,图片排版,文字方向
  25593. var typeset = {
  25594. 'justify': ['left', 'right', 'center', 'justify'],
  25595. 'imagefloat': ['none', 'left', 'center', 'right'],
  25596. 'directionality': ['ltr', 'rtl']
  25597. };
  25598. for (var p in typeset) {
  25599. (function (cmd, val) {
  25600. for (var i = 0, ci; ci = val[i++];) {
  25601. (function (cmd2) {
  25602. editorui[cmd.replace('float', '') + cmd2] = function (editor) {
  25603. var ui = new editorui.Button({
  25604. className: 'edui-for-' + cmd.replace('float', '') + cmd2,
  25605. title: editor.options.labelMap[cmd.replace('float', '') + cmd2] || editor.getLang("labelMap." + cmd.replace('float', '') + cmd2) || '',
  25606. theme: editor.options.theme,
  25607. onclick: function () {
  25608. editor.execCommand(cmd, cmd2);
  25609. }
  25610. });
  25611. editorui.buttons[cmd] = ui;
  25612. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25613. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  25614. ui.setChecked(editor.queryCommandValue(cmd) == cmd2 && !uiReady);
  25615. });
  25616. return ui;
  25617. };
  25618. })(ci)
  25619. }
  25620. })(p, typeset[p])
  25621. }
  25622. //字体颜色和背景颜色
  25623. for (var i = 0, ci; ci = ['backcolor', 'forecolor'][i++];) {
  25624. editorui[ci] = function (cmd) {
  25625. return function (editor) {
  25626. var ui = new editorui.ColorButton({
  25627. className: 'edui-for-' + cmd,
  25628. color: 'default',
  25629. title: editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  25630. editor: editor,
  25631. onpickcolor: function (t, color) {
  25632. editor.execCommand(cmd, color);
  25633. },
  25634. onpicknocolor: function () {
  25635. editor.execCommand(cmd, 'default');
  25636. this.setColor('transparent');
  25637. this.color = 'default';
  25638. },
  25639. onbuttonclick: function () {
  25640. editor.execCommand(cmd, this.color);
  25641. }
  25642. });
  25643. editorui.buttons[cmd] = ui;
  25644. editor.addListener('selectionchange', function () {
  25645. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  25646. });
  25647. return ui;
  25648. };
  25649. }(ci);
  25650. }
  25651. var dialogBtns = {
  25652. noOk: ['searchreplace', 'help', 'spechars', 'webapp', 'preview'],
  25653. ok: ['attachment', 'anchor', 'link', 'insertimage', 'map', 'gmap', 'insertframe', 'wordimage',
  25654. 'insertvideo', 'insertframe', 'edittip', 'edittable', 'edittd', 'scrawl', 'template', 'music', 'background', 'charts']
  25655. };
  25656. for (var p in dialogBtns) {
  25657. (function (type, vals) {
  25658. for (var i = 0, ci; ci = vals[i++];) {
  25659. //todo opera下存在问题
  25660. if (browser.opera && ci === "searchreplace") {
  25661. continue;
  25662. }
  25663. (function (cmd) {
  25664. editorui[cmd] = function (editor, iframeUrl, title) {
  25665. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd];
  25666. title = editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '';
  25667. var dialog;
  25668. //没有iframeUrl不创建dialog
  25669. if (iframeUrl) {
  25670. dialog = new editorui.Dialog(utils.extend({
  25671. iframeUrl: editor.ui.mapUrl(iframeUrl),
  25672. editor: editor,
  25673. className: 'edui-for-' + cmd,
  25674. title: title,
  25675. holdScroll: cmd === 'insertimage',
  25676. fullscreen: /charts|preview/.test(cmd),
  25677. closeDialog: editor.getLang("closeDialog")
  25678. }, type == 'ok' ? {
  25679. buttons: [
  25680. {
  25681. className: 'edui-okbutton',
  25682. label: editor.getLang("ok"),
  25683. editor: editor,
  25684. onclick: function () {
  25685. dialog.close(true);
  25686. }
  25687. },
  25688. {
  25689. className: 'edui-cancelbutton',
  25690. label: editor.getLang("cancel"),
  25691. editor: editor,
  25692. onclick: function () {
  25693. dialog.close(false);
  25694. }
  25695. }
  25696. ]
  25697. } : {}));
  25698. editor.ui._dialogs[cmd + "Dialog"] = dialog;
  25699. }
  25700. var ui = new editorui.Button({
  25701. className: 'edui-for-' + cmd,
  25702. title: title,
  25703. onclick: function () {
  25704. if (dialog) {
  25705. switch (cmd) {
  25706. case "wordimage":
  25707. var images = editor.execCommand("wordimage");
  25708. if (images && images.length) {
  25709. dialog.render();
  25710. dialog.open();
  25711. }
  25712. break;
  25713. case "scrawl":
  25714. if (editor.queryCommandState("scrawl") != -1) {
  25715. dialog.render();
  25716. dialog.open();
  25717. }
  25718. break;
  25719. default:
  25720. dialog.render();
  25721. dialog.open();
  25722. }
  25723. }
  25724. },
  25725. theme: editor.options.theme,
  25726. disabled: (cmd == 'scrawl' && editor.queryCommandState("scrawl") == -1) || (cmd == 'charts')
  25727. });
  25728. editorui.buttons[cmd] = ui;
  25729. editor.addListener('selectionchange', function () {
  25730. //只存在于右键菜单而无工具栏按钮的ui不需要检测状态
  25731. var unNeedCheckState = { 'edittable': 1 };
  25732. if (cmd in unNeedCheckState) return;
  25733. var state = editor.queryCommandState(cmd);
  25734. if (ui.getDom()) {
  25735. ui.setDisabled(state == -1);
  25736. ui.setChecked(state);
  25737. }
  25738. });
  25739. return ui;
  25740. };
  25741. })(ci.toLowerCase())
  25742. }
  25743. })(p, dialogBtns[p]);
  25744. }
  25745. editorui.snapscreen = function (editor, iframeUrl, title) {
  25746. title = editor.options.labelMap['snapscreen'] || editor.getLang("labelMap.snapscreen") || '';
  25747. var ui = new editorui.Button({
  25748. className: 'edui-for-snapscreen',
  25749. title: title,
  25750. onclick: function () {
  25751. editor.execCommand("snapscreen");
  25752. },
  25753. theme: editor.options.theme
  25754. });
  25755. editorui.buttons['snapscreen'] = ui;
  25756. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})["snapscreen"] || iframeUrlMap["snapscreen"];
  25757. if (iframeUrl) {
  25758. var dialog = new editorui.Dialog({
  25759. iframeUrl: editor.ui.mapUrl(iframeUrl),
  25760. editor: editor,
  25761. className: 'edui-for-snapscreen',
  25762. title: title,
  25763. buttons: [
  25764. {
  25765. className: 'edui-okbutton',
  25766. label: editor.getLang("ok"),
  25767. editor: editor,
  25768. onclick: function () {
  25769. dialog.close(true);
  25770. }
  25771. },
  25772. {
  25773. className: 'edui-cancelbutton',
  25774. label: editor.getLang("cancel"),
  25775. editor: editor,
  25776. onclick: function () {
  25777. dialog.close(false);
  25778. }
  25779. }
  25780. ]
  25781. });
  25782. dialog.render();
  25783. editor.ui._dialogs["snapscreenDialog"] = dialog;
  25784. }
  25785. editor.addListener('selectionchange', function () {
  25786. ui.setDisabled(editor.queryCommandState('snapscreen') == -1);
  25787. });
  25788. return ui;
  25789. };
  25790. editorui.insertcode = function (editor, list, title) {
  25791. list = editor.options['insertcode'] || [];
  25792. title = editor.options.labelMap['insertcode'] || editor.getLang("labelMap.insertcode") || '';
  25793. // if (!list.length) return;
  25794. var items = [];
  25795. utils.each(list, function (key, val) {
  25796. items.push({
  25797. label: key,
  25798. value: val,
  25799. theme: editor.options.theme,
  25800. renderLabelHtml: function () {
  25801. return '<div class="edui-label %%-label" >' + (this.label || '') + '</div>';
  25802. }
  25803. });
  25804. });
  25805. var ui = new editorui.Combox({
  25806. editor: editor,
  25807. items: items,
  25808. onselect: function (t, index) {
  25809. editor.execCommand('insertcode', this.items[index].value);
  25810. },
  25811. onbuttonclick: function () {
  25812. this.showPopup();
  25813. },
  25814. title: title,
  25815. initValue: title,
  25816. className: 'edui-for-insertcode',
  25817. indexByValue: function (value) {
  25818. if (value) {
  25819. for (var i = 0, ci; ci = this.items[i]; i++) {
  25820. if (ci.value.indexOf(value) != -1)
  25821. return i;
  25822. }
  25823. }
  25824. return -1;
  25825. }
  25826. });
  25827. editorui.buttons['insertcode'] = ui;
  25828. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25829. if (!uiReady) {
  25830. var state = editor.queryCommandState('insertcode');
  25831. if (state == -1) {
  25832. ui.setDisabled(true);
  25833. } else {
  25834. ui.setDisabled(false);
  25835. var value = editor.queryCommandValue('insertcode');
  25836. if (!value) {
  25837. ui.setValue(title);
  25838. return;
  25839. }
  25840. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  25841. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  25842. ui.setValue(value);
  25843. }
  25844. }
  25845. });
  25846. return ui;
  25847. };
  25848. editorui.fontfamily = function (editor, list, title) {
  25849. list = editor.options['fontfamily'] || [];
  25850. title = editor.options.labelMap['fontfamily'] || editor.getLang("labelMap.fontfamily") || '';
  25851. if (!list.length) return;
  25852. for (var i = 0, ci, items = []; ci = list[i]; i++) {
  25853. var langLabel = editor.getLang('fontfamily')[ci.name] || "";
  25854. (function (key, val) {
  25855. items.push({
  25856. label: key,
  25857. value: val,
  25858. theme: editor.options.theme,
  25859. renderLabelHtml: function () {
  25860. return '<div class="edui-label %%-label" style="font-family:' +
  25861. utils.unhtml(this.value) + '">' + (this.label || '') + '</div>';
  25862. }
  25863. });
  25864. })(ci.label || langLabel, ci.val)
  25865. }
  25866. var ui = new editorui.Combox({
  25867. editor: editor,
  25868. items: items,
  25869. onselect: function (t, index) {
  25870. editor.execCommand('FontFamily', this.items[index].value);
  25871. },
  25872. onbuttonclick: function () {
  25873. this.showPopup();
  25874. },
  25875. title: title,
  25876. initValue: title,
  25877. className: 'edui-for-fontfamily',
  25878. indexByValue: function (value) {
  25879. if (value) {
  25880. for (var i = 0, ci; ci = this.items[i]; i++) {
  25881. if (ci.value.indexOf(value) != -1)
  25882. return i;
  25883. }
  25884. }
  25885. return -1;
  25886. }
  25887. });
  25888. editorui.buttons['fontfamily'] = ui;
  25889. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25890. if (!uiReady) {
  25891. var state = editor.queryCommandState('FontFamily');
  25892. if (state == -1) {
  25893. ui.setDisabled(true);
  25894. } else {
  25895. ui.setDisabled(false);
  25896. var value = editor.queryCommandValue('FontFamily');
  25897. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  25898. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  25899. ui.setValue(value);
  25900. }
  25901. }
  25902. });
  25903. return ui;
  25904. };
  25905. editorui.fontsize = function (editor, list, title) {
  25906. title = editor.options.labelMap['fontsize'] || editor.getLang("labelMap.fontsize") || '';
  25907. list = list || editor.options['fontsize'] || [];
  25908. if (!list.length) return;
  25909. var items = [];
  25910. for (var i = 0; i < list.length; i++) {
  25911. var size = list[i] + 'px';
  25912. items.push({
  25913. label: size,
  25914. value: size,
  25915. theme: editor.options.theme,
  25916. renderLabelHtml: function () {
  25917. return '<div class="edui-label %%-label" style="line-height:1;font-size:' +
  25918. this.value + '">' + (this.label || '') + '</div>';
  25919. }
  25920. });
  25921. }
  25922. var ui = new editorui.Combox({
  25923. editor: editor,
  25924. items: items,
  25925. title: title,
  25926. initValue: title,
  25927. onselect: function (t, index) {
  25928. editor.execCommand('FontSize', this.items[index].value);
  25929. },
  25930. onbuttonclick: function () {
  25931. this.showPopup();
  25932. },
  25933. className: 'edui-for-fontsize'
  25934. });
  25935. editorui.buttons['fontsize'] = ui;
  25936. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25937. if (!uiReady) {
  25938. var state = editor.queryCommandState('FontSize');
  25939. if (state == -1) {
  25940. ui.setDisabled(true);
  25941. } else {
  25942. ui.setDisabled(false);
  25943. ui.setValue(editor.queryCommandValue('FontSize'));
  25944. }
  25945. }
  25946. });
  25947. return ui;
  25948. };
  25949. editorui.paragraph = function (editor, list, title) {
  25950. title = editor.options.labelMap['paragraph'] || editor.getLang("labelMap.paragraph") || '';
  25951. list = editor.options['paragraph'] || [];
  25952. if (utils.isEmptyObject(list)) return;
  25953. var items = [];
  25954. for (var i in list) {
  25955. items.push({
  25956. value: i,
  25957. label: list[i] || editor.getLang("paragraph")[i],
  25958. theme: editor.options.theme,
  25959. renderLabelHtml: function () {
  25960. return '<div class="edui-label %%-label"><span class="edui-for-' + this.value + '">' + (this.label || '') + '</span></div>';
  25961. }
  25962. })
  25963. }
  25964. var ui = new editorui.Combox({
  25965. editor: editor,
  25966. items: items,
  25967. title: title,
  25968. initValue: title,
  25969. className: 'edui-for-paragraph',
  25970. onselect: function (t, index) {
  25971. editor.execCommand('Paragraph', this.items[index].value);
  25972. },
  25973. onbuttonclick: function () {
  25974. this.showPopup();
  25975. }
  25976. });
  25977. editorui.buttons['paragraph'] = ui;
  25978. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25979. if (!uiReady) {
  25980. var state = editor.queryCommandState('Paragraph');
  25981. if (state == -1) {
  25982. ui.setDisabled(true);
  25983. } else {
  25984. ui.setDisabled(false);
  25985. var value = editor.queryCommandValue('Paragraph');
  25986. var index = ui.indexByValue(value);
  25987. if (index != -1) {
  25988. ui.setValue(value);
  25989. } else {
  25990. ui.setValue(ui.initValue);
  25991. }
  25992. }
  25993. }
  25994. });
  25995. return ui;
  25996. };
  25997. //自定义标题
  25998. editorui.customstyle = function (editor) {
  25999. var list = editor.options['customstyle'] || [],
  26000. title = editor.options.labelMap['customstyle'] || editor.getLang("labelMap.customstyle") || '';
  26001. if (!list.length) return;
  26002. var langCs = editor.getLang('customstyle');
  26003. for (var i = 0, items = [], t; t = list[i++];) {
  26004. (function (t) {
  26005. var ck = {};
  26006. ck.label = t.label ? t.label : langCs[t.name];
  26007. ck.style = t.style;
  26008. ck.className = t.className;
  26009. ck.tag = t.tag;
  26010. items.push({
  26011. label: ck.label,
  26012. value: ck,
  26013. theme: editor.options.theme,
  26014. renderLabelHtml: function () {
  26015. return '<div class="edui-label %%-label">' + '<' + ck.tag + ' ' + (ck.className ? ' class="' + ck.className + '"' : "")
  26016. + (ck.style ? ' style="' + ck.style + '"' : "") + '>' + ck.label + "<\/" + ck.tag + ">"
  26017. + '</div>';
  26018. }
  26019. });
  26020. })(t);
  26021. }
  26022. var ui = new editorui.Combox({
  26023. editor: editor,
  26024. items: items,
  26025. title: title,
  26026. initValue: title,
  26027. className: 'edui-for-customstyle',
  26028. onselect: function (t, index) {
  26029. editor.execCommand('customstyle', this.items[index].value);
  26030. },
  26031. onbuttonclick: function () {
  26032. this.showPopup();
  26033. },
  26034. indexByValue: function (value) {
  26035. for (var i = 0, ti; ti = this.items[i++];) {
  26036. if (ti.label == value) {
  26037. return i - 1
  26038. }
  26039. }
  26040. return -1;
  26041. }
  26042. });
  26043. editorui.buttons['customstyle'] = ui;
  26044. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  26045. if (!uiReady) {
  26046. var state = editor.queryCommandState('customstyle');
  26047. if (state == -1) {
  26048. ui.setDisabled(true);
  26049. } else {
  26050. ui.setDisabled(false);
  26051. var value = editor.queryCommandValue('customstyle');
  26052. var index = ui.indexByValue(value);
  26053. if (index != -1) {
  26054. ui.setValue(value);
  26055. } else {
  26056. ui.setValue(ui.initValue);
  26057. }
  26058. }
  26059. }
  26060. });
  26061. return ui;
  26062. };
  26063. editorui.inserttable = function (editor, iframeUrl, title) {
  26064. title = editor.options.labelMap['inserttable'] || editor.getLang("labelMap.inserttable") || '';
  26065. var ui = new editorui.TableButton({
  26066. editor: editor,
  26067. title: title,
  26068. className: 'edui-for-inserttable',
  26069. onpicktable: function (t, numCols, numRows) {
  26070. editor.execCommand('InsertTable', { numRows: numRows, numCols: numCols, border: 1 });
  26071. },
  26072. onbuttonclick: function () {
  26073. this.showPopup();
  26074. }
  26075. });
  26076. editorui.buttons['inserttable'] = ui;
  26077. editor.addListener('selectionchange', function () {
  26078. ui.setDisabled(editor.queryCommandState('inserttable') == -1);
  26079. });
  26080. return ui;
  26081. };
  26082. editorui.lineheight = function (editor) {
  26083. var val = editor.options.lineheight || [];
  26084. if (!val.length) return;
  26085. for (var i = 0, ci, items = []; ci = val[i++];) {
  26086. items.push({
  26087. //todo:写死了
  26088. label: ci,
  26089. value: ci,
  26090. theme: editor.options.theme,
  26091. onclick: function () {
  26092. editor.execCommand("lineheight", this.value);
  26093. }
  26094. })
  26095. }
  26096. var ui = new editorui.MenuButton({
  26097. editor: editor,
  26098. className: 'edui-for-lineheight',
  26099. title: editor.options.labelMap['lineheight'] || editor.getLang("labelMap.lineheight") || '',
  26100. items: items,
  26101. onbuttonclick: function () {
  26102. var value = editor.queryCommandValue('LineHeight') || this.value;
  26103. editor.execCommand("LineHeight", value);
  26104. }
  26105. });
  26106. editorui.buttons['lineheight'] = ui;
  26107. editor.addListener('selectionchange', function () {
  26108. var state = editor.queryCommandState('LineHeight');
  26109. if (state == -1) {
  26110. ui.setDisabled(true);
  26111. } else {
  26112. ui.setDisabled(false);
  26113. var value = editor.queryCommandValue('LineHeight');
  26114. value && ui.setValue((value + '').replace(/cm/, ''));
  26115. ui.setChecked(state)
  26116. }
  26117. });
  26118. return ui;
  26119. };
  26120. var rowspacings = ['top', 'bottom'];
  26121. for (var r = 0, ri; ri = rowspacings[r++];) {
  26122. (function (cmd) {
  26123. editorui['rowspacing' + cmd] = function (editor) {
  26124. var val = editor.options['rowspacing' + cmd] || [];
  26125. if (!val.length) return null;
  26126. for (var i = 0, ci, items = []; ci = val[i++];) {
  26127. items.push({
  26128. label: ci,
  26129. value: ci,
  26130. theme: editor.options.theme,
  26131. onclick: function () {
  26132. editor.execCommand("rowspacing", this.value, cmd);
  26133. }
  26134. })
  26135. }
  26136. var ui = new editorui.MenuButton({
  26137. editor: editor,
  26138. className: 'edui-for-rowspacing' + cmd,
  26139. title: editor.options.labelMap['rowspacing' + cmd] || editor.getLang("labelMap.rowspacing" + cmd) || '',
  26140. items: items,
  26141. onbuttonclick: function () {
  26142. var value = editor.queryCommandValue('rowspacing', cmd) || this.value;
  26143. editor.execCommand("rowspacing", value, cmd);
  26144. }
  26145. });
  26146. editorui.buttons[cmd] = ui;
  26147. editor.addListener('selectionchange', function () {
  26148. var state = editor.queryCommandState('rowspacing', cmd);
  26149. if (state == -1) {
  26150. ui.setDisabled(true);
  26151. } else {
  26152. ui.setDisabled(false);
  26153. var value = editor.queryCommandValue('rowspacing', cmd);
  26154. value && ui.setValue((value + '').replace(/%/, ''));
  26155. ui.setChecked(state)
  26156. }
  26157. });
  26158. return ui;
  26159. }
  26160. })(ri)
  26161. }
  26162. //有序,无序列表
  26163. var lists = ['insertorderedlist', 'insertunorderedlist'];
  26164. for (var l = 0, cl; cl = lists[l++];) {
  26165. (function (cmd) {
  26166. editorui[cmd] = function (editor) {
  26167. var vals = editor.options[cmd],
  26168. _onMenuClick = function () {
  26169. editor.execCommand(cmd, this.value);
  26170. }, items = [];
  26171. for (var i in vals) {
  26172. items.push({
  26173. label: vals[i] || editor.getLang()[cmd][i] || "",
  26174. value: i,
  26175. theme: editor.options.theme,
  26176. onclick: _onMenuClick
  26177. })
  26178. }
  26179. var ui = new editorui.MenuButton({
  26180. editor: editor,
  26181. className: 'edui-for-' + cmd,
  26182. title: editor.getLang("labelMap." + cmd) || '',
  26183. 'items': items,
  26184. onbuttonclick: function () {
  26185. var value = editor.queryCommandValue(cmd) || this.value;
  26186. editor.execCommand(cmd, value);
  26187. }
  26188. });
  26189. editorui.buttons[cmd] = ui;
  26190. editor.addListener('selectionchange', function () {
  26191. var state = editor.queryCommandState(cmd);
  26192. if (state == -1) {
  26193. ui.setDisabled(true);
  26194. } else {
  26195. ui.setDisabled(false);
  26196. var value = editor.queryCommandValue(cmd);
  26197. ui.setValue(value);
  26198. ui.setChecked(state)
  26199. }
  26200. });
  26201. return ui;
  26202. };
  26203. })(cl)
  26204. }
  26205. editorui.fullscreen = function (editor, title) {
  26206. title = editor.options.labelMap['fullscreen'] || editor.getLang("labelMap.fullscreen") || '';
  26207. var ui = new editorui.Button({
  26208. className: 'edui-for-fullscreen',
  26209. title: title,
  26210. theme: editor.options.theme,
  26211. onclick: function () {
  26212. if (editor.ui) {
  26213. editor.ui.setFullScreen(!editor.ui.isFullScreen());
  26214. }
  26215. this.setChecked(editor.ui.isFullScreen());
  26216. }
  26217. });
  26218. editorui.buttons['fullscreen'] = ui;
  26219. editor.addListener('selectionchange', function () {
  26220. var state = editor.queryCommandState('fullscreen');
  26221. ui.setDisabled(state == -1);
  26222. ui.setChecked(editor.ui.isFullScreen());
  26223. });
  26224. return ui;
  26225. };
  26226. // 表情
  26227. editorui["emotion"] = function (editor, iframeUrl) {
  26228. var cmd = "emotion";
  26229. var ui = new editorui.MultiMenuPop({
  26230. title: editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd + "") || '',
  26231. editor: editor,
  26232. className: 'edui-for-' + cmd,
  26233. iframeUrl: editor.ui.mapUrl(iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd])
  26234. });
  26235. editorui.buttons[cmd] = ui;
  26236. editor.addListener('selectionchange', function () {
  26237. ui.setDisabled(editor.queryCommandState(cmd) == -1)
  26238. });
  26239. return ui;
  26240. };
  26241. editorui.autotypeset = function (editor) {
  26242. var ui = new editorui.AutoTypeSetButton({
  26243. editor: editor,
  26244. title: editor.options.labelMap['autotypeset'] || editor.getLang("labelMap.autotypeset") || '',
  26245. className: 'edui-for-autotypeset',
  26246. onbuttonclick: function () {
  26247. editor.execCommand('autotypeset')
  26248. }
  26249. });
  26250. editorui.buttons['autotypeset'] = ui;
  26251. editor.addListener('selectionchange', function () {
  26252. ui.setDisabled(editor.queryCommandState('autotypeset') == -1);
  26253. });
  26254. return ui;
  26255. };
  26256. /* 简单上传插件 */
  26257. editorui["simpleupload"] = function (editor) {
  26258. var name = 'simpleupload',
  26259. ui = new editorui.Button({
  26260. className: 'edui-for-' + name,
  26261. title: editor.options.labelMap[name] || editor.getLang("labelMap." + name) || '',
  26262. onclick: function () { },
  26263. theme: editor.options.theme,
  26264. showText: false
  26265. });
  26266. editorui.buttons[name] = ui;
  26267. editor.addListener('ready', function () {
  26268. var b = ui.getDom('body'),
  26269. iconSpan = b.children[0];
  26270. editor.fireEvent('simpleuploadbtnready', iconSpan);
  26271. });
  26272. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  26273. var state = editor.queryCommandState(name);
  26274. if (state == -1) {
  26275. ui.setDisabled(true);
  26276. ui.setChecked(false);
  26277. } else {
  26278. if (!uiReady) {
  26279. ui.setDisabled(false);
  26280. ui.setChecked(state);
  26281. }
  26282. }
  26283. });
  26284. return ui;
  26285. };
  26286. })();
  26287. // adapter/editor.js
  26288. ///import core
  26289. ///commands 全屏
  26290. ///commandsName FullScreen
  26291. ///commandsTitle 全屏
  26292. (function () {
  26293. var utils = baidu.editor.utils,
  26294. uiUtils = baidu.editor.ui.uiUtils,
  26295. UIBase = baidu.editor.ui.UIBase,
  26296. domUtils = baidu.editor.dom.domUtils;
  26297. var nodeStack = [];
  26298. function EditorUI(options) {
  26299. this.initOptions(options);
  26300. this.initEditorUI();
  26301. }
  26302. EditorUI.prototype = {
  26303. uiName: 'editor',
  26304. initEditorUI: function () {
  26305. this.editor.ui = this;
  26306. this._dialogs = {};
  26307. this.initUIBase();
  26308. this._initToolbars();
  26309. var editor = this.editor,
  26310. me = this;
  26311. editor.addListener('ready', function () {
  26312. //提供getDialog方法
  26313. editor.getDialog = function (name) {
  26314. return editor.ui._dialogs[name + "Dialog"];
  26315. };
  26316. domUtils.on(editor.window, 'scroll', function (evt) {
  26317. baidu.editor.ui.Popup.postHide(evt);
  26318. });
  26319. //提供编辑器实时宽高(全屏时宽高不变化)
  26320. editor.ui._actualFrameWidth = editor.options.initialFrameWidth;
  26321. UE.browser.ie && UE.browser.version === 6 && editor.container.ownerDocument.execCommand("BackgroundImageCache", false, true);
  26322. //display bottom-bar label based on config
  26323. if (editor.options.elementPathEnabled) {
  26324. editor.ui.getDom('elementpath').innerHTML = '<div class="edui-editor-breadcrumb">' + editor.getLang("elementPathTip") + ':</div>';
  26325. }
  26326. if (editor.options.wordCount) {
  26327. function countFn() {
  26328. setCount(editor, me);
  26329. domUtils.un(editor.document, "click", arguments.callee);
  26330. }
  26331. domUtils.on(editor.document, "click", countFn);
  26332. editor.ui.getDom('wordcount').innerHTML = editor.getLang("wordCountTip");
  26333. }
  26334. editor.ui._scale();
  26335. if (editor.options.scaleEnabled) {
  26336. if (editor.autoHeightEnabled) {
  26337. editor.disableAutoHeight();
  26338. }
  26339. me.enableScale();
  26340. } else {
  26341. me.disableScale();
  26342. }
  26343. if (!editor.options.elementPathEnabled && !editor.options.wordCount && !editor.options.scaleEnabled) {
  26344. editor.ui.getDom('elementpath').style.display = "none";
  26345. editor.ui.getDom('wordcount').style.display = "none";
  26346. editor.ui.getDom('scale').style.display = "none";
  26347. }
  26348. if (!editor.selection.isFocus()) return;
  26349. editor.fireEvent('selectionchange', false, true);
  26350. });
  26351. editor.addListener('mousedown', function (t, evt) {
  26352. var el = evt.target || evt.srcElement;
  26353. baidu.editor.ui.Popup.postHide(evt, el);
  26354. baidu.editor.ui.ShortCutMenu.postHide(evt);
  26355. });
  26356. editor.addListener("delcells", function () {
  26357. if (UE.ui['edittip']) {
  26358. new UE.ui['edittip'](editor);
  26359. }
  26360. editor.getDialog('edittip').open();
  26361. });
  26362. var pastePop, isPaste = false, timer;
  26363. editor.addListener("afterpaste", function () {
  26364. if (editor.queryCommandState('pasteplain'))
  26365. return;
  26366. if (baidu.editor.ui.PastePicker) {
  26367. pastePop = new baidu.editor.ui.Popup({
  26368. content: new baidu.editor.ui.PastePicker({ editor: editor }),
  26369. editor: editor,
  26370. className: 'edui-wordpastepop'
  26371. });
  26372. pastePop.render();
  26373. }
  26374. isPaste = true;
  26375. });
  26376. editor.addListener("afterinserthtml", function () {
  26377. clearTimeout(timer);
  26378. timer = setTimeout(function () {
  26379. if (pastePop && (isPaste || editor.ui._isTransfer)) {
  26380. if (pastePop.isHidden()) {
  26381. var span = domUtils.createElement(editor.document, 'span', {
  26382. 'style': "line-height:0px;",
  26383. 'innerHTML': '\ufeff'
  26384. }),
  26385. range = editor.selection.getRange();
  26386. range.insertNode(span);
  26387. var tmp = getDomNode(span, 'firstChild', 'previousSibling');
  26388. tmp && pastePop.showAnchor(tmp.nodeType == 3 ? tmp.parentNode : tmp);
  26389. domUtils.remove(span);
  26390. } else {
  26391. pastePop.show();
  26392. }
  26393. delete editor.ui._isTransfer;
  26394. isPaste = false;
  26395. }
  26396. }, 200)
  26397. });
  26398. editor.addListener('contextmenu', function (t, evt) {
  26399. baidu.editor.ui.Popup.postHide(evt);
  26400. });
  26401. editor.addListener('keydown', function (t, evt) {
  26402. if (pastePop) pastePop.dispose(evt);
  26403. var keyCode = evt.keyCode || evt.which;
  26404. if (evt.altKey && keyCode == 90) {
  26405. UE.ui.buttons['fullscreen'].onclick();
  26406. }
  26407. });
  26408. editor.addListener('wordcount', function (type) {
  26409. setCount(this, me);
  26410. });
  26411. function setCount(editor, ui) {
  26412. editor.setOpt({
  26413. wordCount: true,
  26414. maximumWords: 10000,
  26415. wordCountMsg: editor.options.wordCountMsg || editor.getLang("wordCountMsg"),
  26416. wordOverFlowMsg: editor.options.wordOverFlowMsg || editor.getLang("wordOverFlowMsg")
  26417. });
  26418. var opt = editor.options,
  26419. max = opt.maximumWords,
  26420. msg = opt.wordCountMsg,
  26421. errMsg = opt.wordOverFlowMsg,
  26422. countDom = ui.getDom('wordcount');
  26423. if (!opt.wordCount) {
  26424. return;
  26425. }
  26426. var count = editor.getContentLength(true);
  26427. if (count > max) {
  26428. countDom.innerHTML = errMsg;
  26429. editor.fireEvent("wordcountoverflow");
  26430. } else {
  26431. countDom.innerHTML = msg.replace("{#leave}", max - count).replace("{#count}", count);
  26432. }
  26433. }
  26434. editor.addListener('selectionchange', function () {
  26435. if (editor.options.elementPathEnabled) {
  26436. me[(editor.queryCommandState('elementpath') == -1 ? 'dis' : 'en') + 'ableElementPath']()
  26437. }
  26438. if (editor.options.scaleEnabled) {
  26439. me[(editor.queryCommandState('scale') == -1 ? 'dis' : 'en') + 'ableScale']();
  26440. }
  26441. });
  26442. var popup = new baidu.editor.ui.Popup({
  26443. editor: editor,
  26444. content: '',
  26445. className: 'edui-bubble',
  26446. _onEditButtonClick: function () {
  26447. this.hide();
  26448. editor.ui._dialogs.linkDialog.open();
  26449. },
  26450. _onImgEditButtonClick: function (name) {
  26451. this.hide();
  26452. editor.ui._dialogs[name] && editor.ui._dialogs[name].open();
  26453. },
  26454. _onImgSetFloat: function (value) {
  26455. this.hide();
  26456. editor.execCommand("imagefloat", value);
  26457. },
  26458. _setIframeAlign: function (value) {
  26459. var frame = popup.anchorEl;
  26460. var newFrame = frame.cloneNode(true);
  26461. switch (value) {
  26462. case -2:
  26463. newFrame.setAttribute("align", "");
  26464. break;
  26465. case -1:
  26466. newFrame.setAttribute("align", "left");
  26467. break;
  26468. case 1:
  26469. newFrame.setAttribute("align", "right");
  26470. break;
  26471. }
  26472. frame.parentNode.insertBefore(newFrame, frame);
  26473. domUtils.remove(frame);
  26474. popup.anchorEl = newFrame;
  26475. popup.showAnchor(popup.anchorEl);
  26476. },
  26477. _updateIframe: function () {
  26478. var frame = editor._iframe = popup.anchorEl;
  26479. if (domUtils.hasClass(frame, 'ueditor_baidumap')) {
  26480. editor.selection.getRange().selectNode(frame).select();
  26481. editor.ui._dialogs.mapDialog.open();
  26482. popup.hide();
  26483. } else {
  26484. editor.ui._dialogs.insertframeDialog.open();
  26485. popup.hide();
  26486. }
  26487. },
  26488. _onRemoveButtonClick: function (cmdName) {
  26489. editor.execCommand(cmdName);
  26490. this.hide();
  26491. },
  26492. queryAutoHide: function (el) {
  26493. if (el && el.ownerDocument == editor.document) {
  26494. if (el.tagName.toLowerCase() == 'img' || domUtils.findParentByTagName(el, 'a', true)) {
  26495. return el !== popup.anchorEl;
  26496. }
  26497. }
  26498. return baidu.editor.ui.Popup.prototype.queryAutoHide.call(this, el);
  26499. }
  26500. });
  26501. popup.render();
  26502. if (editor.options.imagePopup) {
  26503. editor.addListener('mouseover', function (t, evt) {
  26504. evt = evt || window.event;
  26505. var el = evt.target || evt.srcElement;
  26506. if (editor.ui._dialogs.insertframeDialog && /iframe/ig.test(el.tagName)) {
  26507. var html = popup.formatHtml(
  26508. '<nobr>' + editor.getLang("property") + ': <span onclick=$$._setIframeAlign(-2) class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;<span onclick=$$._setIframeAlign(-1) class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;<span onclick=$$._setIframeAlign(1) class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' +
  26509. ' <span onclick="$$._updateIframe( this);" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>');
  26510. if (html) {
  26511. popup.getDom('content').innerHTML = html;
  26512. popup.anchorEl = el;
  26513. popup.showAnchor(popup.anchorEl);
  26514. } else {
  26515. popup.hide();
  26516. }
  26517. }
  26518. });
  26519. editor.addListener('selectionchange', function (t, causeByUi) {
  26520. if (!causeByUi) return;
  26521. var html = '', str = "",
  26522. img = editor.selection.getRange().getClosedNode(),
  26523. dialogs = editor.ui._dialogs;
  26524. if (img && img.tagName == 'IMG') {
  26525. var dialogName = 'insertimageDialog';
  26526. if (img.className.indexOf("edui-faked-video") != -1 || img.className.indexOf("edui-upload-video") != -1) {
  26527. dialogName = "insertvideoDialog"
  26528. }
  26529. if (img.className.indexOf("edui-faked-webapp") != -1) {
  26530. dialogName = "webappDialog"
  26531. }
  26532. if (img.src.indexOf("http://api.map.baidu.com") != -1) {
  26533. dialogName = "mapDialog"
  26534. }
  26535. if (img.className.indexOf("edui-faked-music") != -1) {
  26536. dialogName = "musicDialog"
  26537. }
  26538. if (img.src.indexOf("http://maps.google.com/maps/api/staticmap") != -1) {
  26539. dialogName = "gmapDialog"
  26540. }
  26541. if (img.getAttribute("anchorname")) {
  26542. dialogName = "anchorDialog";
  26543. html = popup.formatHtml(
  26544. '<nobr>' + editor.getLang("property") + ': <span onclick=$$._onImgEditButtonClick("anchorDialog") class="edui-clickable">' + editor.getLang("modify") + '</span>&nbsp;&nbsp;' +
  26545. '<span onclick=$$._onRemoveButtonClick(\'anchor\') class="edui-clickable">' + editor.getLang("delete") + '</span></nobr>');
  26546. }
  26547. if (img.getAttribute("word_img")) {
  26548. //todo 放到dialog去做查询
  26549. editor.word_img = [img.getAttribute("word_img")];
  26550. dialogName = "wordimageDialog"
  26551. }
  26552. if (domUtils.hasClass(img, 'loadingclass') || domUtils.hasClass(img, 'loaderrorclass')) {
  26553. dialogName = "";
  26554. }
  26555. if (!dialogs[dialogName]) {
  26556. return;
  26557. }
  26558. str = '<nobr>' + editor.getLang("property") + ': ' +
  26559. '<span onclick=$$._onImgSetFloat("none") class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;' +
  26560. '<span onclick=$$._onImgSetFloat("left") class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;' +
  26561. '<span onclick=$$._onImgSetFloat("right") class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' +
  26562. '<span onclick=$$._onImgSetFloat("center") class="edui-clickable">' + editor.getLang("justifycenter") + '</span>&nbsp;&nbsp;' +
  26563. '<span onclick="$$._onImgEditButtonClick(\'' + dialogName + '\');" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>';
  26564. !html && (html = popup.formatHtml(str))
  26565. }
  26566. if (editor.ui._dialogs.linkDialog) {
  26567. var link = editor.queryCommandValue('link');
  26568. var url;
  26569. if (link && (url = (link.getAttribute('_href') || link.getAttribute('href', 2)))) {
  26570. var txt = url;
  26571. if (url.length > 30) {
  26572. txt = url.substring(0, 20) + "...";
  26573. }
  26574. if (html) {
  26575. html += '<div style="height:5px;"></div>'
  26576. }
  26577. html += popup.formatHtml(
  26578. '<nobr>' + editor.getLang("anthorMsg") + ': <a target="_blank" href="' + url + '" title="' + url + '" >' + txt + '</a>' +
  26579. ' <span class="edui-clickable" onclick="$$._onEditButtonClick();">' + editor.getLang("modify") + '</span>' +
  26580. ' <span class="edui-clickable" onclick="$$._onRemoveButtonClick(\'unlink\');"> ' + editor.getLang("clear") + '</span></nobr>');
  26581. popup.showAnchor(link);
  26582. }
  26583. }
  26584. if (html) {
  26585. popup.getDom('content').innerHTML = html;
  26586. popup.anchorEl = img || link;
  26587. popup.showAnchor(popup.anchorEl);
  26588. } else {
  26589. popup.hide();
  26590. }
  26591. });
  26592. }
  26593. },
  26594. _initToolbars: function () {
  26595. var editor = this.editor;
  26596. var toolbars = this.toolbars || [];
  26597. var toolbarUis = [];
  26598. for (var i = 0; i < toolbars.length; i++) {
  26599. var toolbar = toolbars[i];
  26600. var toolbarUi = new baidu.editor.ui.Toolbar({ theme: editor.options.theme });
  26601. for (var j = 0; j < toolbar.length; j++) {
  26602. var toolbarItem = toolbar[j];
  26603. var toolbarItemUi = null;
  26604. if (typeof toolbarItem == 'string') {
  26605. toolbarItem = toolbarItem.toLowerCase();
  26606. if (toolbarItem == '|') {
  26607. toolbarItem = 'Separator';
  26608. }
  26609. if (toolbarItem == '||') {
  26610. toolbarItem = 'Breakline';
  26611. }
  26612. if (baidu.editor.ui[toolbarItem]) {
  26613. toolbarItemUi = new baidu.editor.ui[toolbarItem](editor);
  26614. }
  26615. //fullscreen这里单独处理一下,放到首行去
  26616. if (toolbarItem == 'fullscreen') {
  26617. if (toolbarUis && toolbarUis[0]) {
  26618. toolbarUis[0].items.splice(0, 0, toolbarItemUi);
  26619. } else {
  26620. toolbarItemUi && toolbarUi.items.splice(0, 0, toolbarItemUi);
  26621. }
  26622. continue;
  26623. }
  26624. } else {
  26625. toolbarItemUi = toolbarItem;
  26626. }
  26627. if (toolbarItemUi && toolbarItemUi.id) {
  26628. toolbarUi.add(toolbarItemUi);
  26629. }
  26630. }
  26631. toolbarUis[i] = toolbarUi;
  26632. }
  26633. //接受外部定制的UI
  26634. utils.each(UE._customizeUI, function (obj, key) {
  26635. var itemUI, index;
  26636. if (obj.id && obj.id != editor.key) {
  26637. return false;
  26638. }
  26639. itemUI = obj.execFn.call(editor, editor, key);
  26640. if (itemUI) {
  26641. index = obj.index;
  26642. if (index === undefined) {
  26643. index = toolbarUi.items.length;
  26644. }
  26645. toolbarUi.add(itemUI, index)
  26646. }
  26647. });
  26648. this.toolbars = toolbarUis;
  26649. },
  26650. getHtmlTpl: function () {
  26651. return '<div id="##" class="%%">' +
  26652. '<div id="##_toolbarbox" class="%%-toolbarbox">' +
  26653. (this.toolbars.length ?
  26654. '<div id="##_toolbarboxouter" class="%%-toolbarboxouter"><div class="%%-toolbarboxinner">' +
  26655. this.renderToolbarBoxHtml() +
  26656. '</div></div>' : '') +
  26657. '<div id="##_toolbarmsg" class="%%-toolbarmsg" style="display:none;">' +
  26658. '<div id = "##_upload_dialog" class="%%-toolbarmsg-upload" onclick="$$.showWordImageDialog();">' + this.editor.getLang("clickToUpload") + '</div>' +
  26659. '<div class="%%-toolbarmsg-close" onclick="$$.hideToolbarMsg();">x</div>' +
  26660. '<div id="##_toolbarmsg_label" class="%%-toolbarmsg-label"></div>' +
  26661. '<div style="height:0;overflow:hidden;clear:both;"></div>' +
  26662. '</div>' +
  26663. '<div id="##_message_holder" class="%%-messageholder"></div>' +
  26664. '</div>' +
  26665. '<div id="##_iframeholder" class="%%-iframeholder">' +
  26666. '</div>' +
  26667. //modify wdcount by matao
  26668. '<div id="##_bottombar" class="%%-bottomContainer"><table><tr>' +
  26669. '<td id="##_elementpath" class="%%-bottombar"></td>' +
  26670. '<td id="##_wordcount" class="%%-wordcount"></td>' +
  26671. '<td id="##_scale" class="%%-scale"><div class="%%-icon"></div></td>' +
  26672. '</tr></table></div>' +
  26673. '<div id="##_scalelayer"></div>' +
  26674. '</div>';
  26675. },
  26676. showWordImageDialog: function () {
  26677. this._dialogs['wordimageDialog'].open();
  26678. },
  26679. renderToolbarBoxHtml: function () {
  26680. var buff = [];
  26681. for (var i = 0; i < this.toolbars.length; i++) {
  26682. buff.push(this.toolbars[i].renderHtml());
  26683. }
  26684. return buff.join('');
  26685. },
  26686. setFullScreen: function (fullscreen) {
  26687. var editor = this.editor,
  26688. container = editor.container.parentNode.parentNode;
  26689. if (this._fullscreen != fullscreen) {
  26690. this._fullscreen = fullscreen;
  26691. this.editor.fireEvent('beforefullscreenchange', fullscreen);
  26692. if (baidu.editor.browser.gecko) {
  26693. var bk = editor.selection.getRange().createBookmark();
  26694. }
  26695. if (fullscreen) {
  26696. while (container.tagName != "BODY") {
  26697. var position = baidu.editor.dom.domUtils.getComputedStyle(container, "position");
  26698. nodeStack.push(position);
  26699. container.style.position = "static";
  26700. container = container.parentNode;
  26701. }
  26702. this._bakHtmlOverflow = document.documentElement.style.overflow;
  26703. this._bakBodyOverflow = document.body.style.overflow;
  26704. this._bakAutoHeight = this.editor.autoHeightEnabled;
  26705. this._bakScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
  26706. this._bakEditorContaninerWidth = editor.iframe.parentNode.offsetWidth;
  26707. if (this._bakAutoHeight) {
  26708. //当全屏时不能执行自动长高
  26709. editor.autoHeightEnabled = false;
  26710. this.editor.disableAutoHeight();
  26711. }
  26712. document.documentElement.style.overflow = 'hidden';
  26713. //修复,滚动条不收起的问题
  26714. window.scrollTo(0, window.scrollY);
  26715. this._bakCssText = this.getDom().style.cssText;
  26716. this._bakCssText1 = this.getDom('iframeholder').style.cssText;
  26717. editor.iframe.parentNode.style.width = '';
  26718. this._updateFullScreen();
  26719. } else {
  26720. while (container.tagName != "BODY") {
  26721. container.style.position = nodeStack.shift();
  26722. container = container.parentNode;
  26723. }
  26724. this.getDom().style.cssText = this._bakCssText;
  26725. this.getDom('iframeholder').style.cssText = this._bakCssText1;
  26726. if (this._bakAutoHeight) {
  26727. editor.autoHeightEnabled = true;
  26728. this.editor.enableAutoHeight();
  26729. }
  26730. document.documentElement.style.overflow = this._bakHtmlOverflow;
  26731. document.body.style.overflow = this._bakBodyOverflow;
  26732. editor.iframe.parentNode.style.width = this._bakEditorContaninerWidth + 'px';
  26733. window.scrollTo(0, this._bakScrollTop);
  26734. }
  26735. if (browser.gecko && editor.body.contentEditable === 'true') {
  26736. var input = document.createElement('input');
  26737. document.body.appendChild(input);
  26738. editor.body.contentEditable = false;
  26739. setTimeout(function () {
  26740. input.focus();
  26741. setTimeout(function () {
  26742. editor.body.contentEditable = true;
  26743. editor.fireEvent('fullscreenchanged', fullscreen);
  26744. editor.selection.getRange().moveToBookmark(bk).select(true);
  26745. baidu.editor.dom.domUtils.remove(input);
  26746. fullscreen && window.scroll(0, 0);
  26747. }, 0)
  26748. }, 0)
  26749. }
  26750. if (editor.body.contentEditable === 'true') {
  26751. this.editor.fireEvent('fullscreenchanged', fullscreen);
  26752. this.triggerLayout();
  26753. }
  26754. }
  26755. },
  26756. _updateFullScreen: function () {
  26757. if (this._fullscreen) {
  26758. var vpRect = uiUtils.getViewportRect();
  26759. this.getDom().style.cssText = 'border:0;position:absolute;left:0;top:' + (this.editor.options.topOffset || 0) + 'px;width:' + vpRect.width + 'px;height:' + vpRect.height + 'px;z-index:' + (this.getDom().style.zIndex * 1 + 100);
  26760. uiUtils.setViewportOffset(this.getDom(), { left: 0, top: this.editor.options.topOffset || 0 });
  26761. this.editor.setHeight(vpRect.height - this.getDom('toolbarbox').offsetHeight - this.getDom('bottombar').offsetHeight - (this.editor.options.topOffset || 0), true);
  26762. //不手动调一下,会导致全屏失效
  26763. if (browser.gecko) {
  26764. try {
  26765. window.onresize();
  26766. } catch (e) {
  26767. }
  26768. }
  26769. }
  26770. },
  26771. _updateElementPath: function () {
  26772. var bottom = this.getDom('elementpath'), list;
  26773. if (this.elementPathEnabled && (list = this.editor.queryCommandValue('elementpath'))) {
  26774. var buff = [];
  26775. for (var i = 0, ci; ci = list[i]; i++) {
  26776. buff[i] = this.formatHtml('<span unselectable="on" onclick="$$.editor.execCommand(&quot;elementpath&quot;, &quot;' + i + '&quot;);">' + ci + '</span>');
  26777. }
  26778. bottom.innerHTML = '<div class="edui-editor-breadcrumb" onmousedown="return false;">' + this.editor.getLang("elementPathTip") + ': ' + buff.join(' &gt; ') + '</div>';
  26779. } else {
  26780. bottom.style.display = 'none'
  26781. }
  26782. },
  26783. disableElementPath: function () {
  26784. var bottom = this.getDom('elementpath');
  26785. bottom.innerHTML = '';
  26786. bottom.style.display = 'none';
  26787. this.elementPathEnabled = false;
  26788. },
  26789. enableElementPath: function () {
  26790. var bottom = this.getDom('elementpath');
  26791. bottom.style.display = '';
  26792. this.elementPathEnabled = true;
  26793. this._updateElementPath();
  26794. },
  26795. _scale: function () {
  26796. var doc = document,
  26797. editor = this.editor,
  26798. editorHolder = editor.container,
  26799. editorDocument = editor.document,
  26800. toolbarBox = this.getDom("toolbarbox"),
  26801. bottombar = this.getDom("bottombar"),
  26802. scale = this.getDom("scale"),
  26803. scalelayer = this.getDom("scalelayer");
  26804. var isMouseMove = false,
  26805. position = null,
  26806. minEditorHeight = 0,
  26807. minEditorWidth = editor.options.minFrameWidth,
  26808. pageX = 0,
  26809. pageY = 0,
  26810. scaleWidth = 0,
  26811. scaleHeight = 0;
  26812. function down() {
  26813. position = domUtils.getXY(editorHolder);
  26814. if (!minEditorHeight) {
  26815. minEditorHeight = editor.options.minFrameHeight + toolbarBox.offsetHeight + bottombar.offsetHeight;
  26816. }
  26817. scalelayer.style.cssText = "position:absolute;left:0;display:;top:0;background-color:#41ABFF;opacity:0.4;filter: Alpha(opacity=40);width:" + editorHolder.offsetWidth + "px;height:"
  26818. + editorHolder.offsetHeight + "px;z-index:" + (editor.options.zIndex + 1);
  26819. domUtils.on(doc, "mousemove", move);
  26820. domUtils.on(editorDocument, "mouseup", up);
  26821. domUtils.on(doc, "mouseup", up);
  26822. }
  26823. var me = this;
  26824. //by xuheng 全屏时关掉缩放
  26825. this.editor.addListener('fullscreenchanged', function (e, fullScreen) {
  26826. if (fullScreen) {
  26827. me.disableScale();
  26828. } else {
  26829. if (me.editor.options.scaleEnabled) {
  26830. me.enableScale();
  26831. var tmpNode = me.editor.document.createElement('span');
  26832. me.editor.body.appendChild(tmpNode);
  26833. me.editor.body.style.height = Math.max(domUtils.getXY(tmpNode).y, me.editor.iframe.offsetHeight - 20) + 'px';
  26834. domUtils.remove(tmpNode)
  26835. }
  26836. }
  26837. });
  26838. function move(event) {
  26839. clearSelection();
  26840. var e = event || window.event;
  26841. pageX = e.pageX || (doc.documentElement.scrollLeft + e.clientX);
  26842. pageY = e.pageY || (doc.documentElement.scrollTop + e.clientY);
  26843. scaleWidth = pageX - position.x;
  26844. scaleHeight = pageY - position.y;
  26845. if (scaleWidth >= minEditorWidth) {
  26846. isMouseMove = true;
  26847. scalelayer.style.width = scaleWidth + 'px';
  26848. }
  26849. if (scaleHeight >= minEditorHeight) {
  26850. isMouseMove = true;
  26851. scalelayer.style.height = scaleHeight + "px";
  26852. }
  26853. }
  26854. function up() {
  26855. if (isMouseMove) {
  26856. isMouseMove = false;
  26857. editor.ui._actualFrameWidth = scalelayer.offsetWidth - 2;
  26858. editorHolder.style.width = editor.ui._actualFrameWidth + 'px';
  26859. editor.setHeight(scalelayer.offsetHeight - bottombar.offsetHeight - toolbarBox.offsetHeight - 2, true);
  26860. }
  26861. if (scalelayer) {
  26862. scalelayer.style.display = "none";
  26863. }
  26864. clearSelection();
  26865. domUtils.un(doc, "mousemove", move);
  26866. domUtils.un(editorDocument, "mouseup", up);
  26867. domUtils.un(doc, "mouseup", up);
  26868. }
  26869. function clearSelection() {
  26870. if (browser.ie)
  26871. doc.selection.clear();
  26872. else
  26873. window.getSelection().removeAllRanges();
  26874. }
  26875. this.enableScale = function () {
  26876. //trace:2868
  26877. if (editor.queryCommandState("source") == 1) return;
  26878. scale.style.display = "";
  26879. this.scaleEnabled = true;
  26880. domUtils.on(scale, "mousedown", down);
  26881. };
  26882. this.disableScale = function () {
  26883. scale.style.display = "none";
  26884. this.scaleEnabled = false;
  26885. domUtils.un(scale, "mousedown", down);
  26886. };
  26887. },
  26888. isFullScreen: function () {
  26889. return this._fullscreen;
  26890. },
  26891. postRender: function () {
  26892. UIBase.prototype.postRender.call(this);
  26893. for (var i = 0; i < this.toolbars.length; i++) {
  26894. this.toolbars[i].postRender();
  26895. }
  26896. var me = this;
  26897. var timerId,
  26898. domUtils = baidu.editor.dom.domUtils,
  26899. updateFullScreenTime = function () {
  26900. clearTimeout(timerId);
  26901. timerId = setTimeout(function () {
  26902. me._updateFullScreen();
  26903. });
  26904. };
  26905. domUtils.on(window, 'resize', updateFullScreenTime);
  26906. me.addListener('destroy', function () {
  26907. domUtils.un(window, 'resize', updateFullScreenTime);
  26908. clearTimeout(timerId);
  26909. })
  26910. },
  26911. showToolbarMsg: function (msg, flag) {
  26912. this.getDom('toolbarmsg_label').innerHTML = msg;
  26913. this.getDom('toolbarmsg').style.display = '';
  26914. //
  26915. if (!flag) {
  26916. var w = this.getDom('upload_dialog');
  26917. w.style.display = 'none';
  26918. }
  26919. },
  26920. hideToolbarMsg: function () {
  26921. this.getDom('toolbarmsg').style.display = 'none';
  26922. },
  26923. mapUrl: function (url) {
  26924. return url ? url.replace('~/', this.editor.options.UEDITOR_HOME_URL || '') : ''
  26925. },
  26926. triggerLayout: function () {
  26927. var dom = this.getDom();
  26928. if (dom.style.zoom == '1') {
  26929. dom.style.zoom = '100%';
  26930. } else {
  26931. dom.style.zoom = '1';
  26932. }
  26933. }
  26934. };
  26935. utils.inherits(EditorUI, baidu.editor.ui.UIBase);
  26936. var instances = {};
  26937. UE.ui.Editor = function (options) {
  26938. var editor = new UE.Editor(options);
  26939. editor.options.editor = editor;
  26940. utils.loadFile(document, {
  26941. href: editor.options.themePath + editor.options.theme + "/css/ueditor.css",
  26942. tag: "link",
  26943. type: "text/css",
  26944. rel: "stylesheet"
  26945. });
  26946. var oldRender = editor.render;
  26947. editor.render = function (holder) {
  26948. if (holder.constructor === String) {
  26949. editor.key = holder;
  26950. instances[holder] = editor;
  26951. }
  26952. utils.domReady(function () {
  26953. editor.langIsReady ? renderUI() : editor.addListener("langReady", renderUI);
  26954. function renderUI() {
  26955. editor.setOpt({
  26956. labelMap: editor.options.labelMap || editor.getLang('labelMap')
  26957. });
  26958. new EditorUI(editor.options);
  26959. if (holder) {
  26960. if (holder.constructor === String) {
  26961. holder = document.getElementById(holder);
  26962. }
  26963. holder && holder.getAttribute('name') && (editor.options.textarea = holder.getAttribute('name'));
  26964. if (holder && /script|textarea/ig.test(holder.tagName)) {
  26965. var newDiv = document.createElement('div');
  26966. holder.parentNode.insertBefore(newDiv, holder);
  26967. var cont = holder.value || holder.innerHTML;
  26968. editor.options.initialContent = /^[\t\r\n ]*$/.test(cont) ? editor.options.initialContent :
  26969. cont.replace(/>[\n\r\t]+([ ]{4})+/g, '>')
  26970. .replace(/[\n\r\t]+([ ]{4})+</g, '<')
  26971. .replace(/>[\n\r\t]+</g, '><');
  26972. holder.className && (newDiv.className = holder.className);
  26973. holder.style.cssText && (newDiv.style.cssText = holder.style.cssText);
  26974. if (/textarea/i.test(holder.tagName)) {
  26975. editor.textarea = holder;
  26976. editor.textarea.style.display = 'none';
  26977. } else {
  26978. holder.parentNode.removeChild(holder);
  26979. }
  26980. if (holder.id) {
  26981. newDiv.id = holder.id;
  26982. domUtils.removeAttributes(holder, 'id');
  26983. }
  26984. holder = newDiv;
  26985. holder.innerHTML = '';
  26986. }
  26987. }
  26988. domUtils.addClass(holder, "edui-" + editor.options.theme);
  26989. editor.ui.render(holder);
  26990. var opt = editor.options;
  26991. //给实例添加一个编辑器的容器引用
  26992. editor.container = editor.ui.getDom();
  26993. var parents = domUtils.findParents(holder, true);
  26994. var displays = [];
  26995. for (var i = 0, ci; ci = parents[i]; i++) {
  26996. displays[i] = ci.style.display;
  26997. ci.style.display = 'block'
  26998. }
  26999. if (opt.initialFrameWidth) {
  27000. opt.minFrameWidth = opt.initialFrameWidth;
  27001. } else {
  27002. opt.minFrameWidth = opt.initialFrameWidth = holder.offsetWidth;
  27003. var styleWidth = holder.style.width;
  27004. if (/%$/.test(styleWidth)) {
  27005. opt.initialFrameWidth = styleWidth;
  27006. }
  27007. }
  27008. if (opt.initialFrameHeight) {
  27009. opt.minFrameHeight = opt.initialFrameHeight;
  27010. } else {
  27011. opt.initialFrameHeight = opt.minFrameHeight = holder.offsetHeight;
  27012. }
  27013. for (var i = 0, ci; ci = parents[i]; i++) {
  27014. ci.style.display = displays[i]
  27015. }
  27016. //编辑器最外容器设置了高度,会导致,编辑器不占位
  27017. //todo 先去掉,没有找到原因
  27018. if (holder.style.height) {
  27019. holder.style.height = ''
  27020. }
  27021. editor.container.style.width = opt.initialFrameWidth + (/%$/.test(opt.initialFrameWidth) ? '' : 'px');
  27022. editor.container.style.zIndex = opt.zIndex;
  27023. oldRender.call(editor, editor.ui.getDom('iframeholder'));
  27024. editor.fireEvent("afteruiready");
  27025. }
  27026. })
  27027. };
  27028. return editor;
  27029. };
  27030. /**
  27031. * @file
  27032. * @name UE
  27033. * @short UE
  27034. * @desc UEditor的顶部命名空间
  27035. */
  27036. /**
  27037. * @name getEditor
  27038. * @since 1.2.4+
  27039. * @grammar UE.getEditor(id,[opt]) => Editor实例
  27040. * @desc 提供一个全局的方法得到编辑器实例
  27041. *
  27042. * * ''id'' 放置编辑器的容器id, 如果容器下的编辑器已经存在,就直接返回
  27043. * * ''opt'' 编辑器的可选参数
  27044. * @example
  27045. * UE.getEditor('containerId',{onready:function(){//创建一个编辑器实例
  27046. * this.setContent('hello')
  27047. * }});
  27048. * UE.getEditor('containerId'); //返回刚创建的实例
  27049. *
  27050. */
  27051. UE.getEditor = function (id, opt) {
  27052. var editor = instances[id];
  27053. if (!editor) {
  27054. editor = instances[id] = new UE.ui.Editor(opt);
  27055. editor.render(id);
  27056. }
  27057. return editor;
  27058. };
  27059. UE.delEditor = function (id) {
  27060. var editor;
  27061. if (editor = instances[id]) {
  27062. editor.key && editor.destroy();
  27063. delete instances[id]
  27064. }
  27065. };
  27066. UE.registerUI = function (uiName, fn, index, editorId) {
  27067. utils.each(uiName.split(/\s+/), function (name) {
  27068. UE._customizeUI[name] = {
  27069. id: editorId,
  27070. execFn: fn,
  27071. index: index
  27072. };
  27073. })
  27074. }
  27075. })();
  27076. // adapter/message.js
  27077. UE.registerUI('message', function (editor) {
  27078. var editorui = baidu.editor.ui;
  27079. var Message = editorui.Message;
  27080. var holder;
  27081. var _messageItems = [];
  27082. var me = editor;
  27083. me.addListener('ready', function () {
  27084. holder = document.getElementById(me.ui.id + '_message_holder');
  27085. updateHolderPos();
  27086. // HaoChuan9421
  27087. // setTimeout(function(){
  27088. // updateHolderPos();
  27089. // }, 500);
  27090. });
  27091. me.addListener('showmessage', function (type, opt) {
  27092. opt = utils.isString(opt) ? {
  27093. 'content': opt
  27094. } : opt;
  27095. var message = new Message({
  27096. 'timeout': opt.timeout,
  27097. 'type': opt.type,
  27098. 'content': opt.content,
  27099. 'keepshow': opt.keepshow,
  27100. 'editor': me
  27101. }),
  27102. mid = opt.id || ('msg_' + (+new Date()).toString(36));
  27103. message.render(holder);
  27104. _messageItems[mid] = message;
  27105. message.reset(opt);
  27106. updateHolderPos();
  27107. return mid;
  27108. });
  27109. me.addListener('updatemessage', function (type, id, opt) {
  27110. opt = utils.isString(opt) ? {
  27111. 'content': opt
  27112. } : opt;
  27113. var message = _messageItems[id];
  27114. message.render(holder);
  27115. message && message.reset(opt);
  27116. });
  27117. me.addListener('hidemessage', function (type, id) {
  27118. var message = _messageItems[id];
  27119. message && message.hide();
  27120. });
  27121. function updateHolderPos() {
  27122. var toolbarbox = me.ui.getDom('toolbarbox');
  27123. if (toolbarbox) {
  27124. holder.style.top = toolbarbox.offsetHeight + 3 + 'px';
  27125. }
  27126. holder.style.zIndex = Math.max(me.options.zIndex, me.iframe.style.zIndex) + 1;
  27127. }
  27128. });
  27129. // adapter/autosave.js
  27130. UE.registerUI('autosave', function (editor) {
  27131. var timer = null, uid = null;
  27132. editor.on('afterautosave', function () {
  27133. clearTimeout(timer);
  27134. timer = setTimeout(function () {
  27135. if (uid) {
  27136. editor.trigger('hidemessage', uid);
  27137. }
  27138. uid = editor.trigger('showmessage', {
  27139. content: editor.getLang('autosave.success'),
  27140. timeout: 2000
  27141. });
  27142. }, 2000)
  27143. })
  27144. });
  27145. })();