血透系统PC前端

image.js 43KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  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') || [".png", ".jpg", ".jpeg", ".gif", ".bmp"]).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. /* 上传插件 */
  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/jpeg,image/png,image/svg,image/webp,image/gif'
  344. },
  345. swf: '../../third-party/webuploader/Uploader.swf',
  346. server: actionUrl,
  347. fileVal: editor.getOpt('imageFieldName'),
  348. duplicate: true,
  349. fileSingleSizeLimit: imageMaxSize, // 默认 2 M
  350. compress: false
  351. });
  352. uploader.addButton({
  353. id: '#filePickerBlock'
  354. });
  355. uploader.addButton({
  356. id: '#filePickerBtn',
  357. label: lang.uploadAddFile
  358. });
  359. setState('pedding');
  360. // 当有文件添加进来时执行,负责view的创建
  361. function addFile(file) {
  362. var $li = $('<li id="' + file.id + '">' +
  363. '<p class="title">' + file.name + '</p>' +
  364. '<p class="imgWrap"></p>' +
  365. '<p class="progress"><span></span></p>' +
  366. '</li>'),
  367. $btns = $('<div class="file-panel">' +
  368. '<span class="cancel">' + lang.uploadDelete + '</span>' +
  369. '<span class="rotateRight">' + lang.uploadTurnRight + '</span>' +
  370. '<span class="rotateLeft">' + lang.uploadTurnLeft + '</span></div>').appendTo($li),
  371. $prgress = $li.find('p.progress span'),
  372. $wrap = $li.find('p.imgWrap'),
  373. $info = $('<p class="error"></p>').hide().appendTo($li),
  374. showError = function (code) {
  375. switch (code) {
  376. case 'exceed_size':
  377. text = lang.errorExceedSize;
  378. break;
  379. case 'interrupt':
  380. text = lang.errorInterrupt;
  381. break;
  382. case 'http':
  383. text = lang.errorHttp;
  384. break;
  385. case 'not_allow_type':
  386. text = lang.errorFileType;
  387. break;
  388. default:
  389. text = lang.errorUploadRetry;
  390. break;
  391. }
  392. $info.text(text).show();
  393. };
  394. if (file.getStatus() === 'invalid') {
  395. showError(file.statusText);
  396. } else {
  397. $wrap.text(lang.uploadPreview);
  398. if (browser.ie && browser.version <= 7) {
  399. $wrap.text(lang.uploadNoPreview);
  400. } else {
  401. uploader.makeThumb(file, function (error, src) {
  402. if (error || !src) {
  403. $wrap.text(lang.uploadNoPreview);
  404. } else {
  405. var $img = $('<img src="' + src + '">');
  406. $wrap.empty().append($img);
  407. $img.on('error', function () {
  408. $wrap.text(lang.uploadNoPreview);
  409. });
  410. }
  411. }, thumbnailWidth, thumbnailHeight);
  412. }
  413. percentages[ file.id ] = [ file.size, 0 ];
  414. file.rotation = 0;
  415. /* 检查文件格式 */
  416. if (!file.ext || acceptExtensions.indexOf(file.ext.toLowerCase()) == -1) {
  417. showError('not_allow_type');
  418. uploader.removeFile(file);
  419. }
  420. }
  421. file.on('statuschange', function (cur, prev) {
  422. if (prev === 'progress') {
  423. $prgress.hide().width(0);
  424. } else if (prev === 'queued') {
  425. $li.off('mouseenter mouseleave');
  426. $btns.remove();
  427. }
  428. // 成功
  429. if (cur === 'error' || cur === 'invalid') {
  430. showError(file.statusText);
  431. percentages[ file.id ][ 1 ] = 1;
  432. } else if (cur === 'interrupt') {
  433. showError('interrupt');
  434. } else if (cur === 'queued') {
  435. percentages[ file.id ][ 1 ] = 0;
  436. } else if (cur === 'progress') {
  437. $info.hide();
  438. $prgress.css('display', 'block');
  439. } else if (cur === 'complete') {
  440. }
  441. $li.removeClass('state-' + prev).addClass('state-' + cur);
  442. });
  443. $li.on('mouseenter', function () {
  444. $btns.stop().animate({height: 30});
  445. });
  446. $li.on('mouseleave', function () {
  447. $btns.stop().animate({height: 0});
  448. });
  449. $btns.on('click', 'span', function () {
  450. var index = $(this).index(),
  451. deg;
  452. switch (index) {
  453. case 0:
  454. uploader.removeFile(file);
  455. return;
  456. case 1:
  457. file.rotation += 90;
  458. break;
  459. case 2:
  460. file.rotation -= 90;
  461. break;
  462. }
  463. if (supportTransition) {
  464. deg = 'rotate(' + file.rotation + 'deg)';
  465. $wrap.css({
  466. '-webkit-transform': deg,
  467. '-mos-transform': deg,
  468. '-o-transform': deg,
  469. 'transform': deg
  470. });
  471. } else {
  472. $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
  473. }
  474. });
  475. $li.insertBefore($filePickerBlock);
  476. }
  477. // 负责view的销毁
  478. function removeFile(file) {
  479. var $li = $('#' + file.id);
  480. delete percentages[ file.id ];
  481. updateTotalProgress();
  482. $li.off().find('.file-panel').off().end().remove();
  483. }
  484. function updateTotalProgress() {
  485. var loaded = 0,
  486. total = 0,
  487. spans = $progress.children(),
  488. percent;
  489. $.each(percentages, function (k, v) {
  490. total += v[ 0 ];
  491. loaded += v[ 0 ] * v[ 1 ];
  492. });
  493. percent = total ? loaded / total : 0;
  494. spans.eq(0).text(Math.round(percent * 100) + '%');
  495. spans.eq(1).css('width', Math.round(percent * 100) + '%');
  496. updateStatus();
  497. }
  498. function setState(val, files) {
  499. if (val != state) {
  500. var stats = uploader.getStats();
  501. $upload.removeClass('state-' + state);
  502. $upload.addClass('state-' + val);
  503. switch (val) {
  504. /* 未选择文件 */
  505. case 'pedding':
  506. $queue.addClass('element-invisible');
  507. $statusBar.addClass('element-invisible');
  508. $placeHolder.removeClass('element-invisible');
  509. $progress.hide(); $info.hide();
  510. uploader.refresh();
  511. break;
  512. /* 可以开始上传 */
  513. case 'ready':
  514. $placeHolder.addClass('element-invisible');
  515. $queue.removeClass('element-invisible');
  516. $statusBar.removeClass('element-invisible');
  517. $progress.hide(); $info.show();
  518. $upload.text(lang.uploadStart);
  519. uploader.refresh();
  520. break;
  521. /* 上传中 */
  522. case 'uploading':
  523. $progress.show(); $info.hide();
  524. $upload.text(lang.uploadPause);
  525. break;
  526. /* 暂停上传 */
  527. case 'paused':
  528. $progress.show(); $info.hide();
  529. $upload.text(lang.uploadContinue);
  530. break;
  531. case 'confirm':
  532. $progress.show(); $info.hide();
  533. $upload.text(lang.uploadStart);
  534. stats = uploader.getStats();
  535. if (stats.successNum && !stats.uploadFailNum) {
  536. setState('finish');
  537. return;
  538. }
  539. break;
  540. case 'finish':
  541. $progress.hide(); $info.show();
  542. if (stats.uploadFailNum) {
  543. $upload.text(lang.uploadRetry);
  544. } else {
  545. $upload.text(lang.uploadStart);
  546. }
  547. break;
  548. }
  549. state = val;
  550. updateStatus();
  551. }
  552. if (!_this.getQueueCount()) {
  553. $upload.addClass('disabled')
  554. } else {
  555. $upload.removeClass('disabled')
  556. }
  557. }
  558. function updateStatus() {
  559. var text = '', stats;
  560. if (state === 'ready') {
  561. text = lang.updateStatusReady.replace('_', fileCount).replace('_KB', WebUploader.formatSize(fileSize));
  562. } else if (state === 'confirm') {
  563. stats = uploader.getStats();
  564. if (stats.uploadFailNum) {
  565. text = lang.updateStatusConfirm.replace('_', stats.successNum).replace('_', stats.successNum);
  566. }
  567. } else {
  568. stats = uploader.getStats();
  569. text = lang.updateStatusFinish.replace('_', fileCount).
  570. replace('_KB', WebUploader.formatSize(fileSize)).
  571. replace('_', stats.successNum);
  572. if (stats.uploadFailNum) {
  573. text += lang.updateStatusError.replace('_', stats.uploadFailNum);
  574. }
  575. }
  576. $info.html(text);
  577. }
  578. uploader.on('fileQueued', function (file) {
  579. /* 选择文件后设置上传相关的url和自定义参数 */
  580. editor.getOpt("imageUploadService")(_this, editor).setUploadData(file);
  581. fileCount++;
  582. fileSize += file.size;
  583. if (fileCount === 1) {
  584. $placeHolder.addClass('element-invisible');
  585. $statusBar.show();
  586. }
  587. addFile(file);
  588. });
  589. uploader.on('fileDequeued', function (file) {
  590. if (file.ext && acceptExtensions.indexOf(file.ext.toLowerCase()) != -1 && file.size <= imageMaxSize) {
  591. fileCount--;
  592. fileSize -= file.size;
  593. }
  594. removeFile(file);
  595. updateTotalProgress();
  596. });
  597. uploader.on('filesQueued', function (file) {
  598. if (!uploader.isInProgress() && (state == 'pedding' || state == 'finish' || state == 'confirm' || state == 'ready')) {
  599. setState('ready');
  600. }
  601. updateTotalProgress();
  602. });
  603. uploader.on('all', function (type, files) {
  604. switch (type) {
  605. case 'uploadFinished':
  606. setState('confirm', files);
  607. break;
  608. case 'startUpload':
  609. /* 设置Uploader配置项 */
  610. editor.getOpt("imageUploadService")(_this, editor).setUploaderOptions(uploader);
  611. setState('uploading', files);
  612. break;
  613. case 'stopUpload':
  614. setState('paused', files);
  615. break;
  616. }
  617. });
  618. uploader.on('uploadBeforeSend', function (object, data, headers) {
  619. editor.getOpt("imageUploadService")(_this, editor).setFormData(object, data, headers);
  620. });
  621. uploader.on('uploadProgress', function (file, percentage) {
  622. var $li = $('#' + file.id),
  623. $percent = $li.find('.progress span');
  624. $percent.css('width', percentage * 100 + '%');
  625. percentages[ file.id ][ 1 ] = percentage;
  626. updateTotalProgress();
  627. });
  628. uploader.on('uploadSuccess', function (file, res) {
  629. var $file = $('#' + file.id);
  630. try {
  631. if (editor.getOpt("imageUploadService")(_this, editor).getResponseSuccess(res)) {
  632. _this.imageList.push(res);
  633. $file.append('<span class="success"></span>');
  634. } else {
  635. $file.find('.error').text(res.message).show();
  636. }
  637. } catch (e) {
  638. $file.find('.error').text(lang.errorServerUpload).show();
  639. }
  640. });
  641. uploader.on('uploadError', function (file, code) {
  642. });
  643. uploader.on('error', function (code, file) {
  644. if (code == 'Q_TYPE_DENIED' || code == 'F_EXCEED_SIZE') {
  645. addFile(file);
  646. }
  647. });
  648. uploader.on('uploadComplete', function (file, ret) {
  649. });
  650. /* 上传按钮 */
  651. $upload.on('click', function () {
  652. if ($(this).hasClass('disabled')) {
  653. return false;
  654. }
  655. if (state === 'ready') {
  656. window.setTimeout(function() {
  657. uploader.upload();
  658. }, 500);
  659. } else if (state === 'paused') {
  660. window.setTimeout(function() {
  661. uploader.upload();
  662. }, 500);
  663. } else if (state === 'uploading') {
  664. uploader.stop();
  665. }
  666. });
  667. $upload.addClass('state-' + state);
  668. updateTotalProgress();
  669. },
  670. getQueueCount: function () {
  671. var file, i, status, readyFile = 0, files = this.uploader.getFiles();
  672. for (i = 0; file = files[i++]; ) {
  673. status = file.getStatus();
  674. if (status == 'queued' || status == 'uploading' || status == 'progress') readyFile++;
  675. }
  676. return readyFile;
  677. },
  678. destroy: function () {
  679. this.$wrap.remove();
  680. },
  681. getInsertList: function () {
  682. var i, data, list = [],
  683. align = getAlign(),
  684. prefix = editor.getOpt('imageUrlPrefix'),
  685. imageSrcField = editor.getOpt("imageUploadService")(this, editor).imageSrcField || 'url',
  686. imageSrc = '',
  687. imageSrcFieldKeys = imageSrcField.split('.');
  688. for (i = 0; i < this.imageList.length; i++) {
  689. data = this.imageList[i];
  690. if(imageSrcFieldKeys.length > 1) {
  691. function setImageSrc(obj, keys, index) {
  692. obj = obj[keys[index]];
  693. if (index < keys.length - 1) {
  694. setImageSrc(obj, keys, index += 1)
  695. } else {
  696. imageSrc = obj;
  697. }
  698. }
  699. setImageSrc(data, imageSrcFieldKeys, 0);
  700. } else {
  701. imageSrc = data[imageSrcField];
  702. }
  703. list.push({
  704. src: prefix + imageSrc,
  705. _src: prefix + imageSrc,
  706. alt: data.original,
  707. floatStyle: align
  708. });
  709. }
  710. return list;
  711. }
  712. };
  713. /* 在线图片 */
  714. function OnlineImage(target) {
  715. this.container = utils.isString(target) ? document.getElementById(target) : target;
  716. this.init();
  717. }
  718. OnlineImage.prototype = {
  719. init: function () {
  720. this.reset();
  721. this.initEvents();
  722. },
  723. /* 初始化容器 */
  724. initContainer: function () {
  725. this.container.innerHTML = '';
  726. this.list = document.createElement('ul');
  727. this.clearFloat = document.createElement('li');
  728. domUtils.addClass(this.list, 'list');
  729. domUtils.addClass(this.clearFloat, 'clearFloat');
  730. this.list.appendChild(this.clearFloat);
  731. this.container.appendChild(this.list);
  732. },
  733. /* 初始化滚动事件,滚动到地步自动拉取数据 */
  734. initEvents: function () {
  735. var _this = this;
  736. /* 滚动拉取图片 */
  737. domUtils.on($G('imageList'), 'scroll', function(e){
  738. var panel = this;
  739. if (panel.scrollHeight - (panel.offsetHeight + panel.scrollTop) < 10) {
  740. _this.getImageData();
  741. }
  742. });
  743. /* 选中图片 */
  744. domUtils.on(this.container, 'click', function (e) {
  745. var target = e.target || e.srcElement,
  746. li = target.parentNode;
  747. if (li.tagName.toLowerCase() == 'li') {
  748. if (domUtils.hasClass(li, 'selected')) {
  749. domUtils.removeClasses(li, 'selected');
  750. } else {
  751. domUtils.addClass(li, 'selected');
  752. }
  753. }
  754. });
  755. },
  756. /* 初始化第一次的数据 */
  757. initData: function () {
  758. /* 拉取数据需要使用的值 */
  759. this.state = 0;
  760. this.listSize = editor.getOpt('imageManagerListSize');
  761. this.listIndex = 0;
  762. this.listEnd = false;
  763. /* 第一次拉取数据 */
  764. this.getImageData();
  765. },
  766. /* 重置界面 */
  767. reset: function() {
  768. this.initContainer();
  769. this.initData();
  770. },
  771. /* 向后台拉取图片列表数据 */
  772. getImageData: function () {
  773. var _this = this;
  774. if(!_this.listEnd && !this.isLoadingData) {
  775. this.isLoadingData = true;
  776. var url = editor.getActionUrl(editor.getOpt('imageManagerActionName')),
  777. isJsonp = utils.isCrossDomainUrl(url);
  778. ajax.request(url, {
  779. 'timeout': 100000,
  780. 'dataType': isJsonp ? 'jsonp':'',
  781. 'data': utils.extend({
  782. start: this.listIndex,
  783. size: this.listSize
  784. }, editor.queryCommandValue('serverparam')),
  785. 'method': 'get',
  786. 'onsuccess': function (r) {
  787. try {
  788. var json = isJsonp ? r:eval('(' + r.responseText + ')');
  789. if (json.state == 'SUCCESS') {
  790. _this.pushData(json.list);
  791. _this.listIndex = parseInt(json.start) + parseInt(json.list.length);
  792. if(_this.listIndex >= json.total) {
  793. _this.listEnd = true;
  794. }
  795. _this.isLoadingData = false;
  796. }
  797. } catch (e) {
  798. if(r.responseText.indexOf('ue_separate_ue') != -1) {
  799. var list = r.responseText.split(r.responseText);
  800. _this.pushData(list);
  801. _this.listIndex = parseInt(list.length);
  802. _this.listEnd = true;
  803. _this.isLoadingData = false;
  804. }
  805. }
  806. },
  807. 'onerror': function () {
  808. _this.isLoadingData = false;
  809. }
  810. });
  811. }
  812. },
  813. /* 添加图片到列表界面上 */
  814. pushData: function (list) {
  815. var i, item, img, icon, _this = this,
  816. urlPrefix = editor.getOpt('imageManagerUrlPrefix');
  817. for (i = 0; i < list.length; i++) {
  818. if(list[i] && list[i].url) {
  819. item = document.createElement('li');
  820. img = document.createElement('img');
  821. icon = document.createElement('span');
  822. domUtils.on(img, 'load', (function(image){
  823. return function(){
  824. _this.scale(image, image.parentNode.offsetWidth, image.parentNode.offsetHeight);
  825. }
  826. })(img));
  827. img.width = 113;
  828. img.setAttribute('src', urlPrefix + list[i].url + (list[i].url.indexOf('?') == -1 ? '?noCache=':'&noCache=') + (+new Date()).toString(36) );
  829. img.setAttribute('_src', urlPrefix + list[i].url);
  830. domUtils.addClass(icon, 'icon');
  831. item.appendChild(img);
  832. item.appendChild(icon);
  833. this.list.insertBefore(item, this.clearFloat);
  834. }
  835. }
  836. },
  837. /* 改变图片大小 */
  838. scale: function (img, w, h, type) {
  839. var ow = img.width,
  840. oh = img.height;
  841. if (type == 'justify') {
  842. if (ow >= oh) {
  843. img.width = w;
  844. img.height = h * oh / ow;
  845. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  846. } else {
  847. img.width = w * ow / oh;
  848. img.height = h;
  849. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  850. }
  851. } else {
  852. if (ow >= oh) {
  853. img.width = w * ow / oh;
  854. img.height = h;
  855. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  856. } else {
  857. img.width = w;
  858. img.height = h * oh / ow;
  859. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  860. }
  861. }
  862. },
  863. getInsertList: function () {
  864. var i, lis = this.list.children, list = [], align = getAlign();
  865. for (i = 0; i < lis.length; i++) {
  866. if (domUtils.hasClass(lis[i], 'selected')) {
  867. var img = lis[i].firstChild,
  868. src = img.getAttribute('_src');
  869. list.push({
  870. src: src,
  871. _src: src,
  872. alt: src.substr(src.lastIndexOf('/') + 1),
  873. floatStyle: align
  874. });
  875. }
  876. }
  877. return list;
  878. }
  879. };
  880. /*搜索图片 */
  881. function SearchImage() {
  882. this.init();
  883. }
  884. SearchImage.prototype = {
  885. init: function () {
  886. this.initEvents();
  887. },
  888. initEvents: function(){
  889. var _this = this;
  890. /* 点击搜索按钮 */
  891. domUtils.on($G('searchBtn'), 'click', function(){
  892. var key = $G('searchTxt').value;
  893. if(key && key != lang.searchRemind) {
  894. _this.getImageData();
  895. }
  896. });
  897. /* 点击清除妞 */
  898. domUtils.on($G('searchReset'), 'click', function(){
  899. $G('searchTxt').value = lang.searchRemind;
  900. $G('searchListUl').innerHTML = '';
  901. $G('searchType').selectedIndex = 0;
  902. });
  903. /* 搜索框聚焦 */
  904. domUtils.on($G('searchTxt'), 'focus', function(){
  905. var key = $G('searchTxt').value;
  906. if(key && key == lang.searchRemind) {
  907. $G('searchTxt').value = '';
  908. }
  909. });
  910. /* 搜索框回车键搜索 */
  911. domUtils.on($G('searchTxt'), 'keydown', function(e){
  912. var keyCode = e.keyCode || e.which;
  913. if (keyCode == 13) {
  914. $G('searchBtn').click();
  915. }
  916. });
  917. /* 选中图片 */
  918. domUtils.on($G('searchList'), 'click', function(e){
  919. var target = e.target || e.srcElement,
  920. li = target.parentNode.parentNode;
  921. if (li.tagName.toLowerCase() == 'li') {
  922. if (domUtils.hasClass(li, 'selected')) {
  923. domUtils.removeClasses(li, 'selected');
  924. } else {
  925. domUtils.addClass(li, 'selected');
  926. }
  927. }
  928. });
  929. },
  930. /* 改变图片大小 */
  931. scale: function (img, w, h) {
  932. var ow = img.width,
  933. oh = img.height;
  934. if (ow >= oh) {
  935. img.width = w * ow / oh;
  936. img.height = h;
  937. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  938. } else {
  939. img.width = w;
  940. img.height = h * oh / ow;
  941. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  942. }
  943. },
  944. getImageData: function(){
  945. var _this = this,
  946. key = $G('searchTxt').value,
  947. type = $G('searchType').value,
  948. keepOriginName = editor.options.keepOriginName ? "1" : "0",
  949. pageNum = $G('pageNum').value,
  950. url = "https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord=" + key + "&cl=2" + type + "&ie=utf-8&oe=utf-8&adpicid=&z=&ic=0&word=" + key + "&se=&tab=&width=&height=&istype=2&qc=&nc=1&fr=&pn=60&rn=" + pageNum + "&gsm=78&" + new Date() + "=";
  951. $G('searchListUl').innerHTML = lang.searchLoading;
  952. ajax.request(url, {
  953. 'dataType': 'jsonp',
  954. 'onsuccess':function(json){
  955. var list = [];
  956. if(json && json.data) {
  957. for(var i = 0; i < json.data.length; i++) {
  958. if(json.data[i].objURL) {
  959. list.push({
  960. title: json.data[i].fromPageTitleEnc,
  961. src: json.data[i].thumbURL,
  962. url: json.data[i].thumbURL
  963. });
  964. }
  965. }
  966. }
  967. _this.setList(list);
  968. },
  969. 'onerror':function(){
  970. $G('searchListUl').innerHTML = lang.searchRetry;
  971. }
  972. });
  973. },
  974. /* 添加图片到列表界面上 */
  975. setList: function (list) {
  976. var i, item, p, img, link, _this = this,
  977. listUl = $G('searchListUl');
  978. listUl.innerHTML = '';
  979. if(list.length) {
  980. for (i = 0; i < list.length; i++) {
  981. item = document.createElement('li');
  982. p = document.createElement('p');
  983. img = document.createElement('img');
  984. link = document.createElement('a');
  985. img.onload = function () {
  986. _this.scale(this, 113, 113);
  987. };
  988. img.width = 113;
  989. img.setAttribute('src', list[i].src);
  990. link.href = list[i].url;
  991. link.target = '_blank';
  992. link.title = list[i].title;
  993. link.innerHTML = list[i].title;
  994. p.appendChild(img);
  995. item.appendChild(p);
  996. item.appendChild(link);
  997. listUl.appendChild(item);
  998. }
  999. } else {
  1000. listUl.innerHTML = lang.searchRetry;
  1001. }
  1002. },
  1003. getInsertList: function () {
  1004. var child,
  1005. src,
  1006. align = getAlign(),
  1007. list = [],
  1008. items = $G('searchListUl').children;
  1009. for(var i = 0; i < items.length; i++) {
  1010. child = items[i].firstChild && items[i].firstChild.firstChild;
  1011. if(child.tagName && child.tagName.toLowerCase() == 'img' && domUtils.hasClass(items[i], 'selected')) {
  1012. src = child.src;
  1013. list.push({
  1014. src: src,
  1015. _src: src,
  1016. alt: src.substr(src.lastIndexOf('/') + 1),
  1017. floatStyle: align
  1018. });
  1019. }
  1020. }
  1021. return list;
  1022. }
  1023. };
  1024. })();