jquery.ui.plupload.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358
  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 started
  126. @param {plupload.Uploader} uploader Uploader instance sending the event.
  127. */
  128. /**
  129. Dispatched when upload is stopped.
  130. @event stopped
  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. var me = $(e.target), fileContainer;
  338. if (me.hasClass('plupload_action_icon')) {
  339. fileContainer = me.closest('.plupload_file');
  340. if (fileContainer.hasClass('plupload_delete')) {
  341. self.removeFile(fileContainer.attr('id'));
  342. e.preventDefault();
  343. }
  344. }
  345. });
  346. uploader = this.uploader = uploaders[id] = new plupload.Uploader($.extend(this.options, options));
  347. // retrieve full normalized set of options
  348. this.options = uploader.getOption();
  349. if (self.options.views.thumbs) {
  350. uploader.settings.required_features.display_media = true;
  351. }
  352. // for backward compatibility
  353. if (self.options.max_file_count) {
  354. plupload.extend(uploader.getOption('filters'), {
  355. max_file_count: self.options.max_file_count
  356. });
  357. }
  358. plupload.addFileFilter('max_file_count', function(maxCount, file, cb) {
  359. if (maxCount <= this.files.length - (this.total.uploaded + this.total.failed)) {
  360. self.browse_button.button('disable');
  361. this.disableBrowse();
  362. this.trigger('Error', {
  363. code : self.FILE_COUNT_ERROR,
  364. message : _("File count error."),
  365. file : file
  366. });
  367. cb(false);
  368. } else {
  369. cb(true);
  370. }
  371. });
  372. uploader.bind('Error', function(up, err) {
  373. var message, details = "";
  374. message = '<strong>' + err.message + '</strong>';
  375. switch (err.code) {
  376. case plupload.FILE_EXTENSION_ERROR:
  377. details = plupload.sprintf(_("File: %s"), err.file.name);
  378. break;
  379. case plupload.FILE_SIZE_ERROR:
  380. details = plupload.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)));
  381. break;
  382. case plupload.FILE_DUPLICATE_ERROR:
  383. details = plupload.sprintf(_("%s already present in the queue."), err.file.name);
  384. break;
  385. case self.FILE_COUNT_ERROR:
  386. details = plupload.sprintf(_("Upload element accepts only %d file(s) at a time. Extra files were stripped."), up.getOption('filters').max_file_count || 0);
  387. break;
  388. case plupload.IMAGE_FORMAT_ERROR :
  389. details = _("Image format either wrong or not supported.");
  390. break;
  391. case plupload.IMAGE_MEMORY_ERROR :
  392. details = _("Runtime ran out of available memory.");
  393. break;
  394. /* // This needs a review
  395. case plupload.IMAGE_DIMENSIONS_ERROR :
  396. details = plupload.sprintf(_('Resoultion out of boundaries! <b>%s</b> runtime supports images only up to %wx%hpx.'), up.runtime, up.features.maxWidth, up.features.maxHeight);
  397. break; */
  398. case plupload.HTTP_ERROR:
  399. details = _("Upload URL might be wrong or doesn't exist.");
  400. break;
  401. }
  402. message += " <br /><i>" + details + "</i>";
  403. self._trigger('error', null, { up: up, error: err } );
  404. // do not show UI if no runtime can be initialized
  405. if (err.code === plupload.INIT_ERROR) {
  406. setTimeout(function() {
  407. self.destroy();
  408. }, 1);
  409. } else {
  410. self.notify('error', message);
  411. }
  412. });
  413. uploader.bind('PostInit', function(up) {
  414. // all buttons are optional, so they can be disabled and hidden
  415. if (!self.options.buttons.browse) {
  416. self.browse_button.button('disable').hide();
  417. up.disableBrowse(true);
  418. } else {
  419. self.browse_button.button('enable');
  420. }
  421. if (!self.options.buttons.start) {
  422. self.start_button.button('disable').hide();
  423. }
  424. if (!self.options.buttons.stop) {
  425. self.stop_button.button('disable').hide();
  426. }
  427. if (!self.options.unique_names && self.options.rename) {
  428. self._enableRenaming();
  429. }
  430. if (self.options.dragdrop && up.features.dragdrop) {
  431. self.filelist.parent().addClass('plupload_dropbox');
  432. }
  433. self._enableViewSwitcher();
  434. self.start_button.click(function(e) {
  435. if (!$(this).button('option', 'disabled')) {
  436. self.start();
  437. }
  438. e.preventDefault();
  439. });
  440. self.stop_button.click(function(e) {
  441. self.stop();
  442. e.preventDefault();
  443. });
  444. self._trigger('ready', null, { up: up });
  445. });
  446. // uploader internal events must run first
  447. uploader.init();
  448. uploader.bind('FileFiltered', function(up, file) {
  449. self._addFiles(file);
  450. });
  451. uploader.bind('FilesAdded', function(up, files) {
  452. self._trigger('selected', null, { up: up, files: files } );
  453. // re-enable sortable
  454. if (self.options.sortable && $.ui.sortable) {
  455. self._enableSortingList();
  456. }
  457. self._trigger('updatelist', null, { filelist: self.filelist });
  458. if (self.options.autostart) {
  459. // set a little delay to make sure that QueueChanged triggered by the core has time to complete
  460. setTimeout(function() {
  461. self.start();
  462. }, 10);
  463. }
  464. });
  465. uploader.bind('FilesRemoved', function(up, files) {
  466. // destroy sortable if enabled
  467. if ($.ui.sortable && self.options.sortable) {
  468. $('tbody', self.filelist).sortable('destroy');
  469. }
  470. $.each(files, function(i, file) {
  471. $('#' + file.id).toggle("highlight", function() {
  472. $(this).remove();
  473. });
  474. });
  475. if (up.files.length) {
  476. // re-initialize sortable
  477. if (self.options.sortable && $.ui.sortable) {
  478. self._enableSortingList();
  479. }
  480. }
  481. self._trigger('updatelist', null, { filelist: self.filelist });
  482. self._trigger('removed', null, { up: up, files: files } );
  483. });
  484. uploader.bind('QueueChanged', function() {
  485. self._handleState();
  486. });
  487. uploader.bind('StateChanged', function(up) {
  488. self._handleState();
  489. if (plupload.STARTED === up.state) {
  490. self._trigger('started', null, { up: this.uploader });
  491. } else if (plupload.STOPPED === up.state) {
  492. self._trigger('stopped', null, { up: this.uploader });
  493. }
  494. });
  495. uploader.bind('UploadFile', function(up, file) {
  496. self._handleFileStatus(file);
  497. });
  498. uploader.bind('FileUploaded', function(up, file, result) {
  499. self._handleFileStatus(file);
  500. self._trigger('uploaded', null, { up: up, file: file, result: result } );
  501. });
  502. uploader.bind('UploadProgress', function(up, file) {
  503. self._handleFileStatus(file);
  504. self._updateTotalProgress();
  505. self._trigger('progress', null, { up: up, file: file } );
  506. });
  507. uploader.bind('UploadComplete', function(up, files) {
  508. self._addFormFields();
  509. self._trigger('complete', null, { up: up, files: files } );
  510. });
  511. },
  512. _setOption: function(key, value) {
  513. var self = this;
  514. if (key == 'buttons' && typeof(value) == 'object') {
  515. value = $.extend(self.options.buttons, value);
  516. if (!value.browse) {
  517. self.browse_button.button('disable').hide();
  518. self.uploader.disableBrowse(true);
  519. } else {
  520. self.browse_button.button('enable').show();
  521. self.uploader.disableBrowse(false);
  522. }
  523. if (!value.start) {
  524. self.start_button.button('disable').hide();
  525. } else {
  526. self.start_button.button('enable').show();
  527. }
  528. if (!value.stop) {
  529. self.stop_button.button('disable').hide();
  530. } else {
  531. self.start_button.button('enable').show();
  532. }
  533. }
  534. self.uploader.setOption(key, value);
  535. },
  536. /**
  537. Start upload. Triggers `start` event.
  538. @method start
  539. */
  540. start: function() {
  541. this.uploader.start();
  542. },
  543. /**
  544. Stop upload. Triggers `stop` event.
  545. @method stop
  546. */
  547. stop: function() {
  548. this.uploader.stop();
  549. },
  550. /**
  551. Enable browse button.
  552. @method enable
  553. */
  554. enable: function() {
  555. this.browse_button.button('enable');
  556. this.uploader.disableBrowse(false);
  557. },
  558. /**
  559. Disable browse button.
  560. @method disable
  561. */
  562. disable: function() {
  563. this.browse_button.button('disable');
  564. this.uploader.disableBrowse(true);
  565. },
  566. /**
  567. Retrieve file by its unique id.
  568. @method getFile
  569. @param {String} id Unique id of the file
  570. @return {plupload.File}
  571. */
  572. getFile: function(id) {
  573. var file;
  574. if (typeof id === 'number') {
  575. file = this.uploader.files[id];
  576. } else {
  577. file = this.uploader.getFile(id);
  578. }
  579. return file;
  580. },
  581. /**
  582. Return array of files currently in the queue.
  583. @method getFiles
  584. @return {Array} Array of files in the queue represented by plupload.File objects
  585. */
  586. getFiles: function() {
  587. return this.uploader.files;
  588. },
  589. /**
  590. Remove the file from the queue.
  591. @method removeFile
  592. @param {plupload.File|String} file File to remove, might be specified directly or by its unique id
  593. */
  594. removeFile: function(file) {
  595. if (plupload.typeOf(file) === 'string') {
  596. file = this.getFile(file);
  597. }
  598. this.uploader.removeFile(file);
  599. },
  600. /**
  601. Clear the file queue.
  602. @method clearQueue
  603. */
  604. clearQueue: function() {
  605. this.uploader.splice();
  606. },
  607. /**
  608. Retrieve internal plupload.Uploader object (usually not required).
  609. @method getUploader
  610. @return {plupload.Uploader}
  611. */
  612. getUploader: function() {
  613. return this.uploader;
  614. },
  615. /**
  616. Trigger refresh procedure, specifically browse_button re-measure and re-position operations.
  617. Might get handy, when UI Widget is placed within the popup, that is constantly hidden and shown
  618. again - without calling this method after each show operation, dialog trigger might get displaced
  619. and disfunctional.
  620. @method refresh
  621. */
  622. refresh: function() {
  623. this.uploader.refresh();
  624. },
  625. /**
  626. Display a message in notification area.
  627. @method notify
  628. @param {Enum} type Type of the message, either `error` or `info`
  629. @param {String} message The text message to display.
  630. */
  631. notify: function(type, message) {
  632. var popup = $(
  633. '<div class="plupload_message">' +
  634. '<span class="plupload_message_close ui-icon ui-icon-circle-close" title="'+_('Close')+'"></span>' +
  635. '<p><span class="ui-icon"></span>' + message + '</p>' +
  636. '</div>'
  637. );
  638. popup
  639. .addClass('ui-state-' + (type === 'error' ? 'error' : 'highlight'))
  640. .find('p .ui-icon')
  641. .addClass('ui-icon-' + (type === 'error' ? 'alert' : 'info'))
  642. .end()
  643. .find('.plupload_message_close')
  644. .click(function() {
  645. popup.remove();
  646. })
  647. .end();
  648. $('.plupload_header', this.container).append(popup);
  649. },
  650. /**
  651. Destroy the widget, the uploader, free associated resources and bring back original html.
  652. @method destroy
  653. */
  654. destroy: function() {
  655. // destroy uploader instance
  656. this.uploader.destroy();
  657. // unbind all button events
  658. $('.plupload_button', this.element).unbind();
  659. // destroy buttons
  660. if ($.ui.button) {
  661. $('.plupload_add, .plupload_start, .plupload_stop', this.container)
  662. .button('destroy');
  663. }
  664. // destroy progressbar
  665. if ($.ui.progressbar) {
  666. this.progressbar.progressbar('destroy');
  667. }
  668. // destroy sortable behavior
  669. if ($.ui.sortable && this.options.sortable) {
  670. $('tbody', this.filelist).sortable('destroy');
  671. }
  672. // restore the elements initial state
  673. this.element
  674. .empty()
  675. .html(this.contents_bak);
  676. this.contents_bak = '';
  677. $.Widget.prototype.destroy.apply(this);
  678. },
  679. _handleState: function() {
  680. var up = this.uploader
  681. , filesPending = up.files.length - (up.total.uploaded + up.total.failed)
  682. , maxCount = up.getOption('filters').max_file_count || 0
  683. ;
  684. if (plupload.STARTED === up.state) {
  685. $([])
  686. .add(this.stop_button)
  687. .add('.plupload_started')
  688. .removeClass('plupload_hidden');
  689. this.start_button.button('disable');
  690. if (!this.options.multiple_queues) {
  691. this.browse_button.button('disable');
  692. up.disableBrowse();
  693. }
  694. $('.plupload_upload_status', this.element).html(plupload.sprintf(_('Uploaded %d/%d files'), up.total.uploaded, up.files.length));
  695. $('.plupload_header_content', this.element).addClass('plupload_header_content_bw');
  696. }
  697. else if (plupload.STOPPED === up.state) {
  698. $([])
  699. .add(this.stop_button)
  700. .add('.plupload_started')
  701. .addClass('plupload_hidden');
  702. if (filesPending) {
  703. this.start_button.button('enable');
  704. } else {
  705. this.start_button.button('disable');
  706. }
  707. if (this.options.multiple_queues) {
  708. $('.plupload_header_content', this.element).removeClass('plupload_header_content_bw');
  709. }
  710. // if max_file_count defined, only that many files can be queued at once
  711. if (this.options.multiple_queues && maxCount && maxCount > filesPending) {
  712. this.browse_button.button('enable');
  713. up.disableBrowse(false);
  714. }
  715. this._updateTotalProgress();
  716. }
  717. if (up.total.queued === 0) {
  718. $('.ui-button-text', this.browse_button).html(_('Add Files'));
  719. } else {
  720. $('.ui-button-text', this.browse_button).html(plupload.sprintf(_('%d files queued'), up.total.queued));
  721. }
  722. // have a helper class on a container expressing whether it has files queued or not
  723. this.container.toggleClass('plupload_files_queued', up.files.length);
  724. up.refresh();
  725. },
  726. _handleFileStatus: function(file) {
  727. var $file = $('#' + file.id), actionClass, iconClass;
  728. // since this method might be called asynchronously, file row might not yet be rendered
  729. if (!$file.length) {
  730. return;
  731. }
  732. switch (file.status) {
  733. case plupload.DONE:
  734. actionClass = 'plupload_done';
  735. iconClass = 'plupload_action_icon ui-icon ui-icon-circle-check';
  736. break;
  737. case plupload.FAILED:
  738. actionClass = 'ui-state-error plupload_failed';
  739. iconClass = 'plupload_action_icon ui-icon ui-icon-alert';
  740. break;
  741. case plupload.QUEUED:
  742. actionClass = 'plupload_delete';
  743. iconClass = 'plupload_action_icon ui-icon ui-icon-circle-minus';
  744. break;
  745. case plupload.UPLOADING:
  746. actionClass = 'ui-state-highlight plupload_uploading';
  747. iconClass = 'plupload_action_icon ui-icon ui-icon-circle-arrow-w';
  748. // scroll uploading file into the view if its bottom boundary is out of it
  749. var scroller = $('.plupload_scroll', this.container)
  750. , scrollTop = scroller.scrollTop()
  751. , scrollerHeight = scroller.height()
  752. , rowOffset = $file.position().top + $file.height()
  753. ;
  754. if (scrollerHeight < rowOffset) {
  755. scroller.scrollTop(scrollTop + rowOffset - scrollerHeight);
  756. }
  757. // Set file specific progress
  758. $file
  759. .find('.plupload_file_percent')
  760. .html(file.percent + '%')
  761. .end()
  762. .find('.plupload_file_progress')
  763. .css('width', file.percent + '%')
  764. .end()
  765. .find('.plupload_file_size')
  766. .html(plupload.formatSize(file.size));
  767. break;
  768. }
  769. actionClass += ' ui-state-default plupload_file';
  770. $file
  771. .attr('class', actionClass)
  772. .find('.plupload_action_icon')
  773. .attr('class', iconClass);
  774. },
  775. _updateTotalProgress: function() {
  776. var up = this.uploader;
  777. // Scroll to end of file list
  778. this.filelist[0].scrollTop = this.filelist[0].scrollHeight;
  779. this.progressbar.progressbar('value', up.total.percent);
  780. this.element
  781. .find('.plupload_total_status')
  782. .html(up.total.percent + '%')
  783. .end()
  784. .find('.plupload_total_file_size')
  785. .html(plupload.formatSize(up.total.size))
  786. .end()
  787. .find('.plupload_upload_status')
  788. .html(plupload.sprintf(_('Uploaded %d/%d files'), up.total.uploaded, up.files.length));
  789. },
  790. _displayThumbs: function() {
  791. var self = this
  792. , tw, th // thumb width/height
  793. , cols
  794. , num = 0 // number of simultaneously visible thumbs
  795. , thumbs = [] // array of thumbs to preload at any given moment
  796. , loading = false
  797. ;
  798. if (!this.options.views.thumbs) {
  799. return;
  800. }
  801. function onLast(el, eventName, cb) {
  802. var timer;
  803. el.on(eventName, function() {
  804. clearTimeout(timer);
  805. timer = setTimeout(function() {
  806. clearTimeout(timer);
  807. cb();
  808. }, 300);
  809. });
  810. }
  811. // calculate number of simultaneously visible thumbs
  812. function measure() {
  813. if (!tw || !th) {
  814. var wrapper = $('.plupload_file:eq(0)', self.filelist);
  815. tw = wrapper.outerWidth(true);
  816. th = wrapper.outerHeight(true);
  817. }
  818. var aw = self.content.width(), ah = self.content.height();
  819. cols = Math.floor(aw / tw);
  820. num = cols * (Math.ceil(ah / th) + 1);
  821. }
  822. function pickThumbsToLoad() {
  823. // calculate index of virst visible thumb
  824. var startIdx = Math.floor(self.content.scrollTop() / th) * cols;
  825. // get potentially visible thumbs that are not yet visible
  826. thumbs = $('.plupload_file .plupload_file_thumb', self.filelist)
  827. .slice(startIdx, startIdx + num)
  828. .filter('.plupload_thumb_toload')
  829. .get();
  830. }
  831. function init() {
  832. function mpl() { // measure, pick, load
  833. if (self.view_mode !== 'thumbs') {
  834. return;
  835. }
  836. measure();
  837. pickThumbsToLoad();
  838. lazyLoad();
  839. }
  840. if ($.fn.resizable) {
  841. onLast(self.container, 'resize', mpl);
  842. }
  843. onLast(self.window, 'resize', mpl);
  844. onLast(self.content, 'scroll', mpl);
  845. self.element.on('viewchanged selected', mpl);
  846. mpl();
  847. }
  848. function preloadThumb(file, cb) {
  849. var img = new o.image.Image();
  850. var resolveUrl = o.core.utils.Url.resolveUrl;
  851. img.onload = function() {
  852. var thumb = $('#' + file.id + ' .plupload_file_thumb', self.filelist);
  853. this.embed(thumb[0], {
  854. width: self.options.thumb_width,
  855. height: self.options.thumb_height,
  856. crop: true,
  857. fit: true,
  858. preserveHeaders: false,
  859. swf_url: resolveUrl(self.options.flash_swf_url),
  860. xap_url: resolveUrl(self.options.silverlight_xap_url)
  861. });
  862. };
  863. img.bind("embedded error", function(e) {
  864. $('#' + file.id, self.filelist)
  865. .find('.plupload_file_thumb')
  866. .removeClass('plupload_thumb_loading')
  867. .addClass('plupload_thumb_' + e.type)
  868. ;
  869. this.destroy();
  870. setTimeout(cb, 1); // detach, otherwise ui might hang (in SilverLight for example)
  871. });
  872. $('#' + file.id, self.filelist)
  873. .find('.plupload_file_thumb')
  874. .removeClass('plupload_thumb_toload')
  875. .addClass('plupload_thumb_loading')
  876. ;
  877. img.load(file.getSource());
  878. }
  879. function lazyLoad() {
  880. if (self.view_mode !== 'thumbs' || loading) {
  881. return;
  882. }
  883. pickThumbsToLoad();
  884. if (!thumbs.length) {
  885. return;
  886. }
  887. loading = true;
  888. preloadThumb(self.getFile($(thumbs.shift()).closest('.plupload_file').attr('id')), function() {
  889. loading = false;
  890. lazyLoad();
  891. });
  892. }
  893. // this has to run only once to measure structures and bind listeners
  894. this.element.on('selected', function onselected() {
  895. self.element.off('selected', onselected);
  896. init();
  897. });
  898. },
  899. _addFiles: function(files) {
  900. var self = this, file_html, html = '';
  901. file_html = '<li class="plupload_file ui-state-default plupload_delete" id="{id}" style="width:{thumb_width}px;">' +
  902. '<div class="plupload_file_thumb plupload_thumb_toload" style="width: {thumb_width}px; height: {thumb_height}px;">' +
  903. '<div class="plupload_file_dummy ui-widget-content" style="line-height: {thumb_height}px;"><span class="ui-state-disabled">{ext} </span></div>' +
  904. '</div>' +
  905. '<div class="plupload_file_status">' +
  906. '<div class="plupload_file_progress ui-widget-header" style="width: 0%"> </div>' +
  907. '<span class="plupload_file_percent">{percent} </span>' +
  908. '</div>' +
  909. '<div class="plupload_file_name" title="{name}">' +
  910. '<span class="plupload_file_name_wrapper">{name} </span>' +
  911. '</div>' +
  912. '<div class="plupload_file_action">' +
  913. '<div class="plupload_action_icon ui-icon ui-icon-circle-minus"> </div>' +
  914. '</div>' +
  915. '<div class="plupload_file_size">{size} </div>' +
  916. '<div class="plupload_file_fields"> </div>' +
  917. '</li>';
  918. if (plupload.typeOf(files) !== 'array') {
  919. files = [files];
  920. }
  921. $.each(files, function(i, file) {
  922. var ext = o.core.utils.Mime.getFileExtension(file.name) || 'none';
  923. html += file_html.replace(/\{(\w+)\}/g, function($0, $1) {
  924. switch ($1) {
  925. case 'thumb_width':
  926. case 'thumb_height':
  927. return self.options[$1];
  928. case 'size':
  929. return plupload.formatSize(file.size);
  930. case 'ext':
  931. return ext;
  932. default:
  933. return file[$1] || '';
  934. }
  935. });
  936. });
  937. self.filelist.append(html);
  938. },
  939. _addFormFields: function() {
  940. var self = this;
  941. // re-add from fresh
  942. $('.plupload_file_fields', this.filelist).html('');
  943. plupload.each(this.uploader.files, function(file, count) {
  944. var fields = ''
  945. , id = self.id + '_' + count
  946. ;
  947. if (file.target_name) {
  948. fields += '<input type="hidden" name="' + id + '_tmpname" value="'+plupload.xmlEncode(file.target_name)+'" />';
  949. }
  950. fields += '<input type="hidden" name="' + id + '_name" value="'+plupload.xmlEncode(file.name)+'" />';
  951. fields += '<input type="hidden" name="' + id + '_status" value="' + (file.status === plupload.DONE ? 'done' : 'failed') + '" />';
  952. $('#' + file.id).find('.plupload_file_fields').html(fields);
  953. });
  954. this.counter.val(this.uploader.files.length);
  955. },
  956. _viewChanged: function(view) {
  957. // update or write a new cookie
  958. if (this.options.views.remember && $.cookie) {
  959. $.cookie('plupload_ui_view', view, { expires: 7, path: '/' });
  960. }
  961. // ugly fix for IE6 - make content area stretchable
  962. if (plupload.ua.browser === 'IE' && plupload.ua.version < 7) {
  963. this.content.attr('style', 'height:expression(document.getElementById("' + this.id + '_container' + '").clientHeight - ' + (view === 'list' ? 132 : 102) + ')');
  964. }
  965. this.container.removeClass('plupload_view_list plupload_view_thumbs').addClass('plupload_view_' + view);
  966. this.view_mode = view;
  967. this._trigger('viewchanged', null, { view: view });
  968. },
  969. _enableViewSwitcher: function() {
  970. var self = this
  971. , view
  972. , switcher = $('.plupload_view_switch', this.container)
  973. , buttons
  974. , button
  975. ;
  976. plupload.each(['list', 'thumbs'], function(view) {
  977. if (!self.options.views[view]) {
  978. switcher.find('[for="' + self.id + '_view_' + view + '"], #'+ self.id +'_view_' + view).remove();
  979. }
  980. });
  981. // check if any visible left
  982. buttons = switcher.find('.plupload_button');
  983. if (buttons.length === 1) {
  984. switcher.hide();
  985. view = buttons.eq(0).data('view');
  986. this._viewChanged(view);
  987. } else if ($.ui.button && buttons.length > 1) {
  988. if (this.options.views.remember && $.cookie) {
  989. view = $.cookie('plupload_ui_view');
  990. }
  991. // if wierd case, bail out to default
  992. if (!~plupload.inArray(view, ['list', 'thumbs'])) {
  993. view = this.options.views.active;
  994. }
  995. switcher
  996. .show()
  997. .buttonset()
  998. .find('.ui-button')
  999. .click(function(e) {
  1000. view = $(this).data('view');
  1001. self._viewChanged(view);
  1002. e.preventDefault(); // avoid auto scrolling to widget in IE and FF (see #850)
  1003. });
  1004. // if view not active - happens when switcher wasn't clicked manually
  1005. button = switcher.find('[for="' + self.id + '_view_'+view+'"]');
  1006. if (button.length) {
  1007. button.trigger('click');
  1008. }
  1009. } else {
  1010. switcher.show();
  1011. this._viewChanged(this.options.views.active);
  1012. }
  1013. // initialize thumb viewer if requested
  1014. if (this.options.views.thumbs) {
  1015. this._displayThumbs();
  1016. }
  1017. },
  1018. _enableRenaming: function() {
  1019. var self = this;
  1020. this.filelist.dblclick(function(e) {
  1021. var nameInput, fileContainer, file, parts, name, ext = "";
  1022. var nameSpan = $(e.target);
  1023. if (!nameSpan.hasClass('plupload_file_name_wrapper')) {
  1024. return;
  1025. }
  1026. fileContainer = nameSpan.closest('.plupload_file');
  1027. if (!fileContainer.hasClass('plupload_delete')) {
  1028. return;
  1029. }
  1030. // Get file name and split out name and extension
  1031. file = self.uploader.getFile(fileContainer[0].id);
  1032. name = file.name;
  1033. parts = /^(.+)(\.[^.]+)$/.exec(name);
  1034. if (parts) {
  1035. name = parts[1];
  1036. ext = parts[2];
  1037. }
  1038. // Display input element
  1039. nameInput = $('<input class="plupload_file_rename" type="text" />').width(nameSpan.width()).insertAfter(nameSpan.hide());
  1040. nameInput.val(name).blur(function() {
  1041. nameSpan.show().parent().scrollLeft(0).end().next().remove();
  1042. }).keydown(function(e) {
  1043. var nameInput = $(this);
  1044. if ($.inArray(e.keyCode, [13, 27]) !== -1) {
  1045. e.preventDefault();
  1046. // Rename file and glue extension back on
  1047. if (e.keyCode === 13) {
  1048. file.name = nameInput.val() + ext;
  1049. nameSpan.html(file.name);
  1050. }
  1051. nameInput.blur();
  1052. }
  1053. })[0].focus();
  1054. });
  1055. },
  1056. _enableSortingList: function() {
  1057. var self = this;
  1058. if ($('.plupload_file', this.filelist).length < 2) {
  1059. return;
  1060. }
  1061. // destroy sortable if enabled
  1062. $('tbody', this.filelist).sortable('destroy');
  1063. // enable
  1064. this.filelist.sortable({
  1065. items: '.plupload_delete',
  1066. cancel: 'object, .plupload_clearer',
  1067. stop: function() {
  1068. var files = [];
  1069. $.each($(this).sortable('toArray'), function(i, id) {
  1070. files[files.length] = self.uploader.getFile(id);
  1071. });
  1072. files.unshift(files.length);
  1073. files.unshift(0);
  1074. // re-populate files array
  1075. Array.prototype.splice.apply(self.uploader.files, files);
  1076. }
  1077. });
  1078. }
  1079. });
  1080. } (window, document, plupload, moxie, jQuery));