jquery.ui.plupload.js 38 KB

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