jquery.ui.plupload.js 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. /**
  2. * jquery.ui.plupload.js
  3. *
  4. * Copyright 2013, Moxiecode Systems AB
  5. * Released under GPL License.
  6. *
  7. * License: http://www.plupload.com/license
  8. * Contributing: http://www.plupload.com/contributing
  9. *
  10. * Depends:
  11. * jquery.ui.core.js
  12. * jquery.ui.widget.js
  13. * jquery.ui.button.js
  14. * jquery.ui.progressbar.js
  15. *
  16. * Optionally:
  17. * jquery.ui.sortable.js
  18. */
  19. /* global jQuery:true */
  20. /**
  21. jQuery UI based implementation of the Plupload API - multi-runtime file uploading API.
  22. To use the widget you must include _jQuery_ and _jQuery UI_ bundle (including `ui.core`, `ui.widget`, `ui.button`,
  23. `ui.progressbar` and `ui.sortable`).
  24. In general the widget is designed the way that you do not usually need to do anything to it after you instantiate it.
  25. But! You still can intervenue, to some extent, in case you need to. Although, due to the fact that widget is based on
  26. _jQuery UI_ widget factory, there are some specifics. See examples below for more details.
  27. @example
  28. <!-- Instantiating: -->
  29. <div id="uploader">
  30. <p>Your browser doesn't have Flash, Silverlight or HTML5 support.</p>
  31. </div>
  32. <script>
  33. $('#uploader').plupload({
  34. url : '../upload.php',
  35. filters : [
  36. {title : "Image files", extensions : "jpg,gif,png"}
  37. ],
  38. rename: true,
  39. sortable: true,
  40. flash_swf_url : '../../js/Moxie.swf',
  41. silverlight_xap_url : '../../js/Moxie.xap',
  42. });
  43. </script>
  44. @example
  45. // Invoking methods:
  46. $('#uploader').plupload(options);
  47. // Display welcome message in the notification area
  48. $('#uploader').plupload('notify', 'info', "This might be obvious, but you need to click 'Add Files' to add some files.");
  49. @example
  50. // Subscribing to the events...
  51. // ... on initialization:
  52. $('#uploader').plupload({
  53. ...
  54. viewchanged: function(event, args) {
  55. // stuff ...
  56. }
  57. });
  58. // ... or after initialization
  59. $('#uploader').on("viewchanged", function(event, args) {
  60. // stuff ...
  61. });
  62. @class UI.Plupload
  63. @constructor
  64. @param {Object} settings For detailed information about each option check documentation.
  65. @param {String} settings.url URL of the server-side upload handler.
  66. @param {Number|String} [settings.chunk_size=0] Chunk size in bytes to slice the file into. Shorcuts with b, kb, mb, gb, tb suffixes also supported. `e.g. 204800 or "204800b" or "200kb"`. By default - disabled.
  67. @param {String} [settings.file_data_name="file"] Name for the file field in Multipart formated message.
  68. @param {Array} [settings.filters=[]] Set of file type filters, each one defined by hash of title and extensions. `e.g. {title : "Image files", extensions : "jpg,jpeg,gif,png"}`. Dispatches `plupload.FILE_EXTENSION_ERROR`
  69. @param {String} [settings.flash_swf_url] URL of the Flash swf.
  70. @param {Object} [settings.headers] Custom headers to send with the upload. Hash of name/value pairs.
  71. @param {Number|String} [settings.max_file_size] Maximum file size that the user can pick, in bytes. Optionally supports b, kb, mb, gb, tb suffixes. `e.g. "10mb" or "1gb"`. By default - not set. Dispatches `plupload.FILE_SIZE_ERROR`.
  72. @param {Number} [settings.max_retries=0] How many times to retry the chunk or file, before triggering Error event.
  73. @param {Boolean} [settings.multipart=true] Whether to send file and additional parameters as Multipart formated message.
  74. @param {Object} [settings.multipart_params] Hash of key/value pairs to send with every file upload.
  75. @param {Boolean} [settings.multi_selection=true] Enable ability to select multiple files at once in file dialog.
  76. @param {Boolean} [settings.prevent_duplicates=false] Do not let duplicates into the queue. Dispatches `plupload.FILE_DUPLICATE_ERROR`.
  77. @param {String|Object} [settings.required_features] Either comma-separated list or hash of required features that chosen runtime should absolutely possess.
  78. @param {Object} [settings.resize] Enable resizng of images on client-side. Applies to `image/jpeg` and `image/png` only. `e.g. {width : 200, height : 200, quality : 90, crop: true}`
  79. @param {Number} [settings.resize.width] If image is bigger, it will be resized.
  80. @param {Number} [settings.resize.height] If image is bigger, it will be resized.
  81. @param {Number} [settings.resize.quality=90] Compression quality for jpegs (1-100).
  82. @param {Boolean} [settings.resize.crop=false] Whether to crop images to exact dimensions. By default they will be resized proportionally.
  83. @param {String} [settings.runtimes="html5,flash,silverlight,html4"] Comma separated list of runtimes, that Plupload will try in turn, moving to the next if previous fails.
  84. @param {String} [settings.silverlight_xap_url] URL of the Silverlight xap.
  85. @param {Boolean} [settings.unique_names=false] If true will generate unique filenames for uploaded files.
  86. @param {Boolean} [settings.autostart=false] Whether to auto start uploading right after file selection.
  87. @param {Boolean} [settings.dragdrop=true] Enable ability to add file to the queue by drag'n'dropping them from the desktop.
  88. @param {Boolean} [settings.rename=false] Enable ability to rename files in the queue.
  89. @param {Boolean} [settings.sortable=false] Enable ability to sort files in the queue, changing their uploading priority.
  90. @param {Object} [settings.buttons] Control the visibility of functional buttons.
  91. @param {Boolean} [settings.buttons.browse=true] Display browse button.
  92. @param {Boolean} [settings.buttons.start=true] Display start button.
  93. @param {Boolean} [settings.buttons.stop=true] Display stop button.
  94. @param {Object} [settings.views] Control various views of the file queue.
  95. @param {Boolean} [settings.views.list=true] Enable list view.
  96. @param {Boolean} [settings.views.thumbs=false] Enable thumbs view.
  97. @param {String} [settings.views.default='list'] Default view.
  98. @param {Boolean} [settings.views.remember=true] Whether to remember the current view (requires jQuery Cookie plugin).
  99. @param {Boolean} [settings.multiple_queues=true] Re-activate the widget after each upload procedure.
  100. @param {Number} [settings.max_file_count=0] Limit the number of files user is able to upload in one go, autosets _multiple_queues_ to _false_ (default is 0 - no limit).
  101. */
  102. (function(window, document, plupload, $) {
  103. /**
  104. Dispatched when the widget is initialized and ready.
  105. @event ready
  106. @param {plupload.Uploader} uploader Uploader instance sending the event.
  107. */
  108. /**
  109. Dispatched when file dialog is closed.
  110. @event selected
  111. @param {plupload.Uploader} uploader Uploader instance sending the event.
  112. @param {Array} files Array of selected files represented by plupload.File objects
  113. */
  114. /**
  115. Dispatched when file dialog is closed.
  116. @event removed
  117. @param {plupload.Uploader} uploader Uploader instance sending the event.
  118. @param {Array} files Array of removed files represented by plupload.File objects
  119. */
  120. /**
  121. Dispatched when upload is started.
  122. @event start
  123. @param {plupload.Uploader} uploader Uploader instance sending the event.
  124. */
  125. /**
  126. Dispatched when upload is stopped.
  127. @event stop
  128. @param {plupload.Uploader} uploader Uploader instance sending the event.
  129. */
  130. /**
  131. Dispatched during the upload process.
  132. @event progress
  133. @param {plupload.Uploader} uploader Uploader instance sending the event.
  134. @param {plupload.File} file File that is being uploaded (includes loaded and percent properties among others).
  135. @param {Number} size Total file size in bytes.
  136. @param {Number} loaded Number of bytes uploaded of the files total size.
  137. @param {Number} percent Number of percentage uploaded of the file.
  138. */
  139. /**
  140. Dispatched when file is uploaded.
  141. @event uploaded
  142. @param {plupload.Uploader} uploader Uploader instance sending the event.
  143. @param {plupload.File} file File that was uploaded.
  144. @param {Enum} status Status constant matching the plupload states QUEUED, UPLOADING, FAILED, DONE.
  145. */
  146. /**
  147. Dispatched when upload of the whole queue is complete.
  148. @event complete
  149. @param {plupload.Uploader} uploader Uploader instance sending the event.
  150. @param {Array} files Array of uploaded files represented by plupload.File objects
  151. */
  152. /**
  153. Dispatched when the view is changed, e.g. from `list` to `thumbs` or vice versa.
  154. @event viewchanged
  155. @param {plupload.Uploader} uploader Uploader instance sending the event.
  156. @param {String} type Current view type.
  157. */
  158. /**
  159. Dispatched when error of some kind is detected.
  160. @event error
  161. @param {plupload.Uploader} uploader Uploader instance sending the event.
  162. @param {String} error Error message.
  163. @param {plupload.File} file File that was uploaded.
  164. @param {Enum} status Status constant matching the plupload states QUEUED, UPLOADING, FAILED, DONE.
  165. */
  166. var uploaders = {};
  167. function _(str) {
  168. return plupload.translate(str) || str;
  169. }
  170. function renderUI(obj) {
  171. obj.id = obj.attr('id');
  172. obj.html(
  173. '<div class="plupload_wrapper">' +
  174. '<div class="ui-widget-content plupload_container">' +
  175. '<div class="ui-state-default ui-widget-header plupload_header">' +
  176. '<div class="plupload_header_content">' +
  177. '<div class="plupload_logo"> </div>' +
  178. '<div class="plupload_header_title">' + _('Select files') + '</div>' +
  179. '<div class="plupload_header_text">' + _('Add files to the upload queue and click the start button.') + '</div>' +
  180. '<div class="plupload_view_switch">' +
  181. '<input type="radio" id="'+obj.id+'_view_list" name="view_mode_'+obj.id+'" checked="checked" /> <label class="plupload_button" for="'+obj.id+'_view_list" data-view="list">' + _('List') + '</label>' +
  182. '<input type="radio" id="'+obj.id+'_view_thumbs" name="view_mode_'+obj.id+'" /> <label class="plupload_button" for="'+obj.id+'_view_thumbs" data-view="thumbs">' + _('Thumbnails') + '</label>' +
  183. '</div>' +
  184. '</div>' +
  185. '</div>' +
  186. '<table class="plupload_filelist plupload_filelist_header ui-widget-header">' +
  187. '<tr>' +
  188. '<td class="plupload_cell plupload_file_name">' + _('Filename') + '</td>' +
  189. '<td class="plupload_cell plupload_file_status">' + _('Status') + '</td>' +
  190. '<td class="plupload_cell plupload_file_size">' + _('Size') + '</td>' +
  191. '<td class="plupload_cell plupload_file_action">&nbsp;</td>' +
  192. '</tr>' +
  193. '</table>' +
  194. '<div class="plupload_content">' +
  195. '<div class="plupload_droptext">' + _("Drag files here.") + '</div>' +
  196. '<ul class="plupload_filelist_content"> </ul>' +
  197. '<div class="plupload_clearer">&nbsp;</div>' +
  198. '</div>' +
  199. '<table class="plupload_filelist plupload_filelist_footer ui-widget-header">' +
  200. '<tr>' +
  201. '<td class="plupload_cell plupload_file_name">' +
  202. '<div class="plupload_buttons"><!-- Visible -->' +
  203. '<a class="plupload_button plupload_add">' + _('Add Files') + '</a>&nbsp;' +
  204. '<a class="plupload_button plupload_start">' + _('Start Upload') + '</a>&nbsp;' +
  205. '<a class="plupload_button plupload_stop plupload_hidden">'+_('Stop Upload') + '</a>&nbsp;' +
  206. '</div>' +
  207. '<div class="plupload_started plupload_hidden"><!-- Hidden -->' +
  208. '<div class="plupload_progress plupload_right">' +
  209. '<div class="plupload_progress_container"></div>' +
  210. '</div>' +
  211. '<div class="plupload_cell plupload_upload_status"></div>' +
  212. '<div class="plupload_clearer">&nbsp;</div>' +
  213. '</div>' +
  214. '</td>' +
  215. '<td class="plupload_file_status"><span class="plupload_total_status">0%</span></td>' +
  216. '<td class="plupload_file_size"><span class="plupload_total_file_size">0 kb</span></td>' +
  217. '<td class="plupload_file_action"></td>' +
  218. '</tr>' +
  219. '</table>' +
  220. '</div>' +
  221. '<input class="plupload_count" value="0" type="hidden">' +
  222. '</div>'
  223. );
  224. }
  225. $.widget("ui.plupload", {
  226. widgetEventPrefix: '',
  227. imgs: {},
  228. contents_bak: '',
  229. options: {
  230. browse_button_hover: 'ui-state-hover',
  231. browse_button_active: 'ui-state-active',
  232. // widget specific
  233. dragdrop : true,
  234. multiple_queues: true, // re-use widget by default
  235. buttons: {
  236. browse: true,
  237. start: true,
  238. stop: true
  239. },
  240. views: {
  241. list: true,
  242. thumbs: false,
  243. active: 'list',
  244. remember: true // requires: https://github.com/carhartl/jquery-cookie, otherwise disabled even if set to true
  245. },
  246. autostart: false,
  247. sortable: false,
  248. rename: false,
  249. max_file_count: 0 // unlimited
  250. },
  251. FILE_COUNT_ERROR: -9001,
  252. _create: function() {
  253. var id = this.element.attr('id');
  254. if (!id) {
  255. id = plupload.guid();
  256. this.element.attr('id', id);
  257. }
  258. this.id = id;
  259. // backup the elements initial state
  260. this.contents_bak = this.element.html();
  261. renderUI(this.element);
  262. // container, just in case
  263. this.container = $('.plupload_container', this.element).attr('id', id + '_container');
  264. this.content = $('.plupload_content', this.element);
  265. if ($.fn.resizable) {
  266. this.container.resizable({
  267. handles: 's',
  268. minHeight: 300
  269. });
  270. }
  271. // list of files, may become sortable
  272. this.filelist = $('.plupload_filelist_content', this.container)
  273. .attr({
  274. id: id + '_filelist',
  275. unselectable: 'on'
  276. });
  277. // buttons
  278. this.browse_button = $('.plupload_add', this.container).attr('id', id + '_browse');
  279. this.start_button = $('.plupload_start', this.container).attr('id', id + '_start');
  280. this.stop_button = $('.plupload_stop', this.container).attr('id', id + '_stop');
  281. this.thumbs_switcher = $('#' + id + '_view_thumbs');
  282. this.list_switcher = $('#' + id + '_view_list');
  283. if ($.ui.button) {
  284. this.browse_button.button({
  285. icons: { primary: 'ui-icon-circle-plus' },
  286. disabled: true
  287. });
  288. this.start_button.button({
  289. icons: { primary: 'ui-icon-circle-arrow-e' },
  290. disabled: true
  291. });
  292. this.stop_button.button({
  293. icons: { primary: 'ui-icon-circle-close' }
  294. });
  295. this.list_switcher.button({
  296. text: false,
  297. icons: { secondary: "ui-icon-grip-dotted-horizontal" }
  298. });
  299. this.thumbs_switcher.button({
  300. text: false,
  301. icons: { secondary: "ui-icon-image" }
  302. });
  303. }
  304. // progressbar
  305. this.progressbar = $('.plupload_progress_container', this.container);
  306. if ($.ui.progressbar) {
  307. this.progressbar.progressbar();
  308. }
  309. // counter
  310. this.counter = $('.plupload_count', this.element)
  311. .attr({
  312. id: id + '_count',
  313. name: id + '_count'
  314. });
  315. // initialize uploader instance
  316. this._initUploader();
  317. },
  318. _initUploader: function() {
  319. var self = this
  320. , id = this.id
  321. , uploader
  322. , options = {
  323. container: id + '_buttons',
  324. browse_button: id + '_browse'
  325. }
  326. ;
  327. $('.plupload_buttons', this.element).attr('id', id + '_buttons');
  328. if (self.options.dragdrop) {
  329. this.filelist.parent().attr('id', this.id + '_dropbox');
  330. options.drop_element = this.id + '_dropbox';
  331. }
  332. if (self.options.views.thumbs) {
  333. if (o.typeOf(self.options.required_features) === 'string') {
  334. self.options.required_features += ",display_media";
  335. } else {
  336. self.options.required_features = "display_media";
  337. }
  338. }
  339. uploader = this.uploader = uploaders[id] = new plupload.Uploader($.extend(this.options, options));
  340. uploader.bind('Error', function(up, err) {
  341. var message, details = "";
  342. message = '<strong>' + err.message + '</strong>';
  343. switch (err.code) {
  344. case plupload.FILE_EXTENSION_ERROR:
  345. details = o.sprintf(_("File: %s"), err.file.name);
  346. break;
  347. case plupload.FILE_SIZE_ERROR:
  348. details = o.sprintf(_("File: %f, size: %s, max file size: %m"), err.file.name, err.file.size, plupload.parseSize(self.options.max_file_size));
  349. break;
  350. case plupload.FILE_DUPLICATE_ERROR:
  351. details = o.sprintf(_("%s already present in the queue."), err.file.name);
  352. break;
  353. case self.FILE_COUNT_ERROR:
  354. details = o.sprintf(_("Upload element accepts only %d file(s) at a time. Extra files were stripped."), self.options.max_file_count);
  355. break;
  356. case plupload.IMAGE_FORMAT_ERROR :
  357. details = _("Image format either wrong or not supported.");
  358. break;
  359. case plupload.IMAGE_MEMORY_ERROR :
  360. details = _("Runtime ran out of available memory.");
  361. break;
  362. /* // This needs a review
  363. case plupload.IMAGE_DIMENSIONS_ERROR :
  364. details = o.sprintf(_('Resoultion out of boundaries! <b>%s</b> runtime supports images only up to %wx%hpx.'), up.runtime, up.features.maxWidth, up.features.maxHeight);
  365. break; */
  366. case plupload.HTTP_ERROR:
  367. details = _("Upload URL might be wrong or doesn't exist.");
  368. break;
  369. }
  370. message += " <br /><i>" + details + "</i>";
  371. self._trigger('error', null, { up: up, error: err } );
  372. // do not show UI if no runtime can be initialized
  373. if (err.code === plupload.INIT_ERROR) {
  374. setTimeout(function() {
  375. self.destroy();
  376. }, 1);
  377. } else {
  378. self.notify('error', message);
  379. }
  380. });
  381. uploader.bind('PostInit', function(up) {
  382. // all buttons are optional, so they can be disabled and hidden
  383. if (!self.options.buttons.browse) {
  384. self.browse_button.button('disable').hide();
  385. up.disableBrowse(true);
  386. } else {
  387. self.browse_button.button('enable');
  388. }
  389. if (!self.options.buttons.start) {
  390. self.start_button.button('disable').hide();
  391. }
  392. if (!self.options.buttons.stop) {
  393. self.stop_button.button('disable').hide();
  394. }
  395. if (!self.options.unique_names && self.options.rename) {
  396. self._enableRenaming();
  397. }
  398. if (self.options.dragdrop && up.features.dragdrop) {
  399. self.filelist.parent().addClass('plupload_dropbox');
  400. }
  401. self._enableViewSwitcher();
  402. self.start_button.click(function(e) {
  403. if (!$(this).button('option', 'disabled')) {
  404. self.start();
  405. }
  406. e.preventDefault();
  407. });
  408. self.stop_button.click(function(e) {
  409. self.stop();
  410. e.preventDefault();
  411. });
  412. self._trigger('ready', null, { up: up });
  413. });
  414. // check if file count doesn't exceed the limit
  415. if (self.options.max_file_count) {
  416. self.options.multiple_queues = false; // one go only
  417. uploader.bind('FilesAdded', function(up, selectedFiles) {
  418. var selectedCount = selectedFiles.length
  419. , extraCount = up.files.length + selectedCount - self.options.max_file_count
  420. ;
  421. if (extraCount > 0) {
  422. selectedFiles.splice(selectedCount - extraCount, extraCount);
  423. up.trigger('Error', {
  424. code : self.FILE_COUNT_ERROR,
  425. message : _('File count error.')
  426. });
  427. }
  428. });
  429. }
  430. // uploader internal events must run first
  431. uploader.init();
  432. uploader.bind('FilesAdded', function(up, files) {
  433. self._addFiles(files);
  434. self._trigger('selected', null, { up: up, files: files } );
  435. if (self.options.autostart) {
  436. // set a little delay to make sure that QueueChanged triggered by the core has time to complete
  437. setTimeout(function() {
  438. self.start();
  439. }, 10);
  440. }
  441. });
  442. uploader.bind('FilesRemoved', function(up, files) {
  443. self._trigger('removed', null, { up: up, files: files } );
  444. });
  445. uploader.bind('QueueChanged', function() {
  446. self._handleState();
  447. self._updateTotalProgress();
  448. });
  449. uploader.bind('StateChanged', function() {
  450. self._handleState();
  451. });
  452. uploader.bind('UploadFile', function(up, file) {
  453. self._handleFileStatus(file);
  454. });
  455. uploader.bind('FileUploaded', function(up, file) {
  456. self._handleFileStatus(file);
  457. self._trigger('uploaded', null, { up: up, file: file } );
  458. });
  459. uploader.bind('UploadProgress', function(up, file) {
  460. self._handleFileStatus(file);
  461. self._updateTotalProgress();
  462. self._trigger('progress', null, { up: up, file: file } );
  463. });
  464. uploader.bind('UploadComplete', function(up, files) {
  465. self._addFormFields();
  466. self._trigger('complete', null, { up: up, files: files } );
  467. });
  468. },
  469. _setOption: function(key, value) {
  470. var self = this;
  471. if (key == 'buttons' && typeof(value) == 'object') {
  472. value = $.extend(self.options.buttons, value);
  473. if (!value.browse) {
  474. self.browse_button.button('disable').hide();
  475. self.uploader.disableBrowse(true);
  476. } else {
  477. self.browse_button.button('enable').show();
  478. self.uploader.disableBrowse(false);
  479. }
  480. if (!value.start) {
  481. self.start_button.button('disable').hide();
  482. } else {
  483. self.start_button.button('enable').show();
  484. }
  485. if (!value.stop) {
  486. self.stop_button.button('disable').hide();
  487. } else {
  488. self.start_button.button('enable').show();
  489. }
  490. }
  491. self.uploader.settings[key] = value;
  492. },
  493. /**
  494. Start upload. Triggers `start` event.
  495. @method start
  496. */
  497. start: function() {
  498. this.uploader.start();
  499. this._trigger('start', null, { up: this.uploader });
  500. },
  501. /**
  502. Stop upload. Triggers `stop` event.
  503. @method stop
  504. */
  505. stop: function() {
  506. this.uploader.stop();
  507. this._trigger('stop', null, { up: this.uploader });
  508. },
  509. /**
  510. Enable browse button.
  511. @method enable
  512. */
  513. enable: function() {
  514. this.browse_button.button('enable');
  515. this.uploader.disableBrowse(false);
  516. },
  517. /**
  518. Disable browse button.
  519. @method disable
  520. */
  521. disable: function() {
  522. this.browse_button.button('disable');
  523. this.uploader.disableBrowse(true);
  524. },
  525. /**
  526. Retrieve file by it's unique id.
  527. @method getFile
  528. @param {String} id Unique id of the file
  529. @return {plupload.File}
  530. */
  531. getFile: function(id) {
  532. var file;
  533. if (typeof id === 'number') {
  534. file = this.uploader.files[id];
  535. } else {
  536. file = this.uploader.getFile(id);
  537. }
  538. return file;
  539. },
  540. /**
  541. Return array of files currently in the queue.
  542. @method getFiles
  543. @return {Array} Array of files in the queue represented by plupload.File objects
  544. */
  545. getFiles: function() {
  546. return this.uploader.files;
  547. },
  548. /**
  549. Remove the file from the queue.
  550. @method removeFile
  551. @param {plupload.File|String} file File to remove, might be specified directly or by it's unique id
  552. */
  553. removeFile: function(file) {
  554. if (plupload.typeOf(file) === 'string') {
  555. file = this.getFile(file);
  556. }
  557. this._removeFiles(file);
  558. },
  559. /**
  560. Clear the file queue.
  561. @method clearQueue
  562. */
  563. clearQueue: function() {
  564. this.uploader.splice();
  565. },
  566. /**
  567. Retrieve internal plupload.Uploader object (usually not required).
  568. @method getUploader
  569. @return {plupload.Uploader}
  570. */
  571. getUploader: function() {
  572. return this.uploader;
  573. },
  574. /**
  575. Trigger refresh procedure, specifically browse_button re-measure and re-position operations.
  576. Might get handy, when UI Widget is placed within the popup, that is constantly hidden and shown
  577. again - without calling this method after each show operation, dialog trigger might get displaced
  578. and disfunctional.
  579. @method refresh
  580. */
  581. refresh: function() {
  582. this.uploader.refresh();
  583. },
  584. /**
  585. Display a message in notification area.
  586. @method notify
  587. @param {Enum} type Type of the message, either `error` or `info`
  588. @param {String} message The text message to display.
  589. */
  590. notify: function(type, message) {
  591. var popup = $(
  592. '<div class="plupload_message">' +
  593. '<span class="plupload_message_close ui-icon ui-icon-circle-close" title="'+_('Close')+'"></span>' +
  594. '<p><span class="ui-icon"></span>' + message + '</p>' +
  595. '</div>'
  596. );
  597. popup
  598. .addClass('ui-state-' + (type === 'error' ? 'error' : 'highlight'))
  599. .find('p .ui-icon')
  600. .addClass('ui-icon-' + (type === 'error' ? 'alert' : 'info'))
  601. .end()
  602. .find('.plupload_message_close')
  603. .click(function() {
  604. popup.remove();
  605. })
  606. .end();
  607. $('.plupload_header', this.container).append(popup);
  608. },
  609. /**
  610. Destroy the widget, the uploader, free associated resources and bring back original html.
  611. @method destroy
  612. */
  613. destroy: function() {
  614. this._removeFiles([].slice.call(this.uploader.files));
  615. // destroy uploader instance
  616. this.uploader.destroy();
  617. // unbind all button events
  618. $('.plupload_button', this.element).unbind();
  619. // destroy buttons
  620. if ($.ui.button) {
  621. $('.plupload_add, .plupload_start, .plupload_stop', this.container)
  622. .button('destroy');
  623. }
  624. // destroy progressbar
  625. if ($.ui.progressbar) {
  626. this.progressbar.progressbar('destroy');
  627. }
  628. // destroy sortable behavior
  629. if ($.ui.sortable && this.options.sortable) {
  630. $('tbody', this.filelist).sortable('destroy');
  631. }
  632. // restore the elements initial state
  633. this.element
  634. .empty()
  635. .html(this.contents_bak);
  636. this.contents_bak = '';
  637. $.Widget.prototype.destroy.apply(this);
  638. },
  639. _handleState: function() {
  640. var up = this.uploader;
  641. if (up.state === plupload.STARTED) {
  642. $(this.start_button).button('disable');
  643. $([])
  644. .add(this.stop_button)
  645. .add('.plupload_started')
  646. .removeClass('plupload_hidden');
  647. $('.plupload_upload_status', this.element).html(o.sprintf(_('Uploaded %d/%d files'), up.total.uploaded, up.files.length));
  648. $('.plupload_header_content', this.element).addClass('plupload_header_content_bw');
  649. } else if (up.state === plupload.STOPPED) {
  650. $([])
  651. .add(this.stop_button)
  652. .add('.plupload_started')
  653. .addClass('plupload_hidden');
  654. if (this.options.multiple_queues) {
  655. $('.plupload_header_content', this.element).removeClass('plupload_header_content_bw');
  656. } else {
  657. $([])
  658. .add(this.browse_button)
  659. .add(this.start_button)
  660. .button('disable');
  661. up.disableBrowse();
  662. }
  663. if (up.files.length === (up.total.uploaded + up.total.failed)) {
  664. this.start_button.button('disable');
  665. } else {
  666. this.start_button.button('enable');
  667. }
  668. this._updateTotalProgress();
  669. }
  670. if (up.total.queued === 0) {
  671. $('.ui-button-text', this.browse_button).html(_('Add Files'));
  672. } else {
  673. $('.ui-button-text', this.browse_button).html(o.sprintf(_('%d files queued'), up.total.queued));
  674. }
  675. up.refresh();
  676. },
  677. _handleFileStatus: function(file) {
  678. var self = this, actionClass, iconClass;
  679. // since this method might be called asynchronously, file row might not yet be rendered
  680. if (!$('#' + file.id).length) {
  681. return;
  682. }
  683. switch (file.status) {
  684. case plupload.DONE:
  685. actionClass = 'plupload_done';
  686. iconClass = 'ui-icon ui-icon-circle-check';
  687. break;
  688. case plupload.FAILED:
  689. actionClass = 'ui-state-error plupload_failed';
  690. iconClass = 'ui-icon ui-icon-alert';
  691. break;
  692. case plupload.QUEUED:
  693. actionClass = 'plupload_delete';
  694. iconClass = 'ui-icon ui-icon-circle-minus';
  695. break;
  696. case plupload.UPLOADING:
  697. actionClass = 'ui-state-highlight plupload_uploading';
  698. iconClass = 'ui-icon ui-icon-circle-arrow-w';
  699. // scroll uploading file into the view if its bottom boundary is out of it
  700. var scroller = $('.plupload_scroll', this.container)
  701. , scrollTop = scroller.scrollTop()
  702. , scrollerHeight = scroller.height()
  703. , rowOffset = $('#' + file.id).position().top + $('#' + file.id).height()
  704. ;
  705. if (scrollerHeight < rowOffset) {
  706. scroller.scrollTop(scrollTop + rowOffset - scrollerHeight);
  707. }
  708. // Set file specific progress
  709. $('#' + file.id)
  710. .find('.plupload_file_percent')
  711. .html(file.percent + '%')
  712. .end()
  713. .find('.plupload_file_progress')
  714. .css('width', file.percent + '%')
  715. .end()
  716. .find('.plupload_file_size')
  717. .html(plupload.formatSize(file.size));
  718. break;
  719. }
  720. actionClass += ' ui-state-default plupload_file';
  721. $('#' + file.id)
  722. .attr('class', actionClass)
  723. .find('.ui-icon')
  724. .attr('class', iconClass)
  725. .end()
  726. .filter('.plupload_delete, .plupload_done, .plupload_failed')
  727. .find('.ui-icon')
  728. .click(function(e) {
  729. self._removeFiles(file);
  730. e.preventDefault();
  731. });
  732. },
  733. _updateTotalProgress: function() {
  734. var up = this.uploader;
  735. // Scroll to end of file list
  736. this.filelist[0].scrollTop = this.filelist[0].scrollHeight;
  737. this.progressbar.progressbar('value', up.total.percent);
  738. this.element
  739. .find('.plupload_total_status')
  740. .html(up.total.percent + '%')
  741. .end()
  742. .find('.plupload_total_file_size')
  743. .html(plupload.formatSize(up.total.size))
  744. .end()
  745. .find('.plupload_upload_status')
  746. .html(o.sprintf(_('Uploaded %d/%d files'), up.total.uploaded, up.files.length));
  747. },
  748. _addFiles: function(files) {
  749. var self = this, file_html, queue = [];
  750. file_html = '<li class="plupload_file ui-state-default" id="%id%">' +
  751. '<div class="plupload_file_thumb"> </div>' +
  752. '<div class="plupload_file_name" title="%name%"><span class="plupload_file_namespan">%name%</span></div>' +
  753. '<div class="plupload_file_action"><div class="ui-icon"> </div></div>' +
  754. '<div class="plupload_file_size">%size% </div>' +
  755. '<div class="plupload_file_fields"> </div>' +
  756. '</li>';
  757. if (plupload.typeOf(files) !== 'array') {
  758. files = [files];
  759. }
  760. // destroy sortable if enabled
  761. if ($.ui.sortable && this.options.sortable) {
  762. $('tbody', self.filelist).sortable('destroy');
  763. }
  764. // loop over files to add
  765. $.each(files, function(i, file) {
  766. self.filelist.append(file_html.replace(/%(\w+)%/g, function($0, $1) {
  767. if ('size' === $1) {
  768. return plupload.formatSize(file.size);
  769. } else {
  770. return file[$1] || '';
  771. }
  772. }));
  773. if (self.options.views.thumbs) {
  774. queue.push(function(cb) {
  775. var img = new o.Image();
  776. img.onload = function() {
  777. this.embed($('#' + file.id + ' .plupload_file_thumb', self.filelist)[0], {
  778. width: 100,
  779. height: 60,
  780. crop: true,
  781. swf_url: mOxie.resolveUrl(self.options.flash_swf_url),
  782. xap_url: mOxie.resolveUrl(self.options.silverlight_xap_url)
  783. });
  784. };
  785. img.onembedded = function() {
  786. $('#' + file.id + ' .plupload_file_thumb', self.filelist).addClass('plupload_file_thumb_loaded');
  787. this.destroy();
  788. setTimeout(cb, 1); // detach, otherwise ui might hang (in SilverLight for example)
  789. };
  790. img.onerror = function() {
  791. var ext = file.name.match(/\.([^\.]{1,7})$/);
  792. $('#' + file.id + ' .plupload_file_thumb', self.filelist)
  793. .html('<div class="plupload_file_dummy ui-widget-content"><span class="ui-state-disabled">' + (ext ? ext[1] : 'none') + '</span></div>');
  794. this.destroy();
  795. setTimeout(cb, 1);
  796. };
  797. img.load(file.getSource());
  798. });
  799. }
  800. self._handleFileStatus(file);
  801. });
  802. if (queue.length) {
  803. o.inSeries(queue);
  804. }
  805. // re-enable sortable
  806. if (this.options.sortable && $.ui.sortable) {
  807. this._enableSortingList();
  808. }
  809. this._trigger('updatelist', null, { filelist: this.filelist });
  810. },
  811. _removeFiles: function(files) {
  812. var self = this, up = this.uploader;
  813. if (plupload.typeOf(files) !== 'array') {
  814. files = [files];
  815. }
  816. // destroy sortable if enabled
  817. if ($.ui.sortable && this.options.sortable) {
  818. $('tbody', self.filelist).sortable('destroy');
  819. }
  820. $.each(files, function(i, file) {
  821. if (file.imgs && file.imgs.length) {
  822. $.each(file.imgs, function(ii, img) {
  823. img.destroy();
  824. });
  825. file.imgs = [];
  826. }
  827. $('#' + file.id).remove();
  828. up.removeFile(file);
  829. });
  830. if (up.files.length) {
  831. // re-initialize sortable
  832. if (this.options.sortable && $.ui.sortable) {
  833. this._enableSortingList();
  834. }
  835. }
  836. this._trigger('updatelist', null, { filelist: this.filelist });
  837. },
  838. _addFormFields: function() {
  839. var self = this;
  840. // re-add from fresh
  841. $('.plupload_file_fields', this.filelist).html('');
  842. plupload.each(this.uploader.files, function(file, count) {
  843. var fields = ''
  844. , id = self.id + '_' + count
  845. ;
  846. if (file.target_name) {
  847. fields += '<input type="hidden" name="' + id + '_tmpname" value="'+plupload.xmlEncode(file.target_name)+'" />';
  848. }
  849. fields += '<input type="hidden" name="' + id + '_name" value="'+plupload.xmlEncode(file.name)+'" />';
  850. fields += '<input type="hidden" name="' + id + '_status" value="' + (file.status === plupload.DONE ? 'done' : 'failed') + '" />';
  851. $('#' + file.id).find('.plupload_file_fields').html(fields);
  852. });
  853. this.counter.val(this.uploader.files.length);
  854. },
  855. _viewChanged: function(view) {
  856. // update or write a new cookie
  857. if (this.options.views.remember && $.cookie) {
  858. $.cookie('plupload_ui_view', view, { expires: 7, path: '/' });
  859. }
  860. // ugly fix for IE6 - make content area stretchable
  861. if (mOxie.Env.browser === 'IE' && mOxie.Env.version < 7) {
  862. this.content.attr('style', 'height:expression(document.getElementById("' + this.id + '_container' + '").clientHeight - ' + (view === 'list' ? 133 : 103) + ');');
  863. }
  864. this.container.removeClass('plupload_view_list plupload_view_thumbs').addClass('plupload_view_' + view);
  865. this.view_mode = view;
  866. this._trigger('viewchanged', null, { view: view });
  867. },
  868. _enableViewSwitcher: function() {
  869. var self = this
  870. , view
  871. , switcher = $('.plupload_view_switch', this.container)
  872. , buttons
  873. , button
  874. ;
  875. plupload.each(['list', 'thumbs'], function(view) {
  876. if (!self.options.views[view]) {
  877. switcher.find('[for="' + self.id + '_view_' + view + '"], #'+ self.id +'_view_' + view).remove();
  878. }
  879. });
  880. // check if any visible left
  881. buttons = switcher.find('.plupload_button');
  882. if (buttons.length === 1) {
  883. switcher.hide();
  884. view = buttons.eq(0).data('view');
  885. this._viewChanged(view);
  886. } else if ($.ui.button && buttons.length > 1) {
  887. if (this.options.views.remember && $.cookie) {
  888. view = $.cookie('plupload_ui_view');
  889. }
  890. // if wierd case, bail out to default
  891. if (!~plupload.inArray(view, ['list', 'thumbs'])) {
  892. view = this.options.views.active;
  893. }
  894. switcher
  895. .show()
  896. .buttonset()
  897. .find('.ui-button')
  898. .click(function(e) {
  899. view = $(this).data('view');
  900. self._viewChanged(view);
  901. e.preventDefault(); // avoid auto scrolling to widget in IE and FF (see #850)
  902. });
  903. // if view not active - happens when switcher wasn't clicked manually
  904. button = switcher.find('[for="' + self.id + '_view_'+view+'"]');
  905. if (button.length) {
  906. button.trigger('click');
  907. }
  908. } else {
  909. switcher.show();
  910. this._viewChanged(this.options.views.active);
  911. }
  912. },
  913. _enableRenaming: function() {
  914. var self = this;
  915. this.filelist.dblclick(function(e) {
  916. var nameSpan = $(e.target), nameInput, file, parts, name, ext = "";
  917. if (!nameSpan.hasClass('plupload_file_namespan')) {
  918. return;
  919. }
  920. // Get file name and split out name and extension
  921. file = self.uploader.getFile(nameSpan.closest('.plupload_file')[0].id);
  922. name = file.name;
  923. parts = /^(.+)(\.[^.]+)$/.exec(name);
  924. if (parts) {
  925. name = parts[1];
  926. ext = parts[2];
  927. }
  928. // Display input element
  929. nameInput = $('<input class="plupload_file_rename" type="text" />').width(nameSpan.width()).insertAfter(nameSpan.hide());
  930. nameInput.val(name).blur(function() {
  931. nameSpan.show().parent().scrollLeft(0).end().next().remove();
  932. }).keydown(function(e) {
  933. var nameInput = $(this);
  934. if ($.inArray(e.keyCode, [13, 27]) !== -1) {
  935. e.preventDefault();
  936. // Rename file and glue extension back on
  937. if (e.keyCode === 13) {
  938. file.name = nameInput.val() + ext;
  939. nameSpan.html(file.name);
  940. }
  941. nameInput.blur();
  942. }
  943. })[0].focus();
  944. });
  945. },
  946. _enableSortingList: function() {
  947. var self = this, filelist = $('.plupload_filelist_content', this.element);
  948. if ($('.plupload_file', filelist).length < 2) {
  949. return;
  950. }
  951. filelist.sortable({
  952. items: '.plupload_delete',
  953. cancel: 'object, .plupload_clearer',
  954. stop: function() {
  955. var files = [];
  956. $.each($(this).sortable('toArray'), function(i, id) {
  957. files[files.length] = self.uploader.getFile(id);
  958. });
  959. files.unshift(files.length);
  960. files.unshift(0);
  961. // re-populate files array
  962. Array.prototype.splice.apply(self.uploader.files, files);
  963. }
  964. });
  965. }
  966. });
  967. } (window, document, plupload, jQuery));