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.

1123 lines
42 KiB

3 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. if(locker.checked) {
  164. var proportion =locker.getAttribute('data-proportion');
  165. $G('height').value = Math.round(this.value / proportion);
  166. } else {
  167. _this.updateLocker();
  168. }
  169. updatePreview();
  170. });
  171. domUtils.on($G("height"), 'keyup', function(){
  172. if(locker.checked) {
  173. var proportion =locker.getAttribute('data-proportion');
  174. $G('width').value = Math.round(this.value * proportion);
  175. } else {
  176. _this.updateLocker();
  177. }
  178. updatePreview();
  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. if (file.ext && acceptExtensions.indexOf(file.ext.toLowerCase()) != -1 && file.size <= imageMaxSize) {
  599. fileCount--;
  600. fileSize -= file.size;
  601. }
  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. if (actionUrl.toLowerCase().indexOf('jsp') != -1) {
  631. header['X-Requested-With'] = 'XMLHttpRequest';
  632. }
  633. });
  634. uploader.on('uploadProgress', function (file, percentage) {
  635. var $li = $('#' + file.id),
  636. $percent = $li.find('.progress span');
  637. $percent.css('width', percentage * 100 + '%');
  638. percentages[ file.id ][ 1 ] = percentage;
  639. updateTotalProgress();
  640. });
  641. uploader.on('uploadSuccess', function (file, ret) {
  642. var $file = $('#' + file.id);
  643. try {
  644. var responseText = (ret._raw || ret),
  645. json = utils.str2json(responseText);
  646. if (json.state == 'SUCCESS') {
  647. _this.imageList.push(json);
  648. $file.append('<span class="success"></span>');
  649. } else {
  650. $file.find('.error').text(json.state).show();
  651. }
  652. } catch (e) {
  653. $file.find('.error').text(lang.errorServerUpload).show();
  654. }
  655. });
  656. uploader.on('uploadError', function (file, code) {
  657. });
  658. uploader.on('error', function (code, file) {
  659. if (code == 'Q_TYPE_DENIED' || code == 'F_EXCEED_SIZE') {
  660. addFile(file);
  661. }
  662. });
  663. uploader.on('uploadComplete', function (file, ret) {
  664. });
  665. $upload.on('click', function () {
  666. if ($(this).hasClass('disabled')) {
  667. return false;
  668. }
  669. if (state === 'ready') {
  670. uploader.upload();
  671. } else if (state === 'paused') {
  672. uploader.upload();
  673. } else if (state === 'uploading') {
  674. uploader.stop();
  675. }
  676. });
  677. $upload.addClass('state-' + state);
  678. updateTotalProgress();
  679. },
  680. getQueueCount: function () {
  681. var file, i, status, readyFile = 0, files = this.uploader.getFiles();
  682. for (i = 0; file = files[i++]; ) {
  683. status = file.getStatus();
  684. if (status == 'queued' || status == 'uploading' || status == 'progress') readyFile++;
  685. }
  686. return readyFile;
  687. },
  688. destroy: function () {
  689. this.$wrap.remove();
  690. },
  691. getInsertList: function () {
  692. var i, data, list = [],
  693. align = getAlign(),
  694. prefix = editor.getOpt('imageUrlPrefix');
  695. for (i = 0; i < this.imageList.length; i++) {
  696. data = this.imageList[i];
  697. list.push({
  698. src: prefix + data.url,
  699. _src: prefix + data.url,
  700. alt: data.original,
  701. floatStyle: align
  702. });
  703. }
  704. return list;
  705. }
  706. };
  707. /* 在线图片 */
  708. function OnlineImage(target) {
  709. this.container = utils.isString(target) ? document.getElementById(target) : target;
  710. this.init();
  711. }
  712. OnlineImage.prototype = {
  713. init: function () {
  714. this.reset();
  715. this.initEvents();
  716. },
  717. /* 初始化容器 */
  718. initContainer: function () {
  719. this.container.innerHTML = '';
  720. this.list = document.createElement('ul');
  721. this.clearFloat = document.createElement('li');
  722. domUtils.addClass(this.list, 'list');
  723. domUtils.addClass(this.clearFloat, 'clearFloat');
  724. this.list.appendChild(this.clearFloat);
  725. this.container.appendChild(this.list);
  726. },
  727. /* 初始化滚动事件,滚动到地步自动拉取数据 */
  728. initEvents: function () {
  729. var _this = this;
  730. /* 滚动拉取图片 */
  731. domUtils.on($G('imageList'), 'scroll', function(e){
  732. var panel = this;
  733. if (panel.scrollHeight - (panel.offsetHeight + panel.scrollTop) < 10) {
  734. _this.getImageData();
  735. }
  736. });
  737. /* 选中图片 */
  738. domUtils.on(this.container, 'click', function (e) {
  739. var target = e.target || e.srcElement,
  740. li = target.parentNode;
  741. if (li.tagName.toLowerCase() == 'li') {
  742. if (domUtils.hasClass(li, 'selected')) {
  743. domUtils.removeClasses(li, 'selected');
  744. } else {
  745. domUtils.addClass(li, 'selected');
  746. }
  747. }
  748. });
  749. },
  750. /* 初始化第一次的数据 */
  751. initData: function () {
  752. /* 拉取数据需要使用的值 */
  753. this.state = 0;
  754. this.listSize = editor.getOpt('imageManagerListSize');
  755. this.listIndex = 0;
  756. this.listEnd = false;
  757. /* 第一次拉取数据 */
  758. this.getImageData();
  759. },
  760. /* 重置界面 */
  761. reset: function() {
  762. this.initContainer();
  763. this.initData();
  764. },
  765. /* 向后台拉取图片列表数据 */
  766. getImageData: function () {
  767. var _this = this;
  768. if(!_this.listEnd && !this.isLoadingData) {
  769. this.isLoadingData = true;
  770. var url = editor.getActionUrl(editor.getOpt('imageManagerActionName')),
  771. isJsonp = utils.isCrossDomainUrl(url);
  772. ajax.request(url, {
  773. 'timeout': 100000,
  774. 'dataType': isJsonp ? 'jsonp':'',
  775. 'data': utils.extend({
  776. start: this.listIndex,
  777. size: this.listSize
  778. }, editor.queryCommandValue('serverparam')),
  779. 'method': 'get',
  780. 'onsuccess': function (r) {
  781. try {
  782. var json = isJsonp ? r:eval('(' + r.responseText + ')');
  783. if (json.state == 'SUCCESS') {
  784. _this.pushData(json.list);
  785. _this.listIndex = parseInt(json.start) + parseInt(json.list.length);
  786. if(_this.listIndex >= json.total) {
  787. _this.listEnd = true;
  788. }
  789. _this.isLoadingData = false;
  790. }
  791. } catch (e) {
  792. if(r.responseText.indexOf('ue_separate_ue') != -1) {
  793. var list = r.responseText.split(r.responseText);
  794. _this.pushData(list);
  795. _this.listIndex = parseInt(list.length);
  796. _this.listEnd = true;
  797. _this.isLoadingData = false;
  798. }
  799. }
  800. },
  801. 'onerror': function () {
  802. _this.isLoadingData = false;
  803. }
  804. });
  805. }
  806. },
  807. /* 添加图片到列表界面上 */
  808. pushData: function (list) {
  809. var i, item, img, icon, _this = this,
  810. urlPrefix = editor.getOpt('imageManagerUrlPrefix');
  811. for (i = 0; i < list.length; i++) {
  812. if(list[i] && list[i].url) {
  813. item = document.createElement('li');
  814. img = document.createElement('img');
  815. icon = document.createElement('span');
  816. domUtils.on(img, 'load', (function(image){
  817. return function(){
  818. _this.scale(image, image.parentNode.offsetWidth, image.parentNode.offsetHeight);
  819. }
  820. })(img));
  821. img.width = 113;
  822. img.setAttribute('src', urlPrefix + list[i].url + (list[i].url.indexOf('?') == -1 ? '?noCache=':'&noCache=') + (+new Date()).toString(36) );
  823. img.setAttribute('_src', urlPrefix + list[i].url);
  824. domUtils.addClass(icon, 'icon');
  825. item.appendChild(img);
  826. item.appendChild(icon);
  827. this.list.insertBefore(item, this.clearFloat);
  828. }
  829. }
  830. },
  831. /* 改变图片大小 */
  832. scale: function (img, w, h, type) {
  833. var ow = img.width,
  834. oh = img.height;
  835. if (type == 'justify') {
  836. if (ow >= oh) {
  837. img.width = w;
  838. img.height = h * oh / ow;
  839. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  840. } else {
  841. img.width = w * ow / oh;
  842. img.height = h;
  843. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  844. }
  845. } else {
  846. if (ow >= oh) {
  847. img.width = w * ow / oh;
  848. img.height = h;
  849. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  850. } else {
  851. img.width = w;
  852. img.height = h * oh / ow;
  853. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  854. }
  855. }
  856. },
  857. getInsertList: function () {
  858. var i, lis = this.list.children, list = [], align = getAlign();
  859. for (i = 0; i < lis.length; i++) {
  860. if (domUtils.hasClass(lis[i], 'selected')) {
  861. var img = lis[i].firstChild,
  862. src = img.getAttribute('_src');
  863. list.push({
  864. src: src,
  865. _src: src,
  866. alt: src.substr(src.lastIndexOf('/') + 1),
  867. floatStyle: align
  868. });
  869. }
  870. }
  871. return list;
  872. }
  873. };
  874. /*搜索图片 */
  875. function SearchImage() {
  876. this.init();
  877. }
  878. SearchImage.prototype = {
  879. init: function () {
  880. this.initEvents();
  881. },
  882. initEvents: function(){
  883. var _this = this;
  884. /* 点击搜索按钮 */
  885. domUtils.on($G('searchBtn'), 'click', function(){
  886. var key = $G('searchTxt').value;
  887. if(key && key != lang.searchRemind) {
  888. _this.getImageData();
  889. }
  890. });
  891. /* 点击清除妞 */
  892. domUtils.on($G('searchReset'), 'click', function(){
  893. $G('searchTxt').value = lang.searchRemind;
  894. $G('searchListUl').innerHTML = '';
  895. $G('searchType').selectedIndex = 0;
  896. });
  897. /* 搜索框聚焦 */
  898. domUtils.on($G('searchTxt'), 'focus', function(){
  899. var key = $G('searchTxt').value;
  900. if(key && key == lang.searchRemind) {
  901. $G('searchTxt').value = '';
  902. }
  903. });
  904. /* 搜索框回车键搜索 */
  905. domUtils.on($G('searchTxt'), 'keydown', function(e){
  906. var keyCode = e.keyCode || e.which;
  907. if (keyCode == 13) {
  908. $G('searchBtn').click();
  909. }
  910. });
  911. /* 选中图片 */
  912. domUtils.on($G('searchList'), 'click', function(e){
  913. var target = e.target || e.srcElement,
  914. li = target.parentNode.parentNode;
  915. if (li.tagName.toLowerCase() == 'li') {
  916. if (domUtils.hasClass(li, 'selected')) {
  917. domUtils.removeClasses(li, 'selected');
  918. } else {
  919. domUtils.addClass(li, 'selected');
  920. }
  921. }
  922. });
  923. },
  924. /* 改变图片大小 */
  925. scale: function (img, w, h) {
  926. var ow = img.width,
  927. oh = img.height;
  928. if (ow >= oh) {
  929. img.width = w * ow / oh;
  930. img.height = h;
  931. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  932. } else {
  933. img.width = w;
  934. img.height = h * oh / ow;
  935. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  936. }
  937. },
  938. getImageData: function(){
  939. var _this = this,
  940. key = $G('searchTxt').value,
  941. type = $G('searchType').value,
  942. keepOriginName = editor.options.keepOriginName ? "1" : "0",
  943. 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;
  944. $G('searchListUl').innerHTML = lang.searchLoading;
  945. ajax.request(url, {
  946. 'dataType': 'jsonp',
  947. 'charset': 'GB18030',
  948. 'onsuccess':function(json){
  949. var list = [];
  950. if(json && json.data) {
  951. for(var i = 0; i < json.data.length; i++) {
  952. if(json.data[i].objURL) {
  953. list.push({
  954. title: json.data[i].fromPageTitleEnc,
  955. src: json.data[i].objURL,
  956. url: json.data[i].fromURL
  957. });
  958. }
  959. }
  960. }
  961. _this.setList(list);
  962. },
  963. 'onerror':function(){
  964. $G('searchListUl').innerHTML = lang.searchRetry;
  965. }
  966. });
  967. },
  968. /* 添加图片到列表界面上 */
  969. setList: function (list) {
  970. var i, item, p, img, link, _this = this,
  971. listUl = $G('searchListUl');
  972. listUl.innerHTML = '';
  973. if(list.length) {
  974. for (i = 0; i < list.length; i++) {
  975. item = document.createElement('li');
  976. p = document.createElement('p');
  977. img = document.createElement('img');
  978. link = document.createElement('a');
  979. img.onload = function () {
  980. _this.scale(this, 113, 113);
  981. };
  982. img.width = 113;
  983. img.setAttribute('src', list[i].src);
  984. link.href = list[i].url;
  985. link.target = '_blank';
  986. link.title = list[i].title;
  987. link.innerHTML = list[i].title;
  988. p.appendChild(img);
  989. item.appendChild(p);
  990. item.appendChild(link);
  991. listUl.appendChild(item);
  992. }
  993. } else {
  994. listUl.innerHTML = lang.searchRetry;
  995. }
  996. },
  997. getInsertList: function () {
  998. var child,
  999. src,
  1000. align = getAlign(),
  1001. list = [],
  1002. items = $G('searchListUl').children;
  1003. for(var i = 0; i < items.length; i++) {
  1004. child = items[i].firstChild && items[i].firstChild.firstChild;
  1005. if(child.tagName && child.tagName.toLowerCase() == 'img' && domUtils.hasClass(items[i], 'selected')) {
  1006. src = child.src;
  1007. list.push({
  1008. src: src,
  1009. _src: src,
  1010. alt: src.substr(src.lastIndexOf('/') + 1),
  1011. floatStyle: align
  1012. });
  1013. }
  1014. }
  1015. return list;
  1016. }
  1017. };
  1018. })();