image.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  1. /**
  2. * User: Jinqn
  3. * Date: 14-04-08
  4. * Time: 下午16:34
  5. * 上传图片对话框逻辑代码,包括tab: 远程图片/上传图片/在线图片/搜索图片
  6. */
  7. (function () {
  8. var remoteImage,
  9. uploadImage,
  10. onlineImage,
  11. searchImage;
  12. window.onload = function () {
  13. initTabs();
  14. initAlign();
  15. initButtons();
  16. };
  17. /* 初始化tab标签 */
  18. function initTabs() {
  19. var tabs = $G('tabhead').children;
  20. for (var i = 0; i < tabs.length; i++) {
  21. domUtils.on(tabs[i], "click", function (e) {
  22. var target = e.target || e.srcElement;
  23. setTabFocus(target.getAttribute('data-content-id'));
  24. });
  25. }
  26. var img = editor.selection.getRange().getClosedNode();
  27. if (img && img.tagName && img.tagName.toLowerCase() == 'img') {
  28. setTabFocus('remote');
  29. } else {
  30. setTabFocus('upload');
  31. }
  32. }
  33. /* 初始化tabbody */
  34. function setTabFocus(id) {
  35. if(!id) return;
  36. var i, bodyId, tabs = $G('tabhead').children;
  37. for (i = 0; i < tabs.length; i++) {
  38. bodyId = tabs[i].getAttribute('data-content-id');
  39. if (bodyId == id) {
  40. domUtils.addClass(tabs[i], 'focus');
  41. domUtils.addClass($G(bodyId), 'focus');
  42. } else {
  43. domUtils.removeClasses(tabs[i], 'focus');
  44. domUtils.removeClasses($G(bodyId), 'focus');
  45. }
  46. }
  47. switch (id) {
  48. case 'remote':
  49. remoteImage = remoteImage || new RemoteImage();
  50. break;
  51. case 'upload':
  52. setAlign(editor.getOpt('imageInsertAlign'));
  53. uploadImage = uploadImage || new UploadImage('queueList');
  54. break;
  55. case 'online':
  56. setAlign(editor.getOpt('imageManagerInsertAlign'));
  57. onlineImage = onlineImage || new OnlineImage('imageList');
  58. onlineImage.reset();
  59. break;
  60. case 'search':
  61. setAlign(editor.getOpt('imageManagerInsertAlign'));
  62. searchImage = searchImage || new SearchImage();
  63. break;
  64. }
  65. }
  66. /* 初始化onok事件 */
  67. function initButtons() {
  68. dialog.onok = function () {
  69. var remote = false, list = [], id, tabs = $G('tabhead').children;
  70. for (var i = 0; i < tabs.length; i++) {
  71. if (domUtils.hasClass(tabs[i], 'focus')) {
  72. id = tabs[i].getAttribute('data-content-id');
  73. break;
  74. }
  75. }
  76. switch (id) {
  77. case 'remote':
  78. list = remoteImage.getInsertList();
  79. break;
  80. case 'upload':
  81. list = uploadImage.getInsertList();
  82. var count = uploadImage.getQueueCount();
  83. if (count) {
  84. $('.info', '#queueList').html('<span style="color:red;">' + '还有2个未上传文件'.replace(/[\d]/, count) + '</span>');
  85. return false;
  86. }
  87. break;
  88. case 'online':
  89. list = onlineImage.getInsertList();
  90. break;
  91. case 'search':
  92. list = searchImage.getInsertList();
  93. remote = true;
  94. break;
  95. }
  96. if(list) {
  97. editor.execCommand('insertimage', list);
  98. remote && editor.fireEvent("catchRemoteImage");
  99. }
  100. };
  101. }
  102. /* 初始化对其方式的点击事件 */
  103. function initAlign(){
  104. /* 点击align图标 */
  105. domUtils.on($G("alignIcon"), 'click', function(e){
  106. var target = e.target || e.srcElement;
  107. if(target.className && target.className.indexOf('-align') != -1) {
  108. setAlign(target.getAttribute('data-align'));
  109. }
  110. });
  111. }
  112. /* 设置对齐方式 */
  113. function setAlign(align){
  114. align = align || 'none';
  115. var aligns = $G("alignIcon").children;
  116. for(i = 0; i < aligns.length; i++){
  117. if(aligns[i].getAttribute('data-align') == align) {
  118. domUtils.addClass(aligns[i], 'focus');
  119. $G("align").value = aligns[i].getAttribute('data-align');
  120. } else {
  121. domUtils.removeClasses(aligns[i], 'focus');
  122. }
  123. }
  124. }
  125. /* 获取对齐方式 */
  126. function getAlign(){
  127. var align = $G("align").value || 'none';
  128. return align == 'none' ? '':align;
  129. }
  130. /* 在线图片 */
  131. function RemoteImage(target) {
  132. this.container = utils.isString(target) ? document.getElementById(target) : target;
  133. this.init();
  134. }
  135. RemoteImage.prototype = {
  136. init: function () {
  137. this.initContainer();
  138. this.initEvents();
  139. },
  140. initContainer: function () {
  141. this.dom = {
  142. 'url': $G('url'),
  143. 'width': $G('width'),
  144. 'height': $G('height'),
  145. 'border': $G('border'),
  146. 'vhSpace': $G('vhSpace'),
  147. 'title': $G('title'),
  148. 'align': $G('align')
  149. };
  150. var img = editor.selection.getRange().getClosedNode();
  151. if (img) {
  152. this.setImage(img);
  153. }
  154. },
  155. initEvents: function () {
  156. var _this = this,
  157. locker = $G('lock');
  158. /* 改变url */
  159. domUtils.on($G("url"), 'keyup', updatePreview);
  160. domUtils.on($G("border"), 'keyup', updatePreview);
  161. domUtils.on($G("title"), 'keyup', updatePreview);
  162. domUtils.on($G("width"), 'keyup', function(){
  163. updatePreview();
  164. if(locker.checked) {
  165. var proportion =locker.getAttribute('data-proportion');
  166. $G('height').value = Math.round(this.value / proportion);
  167. } else {
  168. _this.updateLocker();
  169. }
  170. });
  171. domUtils.on($G("height"), 'keyup', function(){
  172. updatePreview();
  173. if(locker.checked) {
  174. var proportion =locker.getAttribute('data-proportion');
  175. $G('width').value = Math.round(this.value * proportion);
  176. } else {
  177. _this.updateLocker();
  178. }
  179. });
  180. domUtils.on($G("lock"), 'change', function(){
  181. var proportion = parseInt($G("width").value) /parseInt($G("height").value);
  182. locker.setAttribute('data-proportion', proportion);
  183. });
  184. function updatePreview(){
  185. _this.setPreview();
  186. }
  187. },
  188. updateLocker: function(){
  189. var width = $G('width').value,
  190. height = $G('height').value,
  191. locker = $G('lock');
  192. if(width && height && width == parseInt(width) && height == parseInt(height)) {
  193. locker.disabled = false;
  194. locker.title = '';
  195. } else {
  196. locker.checked = false;
  197. locker.disabled = 'disabled';
  198. locker.title = lang.remoteLockError;
  199. }
  200. },
  201. setImage: function(img){
  202. /* 不是正常的图片 */
  203. if (!img.tagName || img.tagName.toLowerCase() != 'img' && !img.getAttribute("src") || !img.src) return;
  204. var wordImgFlag = img.getAttribute("word_img"),
  205. src = wordImgFlag ? wordImgFlag.replace("&amp;", "&") : (img.getAttribute('_src') || img.getAttribute("src", 2).replace("&amp;", "&")),
  206. align = editor.queryCommandValue("imageFloat");
  207. /* 防止onchange事件循环调用 */
  208. if (src !== $G("url").value) $G("url").value = src;
  209. if(src) {
  210. /* 设置表单内容 */
  211. $G("width").value = img.width || '';
  212. $G("height").value = img.height || '';
  213. $G("border").value = img.getAttribute("border") || '0';
  214. $G("vhSpace").value = img.getAttribute("vspace") || '0';
  215. $G("title").value = img.title || img.alt || '';
  216. setAlign(align);
  217. this.setPreview();
  218. this.updateLocker();
  219. }
  220. },
  221. getData: function(){
  222. var data = {};
  223. for(var k in this.dom){
  224. data[k] = this.dom[k].value;
  225. }
  226. return data;
  227. },
  228. setPreview: function(){
  229. var url = $G('url').value,
  230. ow = $G('width').value,
  231. oh = $G('height').value,
  232. border = $G('border').value,
  233. title = $G('title').value,
  234. preview = $G('preview'),
  235. width,
  236. height;
  237. width = ((!ow || !oh) ? preview.offsetWidth:Math.min(ow, preview.offsetWidth));
  238. width = width+(border*2) > preview.offsetWidth ? width:(preview.offsetWidth - (border*2));
  239. height = (!ow || !oh) ? '':width*oh/ow;
  240. if(url) {
  241. preview.innerHTML = '<img src="' + url + '" width="' + width + '" height="' + height + '" border="' + border + 'px solid #000" title="' + title + '" />';
  242. }
  243. },
  244. getInsertList: function () {
  245. var data = this.getData();
  246. if(data['url']) {
  247. return [{
  248. src: data['url'],
  249. _src: data['url'],
  250. width: data['width'] || '',
  251. height: data['height'] || '',
  252. border: data['border'] || '',
  253. floatStyle: data['align'] || '',
  254. vspace: data['vhSpace'] || '',
  255. alt: data['title'] || '',
  256. style: "width:" + data['width'] + "px;height:" + data['height'] + "px;"
  257. }];
  258. } else {
  259. return [];
  260. }
  261. }
  262. };
  263. /* 上传图片 */
  264. function UploadImage(target) {
  265. this.$wrap = target.constructor == String ? $('#' + target) : $(target);
  266. this.init();
  267. }
  268. UploadImage.prototype = {
  269. init: function () {
  270. this.imageList = [];
  271. this.initContainer();
  272. this.initUploader();
  273. },
  274. initContainer: function () {
  275. this.$queue = this.$wrap.find('.filelist');
  276. },
  277. /* 初始化容器 */
  278. initUploader: function () {
  279. var _this = this,
  280. $ = jQuery, // just in case. Make sure it's not an other libaray.
  281. $wrap = _this.$wrap,
  282. // 图片容器
  283. $queue = $wrap.find('.filelist'),
  284. // 状态栏,包括进度和控制按钮
  285. $statusBar = $wrap.find('.statusBar'),
  286. // 文件总体选择信息。
  287. $info = $statusBar.find('.info'),
  288. // 上传按钮
  289. $upload = $wrap.find('.uploadBtn'),
  290. // 上传按钮
  291. $filePickerBtn = $wrap.find('.filePickerBtn'),
  292. // 上传按钮
  293. $filePickerBlock = $wrap.find('.filePickerBlock'),
  294. // 没选择文件之前的内容。
  295. $placeHolder = $wrap.find('.placeholder'),
  296. // 总体进度条
  297. $progress = $statusBar.find('.progress').hide(),
  298. // 添加的文件数量
  299. fileCount = 0,
  300. // 添加的文件总大小
  301. fileSize = 0,
  302. // 优化retina, 在retina下这个值是2
  303. ratio = window.devicePixelRatio || 1,
  304. // 缩略图大小
  305. thumbnailWidth = 113 * ratio,
  306. thumbnailHeight = 113 * ratio,
  307. // 可能有pedding, ready, uploading, confirm, done.
  308. state = '',
  309. // 所有文件的进度信息,key为file id
  310. percentages = {},
  311. supportTransition = (function () {
  312. var s = document.createElement('p').style,
  313. r = 'transition' in s ||
  314. 'WebkitTransition' in s ||
  315. 'MozTransition' in s ||
  316. 'msTransition' in s ||
  317. 'OTransition' in s;
  318. s = null;
  319. return r;
  320. })(),
  321. // WebUploader实例
  322. uploader,
  323. actionUrl = editor.getActionUrl(editor.getOpt('imageActionName')),
  324. acceptExtensions = (editor.getOpt('imageAllowFiles') || []).join('').replace(/\./g, ',').replace(/^[,]/, ''),
  325. imageMaxSize = editor.getOpt('imageMaxSize'),
  326. imageCompressBorder = editor.getOpt('imageCompressBorder');
  327. if (!WebUploader.Uploader.support()) {
  328. $('#filePickerReady').after($('<div>').html(lang.errorNotSupport)).hide();
  329. return;
  330. } else if (!editor.getOpt('imageActionName')) {
  331. $('#filePickerReady').after($('<div>').html(lang.errorLoadConfig)).hide();
  332. return;
  333. }
  334. uploader = _this.uploader = WebUploader.create({
  335. pick: {
  336. id: '#filePickerReady',
  337. label: lang.uploadSelectFile
  338. },
  339. accept: {
  340. title: 'Images',
  341. extensions: acceptExtensions,
  342. mimeTypes: 'image/*'
  343. },
  344. swf: '../../third-party/webuploader/Uploader.swf',
  345. server: actionUrl,
  346. fileVal: editor.getOpt('imageFieldName'),
  347. duplicate: true,
  348. fileSingleSizeLimit: imageMaxSize, // 默认 2 M
  349. compress: editor.getOpt('imageCompressEnable') ? {
  350. width: imageCompressBorder,
  351. height: imageCompressBorder,
  352. // 图片质量,只有type为`image/jpeg`的时候才有效。
  353. quality: 90,
  354. // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
  355. allowMagnify: false,
  356. // 是否允许裁剪。
  357. crop: false,
  358. // 是否保留头部meta信息。
  359. preserveHeaders: true
  360. }:false
  361. });
  362. uploader.addButton({
  363. id: '#filePickerBlock'
  364. });
  365. uploader.addButton({
  366. id: '#filePickerBtn',
  367. label: lang.uploadAddFile
  368. });
  369. setState('pedding');
  370. // 当有文件添加进来时执行,负责view的创建
  371. function addFile(file) {
  372. var $li = $('<li id="' + file.id + '">' +
  373. '<p class="title">' + file.name + '</p>' +
  374. '<p class="imgWrap"></p>' +
  375. '<p class="progress"><span></span></p>' +
  376. '</li>'),
  377. $btns = $('<div class="file-panel">' +
  378. '<span class="cancel">' + lang.uploadDelete + '</span>' +
  379. '<span class="rotateRight">' + lang.uploadTurnRight + '</span>' +
  380. '<span class="rotateLeft">' + lang.uploadTurnLeft + '</span></div>').appendTo($li),
  381. $prgress = $li.find('p.progress span'),
  382. $wrap = $li.find('p.imgWrap'),
  383. $info = $('<p class="error"></p>').hide().appendTo($li),
  384. showError = function (code) {
  385. switch (code) {
  386. case 'exceed_size':
  387. text = lang.errorExceedSize;
  388. break;
  389. case 'interrupt':
  390. text = lang.errorInterrupt;
  391. break;
  392. case 'http':
  393. text = lang.errorHttp;
  394. break;
  395. case 'not_allow_type':
  396. text = lang.errorFileType;
  397. break;
  398. default:
  399. text = lang.errorUploadRetry;
  400. break;
  401. }
  402. $info.text(text).show();
  403. };
  404. if (file.getStatus() === 'invalid') {
  405. showError(file.statusText);
  406. } else {
  407. $wrap.text(lang.uploadPreview);
  408. if (browser.ie && browser.version <= 7) {
  409. $wrap.text(lang.uploadNoPreview);
  410. } else {
  411. uploader.makeThumb(file, function (error, src) {
  412. if (error || !src) {
  413. $wrap.text(lang.uploadNoPreview);
  414. } else {
  415. var $img = $('<img src="' + src + '">');
  416. $wrap.empty().append($img);
  417. $img.on('error', function () {
  418. $wrap.text(lang.uploadNoPreview);
  419. });
  420. }
  421. }, thumbnailWidth, thumbnailHeight);
  422. }
  423. percentages[ file.id ] = [ file.size, 0 ];
  424. file.rotation = 0;
  425. /* 检查文件格式 */
  426. if (!file.ext || acceptExtensions.indexOf(file.ext.toLowerCase()) == -1) {
  427. showError('not_allow_type');
  428. uploader.removeFile(file);
  429. }
  430. }
  431. file.on('statuschange', function (cur, prev) {
  432. if (prev === 'progress') {
  433. $prgress.hide().width(0);
  434. } else if (prev === 'queued') {
  435. $li.off('mouseenter mouseleave');
  436. $btns.remove();
  437. }
  438. // 成功
  439. if (cur === 'error' || cur === 'invalid') {
  440. showError(file.statusText);
  441. percentages[ file.id ][ 1 ] = 1;
  442. } else if (cur === 'interrupt') {
  443. showError('interrupt');
  444. } else if (cur === 'queued') {
  445. percentages[ file.id ][ 1 ] = 0;
  446. } else if (cur === 'progress') {
  447. $info.hide();
  448. $prgress.css('display', 'block');
  449. } else if (cur === 'complete') {
  450. }
  451. $li.removeClass('state-' + prev).addClass('state-' + cur);
  452. });
  453. $li.on('mouseenter', function () {
  454. $btns.stop().animate({height: 30});
  455. });
  456. $li.on('mouseleave', function () {
  457. $btns.stop().animate({height: 0});
  458. });
  459. $btns.on('click', 'span', function () {
  460. var index = $(this).index(),
  461. deg;
  462. switch (index) {
  463. case 0:
  464. uploader.removeFile(file);
  465. return;
  466. case 1:
  467. file.rotation += 90;
  468. break;
  469. case 2:
  470. file.rotation -= 90;
  471. break;
  472. }
  473. if (supportTransition) {
  474. deg = 'rotate(' + file.rotation + 'deg)';
  475. $wrap.css({
  476. '-webkit-transform': deg,
  477. '-mos-transform': deg,
  478. '-o-transform': deg,
  479. 'transform': deg
  480. });
  481. } else {
  482. $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
  483. }
  484. });
  485. $li.insertBefore($filePickerBlock);
  486. }
  487. // 负责view的销毁
  488. function removeFile(file) {
  489. var $li = $('#' + file.id);
  490. delete percentages[ file.id ];
  491. updateTotalProgress();
  492. $li.off().find('.file-panel').off().end().remove();
  493. }
  494. function updateTotalProgress() {
  495. var loaded = 0,
  496. total = 0,
  497. spans = $progress.children(),
  498. percent;
  499. $.each(percentages, function (k, v) {
  500. total += v[ 0 ];
  501. loaded += v[ 0 ] * v[ 1 ];
  502. });
  503. percent = total ? loaded / total : 0;
  504. spans.eq(0).text(Math.round(percent * 100) + '%');
  505. spans.eq(1).css('width', Math.round(percent * 100) + '%');
  506. updateStatus();
  507. }
  508. function setState(val, files) {
  509. if (val != state) {
  510. var stats = uploader.getStats();
  511. $upload.removeClass('state-' + state);
  512. $upload.addClass('state-' + val);
  513. switch (val) {
  514. /* 未选择文件 */
  515. case 'pedding':
  516. $queue.addClass('element-invisible');
  517. $statusBar.addClass('element-invisible');
  518. $placeHolder.removeClass('element-invisible');
  519. $progress.hide(); $info.hide();
  520. uploader.refresh();
  521. break;
  522. /* 可以开始上传 */
  523. case 'ready':
  524. $placeHolder.addClass('element-invisible');
  525. $queue.removeClass('element-invisible');
  526. $statusBar.removeClass('element-invisible');
  527. $progress.hide(); $info.show();
  528. $upload.text(lang.uploadStart);
  529. uploader.refresh();
  530. break;
  531. /* 上传中 */
  532. case 'uploading':
  533. $progress.show(); $info.hide();
  534. $upload.text(lang.uploadPause);
  535. break;
  536. /* 暂停上传 */
  537. case 'paused':
  538. $progress.show(); $info.hide();
  539. $upload.text(lang.uploadContinue);
  540. break;
  541. case 'confirm':
  542. $progress.show(); $info.hide();
  543. $upload.text(lang.uploadStart);
  544. stats = uploader.getStats();
  545. if (stats.successNum && !stats.uploadFailNum) {
  546. setState('finish');
  547. return;
  548. }
  549. break;
  550. case 'finish':
  551. $progress.hide(); $info.show();
  552. if (stats.uploadFailNum) {
  553. $upload.text(lang.uploadRetry);
  554. } else {
  555. $upload.text(lang.uploadStart);
  556. }
  557. break;
  558. }
  559. state = val;
  560. updateStatus();
  561. }
  562. if (!_this.getQueueCount()) {
  563. $upload.addClass('disabled')
  564. } else {
  565. $upload.removeClass('disabled')
  566. }
  567. }
  568. function updateStatus() {
  569. var text = '', stats;
  570. if (state === 'ready') {
  571. text = lang.updateStatusReady.replace('_', fileCount).replace('_KB', WebUploader.formatSize(fileSize));
  572. } else if (state === 'confirm') {
  573. stats = uploader.getStats();
  574. if (stats.uploadFailNum) {
  575. text = lang.updateStatusConfirm.replace('_', stats.successNum).replace('_', stats.successNum);
  576. }
  577. } else {
  578. stats = uploader.getStats();
  579. text = lang.updateStatusFinish.replace('_', fileCount).
  580. replace('_KB', WebUploader.formatSize(fileSize)).
  581. replace('_', stats.successNum);
  582. if (stats.uploadFailNum) {
  583. text += lang.updateStatusError.replace('_', stats.uploadFailNum);
  584. }
  585. }
  586. $info.html(text);
  587. }
  588. uploader.on('fileQueued', function (file) {
  589. fileCount++;
  590. fileSize += file.size;
  591. if (fileCount === 1) {
  592. $placeHolder.addClass('element-invisible');
  593. $statusBar.show();
  594. }
  595. addFile(file);
  596. });
  597. uploader.on('fileDequeued', function (file) {
  598. fileCount--;
  599. fileSize -= file.size;
  600. removeFile(file);
  601. updateTotalProgress();
  602. });
  603. uploader.on('filesQueued', function (file) {
  604. if (!uploader.isInProgress() && (state == 'pedding' || state == 'finish' || state == 'confirm' || state == 'ready')) {
  605. setState('ready');
  606. }
  607. updateTotalProgress();
  608. });
  609. uploader.on('all', function (type, files) {
  610. switch (type) {
  611. case 'uploadFinished':
  612. setState('confirm', files);
  613. break;
  614. case 'startUpload':
  615. /* 添加额外的GET参数 */
  616. var params = utils.serializeParam(editor.queryCommandValue('serverparam')) || '',
  617. url = utils.formatUrl(actionUrl + (actionUrl.indexOf('?') == -1 ? '?':'&') + 'encode=utf-8&' + params);
  618. uploader.option('server', url);
  619. setState('uploading', files);
  620. break;
  621. case 'stopUpload':
  622. setState('paused', files);
  623. break;
  624. }
  625. });
  626. uploader.on('uploadBeforeSend', function (file, data, header) {
  627. //这里可以通过data对象添加POST参数
  628. if (actionUrl.toLowerCase().indexOf('jsp') != -1) {
  629. header['X_Requested_With'] = 'XMLHttpRequest';
  630. }
  631. });
  632. uploader.on('uploadProgress', function (file, percentage) {
  633. var $li = $('#' + file.id),
  634. $percent = $li.find('.progress span');
  635. $percent.css('width', percentage * 100 + '%');
  636. percentages[ file.id ][ 1 ] = percentage;
  637. updateTotalProgress();
  638. });
  639. uploader.on('uploadSuccess', function (file, ret) {
  640. var $file = $('#' + file.id);
  641. try {
  642. var responseText = (ret._raw || ret),
  643. json = utils.str2json(responseText);
  644. if (json.state == 'SUCCESS') {
  645. _this.imageList.push(json);
  646. $file.append('<span class="success"></span>');
  647. } else {
  648. $file.find('.error').text(json.state).show();
  649. }
  650. } catch (e) {
  651. $file.find('.error').text(lang.errorServerUpload).show();
  652. }
  653. });
  654. uploader.on('uploadError', function (file, code) {
  655. });
  656. uploader.on('error', function (code, file) {
  657. if (code == 'Q_TYPE_DENIED' || code == 'F_EXCEED_SIZE') {
  658. addFile(file);
  659. }
  660. });
  661. uploader.on('uploadComplete', function (file, ret) {
  662. });
  663. $upload.on('click', function () {
  664. if ($(this).hasClass('disabled')) {
  665. return false;
  666. }
  667. if (state === 'ready') {
  668. uploader.upload();
  669. } else if (state === 'paused') {
  670. uploader.upload();
  671. } else if (state === 'uploading') {
  672. uploader.stop();
  673. }
  674. });
  675. $upload.addClass('state-' + state);
  676. updateTotalProgress();
  677. },
  678. getQueueCount: function () {
  679. var file, i, status, readyFile = 0, files = this.uploader.getFiles();
  680. for (i = 0; file = files[i++]; ) {
  681. status = file.getStatus();
  682. if (status == 'queued' || status == 'uploading' || status == 'progress') readyFile++;
  683. }
  684. return readyFile;
  685. },
  686. destroy: function () {
  687. this.$wrap.remove();
  688. },
  689. getInsertList: function () {
  690. var i, data, list = [],
  691. align = getAlign(),
  692. prefix = editor.getOpt('imageUrlPrefix');
  693. for (i = 0; i < this.imageList.length; i++) {
  694. data = this.imageList[i];
  695. list.push({
  696. src: prefix + data.url,
  697. _src: prefix + data.url,
  698. alt: data.original,
  699. floatStyle: align
  700. });
  701. }
  702. return list;
  703. }
  704. };
  705. /* 在线图片 */
  706. function OnlineImage(target) {
  707. this.container = utils.isString(target) ? document.getElementById(target) : target;
  708. this.init();
  709. }
  710. OnlineImage.prototype = {
  711. init: function () {
  712. this.reset();
  713. this.initEvents();
  714. },
  715. /* 初始化容器 */
  716. initContainer: function () {
  717. this.container.innerHTML = '';
  718. this.list = document.createElement('ul');
  719. this.clearFloat = document.createElement('li');
  720. domUtils.addClass(this.list, 'list');
  721. domUtils.addClass(this.clearFloat, 'clearFloat');
  722. this.list.appendChild(this.clearFloat);
  723. this.container.appendChild(this.list);
  724. },
  725. /* 初始化滚动事件,滚动到地步自动拉取数据 */
  726. initEvents: function () {
  727. var _this = this;
  728. /* 滚动拉取图片 */
  729. domUtils.on($G('imageList'), 'scroll', function(e){
  730. var panel = this;
  731. if (panel.scrollHeight - (panel.offsetHeight + panel.scrollTop) < 10) {
  732. _this.getImageData();
  733. }
  734. });
  735. /* 选中图片 */
  736. domUtils.on(this.container, 'click', function (e) {
  737. var target = e.target || e.srcElement,
  738. li = target.parentNode;
  739. if (li.tagName.toLowerCase() == 'li') {
  740. if (domUtils.hasClass(li, 'selected')) {
  741. domUtils.removeClasses(li, 'selected');
  742. } else {
  743. domUtils.addClass(li, 'selected');
  744. }
  745. }
  746. });
  747. },
  748. /* 初始化第一次的数据 */
  749. initData: function () {
  750. /* 拉取数据需要使用的值 */
  751. this.state = 0;
  752. this.listSize = editor.getOpt('imageManagerListSize');
  753. this.listIndex = 0;
  754. this.listEnd = false;
  755. /* 第一次拉取数据 */
  756. this.getImageData();
  757. },
  758. /* 重置界面 */
  759. reset: function() {
  760. this.initContainer();
  761. this.initData();
  762. },
  763. /* 向后台拉取图片列表数据 */
  764. getImageData: function () {
  765. var _this = this;
  766. if(!_this.listEnd && !this.isLoadingData) {
  767. this.isLoadingData = true;
  768. var url = editor.getActionUrl(editor.getOpt('imageManagerActionName')),
  769. isJsonp = utils.isCrossDomainUrl(url);
  770. ajax.request(url, {
  771. 'timeout': 100000,
  772. 'dataType': isJsonp ? 'jsonp':'',
  773. 'data': utils.extend({
  774. start: this.listIndex,
  775. size: this.listSize
  776. }, editor.queryCommandValue('serverparam')),
  777. 'method': 'get',
  778. 'onsuccess': function (r) {
  779. try {
  780. var json = isJsonp ? r:eval('(' + r.responseText + ')');
  781. if (json.state == 'SUCCESS') {
  782. _this.pushData(json.list);
  783. _this.listIndex = parseInt(json.start) + parseInt(json.list.length);
  784. if(_this.listIndex >= json.total) {
  785. _this.listEnd = true;
  786. }
  787. _this.isLoadingData = false;
  788. }
  789. } catch (e) {
  790. if(r.responseText.indexOf('ue_separate_ue') != -1) {
  791. var list = r.responseText.split(r.responseText);
  792. _this.pushData(list);
  793. _this.listIndex = parseInt(list.length);
  794. _this.listEnd = true;
  795. _this.isLoadingData = false;
  796. }
  797. }
  798. },
  799. 'onerror': function () {
  800. _this.isLoadingData = false;
  801. }
  802. });
  803. }
  804. },
  805. /* 添加图片到列表界面上 */
  806. pushData: function (list) {
  807. var i, item, img, icon, _this = this,
  808. urlPrefix = editor.getOpt('imageManagerUrlPrefix');
  809. for (i = 0; i < list.length; i++) {
  810. if(list[i] && list[i].url) {
  811. item = document.createElement('li');
  812. img = document.createElement('img');
  813. icon = document.createElement('span');
  814. domUtils.on(img, 'load', (function(image){
  815. return function(){
  816. _this.scale(image, image.parentNode.offsetWidth, image.parentNode.offsetHeight);
  817. }
  818. })(img));
  819. img.width = 113;
  820. img.setAttribute('src', urlPrefix + list[i].url + (list[i].url.indexOf('?') == -1 ? '?noCache=':'&noCache=') + (+new Date()).toString(36) );
  821. img.setAttribute('_src', urlPrefix + list[i].url);
  822. domUtils.addClass(icon, 'icon');
  823. item.appendChild(img);
  824. item.appendChild(icon);
  825. this.list.insertBefore(item, this.clearFloat);
  826. }
  827. }
  828. },
  829. /* 改变图片大小 */
  830. scale: function (img, w, h, type) {
  831. var ow = img.width,
  832. oh = img.height;
  833. if (type == 'justify') {
  834. if (ow >= oh) {
  835. img.width = w;
  836. img.height = h * oh / ow;
  837. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  838. } else {
  839. img.width = w * ow / oh;
  840. img.height = h;
  841. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  842. }
  843. } else {
  844. if (ow >= oh) {
  845. img.width = w * ow / oh;
  846. img.height = h;
  847. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  848. } else {
  849. img.width = w;
  850. img.height = h * oh / ow;
  851. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  852. }
  853. }
  854. },
  855. getInsertList: function () {
  856. var i, lis = this.list.children, list = [], align = getAlign();
  857. for (i = 0; i < lis.length; i++) {
  858. if (domUtils.hasClass(lis[i], 'selected')) {
  859. var img = lis[i].firstChild,
  860. src = img.getAttribute('_src');
  861. list.push({
  862. src: src,
  863. _src: src,
  864. alt: src.substr(src.lastIndexOf('/') + 1),
  865. floatStyle: align
  866. });
  867. }
  868. }
  869. return list;
  870. }
  871. };
  872. /*搜索图片 */
  873. function SearchImage() {
  874. this.init();
  875. }
  876. SearchImage.prototype = {
  877. init: function () {
  878. this.initEvents();
  879. },
  880. initEvents: function(){
  881. var _this = this;
  882. /* 点击搜索按钮 */
  883. domUtils.on($G('searchBtn'), 'click', function(){
  884. var key = $G('searchTxt').value;
  885. if(key && key != lang.searchRemind) {
  886. _this.getImageData();
  887. }
  888. });
  889. /* 点击清除妞 */
  890. domUtils.on($G('searchReset'), 'click', function(){
  891. $G('searchTxt').value = lang.searchRemind;
  892. $G('searchListUl').innerHTML = '';
  893. $G('searchType').selectedIndex = 0;
  894. });
  895. /* 搜索框聚焦 */
  896. domUtils.on($G('searchTxt'), 'focus', function(){
  897. var key = $G('searchTxt').value;
  898. if(key && key == lang.searchRemind) {
  899. $G('searchTxt').value = '';
  900. }
  901. });
  902. /* 搜索框回车键搜索 */
  903. domUtils.on($G('searchTxt'), 'keydown', function(e){
  904. var keyCode = e.keyCode || e.which;
  905. if (keyCode == 13) {
  906. $G('searchBtn').click();
  907. }
  908. });
  909. /* 选中图片 */
  910. domUtils.on($G('searchList'), 'click', function(e){
  911. var target = e.target || e.srcElement,
  912. li = target.parentNode.parentNode;
  913. if (li.tagName.toLowerCase() == 'li') {
  914. if (domUtils.hasClass(li, 'selected')) {
  915. domUtils.removeClasses(li, 'selected');
  916. } else {
  917. domUtils.addClass(li, 'selected');
  918. }
  919. }
  920. });
  921. },
  922. /* 改变图片大小 */
  923. scale: function (img, w, h) {
  924. var ow = img.width,
  925. oh = img.height;
  926. if (ow >= oh) {
  927. img.width = w * ow / oh;
  928. img.height = h;
  929. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  930. } else {
  931. img.width = w;
  932. img.height = h * oh / ow;
  933. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  934. }
  935. },
  936. getImageData: function(){
  937. var _this = this,
  938. key = $G('searchTxt').value,
  939. type = $G('searchType').value,
  940. keepOriginName = editor.options.keepOriginName ? "1" : "0",
  941. url = "http://image.baidu.com/i?ct=201326592&cl=2&lm=-1&st=-1&tn=baiduimagejson&istype=2&rn=32&fm=index&pv=&word=" + key + type + "&ie=utf-8&oe=utf-8&keeporiginname=" + keepOriginName + "&" + +new Date;
  942. $G('searchListUl').innerHTML = lang.searchLoading;
  943. ajax.request(url, {
  944. 'dataType': 'jsonp',
  945. 'charset': 'GB18030',
  946. 'onsuccess':function(json){
  947. var list = [];
  948. if(json && json.data) {
  949. for(var i = 0; i < json.data.length; i++) {
  950. if(json.data[i].objURL) {
  951. list.push({
  952. title: json.data[i].fromPageTitleEnc,
  953. src: json.data[i].objURL,
  954. url: json.data[i].fromURL
  955. });
  956. }
  957. }
  958. }
  959. _this.setList(list);
  960. },
  961. 'onerror':function(){
  962. $G('searchListUl').innerHTML = lang.searchRetry;
  963. }
  964. });
  965. },
  966. /* 添加图片到列表界面上 */
  967. setList: function (list) {
  968. var i, item, p, img, link, _this = this,
  969. listUl = $G('searchListUl');
  970. listUl.innerHTML = '';
  971. if(list.length) {
  972. for (i = 0; i < list.length; i++) {
  973. item = document.createElement('li');
  974. p = document.createElement('p');
  975. img = document.createElement('img');
  976. link = document.createElement('a');
  977. img.onload = function () {
  978. _this.scale(this, 113, 113);
  979. };
  980. img.width = 113;
  981. img.setAttribute('src', list[i].src);
  982. link.href = list[i].url;
  983. link.target = '_blank';
  984. link.title = list[i].title;
  985. link.innerHTML = list[i].title;
  986. p.appendChild(img);
  987. item.appendChild(p);
  988. item.appendChild(link);
  989. listUl.appendChild(item);
  990. }
  991. } else {
  992. listUl.innerHTML = lang.searchRetry;
  993. }
  994. },
  995. getInsertList: function () {
  996. var child,
  997. src,
  998. align = getAlign(),
  999. list = [],
  1000. items = $G('searchListUl').children;
  1001. for(var i = 0; i < items.length; i++) {
  1002. child = items[i].firstChild && items[i].firstChild.firstChild;
  1003. if(child.tagName && child.tagName.toLowerCase() == 'img' && domUtils.hasClass(items[i], 'selected')) {
  1004. src = child.src;
  1005. list.push({
  1006. src: src,
  1007. _src: src,
  1008. alt: src.substr(src.lastIndexOf('/') + 1),
  1009. floatStyle: align
  1010. });
  1011. }
  1012. }
  1013. return list;
  1014. }
  1015. };
  1016. })();