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

1140 lines
125 KiB

8 years ago
8 years ago
  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. title: data['title'] || '',
  256. alt: data['title'] || '',
  257. style: "width:" + data['width'] + "px;height:" + data['height'] + "px;"
  258. }];
  259. } else {
  260. return [];
  261. }
  262. }
  263. };
  264. /* 上传图片 */
  265. function UploadImage(target) {
  266. this.$wrap = target.constructor == String ? $('#' + target) : $(target);
  267. this.init();
  268. }
  269. UploadImage.prototype = {
  270. init: function () {
  271. this.imageList = [];
  272. this.initContainer();
  273. this.initUploader();
  274. },
  275. initContainer: function () {
  276. this.$queue = this.$wrap.find('.filelist');
  277. },
  278. /* 初始化容器 */
  279. initUploader: function () {
  280. var _this = this,
  281. $ = jQuery, // just in case. Make sure it's not an other libaray.
  282. $wrap = _this.$wrap,
  283. // 图片容器
  284. $queue = $wrap.find('.filelist'),
  285. // 状态栏,包括进度和控制按钮
  286. $statusBar = $wrap.find('.statusBar'),
  287. // 文件总体选择信息。
  288. $info = $statusBar.find('.info'),
  289. // 上传按钮
  290. $upload = $wrap.find('.uploadBtn'),
  291. // 上传按钮
  292. $filePickerBtn = $wrap.find('.filePickerBtn'),
  293. // 上传按钮
  294. $filePickerBlock = $wrap.find('.filePickerBlock'),
  295. // 没选择文件之前的内容。
  296. $placeHolder = $wrap.find('.placeholder'),
  297. // 总体进度条
  298. $progress = $statusBar.find('.progress').hide(),
  299. // 添加的文件数量
  300. fileCount = 0,
  301. // 添加的文件总大小
  302. fileSize = 0,
  303. // 优化retina, 在retina下这个值是2
  304. ratio = window.devicePixelRatio || 1,
  305. // 缩略图大小
  306. thumbnailWidth = 113 * ratio,
  307. thumbnailHeight = 113 * ratio,
  308. // 可能有pedding, ready, uploading, confirm, done.
  309. state = '',
  310. // 所有文件的进度信息,key为file id
  311. percentages = {},
  312. supportTransition = (function () {
  313. var s = document.createElement('p').style,
  314. r = 'transition' in s ||
  315. 'WebkitTransition' in s ||
  316. 'MozTransition' in s ||
  317. 'msTransition' in s ||
  318. 'OTransition' in s;
  319. s = null;
  320. return r;
  321. })(),
  322. // WebUploader实例
  323. uploader,
  324. actionUrl = editor.getActionUrl(editor.getOpt('imageActionName')),
  325. acceptExtensions = (editor.getOpt('imageAllowFiles') || []).join('').replace(/\./g, ',').replace(/^[,]/, ''),
  326. imageMaxSize = editor.getOpt('imageMaxSize'),
  327. imageCompressBorder = editor.getOpt('imageCompressBorder');
  328. if (!WebUploader.Uploader.support()) {
  329. $('#filePickerReady').after($('<div>').html(lang.errorNotSupport)).hide();
  330. return;
  331. } else if (!editor.getOpt('imageActionName')) {
  332. $('#filePickerReady').after($('<div>').html(lang.errorLoadConfig)).hide();
  333. return;
  334. }
  335. uploader = _this.uploader = WebUploader.create({
  336. pick: {
  337. id: '#filePickerReady',
  338. label: lang.uploadSelectFile
  339. },
  340. accept: {
  341. title: 'Images',
  342. extensions: acceptExtensions,
  343. mimeTypes: 'image/gif,image/jpeg,image/png,image/jpg,image/bmp'
  344. //mimeTypes: 'image/*' //这个是自己注释掉的,用这个调用图片上传的时候会比较卡
  345. },
  346. swf: '../../third-party/webuploader/Uploader.swf',
  347. server: actionUrl,
  348. fileVal: editor.getOpt('imageFieldName'),
  349. duplicate: true,
  350. fileSingleSizeLimit: imageMaxSize, // 默认 2 M
  351. compress: editor.getOpt('imageCompressEnable') ? {
  352. width: imageCompressBorder,
  353. height: imageCompressBorder,
  354. // 图片质量,只有type为`image/jpeg`的时候才有效。
  355. quality: 90,
  356. // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
  357. allowMagnify: false,
  358. // 是否允许裁剪。
  359. crop: false,
  360. // 是否保留头部meta信息。
  361. preserveHeaders: true
  362. }:false
  363. });
  364. uploader.addButton({
  365. id: '#filePickerBlock'
  366. });
  367. uploader.addButton({
  368. id: '#filePickerBtn',
  369. label: lang.uploadAddFile
  370. });
  371. setState('pedding');
  372. // 当有文件添加进来时执行,负责view的创建
  373. function addFile(file) {
  374. var $li = $('<li id="' + file.id + '">' +
  375. '<p class="title">' + file.name + '</p>' +
  376. '<p class="imgWrap"></p>' +
  377. '<p class="progress"><span></span></p>' +
  378. '</li>'),
  379. $btns = $('<div class="file-panel">' +
  380. '<span class="cancel">' + lang.uploadDelete + '</span>' +
  381. '<span class="rotateRight">' + lang.uploadTurnRight + '</span>' +
  382. '<span class="rotateLeft">' + lang.uploadTurnLeft + '</span></div>').appendTo($li),
  383. $prgress = $li.find('p.progress span'),
  384. $wrap = $li.find('p.imgWrap'),
  385. $info = $('<p class="error"></p>').hide().appendTo($li),
  386. showError = function (code) {
  387. switch (code) {
  388. case 'exceed_size':
  389. text = lang.errorExceedSize;
  390. break;
  391. case 'interrupt':
  392. text = lang.errorInterrupt;
  393. break;
  394. case 'http':
  395. text = lang.errorHttp;
  396. break;
  397. case 'not_allow_type':
  398. text = lang.errorFileType;
  399. break;
  400. default:
  401. text = lang.errorUploadRetry;
  402. break;
  403. }
  404. $info.text(text).show();
  405. };
  406. if (file.getStatus() === 'invalid') {
  407. showError(file.statusText);
  408. } else {
  409. $wrap.text(lang.uploadPreview);
  410. if (browser.ie && browser.version <= 7) {
  411. $wrap.text(lang.uploadNoPreview);
  412. } else {
  413. uploader.makeThumb(file, function (error, src) {
  414. if (error || !src) {
  415. $wrap.text(lang.uploadNoPreview);
  416. } else {
  417. var $img = $('<img src="' + src + '">');
  418. $wrap.empty().append($img);
  419. $img.on('error', function () {
  420. $wrap.text(lang.uploadNoPreview);
  421. });
  422. }
  423. }, thumbnailWidth, thumbnailHeight);
  424. }
  425. percentages[ file.id ] = [ file.size, 0 ];
  426. file.rotation = 0;
  427. /* 检查文件格式 */
  428. if (!file.ext || acceptExtensions.indexOf(file.ext.toLowerCase()) == -1) {
  429. showError('not_allow_type');
  430. uploader.removeFile(file);
  431. }
  432. }
  433. file.on('statuschange', function (cur, prev) {
  434. if (prev === 'progress') {
  435. $prgress.hide().width(0);
  436. } else if (prev === 'queued') {
  437. $li.off('mouseenter mouseleave');
  438. $btns.remove();
  439. }
  440. // 成功
  441. if (cur === 'error' || cur === 'invalid') {
  442. showError(file.statusText);
  443. percentages[ file.id ][ 1 ] = 1;
  444. } else if (cur === 'interrupt') {
  445. showError('interrupt');
  446. } else if (cur === 'queued') {
  447. percentages[ file.id ][ 1 ] = 0;
  448. } else if (cur === 'progress') {
  449. $info.hide();
  450. $prgress.css('display', 'block');
  451. } else if (cur === 'complete') {
  452. }
  453. $li.removeClass('state-' + prev).addClass('state-' + cur);
  454. });
  455. $li.on('mouseenter', function () {
  456. $btns.stop().animate({height: 30});
  457. });
  458. $li.on('mouseleave', function () {
  459. $btns.stop().animate({height: 0});
  460. });
  461. $btns.on('click', 'span', function () {
  462. var index = $(this).index(),
  463. deg;
  464. switch (index) {
  465. case 0:
  466. uploader.removeFile(file);
  467. return;
  468. case 1:
  469. file.rotation += 90;
  470. break;
  471. case 2:
  472. file.rotation -= 90;
  473. break;
  474. }
  475. if (supportTransition) {
  476. deg = 'rotate(' + file.rotation + 'deg)';
  477. $wrap.css({
  478. '-webkit-transform': deg,
  479. '-mos-transform': deg,
  480. '-o-transform': deg,
  481. 'transform': deg
  482. });
  483. } else {
  484. $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
  485. }
  486. });
  487. $li.insertBefore($filePickerBlock);
  488. }
  489. // 负责view的销毁
  490. function removeFile(file) {
  491. var $li = $('#' + file.id);
  492. delete percentages[ file.id ];
  493. updateTotalProgress();
  494. $li.off().find('.file-panel').off().end().remove();
  495. }
  496. function updateTotalProgress() {
  497. var loaded = 0,
  498. total = 0,
  499. spans = $progress.children(),
  500. percent;
  501. $.each(percentages, function (k, v) {
  502. total += v[ 0 ];
  503. loaded += v[ 0 ] * v[ 1 ];
  504. });
  505. percent = total ? loaded / total : 0;
  506. spans.eq(0).text(Math.round(percent * 100) + '%');
  507. spans.eq(1).css('width', Math.round(percent * 100) + '%');
  508. updateStatus();
  509. }
  510. function setState(val, files) {
  511. if (val != state) {
  512. var stats = uploader.getStats();
  513. $upload.removeClass('state-' + state);
  514. $upload.addClass('state-' + val);
  515. switch (val) {
  516. /* 未选择文件 */
  517. case 'pedding':
  518. $queue.addClass('element-invisible');
  519. $statusBar.addClass('element-invisible');
  520. $placeHolder.removeClass('element-invisible');
  521. $progress.hide(); $info.hide();
  522. uploader.refresh();
  523. break;
  524. /* 可以开始上传 */
  525. case 'ready':
  526. $placeHolder.addClass('element-invisible');
  527. $queue.removeClass('element-invisible');
  528. $statusBar.removeClass('element-invisible');
  529. $progress.hide(); $info.show();
  530. $upload.text(lang.uploadStart);
  531. uploader.refresh();
  532. break;
  533. /* 上传中 */
  534. case 'uploading':
  535. $progress.show(); $info.hide();
  536. $upload.text(lang.uploadPause);
  537. break;
  538. /* 暂停上传 */
  539. case 'paused':
  540. $progress.show(); $info.hide();
  541. $upload.text(lang.uploadContinue);
  542. break;
  543. case 'confirm':
  544. $progress.show(); $info.hide();
  545. $upload.text(lang.uploadStart);
  546. stats = uploader.getStats();
  547. if (stats.successNum && !stats.uploadFailNum) {
  548. setState('finish');
  549. return;
  550. }
  551. break;
  552. case 'finish':
  553. $progress.hide(); $info.show();
  554. if (stats.uploadFailNum) {
  555. $upload.text(lang.uploadRetry);
  556. } else {
  557. $upload.text(lang.uploadStart);
  558. }
  559. break;
  560. }
  561. state = val;
  562. updateStatus();
  563. }
  564. if (!_this.getQueueCount()) {
  565. $upload.addClass('disabled')
  566. } else {
  567. $upload.removeClass('disabled')
  568. }
  569. }
  570. function updateStatus() {
  571. var text = '', stats;
  572. if (state === 'ready') {
  573. text = lang.updateStatusReady.replace('_', fileCount).replace('_KB', WebUploader.formatSize(fileSize));
  574. } else if (state === 'confirm') {
  575. stats = uploader.getStats();
  576. if (stats.uploadFailNum) {
  577. text = lang.updateStatusConfirm.replace('_', stats.successNum).replace('_', stats.successNum);
  578. }
  579. } else {
  580. stats = uploader.getStats();
  581. text = lang.updateStatusFinish.replace('_', fileCount).
  582. replace('_KB', WebUploader.formatSize(fileSize)).
  583. replace('_', stats.successNum);
  584. if (stats.uploadFailNum) {
  585. text += lang.updateStatusError.replace('_', stats.uploadFailNum);
  586. }
  587. }
  588. $info.html(text);
  589. }
  590. uploader.on('fileQueued', function (file) {
  591. fileCount++;
  592. fileSize += file.size;
  593. if (fileCount === 1) {
  594. $placeHolder.addClass('element-invisible');
  595. $statusBar.show();
  596. }
  597. addFile(file);
  598. });
  599. uploader.on('fileDequeued', function (file) {
  600. fileCount--;
  601. fileSize -= file.size;
  602. removeFile(file);
  603. updateTotalProgress();
  604. });
  605. uploader.on('filesQueued', function (file) {
  606. if (!uploader.isInProgress() && (state == 'pedding' || state == 'finish' || state == 'confirm' || state == 'ready')) {
  607. setState('ready');
  608. }
  609. updateTotalProgress();
  610. });
  611. uploader.on('all', function (type, files) {
  612. switch (type) {
  613. case 'uploadFinished':
  614. setState('confirm', files);
  615. break;
  616. case 'startUpload':
  617. /* 添加额外的GET参数 */
  618. var params = utils.serializeParam(editor.queryCommandValue('serverparam')) || '',
  619. url = utils.formatUrl(actionUrl + (actionUrl.indexOf('?') == -1 ? '?':'&') + 'encode=utf-8&' + params);
  620. uploader.option('server', url);
  621. setState('uploading', files);
  622. break;
  623. case 'stopUpload':
  624. setState('paused', files);
  625. break;
  626. }
  627. });
  628. uploader.on('uploadBeforeSend', function (file, data, header) {
  629. //这里可以通过data对象添加POST参数
  630. header['X_Requested_With'] = 'XMLHttpRequest';
  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. title: data.title,
  699. alt: data.original,
  700. floatStyle: align
  701. });
  702. }
  703. return list;
  704. }
  705. };
  706. /* 在线图片 */
  707. function OnlineImage(target) {
  708. this.container = utils.isString(target) ? document.getElementById(target) : target;
  709. this.init();
  710. }
  711. OnlineImage.prototype = {
  712. init: function () {
  713. this.reset();
  714. this.initEvents();
  715. },
  716. /* 初始化容器 */
  717. initContainer: function () {
  718. this.container.innerHTML = '';
  719. this.list = document.createElement('ul');
  720. this.clearFloat = document.createElement('li');
  721. domUtils.addClass(this.list, 'list');
  722. domUtils.addClass(this.clearFloat, 'clearFloat');
  723. this.list.appendChild(this.clearFloat);
  724. this.container.appendChild(this.list);
  725. },
  726. /* 初始化滚动事件,滚动到地步自动拉取数据 */
  727. initEvents: function () {
  728. var _this = this;
  729. /* 滚动拉取图片 */
  730. domUtils.on($G('imageList'), 'scroll', function(e){
  731. var panel = this;
  732. if (panel.scrollHeight - (panel.offsetHeight + panel.scrollTop) < 10) {
  733. _this.getImageData();
  734. }
  735. });
  736. /* 选中图片 */
  737. domUtils.on(this.container, 'click', function (e) {
  738. var target = e.target || e.srcElement,
  739. li = target.parentNode;
  740. if (li.tagName.toLowerCase() == 'li') {
  741. if (domUtils.hasClass(li, 'selected')) {
  742. domUtils.removeClasses(li, 'selected');
  743. } else {
  744. domUtils.addClass(li, 'selected');
  745. }
  746. }
  747. });
  748. },
  749. /* 初始化第一次的数据 */
  750. initData: function () {
  751. /* 拉取数据需要使用的值 */
  752. this.state = 0;
  753. this.listSize = editor.getOpt('imageManagerListSize');
  754. this.listIndex = 0;
  755. this.listEnd = false;
  756. /* 第一次拉取数据 */
  757. this.getImageData();
  758. },
  759. /* 重置界面 */
  760. reset: function() {
  761. this.initContainer();
  762. this.initData();
  763. },
  764. /* 向后台拉取图片列表数据 */
  765. getImageData: function () {
  766. var _this = this;
  767. if(!_this.listEnd && !this.isLoadingData) {
  768. this.isLoadingData = true;
  769. var url = editor.getActionUrl(editor.getOpt('imageManagerActionName')),
  770. isJsonp = utils.isCrossDomainUrl(url);
  771. ajax.request(url, {
  772. 'timeout': 100000,
  773. 'dataType': isJsonp ? 'jsonp':'',
  774. 'data': utils.extend({
  775. start: this.listIndex,
  776. size: this.listSize
  777. }, editor.queryCommandValue('serverparam')),
  778. 'method': 'get',
  779. 'onsuccess': function (r) {
  780. try {
  781. var json = isJsonp ? r:eval('(' + r.responseText + ')');
  782. if (json.state == 'SUCCESS') {
  783. _this.pushData(json.list);
  784. _this.listIndex = parseInt(json.start) + parseInt(json.list.length);
  785. if(_this.listIndex >= json.total) {
  786. _this.listEnd = true;
  787. }
  788. _this.isLoadingData = false;
  789. }
  790. } catch (e) {
  791. if(r.responseText.indexOf('ue_separate_ue') != -1) {
  792. var list = r.responseText.split(r.responseText);
  793. _this.pushData(list);
  794. _this.listIndex = parseInt(list.length);
  795. _this.listEnd = true;
  796. _this.isLoadingData = false;
  797. }
  798. }
  799. },
  800. 'onerror': function () {
  801. _this.isLoadingData = false;
  802. }
  803. });
  804. }
  805. },
  806. /* 添加图片到列表界面上 */
  807. pushData: function (list) {
  808. var i, item, img, icon, _this = this,
  809. urlPrefix = editor.getOpt('imageManagerUrlPrefix');
  810. for (i = 0; i < list.length; i++) {
  811. if(list[i] && list[i].url) {
  812. item = document.createElement('li');
  813. img = document.createElement('img');
  814. icon = document.createElement('span');
  815. domUtils.on(img, 'load', (function(image){
  816. return function(){
  817. _this.scale(image, image.parentNode.offsetWidth, image.parentNode.offsetHeight);
  818. }
  819. })(img));
  820. img.width = 113;
  821. img.setAttribute('src', urlPrefix + list[i].url + (list[i].url.indexOf('?') == -1 ? '?noCache=':'&noCache=') + (+new Date()).toString(36) );
  822. img.setAttribute('_src', urlPrefix + list[i].url);
  823. domUtils.addClass(icon, 'icon');
  824. item.appendChild(img);
  825. item.appendChild(icon);
  826. this.list.insertBefore(item, this.clearFloat);
  827. }
  828. }
  829. },
  830. /* 改变图片大小 */
  831. scale: function (img, w, h, type) {
  832. var ow = img.width,
  833. oh = img.height;
  834. if (type == 'justify') {
  835. if (ow >= oh) {
  836. img.width = w;
  837. img.height = h * oh / ow;
  838. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  839. } else {
  840. img.width = w * ow / oh;
  841. img.height = h;
  842. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  843. }
  844. } else {
  845. if (ow >= oh) {
  846. img.width = w * ow / oh;
  847. img.height = h;
  848. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  849. } else {
  850. img.width = w;
  851. img.height = h * oh / ow;
  852. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  853. }
  854. }
  855. },
  856. getInsertList: function () {
  857. var i, lis = this.list.children, list = [], align = getAlign();
  858. for (i = 0; i < lis.length; i++) {
  859. if (domUtils.hasClass(lis[i], 'selected')) {
  860. var img = lis[i].firstChild,
  861. src = img.getAttribute('_src');
  862. list.push({
  863. src: src,
  864. _src: src,
  865. alt: src.substr(src.lastIndexOf('/') + 1),
  866. floatStyle: align
  867. });
  868. }
  869. }
  870. return list;
  871. }
  872. };
  873. /*搜索图片 */
  874. function SearchImage() {
  875. this.init();
  876. }
  877. SearchImage.prototype = {
  878. init: function () {
  879. this.initEvents();
  880. },
  881. initEvents: function(){
  882. var _this = this;
  883. /* 点击搜索按钮 */
  884. domUtils.on($G('searchBtn'), 'click', function(){
  885. var key = $G('searchTxt').value;
  886. if(key && key != lang.searchRemind) {
  887. _this.getImageData();
  888. }
  889. });
  890. /* 点击清除妞 */
  891. domUtils.on($G('searchReset'), 'click', function(){
  892. $G('searchTxt').value = lang.searchRemind;
  893. $G('searchListUl').innerHTML = '';
  894. $G('searchType').selectedIndex = 0;
  895. });
  896. /* 搜索框聚焦 */
  897. domUtils.on($G('searchTxt'), 'focus', function(){
  898. var key = $G('searchTxt').value;
  899. if(key && key == lang.searchRemind) {
  900. $G('searchTxt').value = '';
  901. }
  902. });
  903. /* 搜索框回车键搜索 */
  904. domUtils.on($G('searchTxt'), 'keydown', function(e){
  905. var keyCode = e.keyCode || e.which;
  906. if (keyCode == 13) {
  907. $G('searchBtn').click();
  908. }
  909. });
  910. /* 选中图片 */
  911. domUtils.on($G('searchList'), 'click', function(e){
  912. var target = e.target || e.srcElement,
  913. li = target.parentNode.parentNode;
  914. if (li.tagName.toLowerCase() == 'li') {
  915. if (domUtils.hasClass(li, 'selected')) {
  916. domUtils.removeClasses(li, 'selected');
  917. } else {
  918. domUtils.addClass(li, 'selected');
  919. }
  920. }
  921. });
  922. },
  923. encodeToGb2312:function (str){
  924. if(!str) return '';
  925. var strOut = "",
  926. z = 'D2BBB6A18140C6DF814181428143CDF2D5C9C8FDC9CFCFC2D8A2B2BBD3EB8144D8A4B3F38145D7A8C7D2D8A7CAC08146C7F0B1FBD2B5B4D4B6ABCBBFD8A9814781488149B6AA814AC1BDD1CF814BC9A5D8AD814CB8F6D1BEE3DCD6D0814D814EB7E1814FB4AE8150C1D98151D8BC8152CDE8B5A4CEAAD6F78153C0F6BED9D8AF815481558156C4CB8157BEC38158D8B1C3B4D2E58159D6AECEDAD5A7BAF5B7A6C0D6815AC6B9C5D2C7C7815BB9D4815CB3CBD2D2815D815ED8BFBEC5C6F2D2B2CFB0CFE7815F816081618162CAE981638164D8C081658166816781688169816AC2F2C2D2816BC8E9816C816D816E816F817081718172817381748175C7AC8176817781788179817A817B817CC1CB817DD3E8D5F9817ECAC2B6FED8A1D3DABFF78180D4C6BBA5D8C1CEE5BEAE81818182D8A88183D1C7D0A9818481858186D8BDD9EFCDF6BFBA8187BDBBBAA5D2E0B2FABAE0C4B68188CFEDBEA9CDA4C1C18189818A818BC7D7D9F1818CD9F4818D818E818F8190C8CBD8E9819181928193D2DACAB2C8CAD8ECD8EAD8C6BDF6C6CDB3F08194D8EBBDF1BDE98195C8D4B4D381968197C2D88198B2D6D7D0CACBCBFBD5CCB8B6CFC98199819A819BD9DAD8F0C7AA819CD8EE819DB4FAC1EED2D4819E819FD8ED81A0D2C7D8EFC3C781A181A281A3D1F681A4D6D9D8F281A5D8F5BCFEBCDB81A681A781A8C8CE81A9B7DD81AAB7C281ABC6F381AC81AD81AE81AF81B081B181B2D8F8D2C181B381B4CEE9BCBFB7FCB7A5D0DD81B581B681B781B881B9D6DAD3C5BBEFBBE1D8F181BA81BBC9A1CEB0B4AB81BCD8F381BDC9CBD8F6C2D7D8F781BE81BFCEB1D8F981C081C181C2B2AEB9C081C3D9A381C4B0E981C5C1E681C6C9EC81C7CBC581C8CBC6D9A481C981CA81CB81CC81CDB5E881CE81CFB5AB81D081D181D281D381D481D5CEBBB5CDD7A1D7F4D3D381D6CCE581D7BACE81D8D9A2D9DCD3E0D8FDB7F0D7F7D8FED8FAD9A1C4E381D981DAD3B6D8F4D9DD81DBD8FB81DCC5E581DD81DEC0D081DF81E0D1F0B0DB81E181E2BCD1D9A681E3D9A581E481E581E681E7D9ACD9AE81E8D9ABCAB981E981EA81EBD9A9D6B681EC81ED81EEB3DED9A881EFC0FD81F0CACC81F1D9AA81F2D9A781F381F4D9B081F581F6B6B181F781F881F9B9A981FAD2C081FB81FCCFC081FD81FEC2C28240BDC4D5ECB2E0C7C8BFEBD9AD8241D9AF8242CEEABAEE82438244824582468247C7D682488249824A824B824C824D824E824F8250B1E3825182528253B4D9B6EDD9B48254825582568257BFA182588259825AD9DEC7CEC0FED9B8825B825C825D825E825FCBD7B7FD8260D9B58261D9B7B1A3D3E1D9B98262D0C58263D9B682648265D9B18266D9B2C1A9D9B382678268BCF3D0DEB8A98269BEE3826AD9BD826B826C826D826ED9BA826FB0B3827082718272D9C28273827482758276827782788279827A827B827C827D827E8280D9C4B1B68281D9BF82828283B5B98284BEF3828582868287CCC8BAF2D2D08288D9C38289828ABDE8828BB3AB828C828D828ED9C5BEEB828FD9C6D9BBC4DF8290D9BED9C1D9C0829182928293829482958296829782988299829A829BD5AE829CD6B5829DC7E3829E829F82A082A1D9C882A282A382A4BCD9D9CA82A582A682A7D9BC82A8D9CBC6AB82A982AA82AB82AC82ADD9C982AE82AF82B082B1D7F682B2CDA382B382B482B582B682B782B882B982BABDA182BB82BC82BD82BE82BF82C0D9CC82C182C282C382C482C582C682C782C882C9C5BCCDB582CA82CB82CCD9CD82CD82CED9C7B3A5BFFE82CF82D082D182D2B8B582D382D4C0FC82D582D682D782D8B0F882D982DA82DB82DC82DD82DE82DF82E082E182E282E382E482E582E682E782E882E982EA82EB82EC82EDB4F682EED9CE82EFD9CFB4A2D9D082F082F1B4DF82F282F382F482F582F6B0C182F782F882F982FA82FB82FC82FDD9D1C9B582FE8340834183428343834483458346834783488349834A834B834C834D834E834F83508351CFF1835283538354835583568357D9D283588359835AC1C5835B835C835D835E835F836083618362836383648365D9D6C9AE8366836783688369D9D5D9D4D9D7836A836B836C836DCBDB836EBDA9836F8370837183728373C6A7837483758376837783788379837A837B837C837DD9D3D9D8837E83808381D9D9838283838384838583868387C8E583888389838A838B838C838D838E838F839083918392839383948395C0DC8396839783988399839A839B839C839D839E839F83A083A183A283A383A483A583A683A783A883A983AA83AB83AC83AD83AE83AF83B083B183B2B6F9D8A3D4CA83B3D4AAD0D6B3E4D5D783B4CFC8B9E283B5BFCB83B6C3E283B783B883B9B6D283BA83BBCDC3D9EED9F083BC83BD83BEB5B383BFB6B583C083C183C283C383C4BEA483C583C6C8EB83C783C8C8AB83C983CAB0CBB9ABC1F9D9E283CBC0BCB9B283CCB9D8D0CBB1F8C6E4BEDFB5E4D7C883CDD1F8BCE6CADE83CE83CFBCBDD9E6D8E783D083D1C4DA83D283D3B8D4C8BD83D483D5B2E1D4D983D683D783D883D9C3B083DA83DBC3E1DAA2C8DF83DCD0B483DDBEFCC5A983DE83DF83E0B9DA83E1DAA383E2D4A9DAA483E383E483E583E683E7D9FBB6AC83E883E9B7EBB1F9D9FCB3E5BEF683EABFF6D2B1C0E483EB83EC83EDB6B3D9FED9FD83EE83EFBEBB83F083F183F2C6E083F3D7BCDAA183F4C1B983F5B5F2C1E883F683F7BCF583F8B4D583F983FA83FB83FC83FD83FE844084418442C1DD8443C4FD84448445BCB8B7B284468447B7EF84488449844A844B844C844DD9EC844EC6BE844FBFADBBCB84508451B5CA8452DBC9D0D78453CDB9B0BCB3
  927. for (var i = 0; i < str.length; i++) {
  928. var c = str.charAt(i),
  929. code = str.charCodeAt(i);
  930. if (c == " ") strOut += "+";
  931. else if (code >= 19968 && code <= 40869) {
  932. var index = code - 19968;
  933. strOut += "%" + z.substr(index * 4, 2) + "%" + z.substr(index * 4 + 2, 2);
  934. } else {
  935. strOut += "%" + str.charCodeAt(i).toString(16);
  936. }
  937. }
  938. return strOut;
  939. },
  940. /* 改变图片大小 */
  941. scale: function (img, w, h) {
  942. var ow = img.width,
  943. oh = img.height;
  944. if (ow >= oh) {
  945. img.width = w * ow / oh;
  946. img.height = h;
  947. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  948. } else {
  949. img.width = w;
  950. img.height = h * oh / ow;
  951. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  952. }
  953. },
  954. getImageData: function(){
  955. var _this = this,
  956. key = $G('searchTxt').value,
  957. type = $G('searchType').value,
  958. keepOriginName = editor.options.keepOriginName ? "1" : "0",
  959. url = "http://image.baidu.com/i?ct=201326592&cl=2&lm=-1&st=-1&tn=baiduimagejson&istype=2&rn=32&fm=index&pv=&word=" + _this.encodeToGb2312(key) + type + "&keeporiginname=" + keepOriginName + "&" + +new Date;
  960. $G('searchListUl').innerHTML = lang.searchLoading;
  961. ajax.request(url, {
  962. 'dataType': 'jsonp',
  963. 'charset': 'GB18030',
  964. 'onsuccess':function(json){
  965. var list = [];
  966. if(json && json.data) {
  967. for(var i = 0; i < json.data.length; i++) {
  968. if(json.data[i].objURL) {
  969. list.push({
  970. title: json.data[i].fromPageTitleEnc,
  971. src: json.data[i].objURL,
  972. url: json.data[i].fromURL
  973. });
  974. }
  975. }
  976. }
  977. _this.setList(list);
  978. },
  979. 'onerror':function(){
  980. $G('searchListUl').innerHTML = lang.searchRetry;
  981. }
  982. });
  983. },
  984. /* 添加图片到列表界面上 */
  985. setList: function (list) {
  986. var i, item, p, img, link, _this = this,
  987. listUl = $G('searchListUl');
  988. listUl.innerHTML = '';
  989. if(list.length) {
  990. for (i = 0; i < list.length; i++) {
  991. item = document.createElement('li');
  992. p = document.createElement('p');
  993. img = document.createElement('img');
  994. link = document.createElement('a');
  995. img.onload = function () {
  996. _this.scale(this, 113, 113);
  997. };
  998. img.width = 113;
  999. img.setAttribute('src', list[i].src);
  1000. link.href = list[i].url;
  1001. link.target = '_blank';
  1002. link.title = list[i].title;
  1003. link.innerHTML = list[i].title;
  1004. p.appendChild(img);
  1005. item.appendChild(p);
  1006. item.appendChild(link);
  1007. listUl.appendChild(item);
  1008. }
  1009. } else {
  1010. listUl.innerHTML = lang.searchRetry;
  1011. }
  1012. },
  1013. getInsertList: function () {
  1014. var child,
  1015. src,
  1016. align = getAlign(),
  1017. list = [],
  1018. items = $G('searchListUl').children;
  1019. for(var i = 0; i < items.length; i++) {
  1020. child = items[i].firstChild && items[i].firstChild.firstChild;
  1021. if(child.tagName && child.tagName.toLowerCase() == 'img' && domUtils.hasClass(items[i], 'selected')) {
  1022. src = child.src;
  1023. list.push({
  1024. src: src,
  1025. _src: src,
  1026. alt: src.substr(src.lastIndexOf('/') + 1),
  1027. floatStyle: align
  1028. });
  1029. }
  1030. }
  1031. return list;
  1032. }
  1033. };
  1034. })();