main.js 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623
  1. var _plugins = {};
  2. function _plugin(name, fn) {
  3. if (name === undefined) {
  4. return _plugins;
  5. }
  6. if (!fn) {
  7. return _plugins[name];
  8. }
  9. _plugins[name] = fn;
  10. }
  11. var _language = {};
  12. function _parseLangKey(key) {
  13. var match, ns = 'core';
  14. if ((match = /^(\w+)\.(\w+)$/.exec(key))) {
  15. ns = match[1];
  16. key = match[2];
  17. }
  18. return { ns : ns, key : key };
  19. }
  20. /**
  21. @example
  22. K.lang('about'); //get core.about
  23. K.lang('about.version'); // get about.version
  24. K.lang('about.').version; // get about.version
  25. K.lang('about', 'en'); //get English core.about
  26. K.lang({
  27. core.about : '关于',
  28. about.version : '4.0'
  29. }, 'zh-CN'); //add language
  30. */
  31. function _lang(mixed, langType) {
  32. langType = langType === undefined ? K.options.langType : langType;
  33. if (typeof mixed === 'string') {
  34. if (!_language[langType]) {
  35. return 'no language';
  36. }
  37. var pos = mixed.length - 1;
  38. if (mixed.substr(pos) === '.') {
  39. return _language[langType][mixed.substr(0, pos)];
  40. }
  41. var obj = _parseLangKey(mixed);
  42. return _language[langType][obj.ns][obj.key];
  43. }
  44. _each(mixed, function(key, val) {
  45. var obj = _parseLangKey(key);
  46. if (!_language[langType]) {
  47. _language[langType] = {};
  48. }
  49. if (!_language[langType][obj.ns]) {
  50. _language[langType][obj.ns] = {};
  51. }
  52. _language[langType][obj.ns][obj.key] = val;
  53. });
  54. }
  55. // 当前range为图片时返回KNode,否则返回undefined
  56. function _getImageFromRange(range, fn) {
  57. if (range.collapsed) {
  58. return;
  59. }
  60. range = range.cloneRange().up();
  61. var sc = range.startContainer, so = range.startOffset;
  62. if (!_WEBKIT && !range.isControl()) {
  63. return;
  64. }
  65. var img = K(sc.childNodes[so]);
  66. if (!img || img.name != 'img') {
  67. return;
  68. }
  69. if (fn(img)) {
  70. return img;
  71. }
  72. }
  73. function _bindContextmenuEvent() {
  74. var self = this, doc = self.edit.doc;
  75. K(doc).contextmenu(function(e) {
  76. if (self.menu) {
  77. self.hideMenu();
  78. }
  79. if (!self.useContextmenu) {
  80. e.preventDefault();
  81. return;
  82. }
  83. if (self._contextmenus.length === 0) {
  84. return;
  85. }
  86. var maxWidth = 0, items = [];
  87. _each(self._contextmenus, function() {
  88. if (this.title == '-') {
  89. items.push(this);
  90. return;
  91. }
  92. if (this.cond && this.cond()) {
  93. items.push(this);
  94. if (this.width && this.width > maxWidth) {
  95. maxWidth = this.width;
  96. }
  97. }
  98. });
  99. while (items.length > 0 && items[0].title == '-') {
  100. items.shift();
  101. }
  102. while (items.length > 0 && items[items.length - 1].title == '-') {
  103. items.pop();
  104. }
  105. var prevItem = null;
  106. _each(items, function(i) {
  107. if (this.title == '-' && prevItem.title == '-') {
  108. delete items[i];
  109. }
  110. prevItem = this;
  111. });
  112. if (items.length > 0) {
  113. e.preventDefault();
  114. var pos = K(self.edit.iframe).pos(),
  115. menu = _menu({
  116. x : pos.x + e.clientX,
  117. y : pos.y + e.clientY,
  118. width : maxWidth,
  119. css : { visibility: 'hidden' },
  120. shadowMode : self.shadowMode
  121. });
  122. _each(items, function() {
  123. if (this.title) {
  124. menu.addItem(this);
  125. }
  126. });
  127. // 下拉菜单超过可视区域时调整菜单位置
  128. var docEl = _docElement(menu.doc),
  129. menuHeight = menu.div.height();
  130. if (e.clientY + menuHeight >= docEl.clientHeight - 100) {
  131. menu.pos(menu.x, _removeUnit(menu.y) - menuHeight);
  132. }
  133. menu.div.css('visibility', 'visible');
  134. self.menu = menu;
  135. }
  136. });
  137. }
  138. function _bindNewlineEvent() {
  139. var self = this, doc = self.edit.doc, newlineTag = self.newlineTag;
  140. if (_IE && newlineTag !== 'br') {
  141. return;
  142. }
  143. if (_GECKO && _V < 3 && newlineTag !== 'p') {
  144. return;
  145. }
  146. if (_OPERA && _V < 9) {
  147. return;
  148. }
  149. var brSkipTagMap = _toMap('h1,h2,h3,h4,h5,h6,pre,li'),
  150. pSkipTagMap = _toMap('p,h1,h2,h3,h4,h5,h6,pre,li,blockquote');
  151. // 取得range的block标签名
  152. function getAncestorTagName(range) {
  153. var ancestor = K(range.commonAncestor());
  154. while (ancestor) {
  155. if (ancestor.type == 1 && !ancestor.isStyle()) {
  156. break;
  157. }
  158. ancestor = ancestor.parent();
  159. }
  160. return ancestor.name;
  161. }
  162. K(doc).keydown(function(e) {
  163. if (e.which != 13 || e.shiftKey || e.ctrlKey || e.altKey) {
  164. return;
  165. }
  166. self.cmd.selection();
  167. var tagName = getAncestorTagName(self.cmd.range);
  168. if (tagName == 'marquee' || tagName == 'select') {
  169. return;
  170. }
  171. // br
  172. if (newlineTag === 'br' && !brSkipTagMap[tagName]) {
  173. e.preventDefault();
  174. self.insertHtml('<br />' + (_IE && _V < 9 ? '' : '\u200B'));
  175. return;
  176. }
  177. // p
  178. if (!pSkipTagMap[tagName]) {
  179. _nativeCommand(doc, 'formatblock', '<p>');
  180. }
  181. });
  182. K(doc).keyup(function(e) {
  183. if (e.which != 13 || e.shiftKey || e.ctrlKey || e.altKey) {
  184. return;
  185. }
  186. if (newlineTag == 'br') {
  187. return;
  188. }
  189. if (_GECKO) {
  190. var root = self.cmd.commonAncestor('p');
  191. var a = self.cmd.commonAncestor('a');
  192. if (a && a.text() == '') {
  193. a.remove(true);
  194. self.cmd.range.selectNodeContents(root[0]).collapse(true);
  195. self.cmd.select();
  196. }
  197. return;
  198. }
  199. self.cmd.selection();
  200. var tagName = getAncestorTagName(self.cmd.range);
  201. if (tagName == 'marquee' || tagName == 'select') {
  202. return;
  203. }
  204. if (!pSkipTagMap[tagName]) {
  205. _nativeCommand(doc, 'formatblock', '<p>');
  206. }
  207. // [WEBKIT] 将DIV改成P
  208. var div = self.cmd.commonAncestor('div');
  209. if (div) {
  210. var p = K('<p></p>'),
  211. child = div[0].firstChild;
  212. while (child) {
  213. var next = child.nextSibling;
  214. p.append(child);
  215. child = next;
  216. }
  217. div.before(p);
  218. div.remove();
  219. self.cmd.range.selectNodeContents(p[0]);
  220. self.cmd.select();
  221. }
  222. });
  223. }
  224. function _bindTabEvent() {
  225. var self = this, doc = self.edit.doc;
  226. K(doc).keydown(function(e) {
  227. if (e.which == 9) {
  228. e.preventDefault();
  229. if (self.afterTab) {
  230. self.afterTab.call(self, e);
  231. return;
  232. }
  233. var cmd = self.cmd, range = cmd.range;
  234. range.shrink();
  235. // Bugfix #271: 回车,按下tab键,光标在下一行显示
  236. if (range.collapsed && range.startContainer.nodeType == 1) {
  237. range.insertNode(K('@&nbsp;', doc)[0]);
  238. cmd.select();
  239. }
  240. self.insertHtml('&nbsp;&nbsp;&nbsp;&nbsp;');
  241. }
  242. });
  243. }
  244. function _bindFocusEvent() {
  245. var self = this;
  246. K(self.edit.textarea[0], self.edit.win).focus(function(e) {
  247. if (self.afterFocus) {
  248. self.afterFocus.call(self, e);
  249. }
  250. }).blur(function(e) {
  251. if (self.afterBlur) {
  252. self.afterBlur.call(self, e);
  253. }
  254. });
  255. }
  256. function _removeBookmarkTag(html) {
  257. return _trim(html.replace(/<span [^>]*id="?__kindeditor_bookmark_\w+_\d+__"?[^>]*><\/span>/ig, ''));
  258. }
  259. function _removeTempTag(html) {
  260. return html.replace(/<div[^>]+class="?__kindeditor_paste__"?[^>]*>[\s\S]*?<\/div>/ig, '');
  261. }
  262. function _addBookmarkToStack(stack, bookmark) {
  263. if (stack.length === 0) {
  264. stack.push(bookmark);
  265. return;
  266. }
  267. var prev = stack[stack.length - 1];
  268. if (_removeBookmarkTag(bookmark.html) !== _removeBookmarkTag(prev.html)) {
  269. stack.push(bookmark);
  270. }
  271. }
  272. // undo: _undoToRedo.call(this, undoStack, redoStack);
  273. // redo: _undoToRedo.call(this, redoStack, undoStack);
  274. function _undoToRedo(fromStack, toStack) {
  275. var self = this, edit = self.edit,
  276. body = edit.doc.body,
  277. range, bookmark;
  278. if (fromStack.length === 0) {
  279. return self;
  280. }
  281. if (edit.designMode) {
  282. range = self.cmd.range;
  283. bookmark = range.createBookmark(true);
  284. bookmark.html = body.innerHTML;
  285. } else {
  286. bookmark = {
  287. html : body.innerHTML
  288. };
  289. }
  290. _addBookmarkToStack(toStack, bookmark);
  291. var prev = fromStack.pop();
  292. if (_removeBookmarkTag(bookmark.html) === _removeBookmarkTag(prev.html) && fromStack.length > 0) {
  293. prev = fromStack.pop();
  294. }
  295. if (edit.designMode) {
  296. edit.html(prev.html);
  297. if (prev.start) {
  298. range.moveToBookmark(prev);
  299. self.select();
  300. }
  301. } else {
  302. K(body).html(_removeBookmarkTag(prev.html));
  303. }
  304. return self;
  305. }
  306. function KEditor(options) {
  307. var self = this;
  308. // save original options
  309. self.options = {};
  310. function setOption(key, val) {
  311. if (KEditor.prototype[key] === undefined) {
  312. self[key] = val;
  313. }
  314. self.options[key] = val;
  315. }
  316. // set options from param
  317. _each(options, function(key, val) {
  318. setOption(key, options[key]);
  319. });
  320. // set options from default setting
  321. _each(K.options, function(key, val) {
  322. if (self[key] === undefined) {
  323. setOption(key, val);
  324. }
  325. });
  326. var se = K(self.srcElement || '<textarea/>');
  327. if (!self.width) {
  328. self.width = se[0].style.width || se.width();
  329. }
  330. if (!self.height) {
  331. self.height = se[0].style.height || se.height();
  332. }
  333. setOption('width', _undef(self.width, self.minWidth));
  334. setOption('height', _undef(self.height, self.minHeight));
  335. setOption('width', _addUnit(self.width));
  336. setOption('height', _addUnit(self.height));
  337. if (_MOBILE && (!_IOS || _V < 534)) {
  338. self.designMode = false;
  339. }
  340. self.srcElement = se;
  341. self.initContent = '';
  342. self.plugin = {};
  343. self.isCreated = false;
  344. // private properties
  345. self._handlers = {};
  346. self._contextmenus = [];
  347. self._undoStack = [];
  348. self._redoStack = [];
  349. self._firstAddBookmark = true;
  350. self.menu = self.contextmenu = null;
  351. self.dialogs = [];
  352. }
  353. KEditor.prototype = {
  354. lang : function(mixed) {
  355. return _lang(mixed, this.langType);
  356. },
  357. loadPlugin : function(name, fn) {
  358. var self = this;
  359. var _pluginStatus = this._pluginStatus;
  360. if (!_pluginStatus) {
  361. _pluginStatus = this._pluginStatus = {};
  362. }
  363. if (_plugins[name]) {
  364. // JS加载中,等待JS加载完成
  365. if (!_isFunction(_plugins[name])) {
  366. setTimeout(function() {
  367. self.loadPlugin(name, fn);
  368. }, 100);
  369. return self;
  370. }
  371. // JS加载完成,避免初始化多次
  372. if(!_pluginStatus[name]) {
  373. _plugins[name].call(self, KindEditor);
  374. _pluginStatus[name] = 'inited';
  375. }
  376. if (fn) {
  377. fn.call(self);
  378. }
  379. return self;
  380. }
  381. // 还没加载相关plugin,动态加载
  382. _plugins[name] = 'loading';
  383. _loadScript(self.pluginsPath + name + '/' + name + '.js?ver=' + encodeURIComponent(K.DEBUG ? _TIME : _VERSION), function() {
  384. // Fix bug: https://github.com/kindsoft/kindeditor/issues/105
  385. setTimeout(function() {
  386. if (_plugins[name]) {
  387. self.loadPlugin(name, fn);
  388. }
  389. }, 0);
  390. });
  391. return self;
  392. },
  393. handler : function(key, fn) {
  394. var self = this;
  395. if (!self._handlers[key]) {
  396. self._handlers[key] = [];
  397. }
  398. if (_isFunction(fn)) {
  399. self._handlers[key].push(fn);
  400. return self;
  401. }
  402. _each(self._handlers[key], function() {
  403. fn = this.call(self, fn);
  404. });
  405. return fn;
  406. },
  407. clickToolbar : function(name, fn) {
  408. var self = this, key = 'clickToolbar' + name;
  409. if (fn === undefined) {
  410. if (self._handlers[key]) {
  411. return self.handler(key);
  412. }
  413. self.loadPlugin(name, function() {
  414. self.handler(key);
  415. });
  416. return self;
  417. }
  418. return self.handler(key, fn);
  419. },
  420. updateState : function() {
  421. var self = this;
  422. _each(('justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,insertunorderedlist,' +
  423. 'subscript,superscript,bold,italic,underline,strikethrough').split(','), function(i, name) {
  424. self.cmd.state(name) ? self.toolbar.select(name) : self.toolbar.unselect(name);
  425. });
  426. return self;
  427. },
  428. addContextmenu : function(item) {
  429. this._contextmenus.push(item);
  430. return this;
  431. },
  432. afterCreate : function(fn) {
  433. return this.handler('afterCreate', fn);
  434. },
  435. beforeRemove : function(fn) {
  436. return this.handler('beforeRemove', fn);
  437. },
  438. beforeGetHtml : function(fn) {
  439. return this.handler('beforeGetHtml', fn);
  440. },
  441. beforeSetHtml : function(fn) {
  442. return this.handler('beforeSetHtml', fn);
  443. },
  444. afterSetHtml : function(fn) {
  445. return this.handler('afterSetHtml', fn);
  446. },
  447. create : function() {
  448. var self = this, fullscreenMode = self.fullscreenMode;
  449. if (self.isCreated) {
  450. return self;
  451. }
  452. if (self.srcElement.data('kindeditor')) {
  453. return self;
  454. }
  455. self.srcElement.data('kindeditor', 'true');
  456. if (fullscreenMode) {
  457. _docElement().style.overflow = 'hidden';
  458. } else {
  459. _docElement().style.overflow = '';
  460. }
  461. var width = fullscreenMode ? _docElement().clientWidth + 'px' : self.width,
  462. height = fullscreenMode ? _docElement().clientHeight + 'px' : self.height;
  463. // 校正IE6和IE7的高度
  464. if ((_IE && _V < 8) || _QUIRKS) {
  465. height = _addUnit(_removeUnit(height) + 2);
  466. }
  467. var container = self.container = K(self.layout);
  468. if (fullscreenMode) {
  469. K(document.body).append(container);
  470. } else {
  471. self.srcElement.before(container);
  472. }
  473. var toolbarDiv = K('.toolbar', container),
  474. editDiv = K('.edit', container),
  475. statusbar = self.statusbar = K('.statusbar', container);
  476. container.removeClass('container')
  477. .addClass('ke-container ke-container-' + self.themeType).css('width', width);
  478. if (fullscreenMode) {
  479. container.css({
  480. position : 'absolute',
  481. left : 0,
  482. top : 0,
  483. 'z-index' : 811211
  484. });
  485. if (!_GECKO) {
  486. self._scrollPos = _getScrollPos();
  487. }
  488. window.scrollTo(0, 0);
  489. // bugfix: [WEBKIT] 高度为0时在dialog里无法粘贴文本
  490. K(document.body).css({
  491. 'height' : '1px',
  492. 'overflow' : 'hidden'
  493. });
  494. K(document.body.parentNode).css('overflow', 'hidden');
  495. self._fullscreenExecuted = true;
  496. } else {
  497. if (self._fullscreenExecuted) {
  498. // 恢复文档高度
  499. K(document.body).css({
  500. 'height' : '',
  501. 'overflow' : ''
  502. });
  503. K(document.body.parentNode).css('overflow', '');
  504. }
  505. if (self._scrollPos) {
  506. window.scrollTo(self._scrollPos.x, self._scrollPos.y);
  507. }
  508. }
  509. // create toolbar
  510. var htmlList = [];
  511. K.each(self.items, function(i, name) {
  512. if (name == '|') {
  513. htmlList.push('<span class="ke-inline-block ke-separator"></span>');
  514. } else if (name == '/') {
  515. htmlList.push('<div class="ke-hr"></div>');
  516. } else {
  517. htmlList.push('<span class="ke-outline" data-name="' + name + '" title="' + self.lang(name) + '" unselectable="on">');
  518. htmlList.push('<span class="ke-toolbar-icon ke-toolbar-icon-url ke-icon-' + name + '" unselectable="on"></span></span>');
  519. }
  520. });
  521. var toolbar = self.toolbar = _toolbar({
  522. src : toolbarDiv,
  523. html : htmlList.join(''),
  524. noDisableItems : self.noDisableItems,
  525. click : function(e, name) {
  526. e.stop();
  527. if (self.menu) {
  528. var menuName = self.menu.name;
  529. self.hideMenu();
  530. if (menuName === name) {
  531. return;
  532. }
  533. }
  534. self.clickToolbar(name);
  535. }
  536. });
  537. // create edit
  538. var editHeight = _removeUnit(height) - toolbar.div.height();
  539. var edit = self.edit = _edit({
  540. height : editHeight > 0 && _removeUnit(height) > self.minHeight ? editHeight : self.minHeight,
  541. src : editDiv,
  542. srcElement : self.srcElement,
  543. designMode : self.designMode,
  544. themesPath : self.themesPath,
  545. bodyClass : self.bodyClass,
  546. cssPath : self.cssPath,
  547. cssData : self.cssData,
  548. beforeGetHtml : function(html) {
  549. html = self.beforeGetHtml(html);
  550. // Bugfix: 浏览器后退产生__kindeditor_bookmark_start_0__
  551. html = _removeBookmarkTag(_removeTempTag(html));
  552. return _formatHtml(html, self.filterMode ? self.htmlTags : null, self.urlType, self.wellFormatMode, self.indentChar);
  553. },
  554. beforeSetHtml : function(html) {
  555. html = _formatHtml(html, self.filterMode ? self.htmlTags : null, '', false);
  556. return self.beforeSetHtml(html);
  557. },
  558. afterSetHtml : function() {
  559. self.edit = edit = this;
  560. self.afterSetHtml();
  561. },
  562. afterCreate : function() {
  563. self.edit = edit = this;
  564. self.cmd = edit.cmd;
  565. // hide menu when click document
  566. self._docMousedownFn = function(e) {
  567. if (self.menu) {
  568. self.hideMenu();
  569. }
  570. };
  571. K(edit.doc, document).mousedown(self._docMousedownFn);
  572. _bindContextmenuEvent.call(self);
  573. _bindNewlineEvent.call(self);
  574. _bindTabEvent.call(self);
  575. _bindFocusEvent.call(self);
  576. // afterChange event
  577. edit.afterChange(function(e) {
  578. if (!edit.designMode) {
  579. return;
  580. }
  581. self.updateState();
  582. self.addBookmark();
  583. if (self.options.afterChange) {
  584. self.options.afterChange.call(self);
  585. }
  586. });
  587. edit.textarea.keyup(function(e) {
  588. if (!e.ctrlKey && !e.altKey && _INPUT_KEY_MAP[e.which]) {
  589. if (self.options.afterChange) {
  590. self.options.afterChange.call(self);
  591. }
  592. }
  593. });
  594. // readonly
  595. if (self.readonlyMode) {
  596. self.readonly();
  597. }
  598. self.isCreated = true;
  599. if (self.initContent === '') {
  600. self.initContent = self.html();
  601. }
  602. // Bugfix: 全屏后和还原后光标没有选中之前光标的位置
  603. if (self._undoStack.length > 0) {
  604. var prev = self._undoStack.pop();
  605. if (prev.start) {
  606. self.html(prev.html);
  607. edit.cmd.range.moveToBookmark(prev);
  608. self.select();
  609. }
  610. }
  611. self.afterCreate();
  612. if (self.options.afterCreate) {
  613. self.options.afterCreate.call(self);
  614. }
  615. }
  616. });
  617. // create statusbar
  618. statusbar.removeClass('statusbar').addClass('ke-statusbar')
  619. .append('<span class="ke-inline-block ke-statusbar-center-icon"></span>')
  620. .append('<span class="ke-inline-block ke-statusbar-right-icon"></span>');
  621. // remove resize event
  622. if (self._fullscreenResizeHandler) {
  623. K(window).unbind('resize', self._fullscreenResizeHandler);
  624. self._fullscreenResizeHandler = null;
  625. }
  626. // reset size
  627. function initResize() {
  628. // Bugfix: 页面刷新后,与第一次访问加载的编译器高度不一致
  629. if (statusbar.height() === 0) {
  630. setTimeout(initResize, 100);
  631. return;
  632. }
  633. self.resize(width, height, false);
  634. }
  635. initResize();
  636. // fullscreen mode
  637. if (fullscreenMode) {
  638. self._fullscreenResizeHandler = function(e) {
  639. if (self.isCreated) {
  640. self.resize(_docElement().clientWidth, _docElement().clientHeight, false);
  641. }
  642. };
  643. K(window).bind('resize', self._fullscreenResizeHandler);
  644. toolbar.select('fullscreen');
  645. statusbar.first().css('visibility', 'hidden');
  646. statusbar.last().css('visibility', 'hidden');
  647. } else {
  648. if (_GECKO) {
  649. K(window).bind('scroll', function(e) {
  650. self._scrollPos = _getScrollPos();
  651. });
  652. }
  653. // bind drag event
  654. if (self.resizeType > 0) {
  655. _drag({
  656. moveEl : container,
  657. clickEl : statusbar,
  658. moveFn : function(x, y, width, height, diffX, diffY) {
  659. height += diffY;
  660. self.resize(null, height);
  661. }
  662. });
  663. } else {
  664. statusbar.first().css('visibility', 'hidden');
  665. }
  666. if (self.resizeType === 2) {
  667. _drag({
  668. moveEl : container,
  669. clickEl : statusbar.last(),
  670. moveFn : function(x, y, width, height, diffX, diffY) {
  671. width += diffX;
  672. height += diffY;
  673. self.resize(width, height);
  674. }
  675. });
  676. } else {
  677. statusbar.last().css('visibility', 'hidden');
  678. }
  679. }
  680. return self;
  681. },
  682. remove : function() {
  683. var self = this;
  684. if (!self.isCreated) {
  685. return self;
  686. }
  687. self.beforeRemove();
  688. self.srcElement.data('kindeditor', '');
  689. if (self.menu) {
  690. self.hideMenu();
  691. }
  692. _each(self.dialogs, function() {
  693. self.hideDialog();
  694. });
  695. K(document).unbind('mousedown', self._docMousedownFn);
  696. self.toolbar.remove();
  697. self.edit.remove();
  698. self.statusbar.last().unbind();
  699. self.statusbar.unbind();
  700. self.container.remove();
  701. self.container = self.toolbar = self.edit = self.menu = null;
  702. self.dialogs = [];
  703. self.isCreated = false;
  704. return self;
  705. },
  706. resize : function(width, height, updateProp) {
  707. var self = this;
  708. updateProp = _undef(updateProp, true);
  709. if (width) {
  710. if (!/%/.test(width)) {
  711. width = _removeUnit(width);
  712. width = width < self.minWidth ? self.minWidth : width;
  713. }
  714. self.container.css('width', _addUnit(width));
  715. if (updateProp) {
  716. self.width = _addUnit(width);
  717. }
  718. }
  719. if (height) {
  720. height = _removeUnit(height);
  721. var editHeight = _removeUnit(height) - self.toolbar.div.height() - self.statusbar.height();
  722. editHeight = editHeight < self.minHeight ? self.minHeight : editHeight;
  723. self.edit.setHeight(editHeight);
  724. if (updateProp) {
  725. self.height = _addUnit(height);
  726. }
  727. }
  728. return self;
  729. },
  730. select : function() {
  731. this.isCreated && this.cmd.select();
  732. return this;
  733. },
  734. html : function(val) {
  735. var self = this;
  736. if (val === undefined) {
  737. return self.isCreated ? self.edit.html() : _elementVal(self.srcElement);
  738. }
  739. self.isCreated ? self.edit.html(val) : _elementVal(self.srcElement, val);
  740. // Bugfix: http://www.kindsoft.net/view.php?bbsid=4&postid=6703&pagenum=1
  741. if (self.isCreated) {
  742. self.cmd.selection();
  743. }
  744. return self;
  745. },
  746. fullHtml : function() {
  747. return this.isCreated ? this.edit.html(undefined, true) : '';
  748. },
  749. text : function(val) {
  750. var self = this;
  751. if (val === undefined) {
  752. return _trim(self.html().replace(/<(?!img|embed).*?>/ig, '').replace(/&nbsp;/ig, ' '));
  753. } else {
  754. return self.html(_escape(val));
  755. }
  756. },
  757. isEmpty : function() {
  758. return _trim(this.text().replace(/\r\n|\n|\r/, '')) === '';
  759. },
  760. isDirty : function() {
  761. return _trim(this.initContent.replace(/\r\n|\n|\r|t/g, '')) !== _trim(this.html().replace(/\r\n|\n|\r|t/g, ''));
  762. },
  763. selectedHtml : function() {
  764. var val = this.isCreated ? this.cmd.range.html() : '';
  765. val = _removeBookmarkTag(_removeTempTag(val));
  766. return val;
  767. },
  768. count : function(mode) {
  769. var self = this;
  770. mode = (mode || 'html').toLowerCase();
  771. if (mode === 'html') {
  772. return self.html().length;
  773. }
  774. if (mode === 'text') {
  775. return self.text().replace(/<(?:img|embed).*?>/ig, 'K').replace(/\r\n|\n|\r/g, '').length;
  776. }
  777. return 0;
  778. },
  779. exec : function(key) {
  780. key = key.toLowerCase();
  781. var self = this, cmd = self.cmd,
  782. changeFlag = _inArray(key, 'selectall,copy,paste,print'.split(',')) < 0;
  783. if (changeFlag) {
  784. self.addBookmark(false);
  785. }
  786. cmd[key].apply(cmd, _toArray(arguments, 1));
  787. // 不需要改变工具栏状态,不需要保存bookmark
  788. if (changeFlag) {
  789. self.updateState();
  790. self.addBookmark(false);
  791. if (self.options.afterChange) {
  792. self.options.afterChange.call(self);
  793. }
  794. }
  795. return self;
  796. },
  797. insertHtml : function(val, quickMode) {
  798. if (!this.isCreated) {
  799. return this;
  800. }
  801. val = this.beforeSetHtml(val);
  802. this.exec('inserthtml', val, quickMode);
  803. return this;
  804. },
  805. appendHtml : function(val) {
  806. this.html(this.html() + val);
  807. if (this.isCreated) {
  808. var cmd = this.cmd;
  809. cmd.range.selectNodeContents(cmd.doc.body).collapse(false);
  810. cmd.select();
  811. }
  812. return this;
  813. },
  814. sync : function() {
  815. _elementVal(this.srcElement, this.html());
  816. return this;
  817. },
  818. focus : function() {
  819. this.isCreated ? this.edit.focus() : this.srcElement[0].focus();
  820. return this;
  821. },
  822. blur : function() {
  823. this.isCreated ? this.edit.blur() : this.srcElement[0].blur();
  824. return this;
  825. },
  826. addBookmark : function(checkSize) {
  827. checkSize = _undef(checkSize, true);
  828. var self = this, edit = self.edit,
  829. body = edit.doc.body,
  830. html = _removeTempTag(body.innerHTML), bookmark;
  831. if (checkSize && self._undoStack.length > 0) {
  832. var prev = self._undoStack[self._undoStack.length - 1];
  833. if (Math.abs(html.length - _removeBookmarkTag(prev.html).length) < self.minChangeSize) {
  834. return self;
  835. }
  836. }
  837. // 第一次执行addBookmark时不执行range.createBookmark
  838. if (edit.designMode && !self._firstAddBookmark) {
  839. var range = self.cmd.range;
  840. bookmark = range.createBookmark(true);
  841. bookmark.html = _removeTempTag(body.innerHTML);
  842. range.moveToBookmark(bookmark);
  843. } else {
  844. bookmark = {
  845. html : html
  846. };
  847. }
  848. self._firstAddBookmark = false;
  849. _addBookmarkToStack(self._undoStack, bookmark);
  850. return self;
  851. },
  852. undo : function() {
  853. return _undoToRedo.call(this, this._undoStack, this._redoStack);
  854. },
  855. redo : function() {
  856. return _undoToRedo.call(this, this._redoStack, this._undoStack);
  857. },
  858. fullscreen : function(bool) {
  859. this.fullscreenMode = (bool === undefined ? !this.fullscreenMode : bool);
  860. this.addBookmark(false);
  861. return this.remove().create();
  862. },
  863. readonly : function(isReadonly) {
  864. isReadonly = _undef(isReadonly, true);
  865. var self = this, edit = self.edit, doc = edit.doc;
  866. if (self.designMode) {
  867. self.toolbar.disableAll(isReadonly, []);
  868. } else {
  869. _each(self.noDisableItems, function() {
  870. self.toolbar[isReadonly ? 'disable' : 'enable'](this);
  871. });
  872. }
  873. if (_IE) {
  874. doc.body.contentEditable = !isReadonly;
  875. } else {
  876. doc.designMode = isReadonly ? 'off' : 'on';
  877. }
  878. edit.textarea[0].disabled = isReadonly;
  879. },
  880. createMenu : function(options) {
  881. var self = this,
  882. name = options.name,
  883. knode = self.toolbar.get(name),
  884. pos = knode.pos();
  885. options.x = pos.x;
  886. options.y = pos.y + knode.height();
  887. options.z = self.options.zIndex;
  888. options.shadowMode = _undef(options.shadowMode, self.shadowMode);
  889. if (options.selectedColor !== undefined) {
  890. options.cls = 'ke-colorpicker-' + self.themeType;
  891. options.noColor = self.lang('noColor');
  892. self.menu = _colorpicker(options);
  893. } else {
  894. options.cls = 'ke-menu-' + self.themeType;
  895. options.centerLineMode = false;
  896. self.menu = _menu(options);
  897. }
  898. return self.menu;
  899. },
  900. hideMenu : function() {
  901. this.menu.remove();
  902. this.menu = null;
  903. return this;
  904. },
  905. hideContextmenu : function() {
  906. this.contextmenu.remove();
  907. this.contextmenu = null;
  908. return this;
  909. },
  910. createDialog : function(options) {
  911. var self = this, name = options.name;
  912. options.z = self.options.zIndex;
  913. options.shadowMode = _undef(options.shadowMode, self.shadowMode);
  914. options.closeBtn = _undef(options.closeBtn, {
  915. name : self.lang('close'),
  916. click : function(e) {
  917. self.hideDialog();
  918. // IE bugfix: 关闭dialog后,跳转到top
  919. if (_IE && self.cmd) {
  920. self.cmd.select();
  921. }
  922. }
  923. });
  924. options.noBtn = _undef(options.noBtn, {
  925. name : self.lang(options.yesBtn ? 'no' : 'close'),
  926. click : function(e) {
  927. self.hideDialog();
  928. // IE bugfix: 关闭dialog后,跳转到top
  929. if (_IE && self.cmd) {
  930. self.cmd.select();
  931. }
  932. }
  933. });
  934. if (self.dialogAlignType != 'page') {
  935. options.alignEl = self.container;
  936. }
  937. options.cls = 'ke-dialog-' + self.themeType;
  938. if (self.dialogs.length > 0) {
  939. var firstDialog = self.dialogs[0],
  940. parentDialog = self.dialogs[self.dialogs.length - 1];
  941. // 提高mask的z-index
  942. firstDialog.setMaskIndex(parentDialog.z + 2);
  943. // 提高dialog的z-index
  944. options.z = parentDialog.z + 3;
  945. // 不显示mask
  946. options.showMask = false;
  947. }
  948. var dialog = _dialog(options);
  949. self.dialogs.push(dialog);
  950. return dialog;
  951. },
  952. hideDialog : function() {
  953. var self = this;
  954. if (self.dialogs.length > 0) {
  955. self.dialogs.pop().remove();
  956. }
  957. if (self.dialogs.length > 0) {
  958. var firstDialog = self.dialogs[0],
  959. parentDialog = self.dialogs[self.dialogs.length - 1];
  960. // 降低mask的z-index
  961. firstDialog.setMaskIndex(parentDialog.z - 1);
  962. }
  963. return self;
  964. },
  965. errorDialog : function(html) {
  966. var self = this;
  967. var dialog = self.createDialog({
  968. width : 750,
  969. title : self.lang('uploadError'),
  970. body : '<div style="padding:10px 20px;"><iframe frameborder="0" style="width:708px;height:400px;"></iframe></div>'
  971. });
  972. var iframe = K('iframe', dialog.div), doc = K.iframeDoc(iframe);
  973. doc.open();
  974. doc.write(html);
  975. doc.close();
  976. K(doc.body).css('background-color', '#FFF');
  977. iframe[0].contentWindow.focus();
  978. return self;
  979. }
  980. };
  981. function _editor(options) {
  982. return new KEditor(options);
  983. }
  984. var _instances = [];
  985. /**
  986. @example
  987. K.create('textarea');
  988. K.create('textarea.class');
  989. K.create('#id');
  990. */
  991. function _create(expr, options) {
  992. options = options || {};
  993. options.basePath = _undef(options.basePath, K.basePath);
  994. options.themesPath = _undef(options.themesPath, options.basePath + 'themes/');
  995. options.langPath = _undef(options.langPath, options.basePath + 'lang/');
  996. options.pluginsPath = _undef(options.pluginsPath, options.basePath + 'plugins/');
  997. // 自动加载CSS文件
  998. if (_undef(options.loadStyleMode, K.options.loadStyleMode)) {
  999. var themeType = _undef(options.themeType, K.options.themeType);
  1000. _loadStyle(options.themesPath + 'default/default.css');
  1001. _loadStyle(options.themesPath + themeType + '/' + themeType + '.css');
  1002. }
  1003. function create(editor) {
  1004. _each(_plugins, function(name, fn) {
  1005. if (_isFunction(fn)) {
  1006. fn.call(editor, KindEditor);
  1007. if (!editor._pluginStatus) {
  1008. editor._pluginStatus = {};
  1009. }
  1010. editor._pluginStatus[name] = 'inited';
  1011. }
  1012. });
  1013. return editor.create();
  1014. }
  1015. var knode = K(expr);
  1016. if (!knode || knode.length === 0) {
  1017. return;
  1018. }
  1019. if (knode.length > 1) {
  1020. knode.each(function() {
  1021. _create(this, options);
  1022. });
  1023. return _instances[0];
  1024. }
  1025. options.srcElement = knode[0];
  1026. var editor = new KEditor(options);
  1027. _instances.push(editor);
  1028. // create editor
  1029. if (_language[editor.langType]) {
  1030. return create(editor);
  1031. }
  1032. // create editor after load lang file
  1033. _loadScript(editor.langPath + editor.langType + '.js?ver=' + encodeURIComponent(K.DEBUG ? _TIME : _VERSION), function() {
  1034. create(editor);
  1035. });
  1036. return editor;
  1037. }
  1038. function _eachEditor(expr, fn) {
  1039. K(expr).each(function(i, el) {
  1040. K.each(_instances, function(j, editor) {
  1041. if (editor && editor.srcElement[0] == el) {
  1042. fn.call(editor, j);
  1043. return false;
  1044. }
  1045. });
  1046. });
  1047. }
  1048. K.remove = function(expr) {
  1049. _eachEditor(expr, function(i) {
  1050. this.remove();
  1051. _instances.splice(i, 1);
  1052. });
  1053. };
  1054. K.sync = function(expr) {
  1055. _eachEditor(expr, function() {
  1056. this.sync();
  1057. });
  1058. };
  1059. K.html = function(expr, val) {
  1060. _eachEditor(expr, function() {
  1061. this.html(val);
  1062. });
  1063. };
  1064. K.insertHtml = function(expr, val) {
  1065. _eachEditor(expr, function() {
  1066. this.insertHtml(val);
  1067. });
  1068. };
  1069. K.appendHtml = function(expr, val) {
  1070. _eachEditor(expr, function() {
  1071. this.appendHtml(val);
  1072. });
  1073. };
  1074. // 解决IE6浏览器重复下载背景图片的问题
  1075. if (_IE && _V < 7) {
  1076. _nativeCommand(document, 'BackgroundImageCache', true);
  1077. }
  1078. K.EditorClass = KEditor;
  1079. K.editor = _editor;
  1080. K.create = _create;
  1081. K.instances = _instances;
  1082. K.plugin = _plugin;
  1083. K.lang = _lang;
  1084. // core plugins
  1085. _plugin('core', function(K) {
  1086. var self = this,
  1087. shortcutKeys = {
  1088. undo : 'Z', redo : 'Y', bold : 'B', italic : 'I', underline : 'U', print : 'P', selectall : 'A'
  1089. };
  1090. // afterChange
  1091. self.afterSetHtml(function() {
  1092. if (self.options.afterChange) {
  1093. self.options.afterChange.call(self);
  1094. }
  1095. });
  1096. // sync
  1097. self.afterCreate(function() {
  1098. if (self.syncType != 'form') {
  1099. return;
  1100. }
  1101. var el = K(self.srcElement), hasForm = false;
  1102. while ((el = el.parent())) {
  1103. if (el.name == 'form') {
  1104. hasForm = true;
  1105. break;
  1106. }
  1107. }
  1108. if (hasForm) {
  1109. el.bind('submit', function(e) {
  1110. self.sync();
  1111. // Bugfix: Firefox下后退,编辑器数据不保存
  1112. K(window).bind('unload', function() {
  1113. self.edit.textarea.remove();
  1114. });
  1115. });
  1116. var resetBtn = K('[type="reset"]', el);
  1117. resetBtn.click(function() {
  1118. self.html(self.initContent);
  1119. self.cmd.selection();
  1120. });
  1121. self.beforeRemove(function() {
  1122. el.unbind();
  1123. resetBtn.unbind();
  1124. });
  1125. }
  1126. });
  1127. // source
  1128. self.clickToolbar('source', function() {
  1129. if (self.edit.designMode) {
  1130. self.toolbar.disableAll(true);
  1131. self.edit.design(false);
  1132. self.toolbar.select('source');
  1133. } else {
  1134. self.toolbar.disableAll(false);
  1135. self.edit.design(true);
  1136. self.toolbar.unselect('source');
  1137. // Bugfix: http://www.kindsoft.net/view.php?bbsid=4&postid=7061&pagenum=1
  1138. if (_GECKO) {
  1139. setTimeout(function() {
  1140. self.cmd.selection();
  1141. }, 0);
  1142. } else {
  1143. self.cmd.selection();
  1144. }
  1145. }
  1146. self.designMode = self.edit.designMode;
  1147. });
  1148. self.afterCreate(function() {
  1149. if (!self.designMode) {
  1150. self.toolbar.disableAll(true).select('source');
  1151. }
  1152. });
  1153. // fullscreen
  1154. self.clickToolbar('fullscreen', function() {
  1155. self.fullscreen();
  1156. });
  1157. if (self.fullscreenShortcut) {
  1158. var loaded = false;
  1159. self.afterCreate(function() {
  1160. K(self.edit.doc, self.edit.textarea).keyup(function(e) {
  1161. if (e.which == 27) {
  1162. // bugfix: 在opera 11上无法全屏,必须用setTimeout
  1163. setTimeout(function() {
  1164. self.fullscreen();
  1165. }, 0);
  1166. }
  1167. });
  1168. if (loaded) {
  1169. // bugfix: 在IE上在代码模式下切换全屏出现奇怪现象
  1170. if (_IE && !self.designMode) {
  1171. return;
  1172. }
  1173. self.focus();
  1174. }
  1175. if (!loaded) {
  1176. loaded = true;
  1177. }
  1178. });
  1179. }
  1180. // undo, redo
  1181. _each('undo,redo'.split(','), function(i, name) {
  1182. if (shortcutKeys[name]) {
  1183. self.afterCreate(function() {
  1184. _ctrl(this.edit.doc, shortcutKeys[name], function() {
  1185. self.clickToolbar(name);
  1186. });
  1187. });
  1188. }
  1189. self.clickToolbar(name, function() {
  1190. self[name]();
  1191. });
  1192. });
  1193. // formatblock
  1194. self.clickToolbar('formatblock', function() {
  1195. var blocks = self.lang('formatblock.formatBlock'),
  1196. heights = {
  1197. h1 : 28,
  1198. h2 : 24,
  1199. h3 : 18,
  1200. H4 : 14,
  1201. p : 12
  1202. },
  1203. curVal = self.cmd.val('formatblock'),
  1204. menu = self.createMenu({
  1205. name : 'formatblock',
  1206. width : self.langType == 'en' ? 200 : 150
  1207. });
  1208. _each(blocks, function(key, val) {
  1209. var style = 'font-size:' + heights[key] + 'px;';
  1210. if (key.charAt(0) === 'h') {
  1211. style += 'font-weight:bold;';
  1212. }
  1213. menu.addItem({
  1214. title : '<span style="' + style + '" unselectable="on">' + val + '</span>',
  1215. height : heights[key] + 12,
  1216. checked : (curVal === key || curVal === val),
  1217. click : function() {
  1218. self.select().exec('formatblock', '<' + key + '>').hideMenu();
  1219. }
  1220. });
  1221. });
  1222. });
  1223. // fontname
  1224. self.clickToolbar('fontname', function() {
  1225. var curVal = self.cmd.val('fontname'),
  1226. menu = self.createMenu({
  1227. name : 'fontname',
  1228. width : 150
  1229. });
  1230. _each(self.lang('fontname.fontName'), function(key, val) {
  1231. menu.addItem({
  1232. title : '<span style="font-family: ' + key + ';" unselectable="on">' + val + '</span>',
  1233. checked : (curVal === key.toLowerCase() || curVal === val.toLowerCase()),
  1234. click : function() {
  1235. self.exec('fontname', key).hideMenu();
  1236. }
  1237. });
  1238. });
  1239. });
  1240. // fontsize
  1241. self.clickToolbar('fontsize', function() {
  1242. var curVal = self.cmd.val('fontsize'),
  1243. menu = self.createMenu({
  1244. name : 'fontsize',
  1245. width : 150
  1246. });
  1247. _each(self.fontSizeTable, function(i, val) {
  1248. menu.addItem({
  1249. title : '<span style="font-size:' + val + ';" unselectable="on">' + val + '</span>',
  1250. height : _removeUnit(val) + 12,
  1251. checked : curVal === val,
  1252. click : function() {
  1253. self.exec('fontsize', val).hideMenu();
  1254. }
  1255. });
  1256. });
  1257. });
  1258. // forecolor,hilitecolor
  1259. _each('forecolor,hilitecolor'.split(','), function(i, name) {
  1260. self.clickToolbar(name, function() {
  1261. self.createMenu({
  1262. name : name,
  1263. selectedColor : self.cmd.val(name) || 'default',
  1264. colors : self.colorTable,
  1265. click : function(color) {
  1266. self.exec(name, color).hideMenu();
  1267. }
  1268. });
  1269. });
  1270. });
  1271. // cut,copy,paste
  1272. _each(('cut,copy,paste').split(','), function(i, name) {
  1273. self.clickToolbar(name, function() {
  1274. self.focus();
  1275. try {
  1276. self.exec(name, null);
  1277. } catch(e) {
  1278. alert(self.lang(name + 'Error'));
  1279. }
  1280. });
  1281. });
  1282. // about
  1283. self.clickToolbar('about', function() {
  1284. var html = '<div style="margin:20px;">' +
  1285. '<div>KindEditor ' + _VERSION + '</div>' +
  1286. '<div>Copyright &copy; <a href="http://www.kindsoft.net/" target="_blank">kindsoft.net</a> All rights reserved.</div>' +
  1287. '</div>';
  1288. self.createDialog({
  1289. name : 'about',
  1290. width : 350,
  1291. title : self.lang('about'),
  1292. body : html
  1293. });
  1294. });
  1295. // link,image,flash,media,anchor
  1296. self.plugin.getSelectedLink = function() {
  1297. return self.cmd.commonAncestor('a');
  1298. };
  1299. self.plugin.getSelectedImage = function() {
  1300. return _getImageFromRange(self.edit.cmd.range, function(img) {
  1301. return !/^ke-\w+$/i.test(img[0].className);
  1302. });
  1303. };
  1304. self.plugin.getSelectedFlash = function() {
  1305. return _getImageFromRange(self.edit.cmd.range, function(img) {
  1306. return img[0].className == 'ke-flash';
  1307. });
  1308. };
  1309. self.plugin.getSelectedMedia = function() {
  1310. return _getImageFromRange(self.edit.cmd.range, function(img) {
  1311. return img[0].className == 'ke-media' || img[0].className == 'ke-rm';
  1312. });
  1313. };
  1314. self.plugin.getSelectedAnchor = function() {
  1315. return _getImageFromRange(self.edit.cmd.range, function(img) {
  1316. return img[0].className == 'ke-anchor';
  1317. });
  1318. };
  1319. _each('link,image,flash,media,anchor'.split(','), function(i, name) {
  1320. var uName = name.charAt(0).toUpperCase() + name.substr(1);
  1321. _each('edit,delete'.split(','), function(j, val) {
  1322. self.addContextmenu({
  1323. title : self.lang(val + uName),
  1324. click : function() {
  1325. self.loadPlugin(name, function() {
  1326. self.plugin[name][val]();
  1327. self.hideMenu();
  1328. });
  1329. },
  1330. cond : self.plugin['getSelected' + uName],
  1331. width : 150,
  1332. iconClass : val == 'edit' ? 'ke-icon-' + name : undefined
  1333. });
  1334. });
  1335. self.addContextmenu({ title : '-' });
  1336. });
  1337. // table
  1338. self.plugin.getSelectedTable = function() {
  1339. return self.cmd.commonAncestor('table');
  1340. };
  1341. self.plugin.getSelectedRow = function() {
  1342. return self.cmd.commonAncestor('tr');
  1343. };
  1344. self.plugin.getSelectedCell = function() {
  1345. return self.cmd.commonAncestor('td');
  1346. };
  1347. _each(('prop,cellprop,colinsertleft,colinsertright,rowinsertabove,rowinsertbelow,rowmerge,colmerge,' +
  1348. 'rowsplit,colsplit,coldelete,rowdelete,insert,delete').split(','), function(i, val) {
  1349. var cond = _inArray(val, ['prop', 'delete']) < 0 ? self.plugin.getSelectedCell : self.plugin.getSelectedTable;
  1350. self.addContextmenu({
  1351. title : self.lang('table' + val),
  1352. click : function() {
  1353. self.loadPlugin('table', function() {
  1354. self.plugin.table[val]();
  1355. self.hideMenu();
  1356. });
  1357. },
  1358. cond : cond,
  1359. width : 170,
  1360. iconClass : 'ke-icon-table' + val
  1361. });
  1362. });
  1363. self.addContextmenu({ title : '-' });
  1364. // other
  1365. _each(('selectall,justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,' +
  1366. 'insertunorderedlist,indent,outdent,subscript,superscript,hr,print,' +
  1367. 'bold,italic,underline,strikethrough,removeformat,unlink').split(','), function(i, name) {
  1368. if (shortcutKeys[name]) {
  1369. self.afterCreate(function() {
  1370. _ctrl(this.edit.doc, shortcutKeys[name], function() {
  1371. self.cmd.selection();
  1372. self.clickToolbar(name);
  1373. });
  1374. });
  1375. }
  1376. self.clickToolbar(name, function() {
  1377. self.focus().exec(name, null);
  1378. });
  1379. });
  1380. // paste
  1381. self.afterCreate(function() {
  1382. var doc = self.edit.doc, cmd, bookmark, div,
  1383. cls = '__kindeditor_paste__', pasting = false;
  1384. function movePastedData() {
  1385. cmd.range.moveToBookmark(bookmark);
  1386. cmd.select();
  1387. if (_WEBKIT) {
  1388. K('div.' + cls, div).each(function() {
  1389. K(this).after('<br />').remove(true);
  1390. });
  1391. K('span.Apple-style-span', div).remove(true);
  1392. K('span.Apple-tab-span', div).remove(true);
  1393. // Bugfix: https://github.com/kindsoft/kindeditor/issues/8
  1394. K('span[style]', div).each(function() {
  1395. if (K(this).css('white-space') == 'nowrap') {
  1396. K(this).remove(true);
  1397. }
  1398. });
  1399. K('meta', div).remove();
  1400. }
  1401. var html = div[0].innerHTML;
  1402. div.remove();
  1403. if (html === '') {
  1404. return;
  1405. }
  1406. // Chrome纯文本粘贴问题
  1407. if (_WEBKIT) {
  1408. html = html.replace(/(<br>)\1/ig, '$1');
  1409. }
  1410. // paste HTML
  1411. if (self.pasteType === 2) {
  1412. // 去除内容为空的p标签
  1413. html = html.replace(/(<(?:p|p\s[^>]*)>) *(<\/p>)/ig, '');
  1414. // paste from ms word
  1415. if (/schemas-microsoft-com|worddocument|mso-\w+/i.test(html)) {
  1416. html = _clearMsWord(html, self.filterMode ? self.htmlTags : K.options.htmlTags);
  1417. } else {
  1418. html = _formatHtml(html, self.filterMode ? self.htmlTags : null);
  1419. html = self.beforeSetHtml(html);
  1420. }
  1421. }
  1422. // paste text
  1423. if (self.pasteType === 1) {
  1424. html = html.replace(/&nbsp;/ig, ' ');
  1425. html = html.replace(/\n\s*\n/g, '\n');
  1426. html = html.replace(/<br[^>]*>/ig, '\n');
  1427. html = html.replace(/<\/p><p[^>]*>/ig, '\n');
  1428. html = html.replace(/<[^>]+>/g, '');
  1429. html = html.replace(/ {2}/g, ' &nbsp;');
  1430. if (self.newlineTag == 'p') {
  1431. if (/\n/.test(html)) {
  1432. html = html.replace(/^/, '<p>').replace(/$/, '<br /></p>').replace(/\n/g, '<br /></p><p>');
  1433. }
  1434. } else {
  1435. html = html.replace(/\n/g, '<br />$&');
  1436. }
  1437. }
  1438. self.insertHtml(html, true);
  1439. }
  1440. K(doc.body).bind('paste', function(e){
  1441. if (self.pasteType === 0) {
  1442. e.stop();
  1443. return;
  1444. }
  1445. if (pasting) {
  1446. return;
  1447. }
  1448. pasting = true;
  1449. K('div.' + cls, doc).remove();
  1450. cmd = self.cmd.selection();
  1451. bookmark = cmd.range.createBookmark();
  1452. div = K('<div class="' + cls + '"></div>', doc).css({
  1453. position : 'absolute',
  1454. width : '1px',
  1455. height : '1px',
  1456. overflow : 'hidden',
  1457. left : '-1981px',
  1458. top : K(bookmark.start).pos().y + 'px',
  1459. 'white-space' : 'nowrap'
  1460. });
  1461. K(doc.body).append(div);
  1462. if (_IE) {
  1463. var rng = cmd.range.get(true);
  1464. rng.moveToElementText(div[0]);
  1465. rng.select();
  1466. rng.execCommand('paste');
  1467. e.preventDefault();
  1468. } else {
  1469. cmd.range.selectNodeContents(div[0]);
  1470. cmd.select();
  1471. div[0].tabIndex = -1;
  1472. div[0].focus();
  1473. }
  1474. setTimeout(function() {
  1475. movePastedData();
  1476. pasting = false;
  1477. }, 0);
  1478. });
  1479. });
  1480. // 取得HTML前执行
  1481. self.beforeGetHtml(function(html) {
  1482. // Bugifx : https://github.com/kindsoft/kindeditor/issues/66
  1483. if (_IE && _V <= 8) {
  1484. html = html.replace(/<div\s+[^>]*data-ke-input-tag="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function(full, tag) {
  1485. return unescape(tag);
  1486. });
  1487. // Bugfix: https://github.com/kindsoft/kindeditor/issues/88
  1488. html = html.replace(/(<input)((?:\s+[^>]*)?>)/ig, function($0, $1, $2) {
  1489. if (!/\s+type="[^"]+"/i.test($0)) {
  1490. return $1 + ' type="text"' + $2;
  1491. }
  1492. return $0;
  1493. });
  1494. }
  1495. return html.replace(/(<(?:noscript|noscript\s[^>]*)>)([\s\S]*?)(<\/noscript>)/ig, function($0, $1, $2, $3) {
  1496. return $1 + _unescape($2).replace(/\s+/g, ' ') + $3;
  1497. })
  1498. .replace(/<img[^>]*class="?ke-(flash|rm|media)"?[^>]*>/ig, function(full) {
  1499. var imgAttrs = _getAttrList(full);
  1500. var styles = _getCssList(imgAttrs.style || '');
  1501. var attrs = _mediaAttrs(imgAttrs['data-ke-tag']);
  1502. var width = _undef(styles.width, '');
  1503. var height = _undef(styles.height, '');
  1504. if (/px/i.test(width)) {
  1505. width = _removeUnit(width);
  1506. }
  1507. if (/px/i.test(height)) {
  1508. height = _removeUnit(height);
  1509. }
  1510. attrs.width = _undef(imgAttrs.width, width);
  1511. attrs.height = _undef(imgAttrs.height, height);
  1512. return _mediaEmbed(attrs);
  1513. })
  1514. .replace(/<img[^>]*class="?ke-anchor"?[^>]*>/ig, function(full) {
  1515. var imgAttrs = _getAttrList(full);
  1516. return '<a name="' + unescape(imgAttrs['data-ke-name']) + '"></a>';
  1517. })
  1518. .replace(/<div\s+[^>]*data-ke-script-attr="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function(full, attr, code) {
  1519. return '<script' + unescape(attr) + '>' + unescape(code) + '</script>';
  1520. })
  1521. .replace(/<div\s+[^>]*data-ke-noscript-attr="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function(full, attr, code) {
  1522. return '<noscript' + unescape(attr) + '>' + unescape(code) + '</noscript>';
  1523. })
  1524. .replace(/(<[^>]*)data-ke-src="([^"]*)"([^>]*>)/ig, function(full, start, src, end) {
  1525. full = full.replace(/(\s+(?:href|src)=")[^"]*(")/i, function($0, $1, $2) {
  1526. return $1 + _unescape(src) + $2;
  1527. });
  1528. full = full.replace(/\s+data-ke-src="[^"]*"/i, '');
  1529. return full;
  1530. })
  1531. .replace(/(<[^>]+\s)data-ke-(on\w+="[^"]*"[^>]*>)/ig, function(full, start, end) {
  1532. return start + end;
  1533. });
  1534. });
  1535. // 设置HTML前执行
  1536. self.beforeSetHtml(function(html) {
  1537. // Bugifx : https://github.com/kindsoft/kindeditor/issues/66
  1538. if (_IE && _V <= 8) {
  1539. html = html.replace(/<input[^>]*>|<(select|button)[^>]*>[\s\S]*?<\/\1>/ig, function(full) {
  1540. var attrs = _getAttrList(full);
  1541. var styles = _getCssList(attrs.style || '');
  1542. if (styles.display == 'none') {
  1543. return '<div class="ke-display-none" data-ke-input-tag="' + escape(full) + '"></div>';
  1544. }
  1545. return full;
  1546. });
  1547. }
  1548. return html.replace(/<embed[^>]*type="([^"]+)"[^>]*>(?:<\/embed>)?/ig, function(full) {
  1549. var attrs = _getAttrList(full);
  1550. attrs.src = _undef(attrs.src, '');
  1551. attrs.width = _undef(attrs.width, 0);
  1552. attrs.height = _undef(attrs.height, 0);
  1553. return _mediaImg(self.themesPath + 'common/blank.gif', attrs);
  1554. })
  1555. .replace(/<a[^>]*name="([^"]+)"[^>]*>(?:<\/a>)?/ig, function(full) {
  1556. var attrs = _getAttrList(full);
  1557. if (attrs.href !== undefined) {
  1558. return full;
  1559. }
  1560. return '<img class="ke-anchor" src="' + self.themesPath + 'common/anchor.gif" data-ke-name="' + escape(attrs.name) + '" />';
  1561. })
  1562. .replace(/<script([^>]*)>([\s\S]*?)<\/script>/ig, function(full, attr, code) {
  1563. return '<div class="ke-script" data-ke-script-attr="' + escape(attr) + '">' + escape(code) + '</div>';
  1564. })
  1565. .replace(/<noscript([^>]*)>([\s\S]*?)<\/noscript>/ig, function(full, attr, code) {
  1566. return '<div class="ke-noscript" data-ke-noscript-attr="' + escape(attr) + '">' + escape(code) + '</div>';
  1567. })
  1568. .replace(/(<[^>]*)(href|src)="([^"]*)"([^>]*>)/ig, function(full, start, key, src, end) {
  1569. if (full.match(/\sdata-ke-src="[^"]*"/i)) {
  1570. return full;
  1571. }
  1572. full = start + key + '="' + src + '"' + ' data-ke-src="' + _escape(src) + '"' + end;
  1573. return full;
  1574. })
  1575. .replace(/(<[^>]+\s)(on\w+="[^"]*"[^>]*>)/ig, function(full, start, end) {
  1576. return start + 'data-ke-' + end;
  1577. })
  1578. .replace(/<table[^>]*\s+border="0"[^>]*>/ig, function(full) {
  1579. if (full.indexOf('ke-zeroborder') >= 0) {
  1580. return full;
  1581. }
  1582. return _addClassToTag(full, 'ke-zeroborder');
  1583. });
  1584. });
  1585. });