doc: lint JS code snippets (#2954)

* doc: lint JS code snippets

* deps: update `lint-staged` deps

* Fix remaining lint warnings and errors

Co-authored-by: Artur Paikin <artur@arturpaikin.com>
This commit is contained in:
Antoine du Hamel 2021-07-04 19:32:50 +02:00 committed by GitHub
parent 8fb6889e26
commit c48064ba56
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
71 changed files with 701 additions and 550 deletions

View file

@ -12,3 +12,4 @@ website/themes/uppy/source/uppy/**
test/endtoend/*/build
examples/dev/output
bundle.js
website/src/_posts/*.md

View file

@ -24,6 +24,7 @@ module.exports = {
plugins: [
'@babel/eslint-plugin',
'jest',
'markdown',
'node',
'prefer-import',
'promise',
@ -212,5 +213,53 @@ module.exports = {
}],
},
},
{
files: ['**/*.md', '*.md'],
processor: 'markdown/markdown',
},
{
files: ['**/*.md/*.js', '**/*.md/*.javascript'],
parserOptions: {
sourceType: 'module',
},
rules: {
'import/no-extraneous-dependencies': ['off'],
'import/no-unresolved': ['off'],
'react/destructuring-assignment': ['off'],
'no-console': ['off'],
'no-undef': ['off'],
'no-unused-vars': ['off'],
'no-restricted-globals': [
'error',
{
name: '__filename',
message: 'Use import.meta.url instead',
},
{
name: '__dirname',
message: 'Not available in ESM',
},
{
name: 'exports',
message: 'Not available in ESM',
},
{
name: 'module',
message: 'Not available in ESM',
},
{
name: 'require',
message: 'Use import instead',
},
],
},
},
{
files: ['**/react/*.md/*.js', '**/react.md/*.js', '**/react-*.md/*.js'],
settings: {
react: { pragma: 'React' },
},
},
],
}

View file

@ -175,22 +175,22 @@ Here's a list of polyfills you'll need to include to make Uppy work in older bro
If you're using a bundler, you need import them before Uppy:
```js
import 'es6-promise/auto';
import 'whatwg-fetch';
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch';
import 'es6-promise/auto'
import 'whatwg-fetch'
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch'
// Order matters: AbortController needs fetch which needs Promise.
import mathLog2 from 'math-log2';
import 'md-gum-polyfill';
import ResizeObserver from 'resize-observer-polyfill';
import 'symbol-es6';
import 'url-polyfill';
import mathLog2 from 'math-log2'
import 'md-gum-polyfill'
import ResizeObserver from 'resize-observer-polyfill'
import 'symbol-es6'
import 'url-polyfill'
Math.log2 ??= mathLog2;
window.ResizeObserver ??= ResizeObserver;
Math.log2 ??= mathLog2
window.ResizeObserver ??= ResizeObserver
export { default } from '@uppy/core';
export * from '@uppy/core';
export { default } from '@uppy/core'
export * from '@uppy/core'
```
If you're using Uppy from CDN, those polyfills are already included in the legacy

View file

@ -5,7 +5,10 @@
"description": "Extensible JavaScript file upload widget with support for drag&drop, resumable uploads, previews, restrictions, file processing/encoding, remote providers like Instagram, Dropbox, Google Drive, S3 and more :dog:",
"lint-staged": {
"*.js": "eslint",
"*.md": "remark -f -q -i .gitignore"
"*.md": [
"remark -f -q -i .gitignore",
"eslint --fix"
]
},
"remarkConfig": {
"plugins": [
@ -73,6 +76,7 @@
"eslint-plugin-import": "2.22.1",
"eslint-plugin-jest": "23.20.0",
"eslint-plugin-jsdoc": "30.2.2",
"eslint-plugin-markdown": "^2.2.0",
"eslint-plugin-node": "11.1.0",
"eslint-plugin-prefer-import": "0.0.1",
"eslint-plugin-promise": "4.2.1",
@ -91,7 +95,7 @@
"json3": "3.3.3",
"last-commit-message": "1.0.0",
"lerna": "^3.22.1",
"lint-staged": "9.5.0",
"lint-staged": "^11.0.0",
"math-log2": "^2.0.0",
"md-gum-polyfill": "^1.0.0",
"mime-types": "2.1.26",

View file

@ -18,7 +18,7 @@ import AwsS3Multipart from '@uppy/aws-s3-multipart'
const uppy = new Uppy()
uppy.use(AwsS3Multipart, {
limit: 2,
companionUrl: 'https://companion.myapp.com/'
companionUrl: 'https://companion.myapp.com/',
})
```

View file

@ -19,7 +19,7 @@ const uppy = new Uppy()
uppy.use(AwsS3, {
limit: 2,
timeout: ms('1 minute'),
companionUrl: 'https://companion.myapp.com/'
companionUrl: 'https://companion.myapp.com/',
})
```

View file

@ -22,7 +22,7 @@ client.get('/drive/list').then(() => {})
const provider = new Provider(uppy, {
companionUrl: 'https://uppy.mywebsite.com/',
provider: providerPluginInstance
provider: providerPluginInstance,
})
provider.checkAuth().then(() => {})

View file

@ -29,37 +29,35 @@ import bodyParser from 'body-parser'
import session from 'express-session'
import companion from '@uppy/companion'
var app = express()
const app = express()
app.use(bodyParser.json())
app.use(session({secret: 'some secrety secret'}))
...
app.use(session({ secret: 'some secrety secret' }))
// ...
// be sure to place this anywhere after app.use(bodyParser.json()) and app.use(session({...})
const options = {
providerOptions: {
google: {
key: 'GOOGLE_KEY',
secret: 'GOOGLE_SECRET'
}
secret: 'GOOGLE_SECRET',
},
},
server: {
host: 'localhost:3020',
protocol: 'http',
},
filePath: '/path/to/folder/'
filePath: '/path/to/folder/',
}
app.use(companion.app(options))
```
To enable companion socket for realtime feed to the client while upload is going on, you call the `socket` method like so.
```javascript
...
var server = app.listen(PORT)
// ...
const server = app.listen(PORT)
companion.socket(server, options)
```
### Run as standalone server
@ -79,7 +77,8 @@ npm start
### Deploy to heroku
Companion can also be deployed to [Heroku](https://www.heroku.com)
```
```sh
mkdir uppy-companion && cd uppy-companion
git init
@ -105,7 +104,7 @@ heroku create
git push heroku master
```
Make sure you set the required [environment variables](https://uppy.io/docs/companion/#Configure-Standalone).
See [full documentation](https://uppy.io/docs/companion/)

View file

@ -27,7 +27,7 @@ import Dashboard from '@uppy/dashboard'
const uppy = new Uppy()
uppy.use(Dashboard, {
target: 'body',
inline: true
inline: true,
})
```

View file

@ -19,7 +19,7 @@ import DragDrop from '@uppy/drag-drop'
const uppy = new Uppy()
uppy.use(DragDrop, {
target: '#upload'
target: '#upload',
})
```

View file

@ -21,7 +21,7 @@ uppy.use(Form, {
getMetaFromForm: true,
addResultToForm: true,
resultName: 'uppyResult',
submitOnSuccess: true
submitOnSuccess: true,
})
```

View file

@ -22,9 +22,9 @@ import ImageEditor from '@uppy/image-editor'
const uppy = Uppy()
uppy.use(Dashboard)
uppy.use(ImageEditor, {
uppy.use(ImageEditor, {
target: Dashboard,
quality: 0.7
quality: 0.7,
})
```

View file

@ -17,7 +17,7 @@ import Informer from '@uppy/informer'
const uppy = new Uppy()
uppy.use(Informer, {
target: '#mount-point'
target: '#mount-point',
})
```

View file

@ -22,13 +22,14 @@ $ npm install @uppy/core @uppy/locales
```js
import Uppy from '@uppy/core'
import Russian from '@uppy/locales/lib/ru_RU'
const uppy = new Uppy({
debug: true,
meta: {
username: 'John',
license: 'Creative Commons'
license: 'Creative Commons',
},
locale: Russian
locale: Russian,
})
```

View file

@ -16,7 +16,6 @@ import Plugin from '@uppy/core/lib/plugin'
import { ProviderViews } from '@uppy/provider-views'
class GoogleDrive extends UIPlugin {
constructor () { /* snip */ }
install () {
this.view = new ProviderViews(this)
// snip
@ -25,7 +24,7 @@ class GoogleDrive extends UIPlugin {
onFirstRender () {
return Promise.all([
this.provider.fetchPreAuthToken(),
this.view.getFolder('root', '/')
this.view.getFolder('root', '/'),
])
}

View file

@ -11,7 +11,9 @@ Uppy is being developed by the folks at [Transloadit](https://transloadit.com),
## Example
<!-- eslint-disable react/state-in-constructor -->
```js
import React from 'react'
import Uppy from '@uppy/core'
import { DashboardModal } from '@uppy/react'
@ -19,6 +21,7 @@ const uppy = new Uppy()
class Example extends React.Component {
state = { open: false }
render () {
return (
<DashboardModal

View file

@ -21,7 +21,7 @@ uppy.use(StatusBar, {
target: 'body',
hideUploadButton: false,
showProgressDetails: false,
hideAfterFinish: true
hideAfterFinish: true,
})
```

View file

@ -16,7 +16,7 @@ import Uppy from '@uppy/core'
import DefaultStore from '@uppy/store-default'
const uppy = new Uppy({
store: DefaultStore()
store: DefaultStore(),
})
```

View file

@ -22,15 +22,15 @@ import reducers from './reducers'
const reducer = combineReducers({
...reducers,
uppy: ReduxStore.reducer
uppy: ReduxStore.reducer,
})
const store = createStore(reducer)
const uppy = new Uppy({
store: ReduxStore({
store: store
})
store,
}),
})
```

View file

@ -17,7 +17,7 @@ import ThumbnailGenerator from '@uppy/thumbnail-generator'
const uppy = new Uppy()
uppy.use(ThumbnailGenerator, {
thumbnailWidth: 200
thumbnailWidth: 200,
})
```

View file

@ -19,7 +19,7 @@ const uppy = new Uppy()
uppy.use(Tus, {
endpoint: 'https://tusd.tusdemo.net/files/', // use your tus endpoint here
resume: true,
retryDelays: [0, 1000, 3000, 5000]
retryDelays: [0, 1000, 3000, 5000],
})
```

View file

@ -19,7 +19,7 @@ const uppy = new Uppy()
uppy.use(Webcam, {
mirror: true,
facingMode: 'user',
showRecordingLength: true
showRecordingLength: true,
})
```

View file

@ -35,7 +35,7 @@ Renée is working hard to fix outdated warnings in our examples. Other than that
The biggest update that will be part of Uppy 1.0 is support for React Native. Yesterday, Renée, Artur, Ife, [Evgenia](https://github.com/lakesare) and [Kevin](https://github.com/kvz) had a call and talked extensively about what would be needed to have a minimum viable product. They settled on the following six subtasks, which I'm copying directly from their notes: :)
```md
```markdown
MVP for React Native support should:
- [ ] get a link provider example to work, including showing Companion progress and resumability

View file

@ -12,9 +12,10 @@ The `@uppy/aws-s3-multipart` plugin can be used to upload files directly to an S
```js
import AwsS3Multipart from '@uppy/aws-s3-multipart'
uppy.use(AwsS3Multipart, {
limit: 4,
companionUrl: 'https://uppy-companion.myapp.net/'
companionUrl: 'https://uppy-companion.myapp.net/',
})
```
@ -31,7 +32,7 @@ npm install @uppy/aws-s3-multipart
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const AwsS3Multipart = Uppy.AwsS3Multipart
const { AwsS3Multipart } = Uppy
```
## Options
@ -111,6 +112,7 @@ Return a Promise for an object with keys:
- `url` - The presigned URL to upload a part. This can be generated on the server using the S3 SDK like so:
<!-- eslint-disable node/handle-callback-err -->
```js
sdkInstance.getSignedUrl('uploadPart', {
Bucket: 'target',

View file

@ -18,7 +18,7 @@ import ms from 'ms'
uppy.use(AwsS3, {
limit: 2,
timeout: ms('1 minute'),
companionUrl: 'https://uppy-companion.myapp.com/'
companionUrl: 'https://uppy-companion.myapp.com/',
})
```
@ -39,7 +39,7 @@ npm install @uppy/aws-s3
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const AwsS3 = Uppy.AwsS3
const { AwsS3 } = Uppy
```
## Options
@ -56,7 +56,7 @@ When using [Companion][companion docs] to sign S3 uploads, set this option to th
```js
uppy.use(AwsS3, {
companionUrl: 'https://uppy-companion.my-app.com/'
companionUrl: 'https://uppy-companion.my-app.com/',
})
```
@ -120,9 +120,11 @@ Localize text that is shown to the user.
The default English strings are:
```js
strings: {
// Shown in the StatusBar while the upload is being signed.
preparingUpload: 'Preparing upload...'
const locales = {
strings: {
// Shown in the StatusBar while the upload is being signed.
preparingUpload: 'Preparing upload...',
},
}
```
@ -216,11 +218,11 @@ Companion uses POST uploads by default, but you can also use them with your own
```js
// `s3` is an instance of the AWS JavaScript SDK's S3 client
s3.createPresignedPost({
...,
// ...
Fields: {
...,
success_action_status: '201'
}
// ...
success_action_status: '201',
},
})
```
@ -318,12 +320,12 @@ uppy.use(AwsS3, {
// Send and receive JSON.
headers: {
accept: 'application/json',
'content-type': 'application/json'
'content-type': 'application/json',
},
body: JSON.stringify({
filename: file.name,
contentType: file.type
})
contentType: file.type,
}),
}).then((response) => {
// Parse the JSON response.
return response.json()
@ -335,11 +337,11 @@ uppy.use(AwsS3, {
fields: data.fields,
// Provide content type header required by S3
headers: {
'Content-Type': file.type
}
'Content-Type': file.type,
},
}
})
}
},
})
```
@ -352,7 +354,7 @@ generated in `getUploadParameters(file)` via the `file.meta` field:
```js
uppy.on('upload-success', (file, data) => {
file.meta['key'] // the S3 object key of the uploaded file
const s3Key = file.meta['key'] // the S3 object key of the uploaded file
})
```

View file

@ -36,7 +36,7 @@ npm install @uppy/box
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const Box = Uppy.Box
const { Box } = Uppy
```
## Setting Up
@ -53,9 +53,9 @@ companion.app({
providerOptions: {
box: {
key: 'Box API key',
secret: 'Box API secret'
}
}
secret: 'Box API secret',
},
},
})
```
@ -129,7 +129,9 @@ Localize text that is shown to the user.
The default English strings are:
```js
strings: {
// TODO
const locales = {
strings: {
// TODO
},
}
```

View file

@ -66,7 +66,7 @@ const app = express()
// If you are using something else in your app, you can add these
// middlewares in the same subpath as Companion instead.
app.use(bodyParser.json())
app.use(session({secret: 'some secrety secret'}))
app.use(session({ secret: 'some secrety secret' }))
const options = {
providerOptions: {
@ -245,49 +245,49 @@ See [env.example.sh](https://github.com/transloadit/uppy/blob/master/env.example
### Options
```javascript
{
const options = {
providerOptions: {
drive: {
key: "***",
secret: "***"
key: '***',
secret: '***',
},
dropbox: {
key: "***",
secret: "***"
key: '***',
secret: '***',
},
instagram: {
key: "***",
secret: "***"
key: '***',
secret: '***',
},
facebook: {
key: "***",
secret: "***"
key: '***',
secret: '***',
},
onedrive: {
key: "***",
secret: "***"
key: '***',
secret: '***',
},
s3: {
getKey: (req, filename, metadata) => filename,
key: "***",
secret: "***",
bucket: "bucket-name",
region: "us-east-1",
key: '***',
secret: '***',
bucket: 'bucket-name',
region: 'us-east-1',
useAccelerateEndpoint: false, // default: false,
expires: 3600, // default: 300 (5 minutes)
acl: "private" // default: public-read
}
acl: 'private', // default: public-read
},
},
server: {
host: "localhost:3020", // or yourdomain.com
protocol: "http"
host: 'localhost:3020', // or yourdomain.com
protocol: 'http',
},
filePath: "path/to/download/folder",
sendSelfEndpoint: "localhost:3020",
filePath: 'path/to/download/folder',
sendSelfEndpoint: 'localhost:3020',
secret: 'mysecret',
uploadUrls: ['https://myuploadurl.com', 'http://myuploadurl2.com']
uploadUrls: ['https://myuploadurl.com', 'http://myuploadurl2.com'],
debug: true,
metrics: false
metrics: false,
}
```
@ -381,16 +381,20 @@ app.use(uppy.app({
s3: {
getKey: (req, filename, metadata) => `${req.user.id}/${filename}`,
/* auth options */
}
}
},
},
}))
```
The default implementation returns the `filename`, so all files will be uploaded to the root of the bucket as their original file name.
```js
({
getKey: (req, filename, metadata) => filename
})
app.use(uppy.app({
providerOptions: {
s3: {
getKey: (req, filename, metadata) => filename,
},
},
}))
```
### Running in Kubernetes
@ -402,22 +406,22 @@ We have [a detailed guide on running Companion in Kubernetes](https://github.com
As of now, Companion supports the [providers listed here](https://uppy.io/docs/companion/#Supported-providers) out of the box, but you may also choose to add your own custom providers. You can do this by passing the `customProviders` option when calling the Uppy `app` method. The custom provider is expected to support Oauth 1 or 2 for authentication/authorization.
```javascript
import providerModule from '/path/to/provider/module'
import providerModule from './path/to/provider/module'
let options = {
customProviders: {
myprovidername: {
config: {
authorize_url: "https://mywebsite.com/authorize",
access_url: "https://mywebsite.com/token",
oauth: 2,
key: "***",
secret: "***",
scope: ["read", "write"]
},
module: providerModule
}
}
const options = {
customProviders: {
myprovidername: {
config: {
authorize_url: 'https://mywebsite.com/authorize',
access_url: 'https://mywebsite.com/token',
oauth: 2,
key: '***',
secret: '***',
scope: ['read', 'write'],
},
module: providerModule,
},
},
}
uppy.app(options)
@ -449,43 +453,43 @@ The class must also have an `authProvider` string (lowercased) field which typic
#### list data
```js
```json
{
// username or email of the user whose provider account is being accessed
username: 'johndoe',
"username": "johndoe",
// list of files and folders in the directory. An item is considered a folder
// if it mainly exists as a collection to contain sub-items
items: [
"items": [
{
// boolean value of whether or NOT it's a folder
isFolder: false,
"isFolder": false,
// icon image URL
icon: 'https://random-api.url.com/fileicon.jpg',
"icon": "https://random-api.url.com/fileicon.jpg",
// name of the item
name: 'myfile.jpg',
"name": "myfile.jpg",
// the mime type of the item. Only relevant if the item is NOT a folder
mimeType: 'image/jpg',
"mimeType": "image/jpg",
// the id (in string) of the item
id: 'uniqueitemid',
"id": "uniqueitemid",
// thumbnail image URL. Only relevant if the item is NOT a folder
thumbnail: 'https://random-api.url.com/filethumbnail.jpg',
"thumbnail": "https://random-api.url.com/filethumbnail.jpg",
// for folders this is typically the value that will be passed as "directory" in the list(...) method.
// For files, this is the value that will be passed as id in the download(...) method.
requestPath: 'file-or-folder-requestpath',
"requestPath": "file-or-folder-requestpath",
// datetime string (in ISO 8601 format) of when this item was last modified
modifiedDate: '2020-06-29T19:59:58Z',
"modifiedDate": "2020-06-29T19:59:58Z",
// the size in bytes of the item. Only relevent if the item is NOT a folder
size: 278940,
custom: {
"size": 278940,
"custom": {
// an object that may contain some more custom fields that you may need to send to the client. Only add this object if you have a need for it.
customData1: 'the value',
customData2: 'the value',
},
"customData1": "the value",
"customData2": "the value"
}
// more items here
}
]
],
// if the "items" list is paginated, this is the request path needed to fetch the next page.
nextPagePath: 'directory-name?cursor=cursor-to-next-page'
"nextPagePath": "directory-name?cursor=cursor-to-next-page"
}
```

View file

@ -40,7 +40,7 @@ npm install @uppy/dashboard
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const Dashboard = Uppy.Dashboard
const { Dashboard } = Uppy
```
## CSS
@ -72,7 +72,7 @@ uppy.use(Dashboard, {
width: 750,
height: 550,
thumbnailWidth: 280,
defaultTabIcon: defaultTabIcon,
defaultTabIcon,
showLinkToFileUploadResult: true,
showProgressDetails: false,
hideUploadButton: false,
@ -100,7 +100,7 @@ uppy.use(Dashboard, {
locale: defaultLocale,
browserBackButtonClose: false,
theme: 'light',
autoOpenFileEditor: false
autoOpenFileEditor: false,
})
```
@ -128,7 +128,7 @@ List of plugin IDs that should be shown in the Dashboard's top bar. For example,
```js
uppy.use(Webcam)
uppy.use(Dashboard, {
plugins: ['Webcam']
plugins: ['Webcam'],
})
```
@ -194,7 +194,7 @@ Hide Status Bar after the upload has finished.
This option is passed to the StatusBar, and will render a “Done” button in place of pause/resume/cancel buttons, once the upload/encoding is done. The behaviour of this “Done” button is defined by the handler function — can be used to close file picker modals or clear the upload state. This is what the Dashboard sets by default:
```js
doneButtonHandler: () => {
const doneButtonHandler = () => {
this.uppy.reset()
this.requestCloseModal()
}
@ -239,23 +239,27 @@ It gets passed `({value, onChange}, h)` where `value` is the current value of th
`h` can be useful when using uppy from plain JavaScript, where you cannot write JSX.
```js
.use(Dashboard, {
uppy.use(Dashboard, {
trigger: '#pick-files',
metaFields: [
{ id: 'name', name: 'Name', placeholder: 'file name' },
{ id: 'license', name: 'License', placeholder: 'specify license' },
{ id: 'caption', name: 'Caption', placeholder: 'describe what the image is about' },
{ id: 'public', name: 'Public', render: function({value, onChange}, h) {
return h('input', { type: 'checkbox', onChange: (ev) => onChange(ev.target.checked ? 'on' : 'off'), defaultChecked: value === 'on' })
} }
]
{
id: 'public',
name: 'Public',
render ({ value, onChange }, h) {
return h('input', { type: 'checkbox', onChange: (ev) => onChange(ev.target.checked ? 'on' : 'off'), defaultChecked: value === 'on' })
},
},
],
})
```
If youd like the meta fields to be dynamically assigned depending on, for instance, the file type, pass a function:
```js
.use(Dashboard, {
uppy.use(Dashboard, {
trigger: '#pick-files',
metaFields: (file) => {
const fields = [{ id: 'name', name: 'File name' }]
@ -334,7 +338,7 @@ The Dashboard also contains the [`@uppy/status-bar`](/docs/status-bar) plugin by
The default English strings are:
```js
strings: {
const strings = {
// When `inline: false`, used as the screen reader label for the button that closes the modal.
closeModal: 'Close Modal',
// Used as the screen reader label for the plus (+) button that shows the “Add more files” screen
@ -404,17 +408,17 @@ strings: {
// Used in a title, how many files are currently selected
xFilesSelected: {
0: '%{smart_count} file selected',
1: '%{smart_count} files selected'
1: '%{smart_count} files selected',
},
// TODO
uploadingXFiles: {
0: 'Uploading %{smart_count} file',
1: 'Uploading %{smart_count} files'
1: 'Uploading %{smart_count} files',
},
// TODO
processingXFiles: {
0: 'Processing %{smart_count} file',
1: 'Processing %{smart_count} files'
1: 'Processing %{smart_count} files',
},
// The "powered by Uppy" link at the bottom of the Dashboard.
@ -424,7 +428,7 @@ strings: {
// @uppy/status-bar strings:
uploading: 'Uploading',
complete: 'Complete'
complete: 'Complete',
// ...etc
}
```
@ -490,7 +494,7 @@ Returns `true` if the Dashboard modal is open, `false` otherwise.
```js
const dashboard = uppy.getPlugin('Dashboard')
if ( dashboard.isModalOpen() ) {
if (dashboard.isModalOpen()) {
dashboard.closeModal()
}
```

View file

@ -34,7 +34,7 @@ npm install @uppy/drag-drop
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const DragDrop = Uppy.DragDrop
const { DragDrop } = Uppy
```
## CSS
@ -58,7 +58,7 @@ uppy.use(DragDrop, {
width: '100%',
height: '100%',
note: null,
locale: {}
locale: {},
})
```
@ -103,12 +103,12 @@ Callback for the [`ondrop`][ondrop] event handler.
The default English strings are:
```js
strings: {
const strings = {
// Text to show on the droppable area.
// `%{browse}` is replaced with a link that opens the system file selection dialog.
dropHereOr: 'Drop here or %{browse}',
// Used as the label for the link that opens the system file selection dialog.
browse: 'browse'
browse: 'browse',
}
```

View file

@ -36,7 +36,7 @@ npm install @uppy/dropbox
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const Dropbox = Uppy.Dropbox
const { Dropbox } = Uppy
```
## Setting Up
@ -53,9 +53,9 @@ companion.app({
providerOptions: {
dropbox: {
key: 'Dropbox API key',
secret: 'Dropbox API secret'
}
}
secret: 'Dropbox API secret',
},
},
})
```
@ -130,7 +130,9 @@ Localize text that is shown to the user.
The default English strings are:
```js
strings: {
// TODO
const locale = {
strings: {
// TODO
},
}
```

View file

@ -91,7 +91,9 @@ Localize text that is shown to the user.
The default English strings are:
```js
strings: {
// TODO
const locale = {
strings: {
// TODO
},
}
```

View file

@ -36,7 +36,7 @@ npm install @uppy/file-input
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const FileInput = Uppy.FileInput
const { FileInput } = Uppy
```
## CSS
@ -60,7 +60,7 @@ uppy.use(FileInput, {
pretty: true,
inputName: 'files[]',
locale: {
}
},
})
```
@ -87,8 +87,10 @@ The `name` attribute for the `<input type="file">` element.
When `pretty` is set, specify a custom label for the button.
```js
strings: {
chooseFiles: 'Choose files'
const locale = {
strings: {
chooseFiles: 'Choose files',
},
}
```
@ -103,7 +105,7 @@ If you dont like the look/feel of the button rendered by `@uppy/file-input`,
Then add this JS to attach it to Uppy:
```js
const uppy = new Uppy(...)
const uppy = new Uppy(/* ... */)
const fileInput = document.querySelector('#my-file-input')
fileInput.addEventListener('change', (event) => {
@ -115,7 +117,7 @@ fileInput.addEventListener('change', (event) => {
source: 'file input',
name: file.name,
type: file.type,
data: file
data: file,
})
} catch (err) {
if (err.isRestriction) {

View file

@ -34,7 +34,7 @@ npm install @uppy/form
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const Form = Uppy.Form
const { Form } = Uppy
```
## Options
@ -49,7 +49,7 @@ uppy.use(Form, {
addResultToForm: true,
multipleResults: false,
submitOnSuccess: false,
triggerUploadOnSubmit: false
triggerUploadOnSubmit: false,
})
```

View file

@ -25,7 +25,7 @@ npm install @uppy/golden-retriever
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const GoldenRetriever = Uppy.GoldenRetriever
const { GoldenRetriever } = Uppy
```
## Usage
@ -44,7 +44,7 @@ import('@uppy/golden-retriever/lib/ServiceWorker')
// you app.js entry point
import GoldenRetriever from '@uppy/golden-retriever'
uppy.use(GoldenRetriever, {serviceWorker: true})
uppy.use(GoldenRetriever, { serviceWorker: true })
if ('serviceWorker' in navigator) {
navigator.serviceWorker
@ -53,7 +53,7 @@ if ('serviceWorker' in navigator) {
console.log('ServiceWorker registration successful with scope: ', registration.scope)
})
.catch((error) => {
console.log('Registration failed with ' + error)
console.log(`Registration failed with ${error}`)
})
}
```

View file

@ -36,7 +36,7 @@ npm install @uppy/google-drive
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const GoogleDrive = Uppy.GoogleDrive
const { GoogleDrive } = Uppy
```
## Setting Up
@ -53,9 +53,9 @@ companion.app({
providerOptions: {
drive: {
key: 'Google Drive OAuth client ID',
secret: 'Google Drive OAuth client secret'
}
}
secret: 'Google Drive OAuth client secret',
},
},
})
```
@ -126,7 +126,9 @@ Localize text that is shown to the user.
The default English strings are:
```js
strings: {
// TODO
const locale = {
strings:{
// TODO
},
}
```

View file

@ -25,7 +25,7 @@ const uppy = new Uppy()
uppy.use(Dashboard)
uppy.use(ImageEditor, {
target: Dashboard,
quality: 0.8
quality: 0.8,
})
```
@ -63,7 +63,7 @@ uppy.use(ImageEditor, {
viewMode: 1,
background: false,
autoCropArea: 1,
responsive: true
responsive: true,
},
actions: {
revert: true,
@ -74,8 +74,8 @@ uppy.use(ImageEditor, {
zoomOut: true,
cropSquare: true,
cropWidescreen: true,
cropWidescreenVertical: true
}
cropWidescreenVertical: true,
},
})
```

View file

@ -77,13 +77,13 @@ import Dashboard from '@uppy/dashboard'
// With webpack and `style-loader`, you can import them like this:
import '@uppy/core/dist/style.css'
import '@uppy/dashboard/dist/style.css'
 
const uppy = new Uppy()
.use(Dashboard, {
trigger: '#select-files'
trigger: '#select-files',
})
.use(XHRUpload, { endpoint: 'https://api2.transloadit.com' })
 
uppy.on('complete', (result) => {
console.log('Upload complete! Weve uploaded these files:', result.successful)
})
@ -165,22 +165,23 @@ With a module bundler, you can use the required polyfills like so:
```shell
npm install es6-promise whatwg-fetch abortcontroller-polyfill math-log2 md-gum-polyfill resize-observer-polyfill symbol-es6 url-polyfill
```
```js
import 'es6-promise/auto';
import 'whatwg-fetch';
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch';
import 'es6-promise/auto'
import 'whatwg-fetch'
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch'
// Order matters: AbortController needs fetch which needs Promise.
import mathLog2 from 'math-log2';
import 'md-gum-polyfill';
import ResizeObserver from 'resize-observer-polyfill';
import 'symbol-es6';
import 'url-polyfill';
import mathLog2 from 'math-log2'
import 'md-gum-polyfill'
import ResizeObserver from 'resize-observer-polyfill'
import 'symbol-es6'
import 'url-polyfill'
Math.log2 ??= mathLog2;
window.ResizeObserver ??= ResizeObserver;
Math.log2 ??= mathLog2
window.ResizeObserver ??= ResizeObserver
export { default } from '@uppy/core';
export { default } from '@uppy/core'
export * from '@uppy/core'
```

View file

@ -39,7 +39,7 @@ npm install @uppy/informer
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const Informer = Uppy.Informer
const { Informer } = Uppy
```
## CSS

View file

@ -38,7 +38,7 @@ npm install @uppy/instagram
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const Instagram = Uppy.Instagram
const { Instagram } = Uppy
```
## CSS
@ -97,7 +97,9 @@ Localize text that is shown to the user.
The default English strings are:
```js
strings: {
// TODO
const locale = {
strings: {
// TODO
},
}
```

View file

@ -21,10 +21,11 @@ npm i @uppy/core @uppy/locales
```js
import Uppy from '@uppy/core'
import German from '@uppy/locales/lib/de_DE' // see below for the full list of locales
import German from '@uppy/locales/lib/de_DE'
// see below for the full list of locales
const uppy = new Uppy({
debug: true,
locale: German
locale: German,
})
```
@ -52,10 +53,11 @@ Many plugins come with their own locale strings, and the packs we provide consis
import Uppy from '@uppy/core'
import DragDrop from '@uppy/drag-drop'
import Russian from '@uppy/locales/lib/ru_RU'
const uppy = new Uppy({
debug: true,
autoProceed: true,
locale: Russian
locale: Russian,
})
uppy.use(DragDrop, {
target: '.UppyDragDrop',
@ -63,9 +65,9 @@ uppy.use(DragDrop, {
// but you can also override specific strings like so:
locale: {
strings: {
browse: 'выберите ;-)'
}
}
browse: 'выберите ;-)',
},
},
})
```

View file

@ -91,7 +91,9 @@ Localize text that is shown to the user.
The default English strings are:
```js
strings: {
// TODO
const locale = {
strings: {
// TODO
},
}
```

View file

@ -19,6 +19,7 @@ Can be a `string` CSS selector, a DOM element, or a Plugin class. Consider the f
```js
import Uppy from '@uppy/core'
import DragDrop from '@uppy/drag-drop'
const uppy = new Uppy()
uppy.use(DragDrop, { target: 'body' })
// or: uppy.use(DragDrop, { target: document.body })
@ -30,11 +31,12 @@ While in this one, we are using the `@uppy/dashboard` plugin, which can act as a
import Uppy from '@uppy/core'
import Dashboard from '@uppy/dashboard'
import GoogleDrive from '@uppy/google-drive'
const uppy = new Uppy()
uppy.use(Dashboard, {
trigger: '#uppyModalOpener'
trigger: '#uppyModalOpener',
})
uppy.use(GoogleDrive, {target: Dashboard})
uppy.use(GoogleDrive, { target: Dashboard })
```
In the example above, the `Dashboard` gets rendered into an element with ID `uppy`, while `GoogleDrive` is rendered into the `Dashboard` itself.
@ -44,11 +46,11 @@ In the example above, the `Dashboard` gets rendered into an element with ID `upp
Same as with Uppy.Cores setting above, this allows you to override plugins locale string, so that instead of `Select files` in English, your users will see `Выберите файлы` in Russian. Example:
```js
.use(FileInput, {
uppy.use(FileInput, {
target: 'body',
locale: {
strings: { selectToUpload: 'Выберите файл для загрузки' }
}
strings: { selectToUpload: 'Выберите файл для загрузки' },
},
})
```
@ -64,7 +66,7 @@ You can change options for a plugin on the fly, like this:
// First get the plugin by its `id`,
// then change, for example, `width` on the fly
uppy.getPlugin('Dashboard').setOptions({
width: 300
width: 300,
})
```

View file

@ -36,7 +36,7 @@ npm install @uppy/progress-bar
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const ProgressBar = Uppy.ProgressBar
const { ProgressBar } = Uppy
```
## CSS
@ -60,7 +60,7 @@ The `@uppy/progress-bar` plugin has the following configurable options:
uppy.use(ProgressBar, {
target: '.UploadForm',
fixed: false,
hideAfterFinish: true
hideAfterFinish: true,
})
```
@ -79,7 +79,7 @@ When set to true, show the progress bar at the top of the page with `position: f
```js
uppy.use(ProgressBar, {
target: 'body',
fixed: true
fixed: true,
})
```

View file

@ -14,29 +14,30 @@ Usage of the Provider plugins is not that different from any other *acquirer* pl
Here's a quick example:
<!-- eslint-disable import/first, import/newline-after-import -->
```js
import Uppy from '@uppy/core'
import Dashboard from '@uppy/dashboard'
const uppy = new Uppy()
uppy.use(Dashboard, {
trigger: '#pick-files'
trigger: '#pick-files',
})
// for Google Drive
import GoogleDrive from '@uppy/google-drive'
uppy.use(GoogleDrive, {target: Dashboard, companionUrl: 'http://localhost:3020'})
uppy.use(GoogleDrive, { target: Dashboard, companionUrl: 'http://localhost:3020' })
// for Dropbox
import Dropbox from '@uppy/dropbox'
uppy.use(Dropbox, {target: Dashboard, companionUrl: 'http://localhost:3020'})
uppy.use(Dropbox, { target: Dashboard, companionUrl: 'http://localhost:3020' })
// for Instagram
import Instagram from '@uppy/instagram'
uppy.use(Instagram, {target: Dashboard, companionUrl: 'http://localhost:3020'})
uppy.use(Instagram, { target: Dashboard, companionUrl: 'http://localhost:3020' })
// for URL
import Url from '@uppy/url'
uppy.use(Url, {target: Dashboard, companionUrl: 'http://localhost:3020'})
uppy.use(Url, { target: Dashboard, companionUrl: 'http://localhost:3020' })
```
⚠️ The [Dashboard](/docs/dashboard) plugin is recommended as a universal container to all Provider plugins. It also comes with file previews, progress reporting and more. If you are using the Dashboard, it already [comes with all the nessesary styles](/docs/dashboard/#CSS) and functionality for Providers to work well.

View file

@ -18,10 +18,10 @@ npm install @uppy/react
```
```js
// Either:
import DashboardModal from '@uppy/react/lib/DashboardModal'
// Or:
import { DashboardModal } from '@uppy/react'
// Alternatively, you can also use a default import:
// import DashboardModal from '@uppy/react/lib/DashboardModal'
```
## CSS
@ -66,12 +66,15 @@ Then do `plugins={['Webcam']}`.
Here is a full example that uses a button to open the modal:
```js
import React from 'react'
import { DashboardModal } from '@uppy/react'
class MusicUploadButton extends React.Component {
constructor (props) {
super(props)
this.state = {
modalOpen: false
modalOpen: false,
}
this.uppy = new Uppy()
@ -88,20 +91,20 @@ class MusicUploadButton extends React.Component {
handleOpen () {
this.setState({
modalOpen: true
modalOpen: true,
})
}
handleClose () {
this.setState({
modalOpen: false
modalOpen: false,
})
}
render () {
return (
<div>
<button onClick={this.handleOpen}>Upload some music</button>
<button type="button" onClick={this.handleOpen}>Upload some music</button>
<DashboardModal
uppy={this.uppy}
closeModalOnClickOutside
@ -110,7 +113,7 @@ class MusicUploadButton extends React.Component {
plugins={['Webcam']}
/>
</div>
);
)
}
}
```

View file

@ -18,10 +18,10 @@ npm install @uppy/react
```
```js
// Either:
import Dashboard from '@uppy/react/lib/Dashboard'
// Or:
import { Dashboard } from '@uppy/react'
// Alternatively, you can also use a default import:
// import Dashboard from '@uppy/react/lib/Dashboard'
```
## CSS
@ -45,7 +45,11 @@ The `<Dashboard />` component supports all [`@uppy/dashboard`][] options as prop
> The `<Dashboard />` cannot be passed to a `target:` option of a remote provider or plugins such as [`@uppy/webcam`][]. To use other plugins like [`@uppy/webcam`][] (Image Editor, Google Drive, etc) with the `<Dashboard />` component, first add them to the Uppy instance, and then specify their `id` in the [`plugins`](/docs/dashboard/#plugins) prop:
<!-- eslint-disable react/jsx-props-no-spreading -->
```js
import React from 'react'
import { Dashboard } from '@uppy/react'
function Uploader () {
const uppy = React.useMemo(() => {
return Uppy()

View file

@ -19,10 +19,10 @@ npm install @uppy/react
```
```js
// Either:
import DragDrop from '@uppy/react/lib/DragDrop';
// Or:
import { DragDrop } from '@uppy/react';
import { DragDrop } from '@uppy/react'
// Alternatively, you can also use a default import:
// import DragDrop from '@uppy/react/lib/DragDrop';
```
## CSS
@ -41,21 +41,23 @@ Import general Core styles from `@uppy/core/dist/style.css` first, then add the
The `<DragDrop />` component supports all [DragDrop](/docs/drag-drop/) options as props. Additionally, an Uppy instance must be provided in the `uppy={}` prop: see [Initializing Uppy](/docs/react/initializing) for details.
```js
// assuming `this.uppy` contains an Uppy instance:
import React from 'react'
import { DragDrop } from '@uppy/react'
<DragDrop
width="100%"
height="100%"
note="Images up to 200×200px"
uppy={this.uppy}
locale={{
strings: {
<DragDrop
width="100%"
height="100%"
note="Images up to 200×200px"
// assuming `this.uppy` contains an Uppy instance:
uppy={this.uppy}
locale={{
strings: {
// Text to show on the droppable area.
// `%{browse}` is replaced with a link that opens the system file selection dialog.
dropHereOr: "Drop here or %{browse}",
// Used as the label for the link that opens the system file selection dialog.
browse: "browse",
},
}}
/>
dropHereOr: 'Drop here or %{browse}',
// Used as the label for the link that opens the system file selection dialog.
browse: 'browse',
},
}}
/>
```

View file

@ -19,10 +19,10 @@ npm install @uppy/react
```
```js
// Either:
import FileInput from '@uppy/react/lib/FileInput';
// Or:
import { FileInput } from '@uppy/react';
import { FileInput } from '@uppy/react'
// Alternatively, you can also use a default import:
// import FileInput from '@uppy/react/lib/FileInput';
```
## CSS
@ -41,11 +41,13 @@ Import general Core styles from `@uppy/core/dist/style.css` first, then add the
The `<FileInput />` component supports all [FileInput](/docs/file-input/) options as props. Additionally, an Uppy instance must be provided in the `uppy={}` prop: see [Initializing Uppy](/docs/react/initializing) for details.
```js
// assuming `this.uppy` contains an Uppy instance:
import React from 'react'
import { FileInput } from '@uppy/react'
<FileInput
uppy={this.uppy}
pretty={true}
inputName='files[]'
/>
<FileInput
// assuming `this.uppy` contains an Uppy instance:
uppy={this.uppy}
pretty
inputName="files[]"
/>
```

View file

@ -18,6 +18,7 @@ The `@uppy/react` package provides a hook `useUppy()` that can manage an Uppy in
```js
import Uppy from '@uppy/core'
import React from 'react'
import Tus from '@uppy/tus'
import { DashboardModal, useUppy } from '@uppy/react'
@ -41,6 +42,9 @@ A simple approach is to create an Uppy instance in your React component's `const
> Do **NOT** initialize Uppy in a `render()` method!
```js
import React from 'react'
import { DashboardModal } from '@uppy/react'
class MyComponent extends React.Component {
constructor (props) {
super(props)

View file

@ -24,14 +24,18 @@ npm install @uppy/react-native
```
```js
import React from 'react'
import UppyFilePicker from '@uppy/react-native'
render () {
<UppyFilePicker
uppy={this.uppy}
show={this.state.isFilePickerVisible}
onRequestClose={this.hideFilePicker}
companionUrl="https://server.uppy.io" />
export default function MyComponent (props) {
return (
<UppyFilePicker
uppy={props.uppy}
show={props.isFilePickerVisible}
onRequestClose={props.hideFilePicker}
companionUrl="https://server.uppy.io"
/>
)
}
```

View file

@ -19,10 +19,10 @@ npm install @uppy/react
```
```js
// Either:
import ProgressBar from '@uppy/react/lib/ProgressBar'
// Or:
import { ProgressBar } from '@uppy/react'
// Alternatively, you can also use a default import:
// import ProgressBar from '@uppy/react/lib/ProgressBar'
```
## CSS
@ -41,11 +41,14 @@ Import general Core styles from `@uppy/core/dist/style.css` first, then add the
The `<ProgressBar />` component supports all [`@uppy/progress-bar`][] options as props. Additionally, an Uppy instance must be provided in the `uppy={}` prop: see [Initializing Uppy](/docs/react/initializing) for details.
```js
<ProgressBar
uppy={uppy}
fixed
hideAfterFinish
/>
import React from 'react'
import { ProgressBar } from '@uppy/react'
<ProgressBar
uppy={uppy}
fixed
hideAfterFinish
/>
```
[`@uppy/progress-bar`]: /docs/progress-bar/

View file

@ -19,10 +19,10 @@ npm install @uppy/react
```
```js
// Either:
import StatusBar from '@uppy/react/lib/StatusBar'
// Or:
import { StatusBar } from '@uppy/react'
// Alternatively, you can also use a default import:
// import StatusBar from '@uppy/react/lib/StatusBar'
```
## CSS
@ -41,12 +41,15 @@ Import general Core styles from `@uppy/core/dist/style.css` first, then add the
The `<StatusBar />` component supports all [`@uppy/status-bar`][] options as props. Additionally, an Uppy instance must be provided in the `uppy={}` prop: see [Initializing Uppy](/docs/react/initializing) for details.
```js
<StatusBar
uppy={uppy}
hideUploadButton
hideAfterFinish={false}
showProgressDetails
/>
import React from 'react'
import { StatusBar } from '@uppy/react'
<StatusBar
uppy={uppy}
hideUploadButton
hideAfterFinish={false}
showProgressDetails
/>
```
[`@uppy/status-bar`]: /docs/status-bar/

View file

@ -39,7 +39,7 @@ import { DragDrop } from '@uppy/react'
const uppy = new Uppy({
meta: { type: 'avatar' },
restrictions: { maxNumberOfFiles: 1 },
autoProceed: true
autoProceed: true,
})
uppy.use(Tus, { endpoint: '/upload' })
@ -48,7 +48,7 @@ uppy.on('complete', (result) => {
const url = result.successful[0].uploadURL
store.dispatch({
type: 'SET_USER_AVATAR_URL',
payload: { url: url }
payload: { url },
})
})
@ -64,8 +64,8 @@ const AvatarPicker = ({ currentAvatar }) => {
// `%{browse}` is replaced with a link that opens the system file selection dialog.
dropHereOr: 'Drop here or %{browse}',
// Used as the label for the link that opens the system file selection dialog.
browse: 'browse'
}
browse: 'browse',
},
}}
/>
</div>

View file

@ -20,13 +20,13 @@ import createReduxStore from '@uppy/store-redux'
const reducer = combineReducers({
...reducers,
uppy: ReduxStore.reducer
uppy: ReduxStore.reducer,
})
const uppy = new Uppy({
store: createReduxStore({
store: createStore(reducer) // Thats a lot of stores!
})
store: createStore(reducer), // Thats a lot of stores!
}),
})
```
@ -46,8 +46,8 @@ const uppy = new Uppy({
debug: true,
meta: {
username: 'John',
license: 'Creative Commons'
}
license: 'Creative Commons',
},
})
.use(XHRUpload, { endpoint: 'https://example.com' })
.use(ReduxDevTools)

View file

@ -42,10 +42,10 @@ All the options to the [Transloadit][transloadit plugin] plugin are supported.
You can localize the “Choose files” button that is injected into the form, by setting the `locale.strings` option:
```js
locale: {
const locale = {
strings: {
chooseFiles: 'Choose files'
}
chooseFiles: 'Choose files',
},
}
```
@ -113,7 +113,7 @@ The `triggerUploadOnSubmit: false` option is available for this purpose. We reco
window.Robodog.form('form#upload-form', {
modal: true,
closeAfterFinish: true,
triggerUploadOnSubmit: false
triggerUploadOnSubmit: false,
})
```
@ -156,7 +156,7 @@ Here is a full copy-pasteable code sample with all updated options and event nam
Notice how the form is submitted to the inexistant `/uploads` route once all transcoding is finished. Please do not forget to add your Transloadit auth key to
`window.YOUR_TRANSLOADIT_AUTH_KEY`.
```js
```html
<html>
<head>
<title>Testing Robodog</title>

View file

@ -13,8 +13,8 @@ Show a modal UI that allows users to pick files from their device and from the w
const resultPromise = Robodog.pick({
params: {
auth: { key: '' },
template_id: ''
}
template_id: '',
},
})
```

View file

@ -13,8 +13,8 @@ Upload files straight to Transloadit from your own custom UI. Give us an array o
const resultPromise = Robodog.upload(files, {
params: {
auth: { key: '' },
template_id: ''
}
template_id: '',
},
})
```

View file

@ -57,12 +57,12 @@ const resultPromise = Robodog.pick({
target: 'body',
params: {
auth: { key: '' },
template_id: ''
}
template_id: '',
},
})
resultPromise.then((bundle) => {
bundle.transloadit // Array of Assembly statuses
bundle.results // Array of all Assembly results
const statuses = bundle.transloadit // Array of Assembly statuses
const assemblyResults = bundle.results // Array of all Assembly results
})
```
@ -101,12 +101,12 @@ Upload files straight to Transloadit from your own custom UI. Give us an array o
const resultPromise = Robodog.upload(files, {
params: {
auth: { key: '' },
template_id: ''
}
template_id: '',
},
})
resultPromise.then((bundle) => {
bundle.transloadit // Array of Assembly statuses
bundle.results // Array of all Assembly results
const statuses = bundle.transloadit // Array of Assembly statuses
const assemblyResults = bundle.results // Array of all Assembly results
})
```

View file

@ -35,7 +35,7 @@ npm install @uppy/status-bar
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const StatusBar = Uppy.StatusBar
const { StatusBar } = Uppy
```
## CSS
@ -66,7 +66,7 @@ uppy.use(StatusBar, {
hidePauseResumeButton: false,
hideCancelButton: false,
doneButtonHandler: null,
locale: {}
locale: {},
})
```
@ -110,7 +110,7 @@ Hide the cancel button. Use this if you are providing a custom retry button some
If passed a function, Status Bar will render a “Done” button in place of pause/resume/cancel buttons, once the upload/encoding is done. The behaviour of this “Done” button is defined by the handler function — can be used to close file picker modals or clear the upload state. This is what the Dashboard plugin, which uses Status Bar internally, sets:
```js
doneButtonHandler: () => {
const doneButtonHandler = () => {
this.uppy.reset()
this.requestCloseModal()
}
@ -123,7 +123,7 @@ Localize text that is shown to the user.
The default English strings are:
```js
strings: {
const strings = {
// Shown in the status bar while files are being uploaded.
uploading: 'Uploading',
// Shown in the status bar once all files have been uploaded.
@ -145,7 +145,7 @@ strings: {
// When `showProgressDetails` is set, shows the number of files that have been fully uploaded so far.
filesUploadedOfTotal: {
0: '%{complete} of %{smart_count} file uploaded',
1: '%{complete} of %{smart_count} files uploaded'
1: '%{complete} of %{smart_count} files uploaded',
},
// When `showProgressDetails` is set, shows the amount of bytes that have been uploaded so far.
dataUploadedOfTotal: '%{complete} of %{total}',
@ -154,14 +154,14 @@ strings: {
// Used as the label for the button that starts an upload.
uploadXFiles: {
0: 'Upload %{smart_count} file',
1: 'Upload %{smart_count} files'
1: 'Upload %{smart_count} files',
},
// Used as the label for the button that starts an upload, if another upload has been started in the past
// and new files were added later.
uploadXNewFiles: {
0: 'Upload +%{smart_count} file',
1: 'Upload +%{smart_count} files'
}
1: 'Upload +%{smart_count} files',
},
}
```

View file

@ -29,7 +29,7 @@ To use a store, pass an instance to the [`store` option](/docs/uppy#store-defaul
import defaultStore from '@uppy/store-default'
const uppy = new Uppy({
store: defaultStore()
store: defaultStore(),
})
```
@ -49,9 +49,10 @@ To use the `ReduxStore`, add its reducer to the `uppy` key:
```js
import ReduxStore from '@uppy/store-redux'
const reducer = combineReducers({
...reducers,
uppy: ReduxStore.reducer
uppy: ReduxStore.reducer,
})
```
@ -64,8 +65,8 @@ import ReduxStore from '@uppy/store-redux'
const store = createStore(reducer)
const uppy = new Uppy({
store: ReduxStore({
store: store // That's a lot of stores!
})
store, // That's a lot of stores!
}),
})
```
@ -81,8 +82,8 @@ By default, the `ReduxStore` assumes Uppy state is stored on a `state.uppy[id]`
```js
ReduxStore({
store: store,
id: 'avatarUpload'
store,
id: 'avatarUpload',
})
```
@ -93,10 +94,10 @@ If you'd rather not store the Uppy state under the `state.uppy` key at all, use
```js
const uppy = new Uppy({
store: ReduxStore({
store: store,
store,
id: 'avatarUpload',
selector: state => state.pages.profile.uppy.avatarUpload
})
selector: state => state.pages.profile.uppy.avatarUpload,
}),
})
```
@ -127,7 +128,7 @@ function defaultStore () {
getState: () => state,
setState: (patch) => {
const prevState = state
const nextState = Object.assign({}, prevState, patch)
const nextState = { ...prevState, ...patch }
state = nextState
@ -138,7 +139,7 @@ function defaultStore () {
subscribe: (listener) => {
listeners.add(listener)
return () => listeners.remove(listener)
}
},
}
}
```

View file

@ -40,8 +40,8 @@ import postcss from 'postcss-import'
export default {
plugins: [
postcss
]
postcss,
],
}
```
@ -52,8 +52,8 @@ import preprocess from 'svelte-preprocess'
// ...
svelte({
preprocess: preprocess({
postcss: true
})
postcss: true,
}),
})
// ...
```
@ -78,7 +78,7 @@ import { Dashboard } from '@uppy/svelte'
import Uppy from '@uppy/core'
import Webcam from '@uppy/webcam'
let uppy = new Uppy().use(Webcam);
const uppy = new Uppy().use(Webcam);
</script>
```
@ -100,7 +100,7 @@ Due to the way Svelte handles reactivity, you can simply initialize Uppy the sam
import Uppy from '@uppy/core'
import Webcam from '@uppy/webcam'
let uppy = new Uppy().use(Webcam)
const uppy = new Uppy().use(Webcam)
```
## Components

View file

@ -18,7 +18,7 @@ import ThumbnailGenerator from '@uppy/thumbnail-generator'
uppy.use(ThumbnailGenerator, {
thumbnailWidth: 200,
// thumbnailHeight: 200 // optional, use either width or height,
waitForThumbnailsBeforeUpload: false
waitForThumbnailsBeforeUpload: false,
})
```
@ -37,7 +37,7 @@ npm install @uppy/thumbnail-generator
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const ThumbnailGenerator = Uppy.ThumbnailGenerator
const { ThumbnailGenerator } = Uppy
```
## Options
@ -50,7 +50,7 @@ uppy.use(ThumbnailGenerator, {
thumbnailWidth: 200,
thumbnailHeight: 200,
thumbnailType: 'image/jpeg',
waitForThumbnailsBeforeUpload: false
waitForThumbnailsBeforeUpload: false,
})
```

View file

@ -28,7 +28,7 @@ uppy.use(Transloadit, {
alwaysRunAssembly: false,
signature: null,
fields: {},
limit: 0
limit: 0,
})
```
@ -47,7 +47,7 @@ npm install @uppy/transloadit
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const Transloadit = Uppy.Transloadit
const { Transloadit } = Uppy
```
## Properties
@ -62,7 +62,7 @@ import Transloadit from '@uppy/transloadit'
uppy.use(Dropbox, {
companionUrl: Transloadit.COMPANION,
companionAllowedHosts: Transloadit.COMPANION_PATTERN
companionAllowedHosts: Transloadit.COMPANION_PATTERN,
})
```
@ -72,7 +72,7 @@ The value of this constant is `https://api2.transloadit.com/companion`. If you a
```js
uppy.use(Dropbox, {
companionUrl: 'https://api2-us-east-1.transloadit.com/companion'
companionUrl: 'https://api2-us-east-1.transloadit.com/companion',
})
```
@ -88,7 +88,7 @@ import Transloadit from '@uppy/transloadit'
uppy.use(Dropbox, {
companionUrl: Transloadit.COMPANION,
companionAllowedHosts: Transloadit.COMPANION_PATTERN
companionAllowedHosts: Transloadit.COMPANION_PATTERN,
})
```
@ -121,12 +121,12 @@ uppy.use(Transloadit, {
robot: '/video/encode',
use: {
steps: [':original'],
fields: ['file_input_field2']
fields: ['file_input_field2'],
},
preset: 'iphone'
}
}
}
preset: 'iphone',
},
},
},
})
```
@ -160,14 +160,14 @@ For example, to upload files to an S3 bucket and then transcode them:
uppy.use(AwsS3, {
getUploadParameters (file) {
return { /* upload parameters */ }
}
},
})
uppy.use(Transloadit, {
importFromUploadURLs: true,
params: {
auth: { key: 'YOUR_API_KEY' },
template_id: 'YOUR_TEMPLATE_ID'
}
template_id: 'YOUR_TEMPLATE_ID',
},
})
```
@ -189,10 +189,10 @@ An object of form fields to send along to the Assembly. Keys are field names, an
```js
uppy.use(Transloadit, {
...,
// ...
fields: {
message: 'This is a form field'
}
message: 'This is a form field',
},
})
```
@ -202,7 +202,7 @@ You can also pass an array of field names to send global or file metadata along
uppy.use(Form, { target: 'form#upload-form', getMetaFromForm: true })
uppy.use(Transloadit, {
fields: ['field_name', 'other_field_name'],
params: { ... }
params: { /* ... */ },
})
```
@ -217,21 +217,21 @@ A custom `getAssemblyOptions()` option should return an object or a Promise for
```js
uppy.use(MetaData, {
fields: [
{ id: 'caption' }
]
{ id: 'caption' },
],
})
uppy.use(Transloadit, {
getAssemblyOptions (file) {
return {
params: {
auth: { key: 'TRANSLOADIT_AUTH_KEY_HERE' },
template_id: 'xyz'
template_id: 'xyz',
},
fields: {
caption: file.meta.caption
}
caption: file.meta.caption,
},
}
}
},
})
```
@ -245,13 +245,13 @@ uppy.use(Form, { getMetaFromForm: true })
uppy.use(Transloadit, {
getAssemblyOptions (file) {
return {
params: { ... },
params: { /* ... */ },
// Pass through the fields you need:
fields: {
message: file.meta.message
}
message: file.meta.message,
},
}
}
},
})
```
@ -263,7 +263,7 @@ uppy.use(Transloadit, {
return fetch('/transloadit-params').then((response) => {
return response.json()
})
}
},
})
```
@ -278,14 +278,14 @@ Localize text that is shown to the user.
The default English strings are:
```js
strings: {
const strings = {
// Shown while Assemblies are being created for an upload.
creatingAssembly: 'Preparing upload...'
creatingAssembly: 'Preparing upload...',
// Shown if an Assembly could not be created.
creatingAssemblyFailed: 'Transloadit: Could not create Assembly',
// Shown after uploads have succeeded, but when the Assembly is still executing.
// This only shows if `waitForMetadata` or `waitForEncoding` was enabled.
encoding: 'Encoding...'
encoding: 'Encoding...',
}
```

View file

@ -15,7 +15,7 @@ import Tus from '@uppy/tus'
uppy.use(Tus, {
endpoint: 'https://tusd.tusdemo.net/files/', // use your tus endpoint here
retryDelays: [0, 1000, 3000, 5000]
retryDelays: [0, 1000, 3000, 5000],
})
```
@ -32,7 +32,7 @@ npm install @uppy/tus
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const Tus = Uppy.Tus
const { Tus } = Uppy
```
## Options

View file

@ -27,7 +27,7 @@ npm install @uppy/core
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const Core = Uppy.Core
const { Core } = Uppy
```
## Options
@ -46,7 +46,7 @@ const uppy = new Uppy({
maxTotalFileSize: null,
maxNumberOfFiles: null,
minNumberOfFiles: null,
allowedFileTypes: null
allowedFileTypes: null,
},
meta: {},
onBeforeFileAdded: (currentFile, files) => currentFile,
@ -54,7 +54,7 @@ const uppy = new Uppy({
locale: {},
store: new DefaultStore(),
logger: justErrorsLogger,
infoTimeout: 5000
infoTimeout: 5000,
})
```
@ -92,8 +92,9 @@ Set `logger: Uppy.debugLogger` to get debug info output to the browser console:
```js
import Uppy from '@uppy/core'
const uppy = new Uppy({
logger: Uppy.debugLogger
logger: Uppy.debugLogger,
})
```
@ -105,7 +106,7 @@ Heres an example of a `logger` that does nothing:
const nullLogger = {
debug: (...args) => {},
warn: (...args) => {},
error: (...args) => {}
error: (...args) => {},
}
```
@ -115,7 +116,7 @@ const nullLogger = {
const debugLogger = {
debug: (...args) => console.debug(`[Uppy] [${getTimeStamp()}]`, ...args),
warn: (...args) => console.warn(`[Uppy] [${getTimeStamp()}]`, ...args),
error: (...args) => console.error(`[Uppy] [${getTimeStamp()}]`, ...args)
error: (...args) => console.error(`[Uppy] [${getTimeStamp()}]`, ...args),
}
```
@ -147,9 +148,12 @@ Optionally, provide rules and conditions to limit the type and/or number of file
Metadata object, used for passing things like public keys, usernames, tags and so on:
```js
meta: {
username: 'John'
}
const uppy = new Uppy({
// ...
meta: {
username: 'John',
},
})
```
This global metadata is added to each file in Uppy. It can be modified by two methods:
@ -172,36 +176,45 @@ Use this function to run any number of custom checks on the selected file, or ma
Return true/nothing or a modified file object to proceed with adding the file:
<!-- eslint-disable no-dupe-keys -->
<!-- eslint-disable consistent-return -->
```js
onBeforeFileAdded: (currentFile, files) => {
if (currentFile.name === 'forest-IMG_0616.jpg') {
return true
}
}
const uppy = new Uppy({
// ...
onBeforeFileAdded: (currentFile, files) => {
if (currentFile.name === 'forest-IMG_0616.jpg') {
return true
}
},
// or
// or
onBeforeFileAdded: (currentFile, files) => {
const modifiedFile = {
...currentFile,
name: currentFile.name + '__' + Date.now()
}
return modifiedFile
}
onBeforeFileAdded: (currentFile, files) => {
const modifiedFile = {
...currentFile,
name: `${currentFile.name}__${Date.now()}`,
}
return modifiedFile
},
})
```
Return false to abort adding the file:
<!-- eslint-disable consistent-return -->
```js
onBeforeFileAdded: (currentFile, files) => {
if (!currentFile.type) {
// log to console
uppy.log(`Skipping file because it has no type`)
// show error message to the user
uppy.info(`Skipping file because it has no type`, 'error', 500)
return false
}
}
const uppy = new Uppy({
// ...
onBeforeFileAdded: (currentFile, files) => {
if (!currentFile.type) {
// log to console
uppy.log(`Skipping file because it has no type`)
// show error message to the user
uppy.info(`Skipping file because it has no type`, 'error', 500)
return false
}
},
})
```
**Note:** it is up to you to show a notification to the user about a file not passing validation. We recommend showing a message using [uppy.info()](#uppy-info) and logging to console for debugging purposes via [uppy.log()](#uppy-log).
@ -219,31 +232,38 @@ Use this to check if all files or their total number match your requirements, or
Return true or modified `files` object to proceed:
```js
onBeforeUpload: (files) => {
// Well be careful to return a new object, not mutating the original `files`
const updatedFiles = {}
Object.keys(files).forEach(fileID => {
updatedFiles[fileID] = {
...files[fileID],
name: 'myCustomPrefix' + '__' + files[fileID].name
}
})
return updatedFiles
}
const uppy = new Uppy({
// ...
onBeforeUpload: (files) => {
// Well be careful to return a new object, not mutating the original `files`
const updatedFiles = {}
Object.keys(files).forEach(fileID => {
updatedFiles[fileID] = {
...files[fileID],
name: `${myCustomPrefix}__${files[fileID].name}`,
}
})
return updatedFiles
},
})
```
Return false to abort:
<!-- eslint-disable consistent-return -->
```js
onBeforeUpload: (files) => {
if (Object.keys(files).length < 2) {
// log to console
uppy.log(`Aborting upload because only ${Object.keys(files).length} files were selected`)
// show error message to the user
uppy.info(`You have to select at least 2 files`, 'error', 500)
return false
}
}
const uppy = new Uppy({
// ...
onBeforeUpload: (files) => {
if (Object.keys(files).length < 2) {
// log to console
uppy.log(`Aborting upload because only ${Object.keys(files).length} files were selected`)
// show error message to the user
uppy.info(`You have to select at least 2 files`, 'error', 500)
return false
}
},
})
```
**Note:** it is up to you to show a notification to the user about a file not passing validation. We recommend showing a message using [uppy.info()](#uppy-info) and logging to console for debugging purposes via [uppy.log()](#uppy-log).
@ -253,23 +273,26 @@ onBeforeUpload: (files) => {
This allows you to override language strings:
```js
locale: {
strings: {
youCanOnlyUploadX: {
0: 'You can only upload %{smart_count} file',
1: 'You can only upload %{smart_count} files'
const uppy = new Uppy({
// ...
locale: {
strings: {
youCanOnlyUploadX: {
0: 'You can only upload %{smart_count} file',
1: 'You can only upload %{smart_count} files',
},
youHaveToAtLeastSelectX: {
0: 'You have to select at least %{smart_count} file',
1: 'You have to select at least %{smart_count} files',
},
// **NOTE**: This string is called `exceedsSize2` for backwards compatibility reasons.
// See https://github.com/transloadit/uppy/pull/2077
exceedsSize2: 'This file exceeds maximum allowed size of %{size}',
youCanOnlyUploadFileTypes: 'You can only upload: %{types}',
companionError: 'Connection with Companion failed',
},
youHaveToAtLeastSelectX: {
0: 'You have to select at least %{smart_count} file',
1: 'You have to select at least %{smart_count} files'
},
// **NOTE**: This string is called `exceedsSize2` for backwards compatibility reasons.
// See https://github.com/transloadit/uppy/pull/2077
exceedsSize2: 'This file exceeds maximum allowed size of %{size}',
youCanOnlyUploadFileTypes: 'You can only upload: %{types}',
companionError: 'Connection with Companion failed'
}
}
},
})
```
Instead of overriding strings yourself, consider using [one of our language packs](https://github.com/transloadit/uppy/tree/master/packages/%40uppy/locales) (or contributing one!):
@ -291,9 +314,11 @@ It also offers the pluralization function, which is used to determine which stri
For example, for the Icelandic language, the pluralization function would be:
``` js
locale: {
pluralize: (n) => (n % 10 !== 1 || n % 100 === 11) ? 1 : 0
}
const uppy = new Uppy({
locale: {
pluralize: (n) => ((n % 10 !== 1 || n % 100 === 11) ? 1 : 0),
},
})
```
We are using a forked [Polyglot.js](https://github.com/airbnb/polyglot.js/blob/master/index.js#L37-L60).
@ -408,11 +433,12 @@ uppy.addFile({
type: 'image/jpeg', // file type
data: blob, // file blob
meta: {
// optional, store the directory path of a file so Uppy can tell identical files in different directories apart
// optional, store the directory path of a file so Uppy can tell identical files in different directories apart.
relativePath: webkitFileSystemEntry.relativePath,
},
source: 'Local', // optional, determines the source of the file, for example, Instagram
isRemote: false // optional, set to true if actual file is not in the browser, but on some remote server, for example, when using companion in combination with Instagram
source: 'Local', // optional, determines the source of the file, for example, Instagram.
isRemote: false, // optional, set to true if actual file is not in the browser, but on some remote server, for example,
// when using companion in combination with Instagram.
})
```
@ -445,13 +471,15 @@ Get a specific [File Object][File Objects] by its ID.
```js
const file = uppy.getFile('uppyteamkongjpg1501851828779')
file.id // 'uppyteamkongjpg1501851828779'
file.name // 'nature.jpg'
file.extension // '.jpg'
file.type // 'image/jpeg'
file.data // the Blob object
file.size // 3947642 (returns 'N/A' if size cannot be determined)
file.preview // value that can be used to populate "src" attribute of an "img" tag
const {
id, // 'uppyteamkongjpg1501851828779'
name, // 'nature.jpg'
extension, // '.jpg'
type, // 'image/jpeg'
data, // the Blob object
size, // 3947642 (returns 'N/A' if size cannot be determined)
preview, // value that can be used to populate "src" attribute of an "img" tag
} = file
```
### `uppy.getFiles()`
@ -460,9 +488,8 @@ Get an array of all [File Objects][] that have been added to Uppy.
```js
import prettierBytes from '@transloadit/prettier-bytes'
const items = uppy.getFiles().map(() =>
`<li>${file.name} - ${prettierBytes(file.size)}</li>`
).join('')
const items = uppy.getFiles().map(() => `<li>${file.name} - ${prettierBytes(file.size)}</li>`).join('')
document.querySelector('.file-list').innerHTML = `<ul>${items}</ul>`
```
@ -519,20 +546,20 @@ Update Uppy's internal state. Usually, this method is called internally, but in
Uppys default state on initialization:
```js
{
const state = {
plugins: {},
files: {},
currentUploads: {},
capabilities: {
resumableUploads: false
resumableUploads: false,
},
totalProgress: 0,
meta: Object.assign({}, this.opts.meta),
meta: { ...this.opts.meta },
info: {
isHidden: true,
type: 'info',
message: ''
}
message: '',
},
}
```
@ -540,7 +567,7 @@ Updating state:
```js
uppy.setState({
smth: true
smth: true,
})
```
@ -548,17 +575,19 @@ State in Uppy is considered to be immutable. When updating values, it is your re
```js
// We use Object.assign({}, obj) to create a copy of `obj`.
const updatedFiles = Object.assign({}, uppy.getState().files)
const updatedFiles = { ...uppy.getState().files }
// We use Object.assign({}, obj, update) to create an altered copy of `obj`.
const updatedFile = Object.assign({}, updatedFiles[fileID], {
progress: Object.assign({}, updatedFiles[fileID].progress, {
const updatedFile = {
...updatedFiles[fileID],
progress: {
...updatedFiles[fileID].progress,
bytesUploaded: data.bytesUploaded,
bytesTotal: data.bytesTotal,
percentage: Math.floor((data.bytesUploaded / data.bytesTotal * 100).toFixed(2))
})
})
percentage: Math.floor(100 * (data.bytesUploaded / data.bytesTotal)),
},
}
updatedFiles[data.id] = updatedFile
uppy.setState({files: updatedFiles})
uppy.setState({ files: updatedFiles })
```
### `uppy.getState()`
@ -599,15 +628,15 @@ Change Uppy options on the fly. For example, to conditionally change `restrictio
const uppy = new Uppy()
uppy.setOptions({
restrictions: { maxNumberOfFiles: 3 },
autoProceed: true
autoProceed: true,
})
uppy.setOptions({
locale: {
strings: {
'cancel': 'Отмена'
}
}
cancel: 'Отмена',
},
},
})
```
@ -616,7 +645,7 @@ You can also change options for plugin on the fly, like this:
```js
// Change width of the Dashboard drag-and-drop aread on the fly
uppy.getPlugin('Dashboard').setOptions({
width: 300
width: 300,
})
```
@ -785,20 +814,20 @@ Fired each time a single upload is completed.
For `@uppy/xhr-upload`, the shape is:
```js
```json
{
status, // HTTP status code (0, 200, 300)
body, // response body
uploadURL // the file url, if it was returned
"status": 200, // HTTP status code (0, 200, 300)
"body": "…", // response body
"uploadURL": "…" // the file url, if it was returned
}
```
**Example**
``` javascript
```js
uppy.on('upload-success', (file, response) => {
console.log(file.name, response.uploadURL)
var img = new Image()
const img = new Image()
img.width = 300
img.alt = file.id
img.src = response.uploadURL
@ -812,7 +841,7 @@ Fired when all uploads are complete.
The `result` parameter is an object with arrays of `successful` and `failed` files, just like in [`uppy.upload()`](#uppy-upload)s return value.
``` javascript
```js
uppy.on('complete', (result) => {
console.log('successful files:', result.successful)
console.log('failed files:', result.failed)
@ -844,10 +873,10 @@ Fired each time a single upload has errored.
For `@uppy/xhr-upload`, the shape is:
```js
```json
{
status, // HTTP status code (0, 200, 300)
body // response body
"status": 200, // HTTP status code (0, 200, 300)
"body": "…" // response body
}
```
@ -891,14 +920,14 @@ Fired when “info” message should be visible in the UI. By default, `Informer
``` javascript
uppy.on('info-visible', () => {
const info = uppy.getState().info
const { info } = uppy.getState()
// info: {
// isHidden: false,
// type: 'error',
// message: 'Failed to upload',
// details: 'Error description'
// }
alert(`${info.message} ${info.details}`)
console.log(`${info.message} ${info.details}`)
})
```

View file

@ -36,7 +36,7 @@ npm install @uppy/url
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const Url = Uppy.Url
const { Url } = Uppy
```
## CSS
@ -58,7 +58,7 @@ The `@uppy/url` plugin has the following configurable options:
uppy.use(Url, {
target: Dashboard,
companionUrl: 'https://companion.uppy.io/',
locale: {}
locale: {},
})
```
@ -89,7 +89,7 @@ Localize text that is shown to the user.
The default English strings are:
```js
strings: {
const strings = {
// Label for the "Import" button.
import: 'Import',
// Placeholder text for the URL input.
@ -97,7 +97,7 @@ strings: {
// Error message shown if Companion could not load a URL.
failedToFetch: 'Companion failed to fetch this URL, please make sure its correct',
// Error message shown if the input does not look like a URL.
enterCorrectUrl: 'Incorrect URL: Please make sure you are entering a direct link to a file'
enterCorrectUrl: 'Incorrect URL: Please make sure you are entering a direct link to a file',
}
```

View file

@ -88,11 +88,11 @@ export default {
computed: {
uppy: () => new Uppy().use(Webcam, {
// Config
})
}),
},
beforeDestroy () {
this.uppy.close()
}
},
}
```

View file

@ -35,7 +35,7 @@ npm install @uppy/webcam
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const Webcam = Uppy.Webcam
const { Webcam } = Uppy
```
## CSS
@ -61,7 +61,7 @@ uppy.use(Webcam, {
'video-audio',
'video-only',
'audio-only',
'picture'
'picture',
],
mirror: true,
videoConstraints: {
@ -72,7 +72,7 @@ uppy.use(Webcam, {
showRecordingLength: false,
preferredVideoMimeType: null,
preferredImageMimeType: null,
locale: {}
locale: {},
})
```
@ -159,7 +159,7 @@ Localize text that is shown to the user.
The default English strings are:
```js
strings: {
const strings = {
// Shown before a picture is taken when the `countdown` option is set.
smile: 'Smile!',
// Used as the label for the button that takes a picture.
@ -177,6 +177,6 @@ strings: {
// Title on the “allow access” screen
allowAccessTitle: 'Please allow access to your camera',
// Description on the “allow access” screen
allowAccessDescription: 'In order to take pictures or record video with your camera, please allow camera access for this site.'
allowAccessDescription: 'In order to take pictures or record video with your camera, please allow camera access for this site.',
}
```

View file

@ -23,6 +23,7 @@ The plugin constructor receives the Uppy instance in the first parameter, and an
```js
import { UIPlugin } from '@uppy/core'
export default class MyPlugin extends UIPlugin {
constructor (uppy, opts) {
super(uppy, opts)
@ -43,9 +44,12 @@ All of the below methods are optional! Only implement the methods you need.
Called when the plugin is `.use`d. Do any setup work here, like attaching events or adding [upload hooks](#Upload-Hooks).
```js
install () {
this.uppy.on('upload-progress', this.onProgress)
this.uppy.addPostProcessor(this.afterUpload)
export default class MyPlugin extends UIPlugin {
// ...
install () {
this.uppy.on('upload-progress', this.onProgress)
this.uppy.addPostProcessor(this.afterUpload)
}
}
```
@ -54,9 +58,12 @@ install () {
Called when the plugin is removed, or the Uppy instance is closed. This should undo all of the work done in the `install()` method.
```js
uninstall () {
this.uppy.off('upload-progress', this.onProgress)
this.uppy.removePostProcessor(this.afterUpload)
export default class MyPlugin extends UIPlugin {
// ...
uninstall () {
this.uppy.off('upload-progress', this.onProgress)
this.uppy.removePostProcessor(this.afterUpload)
}
}
```
@ -84,6 +91,7 @@ class MyPlugin extends UIPlugin {
}
prepareUpload (fileIDs) {
console.log(this) // `this` refers to the `MyPlugin` instance.
return Promise.resolve()
}
@ -188,6 +196,7 @@ Since Uppy uses Preact and not React, the default Babel configuration for JSX el
See the Preact [Getting Started Guide](https://preactjs.com/guide/getting-started) for more on Babel and JSX.
<!-- eslint-disable jsdoc/check-tag-names -->
```js
/** @jsx h */
import { UIPlugin } from '@uppy/core'
@ -199,7 +208,9 @@ class NumFiles extends UIPlugin {
return (
<div>
Number of files: {numFiles}
Number of files:
{' '}
{numFiles}
</div>
)
}
@ -217,9 +228,9 @@ this.defaultLocale = {
youCanOnlyUploadX: {
0: 'You can only upload %{smart_count} file',
1: 'You can only upload %{smart_count} files',
2: 'You can only upload %{smart_count} files'
}
}
2: 'You can only upload %{smart_count} files',
},
},
}
```
@ -227,7 +238,7 @@ This allows them to be overridden by Locale Packs, or directly when users pass `
```js
// i18n
this.translator = new Translator([ this.defaultLocale, this.uppy.locale, this.opts.locale ])
this.translator = new Translator([this.defaultLocale, this.uppy.locale, this.opts.locale])
this.i18n = this.translator.translate.bind(this.translator)
this.i18nArray = this.translator.translateArray.bind(this.translator)
// ^-- Only if you're using i18nArray, which allows you to pass in JSX Components as well.
@ -237,6 +248,7 @@ this.i18nArray = this.translator.translateArray.bind(this.translator)
Below is a full example of a [simple plugin](https://github.com/arturi/uppy-plugin-image-compressor) that compresses images before uploading them. You can replace `compressorjs` method with any other work you need to do. This works especially well for async stuff, like calling an external API.
<!-- eslint-disable consistent-return -->
```js
import { UIPlugin } from '@uppy/core'
import Translator from '@uppy/utils/lib/Translator'
@ -250,15 +262,15 @@ class UppyImageCompressor extends UIPlugin {
this.defaultLocale = {
strings: {
compressingImages: 'Compressing images...'
}
compressingImages: 'Compressing images...',
},
}
const defaultOptions = {
quality: 0.6
quality: 0.6,
}
this.opts = Object.assign({}, defaultOptions, opts)
this.opts = { ...defaultOptions, ...opts }
// we use those internally in `this.compress`, so they
// should not be overriden
@ -283,20 +295,16 @@ class UppyImageCompressor extends UIPlugin {
}
compress (blob) {
return new Promise((resolve, reject) => {
new Compressor(blob, Object.assign(
{},
this.opts,
{
success: (result) => {
return resolve(result)
},
error: (err) => {
return reject(err)
}
}
))
})
return new Promise((resolve, reject) => new Compressor(blob, ({
...this.opts,
success: (result) => {
return resolve(result)
},
error: (err) => {
return reject(err)
},
})))
}
prepareUpload (fileIDs) {
@ -304,7 +312,7 @@ class UppyImageCompressor extends UIPlugin {
const file = this.uppy.getFile(fileID)
this.uppy.emit('preprocess-progress', file, {
mode: 'indeterminate',
message: this.i18n('compressingImages')
message: this.i18n('compressingImages'),
})
if (file.type.split('/')[0] !== 'image') {

View file

@ -16,7 +16,7 @@ The `@uppy/xhr-upload` plugin handles classic HTML multipart form uploads, as we
import XHRUpload from '@uppy/xhr-upload'
uppy.use(XHRUpload, {
endpoint: 'http://my-website.org/upload'
endpoint: 'http://my-website.org/upload',
})
```
@ -35,7 +35,7 @@ npm install @uppy/xhr-upload
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const XHRUpload = Uppy.XHRUpload
const { XHRUpload } = Uppy
```
## Options
@ -83,17 +83,17 @@ An object containing HTTP headers to use for the upload request.
Keys are header names, values are header values.
```js
headers: {
'authorization': `Bearer ${window.getCurrentUserToken()}`
const headers = {
authorization: `Bearer ${window.getCurrentUserToken()}`,
}
```
Header values can also be derived from file data by providing a function. The function receives a [File Object][File Objects] and must return an object where the keys are header names, and values are header values.
```js
headers: (file) => {
const headers = (file) => {
return {
'authorization': `Bearer ${window.getCurrentUserToken()}`,
'expires': file.meta.expires
authorization: `Bearer ${window.getCurrentUserToken()}`,
expires: file.meta.expires,
}
}
```
@ -112,10 +112,10 @@ All files will be appended to the provided `fieldName` field in the request. To
```js
uppy.setFileState(fileID, {
xhrUpload: { fieldName: 'pic0' }
xhrUpload: { fieldName: 'pic0' },
})
uppy.setFileState(otherFileID, {
xhrUpload: { fieldName: 'pic1' }
xhrUpload: { fieldName: 'pic1' },
})
```
@ -144,13 +144,13 @@ The `responseText` is the XHR endpoint response as a string.
When an upload has completed, Uppy will extract response data from the upload endpoint. This response data will be available on the file's `.response` property, and be emitted in the [`upload-success`][uppy.upload-success] event:
```js
uppy.getFile(fileID).response
const responseData = uppy.getFile(fileID).response
// { status: HTTP status code,
// body: extracted response data }
uppy.on('upload-success', (file, response) => {
response.status // HTTP status code
response.body // extracted response data
const httpStatus = response.status // HTTP status code
const httpBody = response.body // extracted response data
// do something with file and response
})
@ -170,9 +170,9 @@ That object will be the value of `response.body`. Not all endpoints respond with
For example, an endpoint that responds with an XML document:
```js
getResponseData (responseText, response) {
function getResponseData (responseText, response) {
return {
url: responseText.match(/<Location>(.*?)<\/Location>/)[1]
url: responseText.match(/<Location>(.*?)<\/Location>/)[1],
}
}
```
@ -199,7 +199,7 @@ Pass in a `getResponseError` function to extract error data from the [`XMLHttpRe
For example, if the endpoint responds with a JSON object containing a `{ message }` property, this would show that message to the user:
```js
getResponseError (responseText, response) {
function getResponseError (responseText, response) {
return new Error(JSON.parse(responseText).message)
}
```
@ -235,9 +235,9 @@ Localize text that is shown to the user.
The default English strings are:
```js
strings: {
const strings = {
// Shown in the Informer if an upload is being canceled because it stalled for too long.
timedOut: 'Upload stalled for %{seconds} seconds, aborting.'
timedOut: 'Upload stalled for %{seconds} seconds, aborting.',
}
```
@ -250,7 +250,7 @@ It may be useful to set metadata depending on some file properties, such as the
```js
uppy.on('file-added', (file) => {
uppy.setFileMeta(file.id, {
size: file.size
size: file.size,
})
})
```
@ -262,7 +262,7 @@ By default, all metadata is sent, including Uppy's default `name` and `type` met
```js
uppy.use(XHRUpload, {
// Only send our own `size` metadata field.
metaFields: ['size']
metaFields: ['size'],
})
```
@ -289,7 +289,7 @@ Set a custom `fieldName` to make working with the `$_FILES` array a bit less con
// app.js
uppy.use(XHRUpload, {
endpoint: '/upload.php',
fieldName: 'my_file'
fieldName: 'my_file',
})
```

View file

@ -36,7 +36,7 @@ npm install @uppy/zoom
In the [CDN package](/docs/#With-a-script-tag), it is available on the `Uppy` global object:
```js
const Zoom = Uppy.Zoom
const { Zoom } = Uppy
```
## CSS
@ -95,7 +95,7 @@ Localize text that is shown to the user.
The default English strings are:
```js
strings: {
const strings = {
// TODO
}
```