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.

1125 lines
125 KiB

2 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 = parseInt($G('width').value, 10) || 0,
  231. oh = parseInt($G('height').value, 10) || 0,
  232. border = parseInt($G('border').value, 10) || 0,
  233. title = $G('title').value,
  234. preview = $G('preview'),
  235. width,
  236. height;
  237. url = utils.unhtmlForUrl(url);
  238. title = utils.unhtml(title);
  239. width = ((!ow || !oh) ? preview.offsetWidth : Math.min(ow, preview.offsetWidth));
  240. width = width + (border * 2) > preview.offsetWidth ? width : (preview.offsetWidth - (border * 2));
  241. height = (!ow || !oh) ? '' : width * oh / ow;
  242. if (url) {
  243. preview.innerHTML = '<img src="' + url + '" width="' + width + '" height="' + height + '" border="' + border + 'px solid #000" title="' + title + '" />';
  244. }
  245. },
  246. getInsertList: function () {
  247. var data = this.getData();
  248. if (data['url']) {
  249. return [{
  250. src: data['url'],
  251. _src: data['url'],
  252. width: data['width'] || '',
  253. height: data['height'] || '',
  254. border: data['border'] || '',
  255. floatStyle: data['align'] || '',
  256. vspace: data['vhSpace'] || '',
  257. title: data['title'] || '',
  258. alt: data['title'] || '',
  259. style: "width:" + data['width'] + "px;height:" + data['height'] + "px;"
  260. }];
  261. } else {
  262. return [];
  263. }
  264. }
  265. };
  266. /* 上传图片 */
  267. function UploadImage(target) {
  268. this.$wrap = target.constructor == String ? $('#' + target) : $(target);
  269. this.init();
  270. }
  271. UploadImage.prototype = {
  272. init: function () {
  273. this.imageList = [];
  274. this.initContainer();
  275. this.initUploader();
  276. },
  277. initContainer: function () {
  278. this.$queue = this.$wrap.find('.filelist');
  279. },
  280. /* 初始化容器 */
  281. initUploader: function () {
  282. var _this = this,
  283. $ = jQuery, // just in case. Make sure it's not an other libaray.
  284. $wrap = _this.$wrap,
  285. // 图片容器
  286. $queue = $wrap.find('.filelist'),
  287. // 状态栏,包括进度和控制按钮
  288. $statusBar = $wrap.find('.statusBar'),
  289. // 文件总体选择信息。
  290. $info = $statusBar.find('.info'),
  291. // 上传按钮
  292. $upload = $wrap.find('.uploadBtn'),
  293. // 上传按钮
  294. $filePickerBtn = $wrap.find('.filePickerBtn'),
  295. // 上传按钮
  296. $filePickerBlock = $wrap.find('.filePickerBlock'),
  297. // 没选择文件之前的内容。
  298. $placeHolder = $wrap.find('.placeholder'),
  299. // 总体进度条
  300. $progress = $statusBar.find('.progress').hide(),
  301. // 添加的文件数量
  302. fileCount = 0,
  303. // 添加的文件总大小
  304. fileSize = 0,
  305. // 优化retina, 在retina下这个值是2
  306. ratio = window.devicePixelRatio || 1,
  307. // 缩略图大小
  308. thumbnailWidth = 113 * ratio,
  309. thumbnailHeight = 113 * ratio,
  310. // 可能有pedding, ready, uploading, confirm, done.
  311. state = '',
  312. // 所有文件的进度信息,key为file id
  313. percentages = {},
  314. supportTransition = (function () {
  315. var s = document.createElement('p').style,
  316. r = 'transition' in s ||
  317. 'WebkitTransition' in s ||
  318. 'MozTransition' in s ||
  319. 'msTransition' in s ||
  320. 'OTransition' in s;
  321. s = null;
  322. return r;
  323. })(),
  324. // WebUploader实例
  325. uploader,
  326. actionUrl = editor.getActionUrl(editor.getOpt('imageActionName')),
  327. acceptExtensions = (editor.getOpt('imageAllowFiles') || []).join('').replace(/\./g, ',').replace(/^[,]/, ''),
  328. imageMaxSize = editor.getOpt('imageMaxSize'),
  329. imageCompressBorder = editor.getOpt('imageCompressBorder');
  330. if (!WebUploader.Uploader.support()) {
  331. $('#filePickerReady').after($('<div>').html(lang.errorNotSupport)).hide();
  332. return;
  333. } else if (!editor.getOpt('imageActionName')) {
  334. $('#filePickerReady').after($('<div>').html(lang.errorLoadConfig)).hide();
  335. return;
  336. }
  337. uploader = _this.uploader = WebUploader.create({
  338. pick: {
  339. id: '#filePickerReady',
  340. label: lang.uploadSelectFile
  341. },
  342. accept: {
  343. title: 'Images',
  344. extensions: acceptExtensions,
  345. mimeTypes: 'image/*'
  346. },
  347. swf: '../../third-party/webuploader/Uploader.swf',
  348. server: actionUrl,
  349. fileVal: editor.getOpt('imageFieldName'),
  350. duplicate: true,
  351. fileSingleSizeLimit: imageMaxSize, // 默认 2 M
  352. compress: editor.getOpt('imageCompressEnable') ? {
  353. width: imageCompressBorder,
  354. height: imageCompressBorder,
  355. // 图片质量,只有type为`image/jpeg`的时候才有效。
  356. quality: 90,
  357. // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
  358. allowMagnify: false,
  359. // 是否允许裁剪。
  360. crop: false,
  361. // 是否保留头部meta信息。
  362. preserveHeaders: true
  363. } : false
  364. });
  365. uploader.addButton({
  366. id: '#filePickerBlock'
  367. });
  368. uploader.addButton({
  369. id: '#filePickerBtn',
  370. label: lang.uploadAddFile
  371. });
  372. setState('pedding');
  373. // 当有文件添加进来时执行,负责view的创建
  374. function addFile(file) {
  375. var $li = $('<li id="' + file.id + '">' +
  376. '<p class="title">' + file.name + '</p>' +
  377. '<p class="imgWrap"></p>' +
  378. '<p class="progress"><span></span></p>' +
  379. '</li>'),
  380. $btns = $('<div class="file-panel">' +
  381. '<span class="cancel">' + lang.uploadDelete + '</span>' +
  382. '<span class="rotateRight">' + lang.uploadTurnRight + '</span>' +
  383. '<span class="rotateLeft">' + lang.uploadTurnLeft + '</span></div>').appendTo($li),
  384. $prgress = $li.find('p.progress span'),
  385. $wrap = $li.find('p.imgWrap'),
  386. $info = $('<p class="error"></p>').hide().appendTo($li),
  387. showError = function (code) {
  388. switch (code) {
  389. case 'exceed_size':
  390. text = lang.errorExceedSize;
  391. break;
  392. case 'interrupt':
  393. text = lang.errorInterrupt;
  394. break;
  395. case 'http':
  396. text = lang.errorHttp;
  397. break;
  398. case 'not_allow_type':
  399. text = lang.errorFileType;
  400. break;
  401. default:
  402. text = lang.errorUploadRetry;
  403. break;
  404. }
  405. $info.text(text).show();
  406. };
  407. if (file.getStatus() === 'invalid') {
  408. showError(file.statusText);
  409. } else {
  410. $wrap.text(lang.uploadPreview);
  411. if (browser.ie && browser.version <= 7) {
  412. $wrap.text(lang.uploadNoPreview);
  413. } else {
  414. uploader.makeThumb(file, function (error, src) {
  415. if (error || !src) {
  416. $wrap.text(lang.uploadNoPreview);
  417. } else {
  418. var $img = $('<img src="' + src + '">');
  419. $wrap.empty().append($img);
  420. $img.on('error', function () {
  421. $wrap.text(lang.uploadNoPreview);
  422. });
  423. }
  424. }, thumbnailWidth, thumbnailHeight);
  425. }
  426. percentages[file.id] = [file.size, 0];
  427. file.rotation = 0;
  428. /* 检查文件格式 */
  429. if (!file.ext || acceptExtensions.indexOf(file.ext.toLowerCase()) == -1) {
  430. showError('not_allow_type');
  431. uploader.removeFile(file);
  432. }
  433. }
  434. file.on('statuschange', function (cur, prev) {
  435. if (prev === 'progress') {
  436. $prgress.hide().width(0);
  437. } else if (prev === 'queued') {
  438. $li.off('mouseenter mouseleave');
  439. $btns.remove();
  440. }
  441. // 成功
  442. if (cur === 'error' || cur === 'invalid') {
  443. showError(file.statusText);
  444. percentages[file.id][1] = 1;
  445. } else if (cur === 'interrupt') {
  446. showError('interrupt');
  447. } else if (cur === 'queued') {
  448. percentages[file.id][1] = 0;
  449. } else if (cur === 'progress') {
  450. $info.hide();
  451. $prgress.css('display', 'block');
  452. } else if (cur === 'complete') {
  453. }
  454. $li.removeClass('state-' + prev).addClass('state-' + cur);
  455. });
  456. $li.on('mouseenter', function () {
  457. $btns.stop().animate({ height: 30 });
  458. });
  459. $li.on('mouseleave', function () {
  460. $btns.stop().animate({ height: 0 });
  461. });
  462. $btns.on('click', 'span', function () {
  463. var index = $(this).index(),
  464. deg;
  465. switch (index) {
  466. case 0:
  467. uploader.removeFile(file);
  468. return;
  469. case 1:
  470. file.rotation += 90;
  471. break;
  472. case 2:
  473. file.rotation -= 90;
  474. break;
  475. }
  476. if (supportTransition) {
  477. deg = 'rotate(' + file.rotation + 'deg)';
  478. $wrap.css({
  479. '-webkit-transform': deg,
  480. '-mos-transform': deg,
  481. '-o-transform': deg,
  482. 'transform': deg
  483. });
  484. } else {
  485. $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
  486. }
  487. });
  488. $li.insertBefore($filePickerBlock);
  489. }
  490. // 负责view的销毁
  491. function removeFile(file) {
  492. var $li = $('#' + file.id);
  493. delete percentages[file.id];
  494. updateTotalProgress();
  495. $li.off().find('.file-panel').off().end().remove();
  496. }
  497. function updateTotalProgress() {
  498. var loaded = 0,
  499. total = 0,
  500. spans = $progress.children(),
  501. percent;
  502. $.each(percentages, function (k, v) {
  503. total += v[0];
  504. loaded += v[0] * v[1];
  505. });
  506. percent = total ? loaded / total : 0;
  507. spans.eq(0).text(Math.round(percent * 100) + '%');
  508. spans.eq(1).css('width', Math.round(percent * 100) + '%');
  509. updateStatus();
  510. }
  511. function setState(val, files) {
  512. if (val != state) {
  513. var stats = uploader.getStats();
  514. $upload.removeClass('state-' + state);
  515. $upload.addClass('state-' + val);
  516. switch (val) {
  517. /* 未选择文件 */
  518. case 'pedding':
  519. $queue.addClass('element-invisible');
  520. $statusBar.addClass('element-invisible');
  521. $placeHolder.removeClass('element-invisible');
  522. $progress.hide(); $info.hide();
  523. uploader.refresh();
  524. break;
  525. /* 可以开始上传 */
  526. case 'ready':
  527. $placeHolder.addClass('element-invisible');
  528. $queue.removeClass('element-invisible');
  529. $statusBar.removeClass('element-invisible');
  530. $progress.hide(); $info.show();
  531. $upload.text(lang.uploadStart);
  532. uploader.refresh();
  533. break;
  534. /* 上传中 */
  535. case 'uploading':
  536. $progress.show(); $info.hide();
  537. $upload.text(lang.uploadPause);
  538. break;
  539. /* 暂停上传 */
  540. case 'paused':
  541. $progress.show(); $info.hide();
  542. $upload.text(lang.uploadContinue);
  543. break;
  544. case 'confirm':
  545. $progress.show(); $info.hide();
  546. $upload.text(lang.uploadStart);
  547. stats = uploader.getStats();
  548. if (stats.successNum && !stats.uploadFailNum) {
  549. setState('finish');
  550. return;
  551. }
  552. break;
  553. case 'finish':
  554. $progress.hide(); $info.show();
  555. if (stats.uploadFailNum) {
  556. $upload.text(lang.uploadRetry);
  557. } else {
  558. $upload.text(lang.uploadStart);
  559. }
  560. break;
  561. }
  562. state = val;
  563. updateStatus();
  564. }
  565. if (!_this.getQueueCount()) {
  566. $upload.addClass('disabled')
  567. } else {
  568. $upload.removeClass('disabled')
  569. }
  570. }
  571. function updateStatus() {
  572. var text = '', stats;
  573. if (state === 'ready') {
  574. text = lang.updateStatusReady.replace('_', fileCount).replace('_KB', WebUploader.formatSize(fileSize));
  575. } else if (state === 'confirm') {
  576. stats = uploader.getStats();
  577. if (stats.uploadFailNum) {
  578. text = lang.updateStatusConfirm.replace('_', stats.successNum).replace('_', stats.successNum);
  579. }
  580. } else {
  581. stats = uploader.getStats();
  582. text = lang.updateStatusFinish.replace('_', fileCount).
  583. replace('_KB', WebUploader.formatSize(fileSize)).
  584. replace('_', stats.successNum);
  585. if (stats.uploadFailNum) {
  586. text += lang.updateStatusError.replace('_', stats.uploadFailNum);
  587. }
  588. }
  589. $info.html(text);
  590. }
  591. uploader.on('fileQueued', function (file) {
  592. fileCount++;
  593. fileSize += file.size;
  594. if (fileCount === 1) {
  595. $placeHolder.addClass('element-invisible');
  596. $statusBar.show();
  597. }
  598. addFile(file);
  599. });
  600. uploader.on('fileDequeued', function (file) {
  601. fileCount--;
  602. fileSize -= file.size;
  603. removeFile(file);
  604. updateTotalProgress();
  605. });
  606. uploader.on('filesQueued', function (file) {
  607. if (!uploader.isInProgress() && (state == 'pedding' || state == 'finish' || state == 'confirm' || state == 'ready')) {
  608. setState('ready');
  609. }
  610. updateTotalProgress();
  611. });
  612. uploader.on('all', function (type, files) {
  613. switch (type) {
  614. case 'uploadFinished':
  615. setState('confirm', files);
  616. break;
  617. case 'startUpload':
  618. /* 添加额外的GET参数 */
  619. var params = utils.serializeParam(editor.queryCommandValue('serverparam')) || '',
  620. url = utils.formatUrl(actionUrl + (actionUrl.indexOf('?') == -1 ? '?' : '&') + 'encode=utf-8&' + params);
  621. uploader.option('server', url);
  622. setState('uploading', files);
  623. break;
  624. case 'stopUpload':
  625. setState('paused', files);
  626. break;
  627. }
  628. });
  629. uploader.on('uploadBeforeSend', function (file, data, header) {
  630. //这里可以通过data对象添加POST参数
  631. header['X_Requested_With'] = 'XMLHttpRequest';
  632. });
  633. uploader.on('uploadProgress', function (file, percentage) {
  634. var $li = $('#' + file.id),
  635. $percent = $li.find('.progress span');
  636. $percent.css('width', percentage * 100 + '%');
  637. percentages[file.id][1] = percentage;
  638. updateTotalProgress();
  639. });
  640. uploader.on('uploadSuccess', function (file, ret) {
  641. var $file = $('#' + file.id);
  642. try {
  643. var responseText = (ret._raw || ret),
  644. json = utils.str2json(responseText);
  645. if (json.state == 'SUCCESS') {
  646. _this.imageList.push(json);
  647. $file.append('<span class="success"></span>');
  648. } else {
  649. $file.find('.error').text(json.state).show();
  650. }
  651. } catch (e) {
  652. $file.find('.error').text(lang.errorServerUpload).show();
  653. }
  654. });
  655. uploader.on('uploadError', function (file, code) {
  656. });
  657. uploader.on('error', function (code, file) {
  658. if (code == 'Q_TYPE_DENIED' || code == 'F_EXCEED_SIZE') {
  659. addFile(file);
  660. }
  661. });
  662. uploader.on('uploadComplete', function (file, ret) {
  663. });
  664. $upload.on('click', function () {
  665. if ($(this).hasClass('disabled')) {
  666. return false;
  667. }
  668. if (state === 'ready') {
  669. uploader.upload();
  670. } else if (state === 'paused') {
  671. uploader.upload();
  672. } else if (state === 'uploading') {
  673. uploader.stop();
  674. }
  675. });
  676. $upload.addClass('state-' + state);
  677. updateTotalProgress();
  678. },
  679. getQueueCount: function () {
  680. var file, i, status, readyFile = 0, files = this.uploader.getFiles();
  681. for (i = 0; file = files[i++];) {
  682. status = file.getStatus();
  683. if (status == 'queued' || status == 'uploading' || status == 'progress') readyFile++;
  684. }
  685. return readyFile;
  686. },
  687. destroy: function () {
  688. this.$wrap.remove();
  689. },
  690. getInsertList: function () {
  691. var i, data, list = [],
  692. align = getAlign(),
  693. prefix = editor.getOpt('imageUrlPrefix');
  694. for (i = 0; i < this.imageList.length; i++) {
  695. data = this.imageList[i];
  696. list.push({
  697. src: prefix + data.url,
  698. _src: prefix + data.url,
  699. title: data.title,
  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. encodeToGb2312: function (str) {
  925. if (!str) return '';
  926. var strOut = "",
  927. z = 'D2BBB6A18140C6DF814181428143CDF2D5C9C8FDC9CFCFC2D8A2B2BBD3EB8144D8A4B3F38145D7A8C7D2D8A7CAC08146C7F0B1FBD2B5B4D4B6ABCBBFD8A9814781488149B6AA814AC1BDD1CF814BC9A5D8AD814CB8F6D1BEE3DCD6D0814D814EB7E1814FB4AE8150C1D98151D8BC8152CDE8B5A4CEAAD6F78153C0F6BED9D8AF815481558156C4CB8157BEC38158D8B1C3B4D2E58159D6AECEDAD5A7BAF5B7A6C0D6815AC6B9C5D2C7C7815BB9D4815CB3CBD2D2815D815ED8BFBEC5C6F2D2B2CFB0CFE7815F816081618162CAE981638164D8C081658166816781688169816AC2F2C2D2816BC8E9816C816D816E816F817081718172817381748175C7AC8176817781788179817A817B817CC1CB817DD3E8D5F9817ECAC2B6FED8A1D3DABFF78180D4C6BBA5D8C1CEE5BEAE81818182D8A88183D1C7D0A9818481858186D8BDD9EFCDF6BFBA8187BDBBBAA5D2E0B2FABAE0C4B68188CFEDBEA9CDA4C1C18189818A818BC7D7D9F1818CD9F4818D818E818F8190C8CBD8E9819181928193D2DACAB2C8CAD8ECD8EAD8C6BDF6C6CDB3F08194D8EBBDF1BDE98195C8D4B4D381968197C2D88198B2D6D7D0CACBCBFBD5CCB8B6CFC98199819A819BD9DAD8F0C7AA819CD8EE819DB4FAC1EED2D4819E819FD8ED81A0D2C7D8EFC3C781A181A281A3D1F681A4D6D9D8F281A5D8F5BCFEBCDB81A681A781A8C8CE81A9B7DD81AAB7C281ABC6F381AC81AD81AE81AF81B081B181B2D8F8D2C181B381B4CEE9BCBFB7FCB7A5D0DD81B581B681B781B881B9D6DAD3C5BBEFBBE1D8F181BA81BBC9A1CEB0B4AB81BCD8F381BDC9CBD8F6C2D7D8F781BE81BFCEB1D8F981C081C181C2B2AEB9C081C3D9A381C4B0E981C5C1E681C6C9EC81C7CBC581C8CBC6D9A481C981CA81CB81CC81CDB5E881CE81CFB5AB81D081D181D281D381D481D5CEBBB5CDD7A1D7F4D3D381D6CCE581D7BACE81D8D9A2D9DCD3E0D8FDB7F0D7F7D8FED8FAD9A1C4E381D981DAD3B6D8F4D9DD81DBD8FB81DCC5E581DD81DEC0D081DF81E0D1F0B0DB81E181E2BCD1D9A681E3D9A581E481E581E681E7D9ACD9AE81E8D9ABCAB981E981EA81EBD9A9D6B681EC81ED81EEB3DED9A881EFC0FD81F0CACC81F1D9AA81F2D9A781F381F4D9B081F581F6B6B181F781F881F9B9A981FAD2C081FB81FCCFC081FD81FEC2C28240BDC4D5ECB2E0C7C8BFEBD9AD8241D9AF8242CEEABAEE82438244824582468247C7D682488249824A824B824C824D824E824F8250B1E3825182528253B4D9B6EDD9B48254825582568257BFA182588259825AD9DEC7CEC0FED9B8825B825C825D825E825FCBD7B7FD8260D9B58261D9B7B1A3D3E1D9B98262D0C58263D9B682648265D9B18266D9B2C1A9D9B382678268BCF3D0DEB8A98269BEE3826AD9BD826B826C826D826ED9BA826FB0B3827082718272D9C28273827482758276827782788279827A827B827C827D827E8280D9C4B1B68281D9BF82828283B5B98284BEF3828582868287CCC8BAF2D2D08288D9C38289828ABDE8828BB3AB828C828D828ED9C5BEEB828FD9C6D9BBC4DF8290D9BED9C1D9C0829182928293829482958296829782988299829A829BD5AE829CD6B5829DC7E3829E829F82A082A1D9C882A282A382A4BCD9D9CA82A582A682A7D9BC82A8D9CBC6AB82A982AA82AB82AC82ADD9C982AE82AF82B082B1D7F682B2CDA382B382B482B582B682B782B882B982BABDA182BB82BC82BD82BE82BF82C0D9CC82C182C282C382C482C582C682C782C882C9C5BCCDB582CA82CB82CCD9CD82CD82CED9C7B3A5BFFE82CF82D082D182D2B8B582D382D4C0FC82D582D682D782D8B0F882D982DA82DB82DC82DD82DE82DF82E082E182E282E382E482E582E682E782E882E982EA82EB82EC82EDB4F682EED9CE82EFD9CFB4A2D9D082F082F1B4DF82F282F382F482F582F6B0C182F782F882F982FA82FB82FC82FDD9D1C9B582FE8340834183428343834483458346834783488349834A834B834C834D834E834F83508351CFF1835283538354835583568357D9D283588359835AC1C5835B835C835D835E835F836083618362836383648365D9D6C9AE8366836783688369D9D5D9D4D9D7836A836B836C836DCBDB836EBDA9836F8370837183728373C6A7837483758376837783788379837A837B837C837DD9D3D9D8837E83808381D9D9838283838384838583868387C8E583888389838A838B838C838D838E838F839083918392839383948395C0DC8396839783988399839A839B839C839D839E839F83A083A183A283A383A483A583A683A783A883A983AA83AB83AC83AD83AE83AF83B083B183B2B6F9D8A3D4CA83B3D4AAD0D6B3E4D5D783B4CFC8B9E283B5BFCB83B6C3E283B783B883B9B6D283BA83BBCDC3D9EED9F083BC83BD83BEB5B383BFB6B583C083C183C283C383C4BEA483C583C6C8EB83C783C8C8AB83C983CAB0CBB9ABC1F9D9E283CBC0BCB9B283CCB9D8D0CBB1F8C6E4BEDFB5E4D7C883CDD1F8BCE6CADE83CE83CFBCBDD9E6D8E783D083D1C4DA83D283D3B8D4C8BD83D483D5B2E1D4D983D683D783D883D9C3B083DA83DBC3E1DAA2C8DF83DCD0B483DDBEFCC5A983DE83DF83E0B9DA83E1DAA383E2D4A9DAA483E383E483E583E683E7D9FBB6AC83E883E9B7EBB1F9D9FCB3E5BEF683EABFF6D2B1C0E483EB83EC83EDB6B3D9FED9FD83EE83EFBEBB83F083F183F2C6E083F3D7BCDAA183F4C1B983F5B5F2C1E883F683F7BCF583F8B4D583F983FA83FB83FC83FD83FE844084418442C1DD8443C4FD84448445BCB8B7B284468447B7EF84488449844A844B844C844DD9EC844EC6BE844FBFADBBCB84508451B5CA8452DBC9D0D78453CDB9B0BCB3
  928. for (var i = 0; i < str.length; i++) {
  929. var c = str.charAt(i),
  930. code = str.charCodeAt(i);
  931. if (c == " ") strOut += "+";
  932. else if (code >= 19968 && code <= 40869) {
  933. var index = code - 19968;
  934. strOut += "%" + z.substr(index * 4, 2) + "%" + z.substr(index * 4 + 2, 2);
  935. } else {
  936. strOut += "%" + str.charCodeAt(i).toString(16);
  937. }
  938. }
  939. return strOut;
  940. },
  941. /* 改变图片大小 */
  942. scale: function (img, w, h) {
  943. var ow = img.width,
  944. oh = img.height;
  945. if (ow >= oh) {
  946. img.width = w * ow / oh;
  947. img.height = h;
  948. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  949. } else {
  950. img.width = w;
  951. img.height = h * oh / ow;
  952. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  953. }
  954. },
  955. getImageData: function () {
  956. var _this = this,
  957. key = $G('searchTxt').value,
  958. type = $G('searchType').value,
  959. keepOriginName = editor.options.keepOriginName ? "1" : "0",
  960. 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;
  961. $G('searchListUl').innerHTML = lang.searchLoading;
  962. ajax.request(url, {
  963. 'dataType': 'jsonp',
  964. 'charset': 'GB18030',
  965. 'onsuccess': function (json) {
  966. var list = [];
  967. if (json && json.data) {
  968. for (var i = 0; i < json.data.length; i++) {
  969. if (json.data[i].objURL) {
  970. list.push({
  971. title: json.data[i].fromPageTitleEnc,
  972. src: json.data[i].objURL,
  973. url: json.data[i].fromURL
  974. });
  975. }
  976. }
  977. }
  978. _this.setList(list);
  979. },
  980. 'onerror': function () {
  981. $G('searchListUl').innerHTML = lang.searchRetry;
  982. }
  983. });
  984. },
  985. /* 添加图片到列表界面上 */
  986. setList: function (list) {
  987. var i, item, p, img, link, _this = this,
  988. listUl = $G('searchListUl');
  989. listUl.innerHTML = '';
  990. if (list.length) {
  991. for (i = 0; i < list.length; i++) {
  992. item = document.createElement('li');
  993. p = document.createElement('p');
  994. img = document.createElement('img');
  995. link = document.createElement('a');
  996. img.onload = function () {
  997. _this.scale(this, 113, 113);
  998. };
  999. img.width = 113;
  1000. img.setAttribute('src', list[i].src);
  1001. link.href = list[i].url;
  1002. link.target = '_blank';
  1003. link.title = list[i].title;
  1004. link.innerHTML = list[i].title;
  1005. p.appendChild(img);
  1006. item.appendChild(p);
  1007. item.appendChild(link);
  1008. listUl.appendChild(item);
  1009. }
  1010. } else {
  1011. listUl.innerHTML = lang.searchRetry;
  1012. }
  1013. },
  1014. getInsertList: function () {
  1015. var child,
  1016. src,
  1017. align = getAlign(),
  1018. list = [],
  1019. items = $G('searchListUl').children;
  1020. for (var i = 0; i < items.length; i++) {
  1021. child = items[i].firstChild && items[i].firstChild.firstChild;
  1022. if (child.tagName && child.tagName.toLowerCase() == 'img' && domUtils.hasClass(items[i], 'selected')) {
  1023. src = child.src;
  1024. list.push({
  1025. src: src,
  1026. _src: src,
  1027. alt: src.substr(src.lastIndexOf('/') + 1),
  1028. floatStyle: align
  1029. });
  1030. }
  1031. }
  1032. return list;
  1033. }
  1034. };
  1035. })();