index.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  1. const { Plugin } = require('@uppy/core')
  2. const Translator = require('@uppy/utils/lib/Translator')
  3. const DashboardUI = require('./components/Dashboard')
  4. const StatusBar = require('@uppy/status-bar')
  5. const Informer = require('@uppy/informer')
  6. const ThumbnailGenerator = require('@uppy/thumbnail-generator')
  7. const findAllDOMElements = require('@uppy/utils/lib/findAllDOMElements')
  8. const toArray = require('@uppy/utils/lib/toArray')
  9. const getDroppedFiles = require('@uppy/utils/lib/getDroppedFiles')
  10. const trapFocus = require('./utils/trapFocus')
  11. const cuid = require('cuid')
  12. const ResizeObserver = require('resize-observer-polyfill').default || require('resize-observer-polyfill')
  13. const createSuperFocus = require('./utils/createSuperFocus')
  14. const memoize = require('memoize-one').default || require('memoize-one')
  15. const TAB_KEY = 9
  16. const ESC_KEY = 27
  17. function createPromise () {
  18. const o = {}
  19. o.promise = new Promise((resolve, reject) => {
  20. o.resolve = resolve
  21. o.reject = reject
  22. })
  23. return o
  24. }
  25. function defaultPickerIcon () {
  26. return (
  27. <svg aria-hidden="true" focusable="false" width="30" height="30" viewBox="0 0 30 30">
  28. <path d="M15 30c8.284 0 15-6.716 15-15 0-8.284-6.716-15-15-15C6.716 0 0 6.716 0 15c0 8.284 6.716 15 15 15zm4.258-12.676v6.846h-8.426v-6.846H5.204l9.82-12.364 9.82 12.364H19.26z" />
  29. </svg>
  30. )
  31. }
  32. /**
  33. * Dashboard UI with previews, metadata editing, tabs for various services and more
  34. */
  35. module.exports = class Dashboard extends Plugin {
  36. static VERSION = require('../package.json').version
  37. constructor (uppy, opts) {
  38. super(uppy, opts)
  39. this.id = this.opts.id || 'Dashboard'
  40. this.title = 'Dashboard'
  41. this.type = 'orchestrator'
  42. this.modalName = `uppy-Dashboard-${cuid()}`
  43. this.defaultLocale = {
  44. strings: {
  45. closeModal: 'Close Modal',
  46. importFrom: 'Import from %{name}',
  47. addingMoreFiles: 'Adding more files',
  48. addMoreFiles: 'Add more files',
  49. dashboardWindowTitle: 'File Uploader Window (Press escape to close)',
  50. dashboardTitle: 'File Uploader',
  51. copyLinkToClipboardSuccess: 'Link copied to clipboard',
  52. copyLinkToClipboardFallback: 'Copy the URL below',
  53. copyLink: 'Copy link',
  54. fileSource: 'File source: %{name}',
  55. done: 'Done',
  56. back: 'Back',
  57. addMore: 'Add more',
  58. removeFile: 'Remove file',
  59. editFile: 'Edit file',
  60. editing: 'Editing %{file}',
  61. finishEditingFile: 'Finish editing file',
  62. saveChanges: 'Save changes',
  63. cancel: 'Cancel',
  64. myDevice: 'My Device',
  65. dropPaste: 'Drop files here, paste or %{browse}',
  66. dropPasteImport: 'Drop files here, paste, %{browse} or import from:',
  67. dropHint: 'Drop your files here',
  68. browse: 'browse',
  69. uploadComplete: 'Upload complete',
  70. uploadPaused: 'Upload paused',
  71. resumeUpload: 'Resume upload',
  72. pauseUpload: 'Pause upload',
  73. retryUpload: 'Retry upload',
  74. cancelUpload: 'Cancel upload',
  75. xFilesSelected: {
  76. 0: '%{smart_count} file selected',
  77. 1: '%{smart_count} files selected'
  78. },
  79. uploadingXFiles: {
  80. 0: 'Uploading %{smart_count} file',
  81. 1: 'Uploading %{smart_count} files'
  82. },
  83. processingXFiles: {
  84. 0: 'Processing %{smart_count} file',
  85. 1: 'Processing %{smart_count} files'
  86. },
  87. // The default `poweredBy2` string only combines the `poweredBy` string (%{backwardsCompat}) with the size.
  88. // Locales can override `poweredBy2` to specify a different word order. This is for backwards compat with
  89. // Uppy 1.9.x and below which did a naive concatenation of `poweredBy2 + size` instead of using a locale-specific
  90. // substitution.
  91. // TODO: In 2.0 `poweredBy2` should be removed in and `poweredBy` updated to use substitution.
  92. poweredBy2: '%{backwardsCompat} %{uppy}',
  93. poweredBy: 'Powered by'
  94. }
  95. }
  96. // set default options
  97. const defaultOptions = {
  98. target: 'body',
  99. metaFields: [],
  100. trigger: '#uppy-select-files',
  101. inline: false,
  102. width: 750,
  103. height: 550,
  104. thumbnailWidth: 280,
  105. waitForThumbnailsBeforeUpload: false,
  106. defaultPickerIcon,
  107. showLinkToFileUploadResult: true,
  108. showProgressDetails: false,
  109. hideUploadButton: false,
  110. hideCancelButton: false,
  111. hideRetryButton: false,
  112. hidePauseResumeButton: false,
  113. hideProgressAfterFinish: false,
  114. note: null,
  115. closeModalOnClickOutside: false,
  116. closeAfterFinish: false,
  117. disableStatusBar: false,
  118. disableInformer: false,
  119. disableThumbnailGenerator: false,
  120. disablePageScrollWhenModalOpen: true,
  121. animateOpenClose: true,
  122. proudlyDisplayPoweredByUppy: true,
  123. onRequestCloseModal: () => this.closeModal(),
  124. showSelectedFiles: true,
  125. showRemoveButtonAfterComplete: false,
  126. browserBackButtonClose: false,
  127. theme: 'light'
  128. }
  129. // merge default options with the ones set by user
  130. this.opts = { ...defaultOptions, ...opts }
  131. this.i18nInit()
  132. this.superFocus = createSuperFocus()
  133. this.ifFocusedOnUppyRecently = false
  134. // Timeouts
  135. this.makeDashboardInsidesVisibleAnywayTimeout = null
  136. this.removeDragOverClassTimeout = null
  137. }
  138. setOptions = (newOpts) => {
  139. super.setOptions(newOpts)
  140. this.i18nInit()
  141. }
  142. i18nInit = () => {
  143. this.translator = new Translator([this.defaultLocale, this.uppy.locale, this.opts.locale])
  144. this.i18n = this.translator.translate.bind(this.translator)
  145. this.i18nArray = this.translator.translateArray.bind(this.translator)
  146. this.setPluginState() // so that UI re-renders and we see the updated locale
  147. }
  148. removeTarget = (plugin) => {
  149. const pluginState = this.getPluginState()
  150. // filter out the one we want to remove
  151. const newTargets = pluginState.targets.filter(target => target.id !== plugin.id)
  152. this.setPluginState({
  153. targets: newTargets
  154. })
  155. }
  156. addTarget = (plugin) => {
  157. const callerPluginId = plugin.id || plugin.constructor.name
  158. const callerPluginName = plugin.title || callerPluginId
  159. const callerPluginType = plugin.type
  160. if (callerPluginType !== 'acquirer' &&
  161. callerPluginType !== 'progressindicator' &&
  162. callerPluginType !== 'editor') {
  163. const msg = 'Dashboard: The Dashboard can only be used by plugins of types: acquirer, progressindicator, editor'
  164. this.uppy.log(msg, 'error')
  165. return
  166. }
  167. const target = {
  168. id: callerPluginId,
  169. name: callerPluginName,
  170. type: callerPluginType
  171. }
  172. const state = this.getPluginState()
  173. const newTargets = state.targets.slice()
  174. newTargets.push(target)
  175. this.setPluginState({
  176. targets: newTargets
  177. })
  178. return this.el
  179. }
  180. hideAllPanels = () => {
  181. const update = {
  182. activePickerPanel: false,
  183. showAddFilesPanel: false,
  184. activeOverlayType: null,
  185. fileCardFor: null,
  186. showFileEditor: false
  187. }
  188. const current = this.getPluginState()
  189. if (current.activePickerPanel === update.activePickerPanel &&
  190. current.showAddFilesPanel === update.showAddFilesPanel &&
  191. current.showFileEditor === update.showFileEditor &&
  192. current.activeOverlayType === update.activeOverlayType) {
  193. // avoid doing a state update if nothing changed
  194. return
  195. }
  196. console.log(update)
  197. this.setPluginState(update)
  198. }
  199. showPanel = (id) => {
  200. const { targets } = this.getPluginState()
  201. const activePickerPanel = targets.filter((target) => {
  202. return target.type === 'acquirer' && target.id === id
  203. })[0]
  204. this.setPluginState({
  205. activePickerPanel: activePickerPanel,
  206. activeOverlayType: 'PickerPanel'
  207. })
  208. }
  209. openFileEditor = (file) => {
  210. const { targets } = this.getPluginState()
  211. this.setPluginState({
  212. showFileEditor: true,
  213. activeOverlayType: 'FileEditor'
  214. })
  215. const editors = this._getEditors(targets)
  216. editors.forEach((editor) => {
  217. const editorPlugin = this.uppy.getPlugin(editor.id)
  218. editorPlugin.selectFile(file)
  219. setTimeout(editorPlugin.initEditor, 4)
  220. })
  221. }
  222. openModal = () => {
  223. const { promise, resolve } = createPromise()
  224. // save scroll position
  225. this.savedScrollPosition = window.pageYOffset
  226. // save active element, so we can restore focus when modal is closed
  227. this.savedActiveElement = document.activeElement
  228. if (this.opts.disablePageScrollWhenModalOpen) {
  229. document.body.classList.add('uppy-Dashboard-isFixed')
  230. }
  231. if (this.opts.animateOpenClose && this.getPluginState().isClosing) {
  232. const handler = () => {
  233. this.setPluginState({
  234. isHidden: false
  235. })
  236. this.el.removeEventListener('animationend', handler, false)
  237. resolve()
  238. }
  239. this.el.addEventListener('animationend', handler, false)
  240. } else {
  241. this.setPluginState({
  242. isHidden: false
  243. })
  244. resolve()
  245. }
  246. if (this.opts.browserBackButtonClose) {
  247. this.updateBrowserHistory()
  248. }
  249. // handle ESC and TAB keys in modal dialog
  250. document.addEventListener('keydown', this.handleKeyDownInModal)
  251. this.uppy.emit('dashboard:modal-open')
  252. return promise
  253. }
  254. closeModal = (opts = {}) => {
  255. const {
  256. manualClose = true // Whether the modal is being closed by the user (`true`) or by other means (e.g. browser back button)
  257. } = opts
  258. const { isHidden, isClosing } = this.getPluginState()
  259. if (isHidden || isClosing) {
  260. // short-circuit if animation is ongoing
  261. return
  262. }
  263. const { promise, resolve } = createPromise()
  264. if (this.opts.disablePageScrollWhenModalOpen) {
  265. document.body.classList.remove('uppy-Dashboard-isFixed')
  266. }
  267. if (this.opts.animateOpenClose) {
  268. this.setPluginState({
  269. isClosing: true
  270. })
  271. const handler = () => {
  272. this.setPluginState({
  273. isHidden: true,
  274. isClosing: false
  275. })
  276. this.superFocus.cancel()
  277. this.savedActiveElement.focus()
  278. this.el.removeEventListener('animationend', handler, false)
  279. resolve()
  280. }
  281. this.el.addEventListener('animationend', handler, false)
  282. } else {
  283. this.setPluginState({
  284. isHidden: true
  285. })
  286. this.superFocus.cancel()
  287. this.savedActiveElement.focus()
  288. resolve()
  289. }
  290. // handle ESC and TAB keys in modal dialog
  291. document.removeEventListener('keydown', this.handleKeyDownInModal)
  292. if (manualClose) {
  293. if (this.opts.browserBackButtonClose) {
  294. // Make sure that the latest entry in the history state is our modal name
  295. if (history.state && history.state[this.modalName]) {
  296. // Go back in history to clear out the entry we created (ultimately closing the modal)
  297. history.go(-1)
  298. }
  299. }
  300. }
  301. this.uppy.emit('dashboard:modal-closed')
  302. return promise
  303. }
  304. isModalOpen = () => {
  305. return !this.getPluginState().isHidden || false
  306. }
  307. requestCloseModal = () => {
  308. if (this.opts.onRequestCloseModal) {
  309. return this.opts.onRequestCloseModal()
  310. }
  311. return this.closeModal()
  312. }
  313. setDarkModeCapability = (isDarkModeOn) => {
  314. const { capabilities } = this.uppy.getState()
  315. this.uppy.setState({
  316. capabilities: {
  317. ...capabilities,
  318. darkMode: isDarkModeOn
  319. }
  320. })
  321. }
  322. handleSystemDarkModeChange = (event) => {
  323. const isDarkModeOnNow = event.matches
  324. this.uppy.log(`[Dashboard] Dark mode is ${isDarkModeOnNow ? 'on' : 'off'}`)
  325. this.setDarkModeCapability(isDarkModeOnNow)
  326. }
  327. toggleFileCard = (fileId) => {
  328. if (fileId) {
  329. this.uppy.emit('dashboard:file-edit-start')
  330. } else {
  331. this.uppy.emit('dashboard:file-edit-complete')
  332. }
  333. this.setPluginState({
  334. fileCardFor: fileId || null,
  335. activeOverlayType: fileId ? 'FileCard' : null
  336. })
  337. }
  338. toggleAddFilesPanel = (show) => {
  339. this.setPluginState({
  340. showAddFilesPanel: show,
  341. activeOverlayType: show ? 'AddFiles' : null
  342. })
  343. }
  344. addFiles = (files) => {
  345. const descriptors = files.map((file) => ({
  346. source: this.id,
  347. name: file.name,
  348. type: file.type,
  349. data: file,
  350. meta: {
  351. // path of the file relative to the ancestor directory the user selected.
  352. // e.g. 'docs/Old Prague/airbnb.pdf'
  353. relativePath: file.relativePath || null
  354. }
  355. }))
  356. try {
  357. this.uppy.addFiles(descriptors)
  358. } catch (err) {
  359. this.uppy.log(err)
  360. }
  361. }
  362. // ___Why make insides of Dashboard invisible until first ResizeObserver event is emitted?
  363. // ResizeOberserver doesn't emit the first resize event fast enough, users can see the jump from one .uppy-size-- to another (e.g. in Safari)
  364. // ___Why not apply visibility property to .uppy-Dashboard-inner?
  365. // Because ideally, acc to specs, ResizeObserver should see invisible elements as of width 0. So even though applying invisibility to .uppy-Dashboard-inner works now, it may not work in the future.
  366. startListeningToResize = () => {
  367. // Watch for Dashboard container (`.uppy-Dashboard-inner`) resize
  368. // and update containerWidth/containerHeight in plugin state accordingly.
  369. // Emits first event on initialization.
  370. this.resizeObserver = new ResizeObserver((entries, observer) => {
  371. const uppyDashboardInnerEl = entries[0]
  372. const { width, height } = uppyDashboardInnerEl.contentRect
  373. this.uppy.log(`[Dashboard] resized: ${width} / ${height}`, 'debug')
  374. this.setPluginState({
  375. containerWidth: width,
  376. containerHeight: height,
  377. areInsidesReadyToBeVisible: true
  378. })
  379. })
  380. this.resizeObserver.observe(this.el.querySelector('.uppy-Dashboard-inner'))
  381. // If ResizeObserver fails to emit an event telling us what size to use - default to the mobile view
  382. this.makeDashboardInsidesVisibleAnywayTimeout = setTimeout(() => {
  383. const pluginState = this.getPluginState()
  384. const isModalAndClosed = !this.opts.inline && pluginState.isHidden
  385. if (
  386. // if ResizeObserver hasn't yet fired,
  387. !pluginState.areInsidesReadyToBeVisible &&
  388. // and it's not due to the modal being closed
  389. !isModalAndClosed
  390. ) {
  391. this.uppy.log("[Dashboard] resize event didn't fire on time: defaulted to mobile layout", 'debug')
  392. this.setPluginState({
  393. areInsidesReadyToBeVisible: true
  394. })
  395. }
  396. }, 1000)
  397. }
  398. stopListeningToResize = () => {
  399. this.resizeObserver.disconnect()
  400. clearTimeout(this.makeDashboardInsidesVisibleAnywayTimeout)
  401. }
  402. // Records whether we have been interacting with uppy right now, which is then used to determine whether state updates should trigger a refocusing.
  403. recordIfFocusedOnUppyRecently = (event) => {
  404. if (this.el.contains(event.target)) {
  405. this.ifFocusedOnUppyRecently = true
  406. } else {
  407. this.ifFocusedOnUppyRecently = false
  408. // ___Why run this.superFocus.cancel here when it already runs in superFocusOnEachUpdate?
  409. // Because superFocus is debounced, when we move from Uppy to some other element on the page,
  410. // previously run superFocus sometimes hits and moves focus back to Uppy.
  411. this.superFocus.cancel()
  412. }
  413. }
  414. updateBrowserHistory = () => {
  415. // Ensure history state does not already contain our modal name to avoid double-pushing
  416. if (!history.state || !history.state[this.modalName]) {
  417. // Push to history so that the page is not lost on browser back button press
  418. history.pushState({
  419. ...history.state,
  420. [this.modalName]: true
  421. }, '')
  422. }
  423. // Listen for back button presses
  424. window.addEventListener('popstate', this.handlePopState, false)
  425. }
  426. handlePopState = (event) => {
  427. // Close the modal if the history state no longer contains our modal name
  428. if (this.isModalOpen() && (!event.state || !event.state[this.modalName])) {
  429. this.closeModal({ manualClose: false })
  430. }
  431. // When the browser back button is pressed and uppy is now the latest entry in the history but the modal is closed, fix the history by removing the uppy history entry
  432. // This occurs when another entry is added into the history state while the modal is open, and then the modal gets manually closed
  433. // Solves PR #575 (https://github.com/transloadit/uppy/pull/575)
  434. if (!this.isModalOpen() && event.state && event.state[this.modalName]) {
  435. history.go(-1)
  436. }
  437. }
  438. handleKeyDownInModal = (event) => {
  439. // close modal on esc key press
  440. if (event.keyCode === ESC_KEY) this.requestCloseModal(event)
  441. // trap focus on tab key press
  442. if (event.keyCode === TAB_KEY) trapFocus.forModal(event, this.getPluginState().activeOverlayType, this.el)
  443. }
  444. handleClickOutside = () => {
  445. if (this.opts.closeModalOnClickOutside) this.requestCloseModal()
  446. }
  447. handlePaste = (event) => {
  448. // 1. Let any acquirer plugin (Url/Webcam/etc.) handle pastes to the root
  449. this.uppy.iteratePlugins((plugin) => {
  450. if (plugin.type === 'acquirer') {
  451. // Every Plugin with .type acquirer can define handleRootPaste(event)
  452. plugin.handleRootPaste && plugin.handleRootPaste(event)
  453. }
  454. })
  455. // 2. Add all dropped files
  456. const files = toArray(event.clipboardData.files)
  457. this.addFiles(files)
  458. }
  459. handleInputChange = (event) => {
  460. event.preventDefault()
  461. const files = toArray(event.target.files)
  462. this.addFiles(files)
  463. }
  464. handleDragOver = (event) => {
  465. event.preventDefault()
  466. event.stopPropagation()
  467. // 1. Add a small (+) icon on drop
  468. // (and prevent browsers from interpreting this as files being _moved_ into the browser, https://github.com/transloadit/uppy/issues/1978)
  469. event.dataTransfer.dropEffect = 'copy'
  470. clearTimeout(this.removeDragOverClassTimeout)
  471. this.setPluginState({ isDraggingOver: true })
  472. }
  473. handleDragLeave = (event) => {
  474. event.preventDefault()
  475. event.stopPropagation()
  476. clearTimeout(this.removeDragOverClassTimeout)
  477. // Timeout against flickering, this solution is taken from drag-drop library. Solution with 'pointer-events: none' didn't work across browsers.
  478. this.removeDragOverClassTimeout = setTimeout(() => {
  479. this.setPluginState({ isDraggingOver: false })
  480. }, 50)
  481. }
  482. handleDrop = (event, dropCategory) => {
  483. event.preventDefault()
  484. event.stopPropagation()
  485. clearTimeout(this.removeDragOverClassTimeout)
  486. // 2. Remove dragover class
  487. this.setPluginState({ isDraggingOver: false })
  488. // 3. Let any acquirer plugin (Url/Webcam/etc.) handle drops to the root
  489. this.uppy.iteratePlugins((plugin) => {
  490. if (plugin.type === 'acquirer') {
  491. // Every Plugin with .type acquirer can define handleRootDrop(event)
  492. plugin.handleRootDrop && plugin.handleRootDrop(event)
  493. }
  494. })
  495. // 4. Add all dropped files
  496. let executedDropErrorOnce = false
  497. const logDropError = (error) => {
  498. this.uppy.log(error, 'error')
  499. // In practice all drop errors are most likely the same, so let's just show one to avoid overwhelming the user
  500. if (!executedDropErrorOnce) {
  501. this.uppy.info(error.message, 'error')
  502. executedDropErrorOnce = true
  503. }
  504. }
  505. getDroppedFiles(event.dataTransfer, { logDropError })
  506. .then((files) => {
  507. if (files.length > 0) {
  508. this.uppy.log('[Dashboard] Files were dropped')
  509. this.addFiles(files)
  510. }
  511. })
  512. }
  513. handleRequestThumbnail = (file) => {
  514. if (!this.opts.waitForThumbnailsBeforeUpload) {
  515. this.uppy.emit('thumbnail:request', file)
  516. }
  517. }
  518. /**
  519. * We cancel thumbnail requests when a file item component unmounts to avoid clogging up the queue when the user scrolls past many elements.
  520. */
  521. handleCancelThumbnail = (file) => {
  522. if (!this.opts.waitForThumbnailsBeforeUpload) {
  523. this.uppy.emit('thumbnail:cancel', file)
  524. }
  525. }
  526. handleKeyDownInInline = (event) => {
  527. // Trap focus on tab key press.
  528. if (event.keyCode === TAB_KEY) trapFocus.forInline(event, this.getPluginState().activeOverlayType, this.el)
  529. }
  530. // ___Why do we listen to the 'paste' event on a document instead of onPaste={props.handlePaste} prop, or this.el.addEventListener('paste')?
  531. // Because (at least) Chrome doesn't handle paste if focus is on some button, e.g. 'My Device'.
  532. // => Therefore, the best option is to listen to all 'paste' events, and only react to them when we are focused on our particular Uppy instance.
  533. // ___Why do we still need onPaste={props.handlePaste} for the DashboardUi?
  534. // Because if we click on the 'Drop files here' caption e.g., `document.activeElement` will be 'body'. Which means our standard determination of whether we're pasting into our Uppy instance won't work.
  535. // => Therefore, we need a traditional onPaste={props.handlePaste} handler too.
  536. handlePasteOnBody = (event) => {
  537. const isFocusInOverlay = this.el.contains(document.activeElement)
  538. if (isFocusInOverlay) {
  539. this.handlePaste(event)
  540. }
  541. }
  542. handleComplete = ({ failed, uploadID }) => {
  543. if (this.opts.closeAfterFinish && failed.length === 0) {
  544. // All uploads are done
  545. this.requestCloseModal()
  546. }
  547. }
  548. initEvents = () => {
  549. // Modal open button
  550. if (this.opts.trigger && !this.opts.inline) {
  551. const showModalTrigger = findAllDOMElements(this.opts.trigger)
  552. if (showModalTrigger) {
  553. showModalTrigger.forEach(trigger => trigger.addEventListener('click', this.openModal))
  554. } else {
  555. this.uppy.log('Dashboard modal trigger not found. Make sure `trigger` is set in Dashboard options, unless you are planning to call `dashboard.openModal()` method yourself', 'warning')
  556. }
  557. }
  558. this.startListeningToResize()
  559. document.addEventListener('paste', this.handlePasteOnBody)
  560. this.uppy.on('plugin-remove', this.removeTarget)
  561. this.uppy.on('file-added', this.hideAllPanels)
  562. this.uppy.on('dashboard:modal-closed', this.hideAllPanels)
  563. this.uppy.on('file-editor:complete', this.hideAllPanels)
  564. this.uppy.on('complete', this.handleComplete)
  565. // ___Why fire on capture?
  566. // Because this.ifFocusedOnUppyRecently needs to change before onUpdate() fires.
  567. document.addEventListener('focus', this.recordIfFocusedOnUppyRecently, true)
  568. document.addEventListener('click', this.recordIfFocusedOnUppyRecently, true)
  569. if (this.opts.inline) {
  570. this.el.addEventListener('keydown', this.handleKeyDownInInline)
  571. }
  572. }
  573. removeEvents = () => {
  574. const showModalTrigger = findAllDOMElements(this.opts.trigger)
  575. if (!this.opts.inline && showModalTrigger) {
  576. showModalTrigger.forEach(trigger => trigger.removeEventListener('click', this.openModal))
  577. }
  578. this.stopListeningToResize()
  579. document.removeEventListener('paste', this.handlePasteOnBody)
  580. window.removeEventListener('popstate', this.handlePopState, false)
  581. this.uppy.off('plugin-remove', this.removeTarget)
  582. this.uppy.off('file-added', this.hideAllPanels)
  583. this.uppy.off('dashboard:modal-closed', this.hideAllPanels)
  584. this.uppy.off('complete', this.handleComplete)
  585. document.removeEventListener('focus', this.recordIfFocusedOnUppyRecently)
  586. document.removeEventListener('click', this.recordIfFocusedOnUppyRecently)
  587. if (this.opts.inline) {
  588. this.el.removeEventListener('keydown', this.handleKeyDownInInline)
  589. }
  590. }
  591. superFocusOnEachUpdate = () => {
  592. const isFocusInUppy = this.el.contains(document.activeElement)
  593. // When focus is lost on the page (== focus is on body for most browsers, or focus is null for IE11)
  594. const isFocusNowhere = document.activeElement === document.body || document.activeElement === null
  595. const isInformerHidden = this.uppy.getState().info.isHidden
  596. const isModal = !this.opts.inline
  597. if (
  598. // If update is connected to showing the Informer - let the screen reader calmly read it.
  599. isInformerHidden &&
  600. (
  601. // If we are in a modal - always superfocus without concern for other elements on the page (user is unlikely to want to interact with the rest of the page)
  602. isModal ||
  603. // If we are already inside of Uppy, or
  604. isFocusInUppy ||
  605. // If we are not focused on anything BUT we have already, at least once, focused on uppy
  606. // 1. We focus when isFocusNowhere, because when the element we were focused on disappears (e.g. an overlay), - focus gets lost. If user is typing something somewhere else on the page, - focus won't be 'nowhere'.
  607. // 2. We only focus when focus is nowhere AND this.ifFocusedOnUppyRecently, to avoid focus jumps if we do something else on the page.
  608. // [Practical check] Without '&& this.ifFocusedOnUppyRecently', in Safari, in inline mode, when file is uploading, - navigate via tab to the checkbox, try to press space multiple times. Focus will jump to Uppy.
  609. (isFocusNowhere && this.ifFocusedOnUppyRecently)
  610. )
  611. ) {
  612. this.superFocus(this.el, this.getPluginState().activeOverlayType)
  613. } else {
  614. this.superFocus.cancel()
  615. }
  616. }
  617. afterUpdate = () => {
  618. this.superFocusOnEachUpdate()
  619. }
  620. cancelUpload = (fileID) => {
  621. this.uppy.removeFile(fileID)
  622. }
  623. saveFileCard = (meta, fileID) => {
  624. this.uppy.setFileMeta(fileID, meta)
  625. this.toggleFileCard()
  626. }
  627. _attachRenderFunctionToTarget = (target) => {
  628. const plugin = this.uppy.getPlugin(target.id)
  629. return {
  630. ...target,
  631. icon: plugin.icon || this.opts.defaultPickerIcon,
  632. render: plugin.render
  633. }
  634. }
  635. _isTargetSupported = (target) => {
  636. const plugin = this.uppy.getPlugin(target.id)
  637. // If the plugin does not provide a `supported` check, assume the plugin works everywhere.
  638. if (typeof plugin.isSupported !== 'function') {
  639. return true
  640. }
  641. return plugin.isSupported()
  642. }
  643. _getAcquirers = memoize((targets) => {
  644. return targets
  645. .filter(target => target.type === 'acquirer' && this._isTargetSupported(target))
  646. .map(this._attachRenderFunctionToTarget)
  647. })
  648. _getProgressIndicators = memoize((targets) => {
  649. return targets
  650. .filter(target => target.type === 'progressindicator')
  651. .map(this._attachRenderFunctionToTarget)
  652. })
  653. _getEditors = memoize((targets) => {
  654. return targets
  655. .filter(target => target.type === 'editor')
  656. .map(this._attachRenderFunctionToTarget)
  657. })
  658. render = (state) => {
  659. const pluginState = this.getPluginState()
  660. const { files, capabilities, allowNewUpload } = state
  661. // TODO: move this to Core, to share between Status Bar and Dashboard
  662. // (and any other plugin that might need it, too)
  663. const newFiles = Object.keys(files).filter((file) => {
  664. return !files[file].progress.uploadStarted
  665. })
  666. const uploadStartedFiles = Object.keys(files).filter((file) => {
  667. return files[file].progress.uploadStarted
  668. })
  669. const pausedFiles = Object.keys(files).filter((file) => {
  670. return files[file].isPaused
  671. })
  672. const completeFiles = Object.keys(files).filter((file) => {
  673. return files[file].progress.uploadComplete
  674. })
  675. const erroredFiles = Object.keys(files).filter((file) => {
  676. return files[file].error
  677. })
  678. const inProgressFiles = Object.keys(files).filter((file) => {
  679. return !files[file].progress.uploadComplete &&
  680. files[file].progress.uploadStarted
  681. })
  682. const inProgressNotPausedFiles = inProgressFiles.filter((file) => {
  683. return !files[file].isPaused
  684. })
  685. const processingFiles = Object.keys(files).filter((file) => {
  686. return files[file].progress.preprocess || files[file].progress.postprocess
  687. })
  688. const isUploadStarted = uploadStartedFiles.length > 0
  689. const isAllComplete = state.totalProgress === 100 &&
  690. completeFiles.length === Object.keys(files).length &&
  691. processingFiles.length === 0
  692. const isAllErrored = isUploadStarted &&
  693. erroredFiles.length === uploadStartedFiles.length
  694. const isAllPaused = inProgressFiles.length !== 0 &&
  695. pausedFiles.length === inProgressFiles.length
  696. const acquirers = this._getAcquirers(pluginState.targets)
  697. const progressindicators = this._getProgressIndicators(pluginState.targets)
  698. const editors = this._getEditors(pluginState.targets)
  699. let theme
  700. if (this.opts.theme === 'auto') {
  701. theme = capabilities.darkMode ? 'dark' : 'light'
  702. } else {
  703. theme = this.opts.theme
  704. }
  705. return DashboardUI({
  706. state,
  707. isHidden: pluginState.isHidden,
  708. files,
  709. newFiles,
  710. uploadStartedFiles,
  711. completeFiles,
  712. erroredFiles,
  713. inProgressFiles,
  714. inProgressNotPausedFiles,
  715. processingFiles,
  716. isUploadStarted,
  717. isAllComplete,
  718. isAllErrored,
  719. isAllPaused,
  720. totalFileCount: Object.keys(files).length,
  721. totalProgress: state.totalProgress,
  722. allowNewUpload,
  723. acquirers,
  724. theme,
  725. activePickerPanel: pluginState.activePickerPanel,
  726. showFileEditor: pluginState.showFileEditor,
  727. animateOpenClose: this.opts.animateOpenClose,
  728. isClosing: pluginState.isClosing,
  729. getPlugin: this.uppy.getPlugin,
  730. progressindicators: progressindicators,
  731. editors: editors,
  732. autoProceed: this.uppy.opts.autoProceed,
  733. id: this.id,
  734. closeModal: this.requestCloseModal,
  735. handleClickOutside: this.handleClickOutside,
  736. handleInputChange: this.handleInputChange,
  737. handlePaste: this.handlePaste,
  738. inline: this.opts.inline,
  739. showPanel: this.showPanel,
  740. hideAllPanels: this.hideAllPanels,
  741. log: this.uppy.log,
  742. i18n: this.i18n,
  743. i18nArray: this.i18nArray,
  744. removeFile: this.uppy.removeFile,
  745. uppy: this.uppy,
  746. info: this.uppy.info,
  747. note: this.opts.note,
  748. metaFields: pluginState.metaFields,
  749. resumableUploads: capabilities.resumableUploads || false,
  750. individualCancellation: capabilities.individualCancellation,
  751. isMobileDevice: capabilities.isMobileDevice,
  752. pauseUpload: this.uppy.pauseResume,
  753. retryUpload: this.uppy.retryUpload,
  754. cancelUpload: this.cancelUpload,
  755. cancelAll: this.uppy.cancelAll,
  756. fileCardFor: pluginState.fileCardFor,
  757. toggleFileCard: this.toggleFileCard,
  758. toggleAddFilesPanel: this.toggleAddFilesPanel,
  759. showAddFilesPanel: pluginState.showAddFilesPanel,
  760. saveFileCard: this.saveFileCard,
  761. openFileEditor: this.openFileEditor,
  762. width: this.opts.width,
  763. height: this.opts.height,
  764. showLinkToFileUploadResult: this.opts.showLinkToFileUploadResult,
  765. proudlyDisplayPoweredByUppy: this.opts.proudlyDisplayPoweredByUppy,
  766. hideCancelButton: this.opts.hideCancelButton,
  767. hideRetryButton: this.opts.hideRetryButton,
  768. hidePauseResumeButton: this.opts.hidePauseResumeButton,
  769. showRemoveButtonAfterComplete: this.opts.showRemoveButtonAfterComplete,
  770. containerWidth: pluginState.containerWidth,
  771. containerHeight: pluginState.containerHeight,
  772. areInsidesReadyToBeVisible: pluginState.areInsidesReadyToBeVisible,
  773. isTargetDOMEl: this.isTargetDOMEl,
  774. parentElement: this.el,
  775. allowedFileTypes: this.uppy.opts.restrictions.allowedFileTypes,
  776. maxNumberOfFiles: this.uppy.opts.restrictions.maxNumberOfFiles,
  777. showSelectedFiles: this.opts.showSelectedFiles,
  778. handleRequestThumbnail: this.handleRequestThumbnail,
  779. handleCancelThumbnail: this.handleCancelThumbnail,
  780. // drag props
  781. isDraggingOver: pluginState.isDraggingOver,
  782. handleDragOver: this.handleDragOver,
  783. handleDragLeave: this.handleDragLeave,
  784. handleDrop: this.handleDrop
  785. })
  786. }
  787. discoverProviderPlugins = () => {
  788. this.uppy.iteratePlugins((plugin) => {
  789. if (plugin && !plugin.target && plugin.opts && plugin.opts.target === this.constructor) {
  790. this.addTarget(plugin)
  791. }
  792. })
  793. }
  794. install = () => {
  795. // Set default state for Dashboard
  796. this.setPluginState({
  797. isHidden: true,
  798. fileCardFor: null,
  799. activeOverlayType: null,
  800. showAddFilesPanel: false,
  801. activePickerPanel: false,
  802. showFileEditor: false,
  803. metaFields: this.opts.metaFields,
  804. targets: [],
  805. // We'll make them visible once .containerWidth is determined
  806. areInsidesReadyToBeVisible: false,
  807. isDraggingOver: false
  808. })
  809. const { inline, closeAfterFinish } = this.opts
  810. if (inline && closeAfterFinish) {
  811. throw new Error('[Dashboard] `closeAfterFinish: true` cannot be used on an inline Dashboard, because an inline Dashboard cannot be closed at all. Either set `inline: false`, or disable the `closeAfterFinish` option.')
  812. }
  813. const { allowMultipleUploads } = this.uppy.opts
  814. if (allowMultipleUploads && closeAfterFinish) {
  815. this.uppy.log('[Dashboard] When using `closeAfterFinish`, we recommended setting the `allowMultipleUploads` option to `false` in the Uppy constructor. See https://uppy.io/docs/uppy/#allowMultipleUploads-true', 'warning')
  816. }
  817. const { target } = this.opts
  818. if (target) {
  819. this.mount(target, this)
  820. }
  821. const plugins = this.opts.plugins || []
  822. plugins.forEach((pluginID) => {
  823. const plugin = this.uppy.getPlugin(pluginID)
  824. if (plugin) {
  825. plugin.mount(this, plugin)
  826. }
  827. })
  828. if (!this.opts.disableStatusBar) {
  829. this.uppy.use(StatusBar, {
  830. id: `${this.id}:StatusBar`,
  831. target: this,
  832. hideUploadButton: this.opts.hideUploadButton,
  833. hideRetryButton: this.opts.hideRetryButton,
  834. hidePauseResumeButton: this.opts.hidePauseResumeButton,
  835. hideCancelButton: this.opts.hideCancelButton,
  836. showProgressDetails: this.opts.showProgressDetails,
  837. hideAfterFinish: this.opts.hideProgressAfterFinish,
  838. locale: this.opts.locale
  839. })
  840. }
  841. if (!this.opts.disableInformer) {
  842. this.uppy.use(Informer, {
  843. id: `${this.id}:Informer`,
  844. target: this
  845. })
  846. }
  847. if (!this.opts.disableThumbnailGenerator) {
  848. this.uppy.use(ThumbnailGenerator, {
  849. id: `${this.id}:ThumbnailGenerator`,
  850. thumbnailWidth: this.opts.thumbnailWidth,
  851. waitForThumbnailsBeforeUpload: this.opts.waitForThumbnailsBeforeUpload,
  852. // If we don't block on thumbnails, we can lazily generate them
  853. lazy: !this.opts.waitForThumbnailsBeforeUpload
  854. })
  855. }
  856. // Dark Mode / theme
  857. this.darkModeMediaQuery = (typeof window !== 'undefined' && window.matchMedia)
  858. ? window.matchMedia('(prefers-color-scheme: dark)')
  859. : null
  860. const isDarkModeOnFromTheStart = this.darkModeMediaQuery ? this.darkModeMediaQuery.matches : false
  861. this.uppy.log(`[Dashboard] Dark mode is ${isDarkModeOnFromTheStart ? 'on' : 'off'}`)
  862. this.setDarkModeCapability(isDarkModeOnFromTheStart)
  863. if (this.opts.theme === 'auto') {
  864. this.darkModeMediaQuery.addListener(this.handleSystemDarkModeChange)
  865. }
  866. this.discoverProviderPlugins()
  867. this.initEvents()
  868. }
  869. uninstall = () => {
  870. if (!this.opts.disableInformer) {
  871. const informer = this.uppy.getPlugin(`${this.id}:Informer`)
  872. // Checking if this plugin exists, in case it was removed by uppy-core
  873. // before the Dashboard was.
  874. if (informer) this.uppy.removePlugin(informer)
  875. }
  876. if (!this.opts.disableStatusBar) {
  877. const statusBar = this.uppy.getPlugin(`${this.id}:StatusBar`)
  878. if (statusBar) this.uppy.removePlugin(statusBar)
  879. }
  880. if (!this.opts.disableThumbnailGenerator) {
  881. const thumbnail = this.uppy.getPlugin(`${this.id}:ThumbnailGenerator`)
  882. if (thumbnail) this.uppy.removePlugin(thumbnail)
  883. }
  884. const plugins = this.opts.plugins || []
  885. plugins.forEach((pluginID) => {
  886. const plugin = this.uppy.getPlugin(pluginID)
  887. if (plugin) plugin.unmount()
  888. })
  889. if (this.opts.theme === 'auto') {
  890. this.darkModeMediaQuery.removeListener(this.handleSystemDarkModeChange)
  891. }
  892. this.unmount()
  893. this.removeEvents()
  894. }
  895. }