autofix code

This commit is contained in:
Kevin van Zonneveld 2021-03-09 20:59:02 +01:00
parent 9930818ad6
commit 14c8a8cde8
No known key found for this signature in database
GPG key ID: 5E20B81008764DF4
310 changed files with 4009 additions and 4236 deletions

View file

@ -8,15 +8,15 @@ module.exports = (api) => {
presets: [
['@babel/preset-env', {
modules: false,
loose: true,
targets
}]
loose : true,
targets,
}],
],
plugins: [
['@babel/plugin-proposal-class-properties', { loose: true }],
'@babel/plugin-transform-object-assign',
['@babel/plugin-transform-react-jsx', { pragma: 'h' }],
process.env.IS_RELEASE_BUILD && 'babel-plugin-inline-package-json'
].filter(Boolean)
process.env.IS_RELEASE_BUILD && 'babel-plugin-inline-package-json',
].filter(Boolean),
}
}

View file

@ -16,6 +16,7 @@ const { promisify } = require('util')
const once = require('events.once')
const globby = require('globby')
const fs = require('fs')
const readFile = promisify(fs.readFile)
const writeFile = promisify(fs.writeFile)
@ -36,7 +37,7 @@ async function updateVersions (files, packageName) {
const urlPart = packageName === 'uppy' ? packageName : packageName.slice(1)
const replacements = new Map([
[RegExp(`${urlPart}/v\\d+\\.\\d+\\.\\d+\\/`, 'g'), `${urlPart}/v${version}/`]
[RegExp(`${urlPart}/v\\d+\\.\\d+\\.\\d+\\/`, 'g'), `${urlPart}/v${version}/`],
// maybe more later
])
@ -59,11 +60,11 @@ async function gitAdd (files) {
async function npmRunBuild () {
const npmRun = spawn('npm', ['run', 'build'], {
stdio: 'inherit',
env: {
env : {
...process.env,
FRESH: true, // force rebuild everything
IS_RELEASE_BUILD: true
}
FRESH : true, // force rebuild everything
IS_RELEASE_BUILD: true,
},
})
const [exitCode] = await once(npmRun, 'exit')
if (exitCode !== 0) {
@ -91,7 +92,7 @@ async function main () {
'website/src/docs/**',
'website/src/examples/**',
'website/themes/uppy/layout/**',
'!**/node_modules/**'
'!**/node_modules/**',
])
await updateVersions(files, 'uppy')
@ -106,7 +107,7 @@ async function main () {
await npmRunBuild()
}
main().catch(function (err) {
main().catch((err) => {
console.error(err.stack)
process.exit(1)
})

View file

@ -20,12 +20,12 @@ function buildBundle (srcFile, bundleFile, { minify = false, standalone = '' } =
b.transform(babelify)
b.on('error', handleErr)
return new Promise(function (resolve, reject) {
return new Promise((resolve, reject) => {
b.bundle()
.pipe(exorcist(bundleFile + '.map'))
.pipe(exorcist(`${bundleFile}.map`))
.pipe(fs.createWriteStream(bundleFile), 'utf8')
.on('error', handleErr)
.on('finish', function () {
.on('finish', () => {
if (minify) {
console.info(chalk.green(`✓ Built Minified Bundle [${standalone}]:`), chalk.magenta(bundleFile))
} else {
@ -44,23 +44,23 @@ const methods = [
buildBundle(
'./packages/uppy/bundle.js',
'./packages/uppy/dist/uppy.js',
{ standalone: 'Uppy' }
{ standalone: 'Uppy' },
),
buildBundle(
'./packages/uppy/bundle.js',
'./packages/uppy/dist/uppy.min.js',
{ standalone: 'Uppy', minify: true }
{ standalone: 'Uppy', minify: true },
),
buildBundle(
'./packages/@uppy/robodog/bundle.js',
'./packages/@uppy/robodog/dist/robodog.js',
{ standalone: 'Robodog' }
{ standalone: 'Robodog' },
),
buildBundle(
'./packages/@uppy/robodog/bundle.js',
'./packages/@uppy/robodog/dist/robodog.min.js',
{ standalone: 'Robodog', minify: true }
)
{ standalone: 'Robodog', minify: true },
),
]
// Build minified versions of all the locales
@ -71,11 +71,11 @@ glob.sync(localePackagePath).forEach((localePath) => {
buildBundle(
`./packages/@uppy/locales/src/${localeName}.js`,
`./packages/@uppy/locales/dist/${localeName}.min.js`,
{ minify: true }
)
{ minify: true },
),
)
})
Promise.all(methods).then(function () {
Promise.all(methods).then(() => {
console.info(chalk.yellow('✓ JS bundles 🎉'))
})

View file

@ -30,9 +30,9 @@ async function compileCSS () {
file,
importer (url, from, done) {
resolve(url, {
basedir: path.dirname(from),
filename: from,
extensions: ['.scss']
basedir : path.dirname(from),
filename : from,
extensions: ['.scss'],
}, (err, res) => {
if (err) return done(err)
@ -43,17 +43,17 @@ async function compileCSS () {
done({ file: res })
})
}
},
})
const plugins = [
autoprefixer,
postcssLogical(),
postcssDirPseudoClass()
postcssDirPseudoClass(),
]
const postcssResult = await postcss(plugins)
.process(scssResult.css, { from: file })
postcssResult.warnings().forEach(function (warn) {
postcssResult.warnings().forEach((warn) => {
console.warn(warn.toString())
})
@ -72,19 +72,19 @@ async function compileCSS () {
await writeFile(outfile, postcssResult.css)
console.info(
chalk.green('✓ Built Uppy CSS:'),
chalk.magenta(path.relative(cwd, outfile))
chalk.magenta(path.relative(cwd, outfile)),
)
const minifiedResult = await postcss([
cssnano({ safe: true })
cssnano({ safe: true }),
]).process(postcssResult.css, { from: outfile })
minifiedResult.warnings().forEach(function (warn) {
minifiedResult.warnings().forEach((warn) => {
console.warn(warn.toString())
})
await writeFile(outfile.replace(/\.css$/, '.min.css'), minifiedResult.css)
console.info(
chalk.green('✓ Minified Bundle CSS:'),
chalk.magenta(path.relative(cwd, outfile).replace(/\.css$/, '.min.css'))
chalk.magenta(path.relative(cwd, outfile).replace(/\.css$/, '.min.css')),
)
}
}

View file

@ -18,7 +18,7 @@ const META_FILES = [
'babel.config.js',
'package.json',
'package-lock.json',
'bin/build-lib.js'
'bin/build-lib.js',
]
function lastModified (file) {
@ -27,8 +27,7 @@ function lastModified (file) {
async function buildLib () {
const metaMtimes = await Promise.all(META_FILES.map((filename) =>
lastModified(path.join(__dirname, '..', filename))
))
lastModified(path.join(__dirname, '..', filename))))
const metaMtime = Math.max(...metaMtimes)
const files = await glob(SOURCE)
@ -51,13 +50,14 @@ async function buildLib () {
await mkdirp(path.dirname(libFile))
await Promise.all([
writeFile(libFile, code),
writeFile(libFile + '.map', JSON.stringify(map))
writeFile(`${libFile}.map`, JSON.stringify(map)),
])
console.log(chalk.green('Compiled lib:'), chalk.magenta(libFile))
}
}
console.log('Using Babel version:', require('@babel/core/package.json').version)
buildLib().catch((err) => {
console.error(err.stack)
process.exit(1)

View file

@ -1,5 +1,4 @@
#!/usr/bin/env node
'use strict'
const userAgent = process.env.npm_config_user_agent
if (!userAgent) {

View file

@ -13,16 +13,16 @@ function minifyify (filename) {
if (filename.endsWith('.js')) {
return minify({
sourceMap: false,
toplevel: true,
compress: { unsafe: true }
toplevel : true,
compress : { unsafe: true },
})
}
return new PassThrough()
}
const bundler = browserify(path.join(__dirname, '../packages/uppy/index.js'), {
fullPaths: true,
standalone: 'Uppy'
fullPaths : true,
standalone: 'Uppy',
})
bundler.transform(babelify)

View file

@ -4,6 +4,7 @@ const chalk = require('chalk')
const path = require('path')
const stringifyObject = require('stringify-object')
const fs = require('fs')
const uppy = new Uppy()
let localePack = {}
const plugins = {}
@ -23,13 +24,11 @@ if (mode === 'build') {
function getSources (pluginName) {
const dependencies = {
// because 'provider-views' doesn't have its own locale, it uses Core's defaultLocale
core: ['provider-views']
core: ['provider-views'],
}
const globPath = path.join(__dirname, '..', 'packages', '@uppy', pluginName, 'lib', '**', '*.js')
let contents = glob.sync(globPath).map((file) => {
return fs.readFileSync(file, 'utf-8')
})
let contents = glob.sync(globPath).map((file) => fs.readFileSync(file, 'utf-8'))
if (dependencies[pluginName]) {
dependencies[pluginName].forEach((addPlugin) => {
@ -52,10 +51,10 @@ function buildPluginsList () {
for (const file of files) {
const dirName = path.dirname(file)
const pluginName = path.basename(dirName)
if (pluginName === 'locales' ||
pluginName === 'react-native' ||
pluginName === 'vue' ||
pluginName === 'svelte') {
if (pluginName === 'locales'
|| pluginName === 'react-native'
|| pluginName === 'vue'
|| pluginName === 'svelte') {
continue
}
const Plugin = require(dirName)
@ -68,37 +67,35 @@ function buildPluginsList () {
global.location = { protocol: 'https' }
global.navigator = { userAgent: '' }
global.localStorage = {
key: () => { },
getItem: () => { }
key : () => { },
getItem: () => { },
}
global.window = {
indexedDB: {
open: () => { return {} }
}
open: () => ({}),
},
}
global.document = {
createElement: () => {
return { style: {} }
}
createElement: () => ({ style: {} }),
}
try {
if (pluginName === 'provider-views') {
plugin = new Plugin(plugins['drag-drop'], {
companionPattern: '',
companionUrl: 'https://companion.uppy.io'
companionUrl : 'https://companion.uppy.io',
})
} else if (pluginName === 'store-redux') {
plugin = new Plugin({ store: { dispatch: () => { } } })
} else {
plugin = new Plugin(uppy, {
companionPattern: '',
companionUrl: 'https://companion.uppy.io',
params: {
companionUrl : 'https://companion.uppy.io',
params : {
auth: {
key: 'x'
}
}
key: 'x',
},
},
})
}
} catch (err) {
@ -150,7 +147,7 @@ function checkForUnused (fileContents, pluginName, localePack) {
}
function sortObjectAlphabetically (obj, sortFunc) {
return Object.keys(obj).sort(sortFunc).reduce(function (result, key) {
return Object.keys(obj).sort(sortFunc).reduce((result, key) => {
result[key] = obj[key]
return result
}, {})
@ -158,20 +155,19 @@ function sortObjectAlphabetically (obj, sortFunc) {
function createTypeScriptLocale (plugin, pluginName) {
const allowedStringTypes = Object.keys(plugin.defaultLocale.strings)
.map(key => ` | '${key}'`)
.map((key) => ` | '${key}'`)
.join('\n')
const pluginClassName = pluginName === 'core' ? 'Core' : plugin.id
const localePath = path.join(__dirname, '..', 'packages', '@uppy', pluginName, 'types', 'generatedLocale.d.ts')
const localeTypes =
'import Uppy = require(\'@uppy/core\')\n' +
'\n' +
`type ${pluginClassName}Locale = Uppy.Locale` + '<\n' +
allowedStringTypes + '\n' +
'>\n' +
'\n' +
`export = ${pluginClassName}Locale\n`
const localeTypes = `${'import Uppy = require(\'@uppy/core\')\n'
+ '\n'
+ `type ${pluginClassName}Locale = Uppy.Locale` + '<\n'}${
allowedStringTypes}\n`
+ '>\n'
+ '\n'
+ `export = ${pluginClassName}Locale\n`
fs.writeFileSync(localePath, localeTypes)
}
@ -194,15 +190,15 @@ function build () {
}
const prettyLocale = stringifyObject(localePack, {
indent: ' ',
singleQuotes: true,
inlineCharacterLimit: 12
indent : ' ',
singleQuotes : true,
inlineCharacterLimit: 12,
})
const localeTemplatePath = path.join(__dirname, '..', 'packages', '@uppy', 'locales', 'template.js')
const template = fs.readFileSync(localeTemplatePath, 'utf-8')
const finalLocale = template.replace('en_US.strings = {}', 'en_US.strings = ' + prettyLocale)
const finalLocale = template.replace('en_US.strings = {}', `en_US.strings = ${prettyLocale}`)
const localePackagePath = path.join(__dirname, '..', 'packages', '@uppy', 'locales', 'src', 'en_US.js')
fs.writeFileSync(localePackagePath, finalLocale, 'utf-8')

View file

@ -13,6 +13,7 @@
const path = require('path')
const { execSync } = require('child_process')
const exampleName = process.argv[2]
if (!exampleName) {

View file

@ -11,7 +11,7 @@ async function updateContributorsListInReadme () {
'--cols', '6',
'--format', 'md',
'--showlogin', 'true',
'--sortOrder', 'desc'
'--sortOrder', 'desc',
]
if (process.env.GITHUB_TOKEN) {
@ -27,7 +27,7 @@ async function updateContributorsListInReadme () {
const readmeWithUpdatedContributors = readme.replace(
/<!--contributors-->[\s\S]+<!--\/contributors-->/,
`<!--contributors-->\n${stdout}\n<!--/contributors-->`
`<!--contributors-->\n${stdout}\n<!--/contributors-->`,
)
fs.writeFileSync(README_FILE_NAME, readmeWithUpdatedContributors)
}

View file

@ -33,7 +33,7 @@ const finished = promisify(require('stream').finished)
const AdmZip = require('adm-zip')
function delay (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
return new Promise((resolve) => setTimeout(resolve, ms))
}
const AWS_REGION = 'us-east-1'
@ -79,14 +79,14 @@ async function getRemoteDistFiles (packageName, version) {
*/
async function getLocalDistFiles (packagePath) {
const files = (await packlist({ path: packagePath }))
.filter(f => f.startsWith('dist/'))
.map(f => f.replace(/^dist\//, ''))
.filter((f) => f.startsWith('dist/'))
.map((f) => f.replace(/^dist\//, ''))
const entries = await Promise.all(
files.map(async (f) => [
f,
await readFile(path.join(packagePath, 'dist', f))
])
await readFile(path.join(packagePath, 'dist', f)),
]),
)
return new Map(entries)
@ -111,10 +111,10 @@ async function main (packageName, version) {
const s3 = new AWS.S3({
credentials: new AWS.Credentials({
accessKeyId: process.env.EDGLY_KEY,
secretAccessKey: process.env.EDGLY_SECRET
accessKeyId : process.env.EDGLY_KEY,
secretAccessKey: process.env.EDGLY_SECRET,
}),
region: AWS_REGION
region: AWS_REGION,
})
const remote = !!version
@ -145,7 +145,7 @@ async function main (packageName, version) {
const { Contents: existing } = await s3.listObjects({
Bucket: AWS_BUCKET,
Prefix: outputPath
Prefix: outputPath,
}).promise()
if (existing.length > 0) {
if (process.argv.includes('--force')) {
@ -174,10 +174,10 @@ async function main (packageName, version) {
const key = path.posix.join(outputPath, filename)
console.log(`pushing s3://${AWS_BUCKET}/${key}`)
await s3.putObject({
Bucket: AWS_BUCKET,
Key: key,
Bucket : AWS_BUCKET,
Key : key,
ContentType: mime.lookup(filename),
Body: buffer
Body : buffer,
}).promise()
}
}

View file

@ -5,19 +5,19 @@ const Dashboard = require('@uppy/dashboard')
const AwsS3 = require('@uppy/aws-s3')
const uppy = new Uppy({
debug: true,
autoProceed: false
debug : true,
autoProceed: false,
})
uppy.use(GoogleDrive, {
companionUrl: 'http://localhost:3020'
companionUrl: 'http://localhost:3020',
})
uppy.use(Webcam)
uppy.use(Dashboard, {
inline: true,
target: 'body',
plugins: ['GoogleDrive', 'Webcam']
inline : true,
target : 'body',
plugins: ['GoogleDrive', 'Webcam'],
})
uppy.use(AwsS3, {
companionUrl: 'http://localhost:3020'
companionUrl: 'http://localhost:3020',
})

View file

@ -7,35 +7,35 @@ const app = require('express')()
const DATA_DIR = path.join(__dirname, 'tmp')
app.use(require('cors')({
origin: true,
credentials: true
origin : true,
credentials: true,
}))
app.use(require('cookie-parser')())
app.use(require('body-parser').json())
app.use(require('express-session')({
secret: 'hello planet'
secret: 'hello planet',
}))
const options = {
providerOptions: {
drive: {
key: process.env.COMPANION_GOOGLE_KEY,
secret: process.env.COMPANION_GOOGLE_SECRET
key : process.env.COMPANION_GOOGLE_KEY,
secret: process.env.COMPANION_GOOGLE_SECRET,
},
s3: {
getKey: (req, filename) =>
`whatever/${Math.random().toString(32).slice(2)}/${filename}`,
key: process.env.COMPANION_AWS_KEY,
secret: process.env.COMPANION_AWS_SECRET,
bucket: process.env.COMPANION_AWS_BUCKET,
region: process.env.COMPANION_AWS_REGION,
endpoint: process.env.COMPANION_AWS_ENDPOINT
}
key : process.env.COMPANION_AWS_KEY,
secret : process.env.COMPANION_AWS_SECRET,
bucket : process.env.COMPANION_AWS_BUCKET,
region : process.env.COMPANION_AWS_REGION,
endpoint: process.env.COMPANION_AWS_ENDPOINT,
},
},
server: { host: 'localhost:3020' },
server : { host: 'localhost:3020' },
filePath: DATA_DIR,
secret: 'blah blah',
debug: true
secret : 'blah blah',
debug : true,
}
// Create the data directory here for the sake of the example.
@ -44,7 +44,7 @@ try {
} catch (err) {
fs.mkdirSync(DATA_DIR)
}
process.on('exit', function () {
process.on('exit', () => {
rimraf.sync(DATA_DIR)
})

View file

@ -3,38 +3,36 @@ const Dashboard = require('@uppy/dashboard')
const AwsS3 = require('@uppy/aws-s3')
const uppy = new Uppy({
debug: true
debug: true,
})
uppy.use(Dashboard, {
inline: true,
target: 'body'
target: 'body',
})
uppy.use(AwsS3, {
getUploadParameters (file) {
// Send a request to our PHP signing endpoint.
return fetch('/s3-sign.php', {
method: 'post',
method : 'post',
// Send and receive JSON.
headers: {
accept: 'application/json',
'content-type': 'application/json'
accept : 'application/json',
'content-type': 'application/json',
},
body: JSON.stringify({
filename: file.name,
contentType: file.type
})
}).then((response) => {
filename : file.name,
contentType: file.type,
}),
}).then((response) =>
// Parse the JSON response.
return response.json()
}).then((data) => {
response.json()).then((data) =>
// Return an object in the correct shape.
return {
method: data.method,
url: data.url,
fields: data.fields,
headers: data.headers
}
})
}
({
method : data.method,
url : data.url,
fields : data.fields,
headers: data.headers,
}))
},
})

View file

@ -10,10 +10,10 @@ const babelify = require('babelify')
const port = process.env.PORT || 8080
const b = browserify({
cache: {},
cache : {},
packageCache: {},
debug: true,
entries: path.join(__dirname, './main.js')
debug : true,
entries : path.join(__dirname, './main.js'),
})
b.plugin(watchify)
@ -21,8 +21,8 @@ b.plugin(watchify)
b.transform(babelify)
b.transform(aliasify, {
aliases: {
'@uppy': path.join(__dirname, '../../packages/@uppy')
}
'@uppy': path.join(__dirname, '../../packages/@uppy'),
},
})
function bundle () {
@ -43,6 +43,6 @@ console.log('bundling...')
bundle().on('finish', () => {
// Start the PHP delevopment server.
spawn('php', ['-S', `localhost:${port}`], {
stdio: 'inherit'
stdio: 'inherit',
})
})

View file

@ -15,23 +15,23 @@ const TUS_ENDPOINT = 'https://tusd.tusdemo.net/files/'
const uppy = new Uppy({
debug: true,
meta: {
meta : {
username: 'John',
license: 'Creative Commons'
}
license : 'Creative Commons',
},
})
.use(Dashboard, {
trigger: '#pick-files',
target: '#upload-form',
inline: true,
trigger : '#pick-files',
target : '#upload-form',
inline : true,
replaceTargetContent: true,
metaFields: [
metaFields : [
{ id: 'license', name: 'License', placeholder: 'specify license' },
{ id: 'caption', name: 'Caption', placeholder: 'add caption' }
{ id: 'caption', name: 'Caption', placeholder: 'add caption' },
],
showProgressDetails: true,
showProgressDetails : true,
proudlyDisplayPoweredByUppy: true,
note: '2 files, images and video only'
note : '2 files, images and video only',
})
.use(GoogleDrive, { target: Dashboard, companionUrl: 'http://localhost:3020' })
.use(Instagram, { target: Dashboard, companionUrl: 'http://localhost:3020' })

View file

@ -44,9 +44,9 @@ function removeFile (store, fileID) {
function getFiles (store) {
sendMessageToAllClients({
type: 'uppy/ALL_FILES',
store: store,
files: getCache(store)
type : 'uppy/ALL_FILES',
store,
files: getCache(store),
})
}

View file

@ -4,11 +4,11 @@ module.exports = (api) => {
presets: [
['@babel/preset-env', {
modules: false,
loose: true
}]
loose : true,
}],
],
plugins: [
['@babel/plugin-transform-react-jsx', { pragma: 'h' }]
].filter(Boolean)
['@babel/plugin-transform-react-jsx', { pragma: 'h' }],
].filter(Boolean),
}
}

View file

@ -18,10 +18,10 @@ module.exports = class MyCustomProvider extends Plugin {
)
this.provider = new Provider(uppy, {
companionUrl: this.opts.companionUrl,
companionUrl : this.opts.companionUrl,
companionHeaders: this.opts.companionHeaders || this.opts.serverHeaders,
provider: 'myunsplash',
pluginId: this.id
provider : 'myunsplash',
pluginId : this.id,
})
this.files = []
@ -29,12 +29,12 @@ module.exports = class MyCustomProvider extends Plugin {
this.render = this.render.bind(this)
// merge default options with the ones set by user
this.opts = Object.assign({}, opts)
this.opts = { ...opts }
}
install () {
this.view = new ProviderViews(this, {
provider: this.provider
provider: this.provider,
})
const target = this.opts.target

View file

@ -5,21 +5,21 @@ const MyCustomProvider = require('./MyCustomProvider')
const Dashboard = require('@uppy/dashboard')
const uppy = new Uppy({
debug: true
debug: true,
})
uppy.use(GoogleDrive, {
companionUrl: 'http://localhost:3020'
companionUrl: 'http://localhost:3020',
})
uppy.use(MyCustomProvider, {
companionUrl: 'http://localhost:3020'
companionUrl: 'http://localhost:3020',
})
uppy.use(Dashboard, {
inline: true,
target: 'body',
plugins: ['GoogleDrive', 'MyCustomProvider']
inline : true,
target : 'body',
plugins: ['GoogleDrive', 'MyCustomProvider'],
})
uppy.use(Tus, { endpoint: 'https://tusd.tusdemo.net/files/' })

View file

@ -1,4 +1,5 @@
const request = require('request')
const BASE_URL = 'https://api.unsplash.com'
/**
@ -12,12 +13,12 @@ class MyCustomProvider {
list ({ token, directory }, done) {
const path = directory ? `/${directory}/photos` : ''
const options = {
url: `${BASE_URL}/collections${path}`,
method: 'GET',
json: true,
url : `${BASE_URL}/collections${path}`,
method : 'GET',
json : true,
headers: {
Authorization: `Bearer ${token}`
}
Authorization: `Bearer ${token}`,
},
}
request(options, (err, resp, body) => {
@ -33,12 +34,12 @@ class MyCustomProvider {
download ({ id, token }, onData) {
const options = {
url: `${BASE_URL}/photos/${id}`,
method: 'GET',
json: true,
url : `${BASE_URL}/photos/${id}`,
method : 'GET',
json : true,
headers: {
Authorization: `Bearer ${token}`
}
Authorization: `Bearer ${token}`,
},
}
request(options, (err, resp, body) => {
@ -57,12 +58,12 @@ class MyCustomProvider {
size ({ id, token }, done) {
const options = {
url: `${BASE_URL}/photos/${id}`,
method: 'GET',
json: true,
url : `${BASE_URL}/photos/${id}`,
method : 'GET',
json : true,
headers: {
Authorization: `Bearer ${token}`
}
Authorization: `Bearer ${token}`,
},
}
request(options, (err, resp, body) => {
@ -78,24 +79,24 @@ class MyCustomProvider {
_adaptData (res) {
const data = {
username: null,
items: [],
nextPagePath: null
username : null,
items : [],
nextPagePath: null,
}
const items = res
items.forEach((item) => {
const isFolder = !!item.published_at
data.items.push({
isFolder: isFolder,
icon: isFolder ? item.cover_photo.urls.thumb : item.urls.thumb,
name: item.title || item.description,
mimeType: isFolder ? null : 'image/jpeg',
id: item.id,
thumbnail: isFolder ? item.cover_photo.urls.thumb : item.urls.thumb,
requestPath: item.id,
isFolder,
icon : isFolder ? item.cover_photo.urls.thumb : item.urls.thumb,
name : item.title || item.description,
mimeType : isFolder ? null : 'image/jpeg',
id : item.id,
thumbnail : isFolder ? item.cover_photo.urls.thumb : item.urls.thumb,
requestPath : item.id,
modifiedDate: item.updated_at,
size: null
size : null,
})
})

View file

@ -9,20 +9,20 @@ const app = express()
app.use(bodyParser.json())
app.use(session({
secret: 'some-secret',
resave: true,
saveUninitialized: true
secret : 'some-secret',
resave : true,
saveUninitialized: true,
}))
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', req.headers.origin || '*')
res.setHeader(
'Access-Control-Allow-Methods',
'GET, POST, OPTIONS, PUT, PATCH, DELETE'
'GET, POST, OPTIONS, PUT, PATCH, DELETE',
)
res.setHeader(
'Access-Control-Allow-Headers',
'Authorization, Origin, Content-Type, Accept'
'Authorization, Origin, Content-Type, Accept',
)
next()
})
@ -41,39 +41,37 @@ const ACCESS_URL = 'https://unsplash.com/oauth/token'
const uppyOptions = {
providerOptions: {
drive: {
key: 'your google drive key',
secret: 'your google drive secret'
}
key : 'your google drive key',
secret: 'your google drive secret',
},
},
customProviders: {
myunsplash: {
config: {
// your oauth handlers
authorize_url: AUTHORIZE_URL,
access_url: ACCESS_URL,
oauth: 2,
key: 'your unsplash key here',
secret: 'your unsplash secret here'
access_url : ACCESS_URL,
oauth : 2,
key : 'your unsplash key here',
secret : 'your unsplash secret here',
},
// you provider module
module: require('./customprovider')
}
module: require('./customprovider'),
},
},
server: {
host: 'localhost:3020',
protocol: 'http'
host : 'localhost:3020',
protocol: 'http',
},
filePath: './output',
secret: 'some-secret',
debug: true
secret : 'some-secret',
debug : true,
}
app.use(uppy.app(uppyOptions))
// handle 404
app.use((req, res, next) => {
return res.status(404).json({ message: 'Not Found' })
})
app.use((req, res, next) => res.status(404).json({ message: 'Not Found' }))
// handle server errors
app.use((err, req, res, next) => {

View file

@ -50,22 +50,22 @@ const RESTORE = false
module.exports = () => {
const uppyDashboard = new Uppy({
logger: Uppy.debugLogger,
meta: {
meta : {
username: 'John',
license: 'Creative Commons'
}
license : 'Creative Commons',
},
})
.use(Dashboard, {
trigger: '#pick-files',
trigger : '#pick-files',
// inline: true,
target: '.foo',
target : '.foo',
metaFields: [
{ id: 'license', name: 'License', placeholder: 'specify license' },
{ id: 'caption', name: 'Caption', placeholder: 'add caption' }
{ id: 'caption', name: 'Caption', placeholder: 'add caption' },
],
showProgressDetails: true,
showProgressDetails : true,
proudlyDisplayPoweredByUppy: true,
note: '2 files, images and video only'
note : '2 files, images and video only',
})
.use(GoogleDrive, { target: Dashboard, companionUrl: COMPANION_URL })
.use(Instagram, { target: Dashboard, companionUrl: COMPANION_URL })
@ -77,9 +77,9 @@ module.exports = () => {
.use(Url, { target: Dashboard, companionUrl: COMPANION_URL })
.use(Unsplash, { target: Dashboard, companionUrl: COMPANION_URL })
.use(Webcam, {
target: Dashboard,
target : Dashboard,
showVideoSourceDropdown: true,
showRecordingLength: true
showRecordingLength : true,
})
.use(ScreenCapture, { target: Dashboard })
.use(Form, { target: '#upload-form' })
@ -101,35 +101,35 @@ module.exports = () => {
case 'transloadit':
uppyDashboard.use(Transloadit, {
waitForEncoding: true,
params: {
auth: { key: TRANSLOADIT_KEY },
template_id: TRANSLOADIT_TEMPLATE
}
params : {
auth : { key: TRANSLOADIT_KEY },
template_id: TRANSLOADIT_TEMPLATE,
},
})
break
case 'transloadit-s3':
uppyDashboard.use(AwsS3, { companionUrl: COMPANION_URL })
uppyDashboard.use(Transloadit, {
waitForEncoding: true,
waitForEncoding : true,
importFromUploadURLs: true,
params: {
auth: { key: TRANSLOADIT_KEY },
template_id: TRANSLOADIT_TEMPLATE
}
params : {
auth : { key: TRANSLOADIT_KEY },
template_id: TRANSLOADIT_TEMPLATE,
},
})
break
case 'transloadit-xhr':
uppyDashboard.setMeta({
params: JSON.stringify({
auth: { key: TRANSLOADIT_KEY },
template_id: TRANSLOADIT_TEMPLATE
})
auth : { key: TRANSLOADIT_KEY },
template_id: TRANSLOADIT_TEMPLATE,
}),
})
uppyDashboard.use(XHRUpload, {
method: 'POST',
endpoint: 'https://api2.transloadit.com/assemblies',
method : 'POST',
endpoint : 'https://api2.transloadit.com/assemblies',
metaFields: ['params'],
bundle: true
bundle : true,
})
break
}

View file

@ -6,11 +6,11 @@ const ProgressBar = require('@uppy/progress-bar/src')
module.exports = () => {
const uppyDragDrop = new Uppy({
debug: true,
autoProceed: true
debug : true,
autoProceed: true,
})
.use(DragDrop, {
target: '#uppyDragDrop'
target: '#uppyDragDrop',
})
.use(ProgressBar, { target: '#uppyDragDrop-progress', hideAfterFinish: false })
.use(Tus, { endpoint: 'https://tusd.tusdemo.net/files/' })

View file

@ -19,6 +19,6 @@ 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

@ -40,9 +40,9 @@ function removeFile (store, fileID) {
function getFiles (store) {
sendMessageToAllClients({
type: 'uppy/ALL_FILES',
store: store,
files: getCache(store)
type : 'uppy/ALL_FILES',
store,
files: getCache(store),
})
}

View file

@ -3,12 +3,12 @@ const Dashboard = require('@uppy/dashboard')
const AwsS3 = require('@uppy/aws-s3')
const uppy = new Uppy({
debug: true
debug: true,
})
uppy.use(Dashboard, {
inline: true,
target: 'body'
target: 'body',
})
// No client side changes needed!

View file

@ -26,20 +26,21 @@ const app = router()
// Set up the /params endpoint that will create signed URLs for us.
app.use(require('cors')())
app.use(require('body-parser').json())
app.use('/companion', companion.app({
providerOptions: {
s3: {
// This is the crucial part; set an endpoint template for the service you want to use.
endpoint: 'https://{region}.digitaloceanspaces.com',
getKey: (req, filename) => `uploads/${filename}`,
getKey : (req, filename) => `uploads/${filename}`,
key: process.env.COMPANION_AWS_KEY,
key : process.env.COMPANION_AWS_KEY,
secret: process.env.COMPANION_AWS_SECRET,
bucket: process.env.COMPANION_AWS_BUCKET,
region: process.env.COMPANION_AWS_REGION
}
region: process.env.COMPANION_AWS_REGION,
},
},
server: { serverUrl: `localhost:${PORT}` }
server: { serverUrl: `localhost:${PORT}` },
}))
// Serve the built CSS file.
@ -50,18 +51,18 @@ app.get('/uppy.min.css', (req, res) => {
// Start the development server, budo.
budo(path.join(__dirname, 'main.js'), {
live: true,
stream: process.stdout,
port: PORT,
live : true,
stream : process.stdout,
port : PORT,
middleware: app,
browserify: {
transform: [
'babelify',
['aliasify', {
aliases: {
'@uppy': path.join(__dirname, '../../packages/@uppy')
}
}]
]
}
'@uppy': path.join(__dirname, '../../packages/@uppy'),
},
}],
],
},
})

View file

@ -5,24 +5,24 @@ const GoldenRetriever = require('@uppy/golden-retriever')
// Initialise two Uppy instances with the GoldenRetriever plugin,
// but with different `id`s.
const a = new Uppy({
id: 'a',
debug: true
id : 'a',
debug: true,
})
.use(Dashboard, {
target: '#a',
inline: true,
width: 400
width : 400,
})
.use(GoldenRetriever, { serviceWorker: false })
const b = new Uppy({
id: 'b',
debug: true
id : 'b',
debug: true,
})
.use(Dashboard, {
target: '#b',
inline: true,
width: 400
width : 400,
})
.use(GoldenRetriever, { serviceWorker: false })

View file

@ -4,16 +4,16 @@ const Dashboard = require('@uppy/dashboard')
const xhr = require('@uppy/xhr-upload')
const uppy = new Uppy({
debug: true,
autoProceed: false
debug : true,
autoProceed: false,
})
uppy.use(Webcam)
uppy.use(Dashboard, {
inline: true,
target: 'body',
plugins: ['Webcam']
inline : true,
target : 'body',
plugins: ['Webcam'],
})
uppy.use(xhr, {
endpoint: 'http://localhost:3020/upload'
endpoint: 'http://localhost:3020/upload',
})

View file

@ -1,12 +1,12 @@
var formidable = require('formidable')
var http = require('http')
http.createServer(function (req, res) {
http.createServer((req, res) => {
const headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Content-Type' : 'application/json',
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
'Access-Control-Max-Age': 2592000 // 30 days
'Access-Control-Max-Age' : 2592000, // 30 days
/** add other headers as per requirement */
}
@ -21,7 +21,7 @@ http.createServer(function (req, res) {
form.uploadDir = './uploads'
form.keepExtensions = true
form.parse(req, function (err, fields, files) {
form.parse(req, (err, fields, files) => {
if (err) {
console.log('some error', err)
res.writeHead(200, headers)

View file

@ -4,16 +4,16 @@ const Dashboard = require('@uppy/dashboard')
const XHRUpload = require('@uppy/xhr-upload')
const uppy = new Uppy({
debug: true,
autoProceed: false
debug : true,
autoProceed: false,
})
uppy.use(Webcam)
uppy.use(Dashboard, {
inline: true,
target: 'body',
plugins: ['Webcam']
inline : true,
target : 'body',
plugins: ['Webcam'],
})
uppy.use(XHRUpload, {
endpoint: 'http://localhost:3020/upload.php'
endpoint: 'http://localhost:3020/upload.php',
})

View file

@ -4,16 +4,16 @@ const Dashboard = require('@uppy/dashboard')
const XHRUpload = require('@uppy/xhr-upload')
const uppy = new Uppy({
debug: true,
autoProceed: false
debug : true,
autoProceed: false,
})
uppy.use(Webcam)
uppy.use(Dashboard, {
inline: true,
target: 'body',
plugins: ['Webcam']
inline : true,
target : 'body',
plugins: ['Webcam'],
})
uppy.use(XHRUpload, {
endpoint: 'http://localhost:3020/upload'
endpoint: 'http://localhost:3020/upload',
})

View file

@ -4,7 +4,7 @@ import {
Text,
View,
AsyncStorage,
Image
Image,
} from 'react-native'
import Uppy from '@uppy/core'
import Tus from '@uppy/tus'
@ -20,21 +20,21 @@ export default class App extends React.Component {
super()
this.state = {
progress: 0,
total: 0,
file: null,
uploadURL: null,
progress : 0,
total : 0,
file : null,
uploadURL : null,
isFilePickerVisible: false,
isPaused: false,
uploadStarted: false,
uploadComplete: false,
info: null,
totalProgress: 0
isPaused : false,
uploadStarted : false,
uploadComplete : false,
info : null,
totalProgress : 0,
}
this.isReactNative = (typeof navigator !== 'undefined' &&
typeof navigator.product === 'string' &&
navigator.product.toLowerCase() === 'reactnative')
this.isReactNative = (typeof navigator !== 'undefined'
&& typeof navigator.product === 'string'
&& navigator.product.toLowerCase() === 'reactnative')
this.showFilePicker = this.showFilePicker.bind(this)
this.hideFilePicker = this.hideFilePicker.bind(this)
@ -43,17 +43,17 @@ export default class App extends React.Component {
console.log('Is this React Native?', this.isReactNative)
this.uppy = new Uppy({ autoProceed: true, debug: true })
this.uppy.use(Tus, {
endpoint: 'https://tusd.tusdemo.net/files/',
endpoint : 'https://tusd.tusdemo.net/files/',
urlStorage: AsyncStorage,
fileReader: getTusFileReader,
chunkSize: 10 * 1024 * 1024 // keep the chunk size small to avoid memory exhaustion
chunkSize : 10 * 1024 * 1024, // keep the chunk size small to avoid memory exhaustion
})
this.uppy.on('upload-progress', (file, progress) => {
this.setState({
progress: progress.bytesUploaded,
total: progress.bytesTotal,
progress : progress.bytesUploaded,
total : progress.bytesTotal,
totalProgress: this.uppy.state.totalProgress,
uploadStarted: true
uploadStarted: true,
})
})
this.uppy.on('upload-success', (file, response) => {
@ -61,10 +61,10 @@ export default class App extends React.Component {
})
this.uppy.on('complete', (result) => {
this.setState({
status: 'Upload complete ✅',
uploadURL: result.successful[0] ? result.successful[0].uploadURL : null,
status : 'Upload complete ✅',
uploadURL : result.successful[0] ? result.successful[0].uploadURL : null,
uploadComplete: true,
uploadStarted: false
uploadStarted : false,
})
console.log('Upload complete:', result)
})
@ -72,14 +72,14 @@ export default class App extends React.Component {
this.uppy.on('info-visible', () => {
const info = this.uppy.getState().info
this.setState({
info: info
info,
})
console.log('uppy-info:', info)
})
this.uppy.on('info-hidden', () => {
this.setState({
info: null
info: null,
})
})
}
@ -87,14 +87,14 @@ export default class App extends React.Component {
showFilePicker () {
this.setState({
isFilePickerVisible: true,
uploadStarted: false,
uploadComplete: false
uploadStarted : false,
uploadComplete : false,
})
}
hideFilePicker () {
this.setState({
isFilePickerVisible: false
isFilePickerVisible: false,
})
}
@ -102,12 +102,12 @@ export default class App extends React.Component {
if (this.state.isPaused) {
this.uppy.resumeAll()
this.setState({
isPaused: false
isPaused: false,
})
} else {
this.uppy.pauseAll()
this.setState({
isPaused: true
isPaused: true,
})
}
}
@ -115,16 +115,16 @@ export default class App extends React.Component {
render () {
return (
<View style={{
paddingTop: 100,
paddingLeft: 50,
paddingTop : 100,
paddingLeft : 50,
paddingRight: 50,
flex: 1
flex : 1,
}}
>
<Text style={{
fontSize: 25,
fontSize : 25,
marginBottom: 20,
textAlign: 'center'
textAlign : 'center',
}}
>Uppy in React Native
</Text>
@ -140,8 +140,8 @@ export default class App extends React.Component {
<Text
style={{
marginBottom: 10,
marginTop: 10,
color: '#b8006b'
marginTop : 10,
color : '#b8006b',
}}
>
{this.state.info.message}

View file

@ -36,7 +36,7 @@ function UppyDashboardFileIcon (props) {
<View
style={{
...styles.itemIconContainer,
backgroundColor: color
backgroundColor: color,
}}
>
<SvgUri
@ -61,8 +61,7 @@ export default function FileList (props) {
data={uppyFilesArray}
keyExtractor={(item, index) => item.id}
numColumns={2}
renderItem={({ item }) => {
return (
renderItem={({ item }) => (
<View style={styles.item}>
{item.type === 'image' ? (
<Image
@ -75,8 +74,7 @@ export default function FileList (props) {
<Text style={styles.itemName}>{truncateString(item.name, 20)}</Text>
<Text style={styles.itemType}>{item.type}</Text>
</View>
)
}}
)}
/>
</View>
)
@ -84,48 +82,48 @@ export default function FileList (props) {
const styles = StyleSheet.create({
container: {
marginTop: 20,
marginBottom: 20,
flex: 1,
justifyContent: 'center'
marginTop : 20,
marginBottom : 20,
flex : 1,
justifyContent: 'center',
},
item: {
width: 100,
marginTop: 5,
width : 100,
marginTop : 5,
marginBottom: 15,
marginRight: 25
marginRight : 25,
},
itemImage: {
width: 100,
height: 100,
borderRadius: 5,
marginBottom: 5
},
itemIconContainer: {
width: 100,
height: 100,
width : 100,
height : 100,
borderRadius: 5,
marginBottom: 5,
},
itemIconContainer: {
width : 100,
height : 100,
borderRadius : 5,
marginBottom : 5,
backgroundColor: '#cfd3d6',
alignItems: 'center',
justifyContent: 'center'
alignItems : 'center',
justifyContent : 'center',
},
itemIcon: {
width: 42,
height: 56
width : 42,
height: 56,
},
itemIconSVG: {
width: 50,
height: 50
width : 50,
height: 50,
},
itemName: {
fontSize: 13,
color: '#2c3e50',
fontWeight: '600'
fontSize : 13,
color : '#2c3e50',
fontWeight: '600',
},
itemType: {
fontWeight: '600',
fontSize: 12,
color: '#95a5a6'
}
fontSize : 12,
color : '#95a5a6',
},
})

View file

@ -22,11 +22,11 @@ export default function PauseResumeButton (props) {
const styles = StyleSheet.create({
button: {
backgroundColor: '#cc0077',
padding: 10
padding : 10,
},
text: {
color: '#fff',
color : '#fff',
textAlign: 'center',
fontSize: 17
}
fontSize : 17,
},
})

View file

@ -9,25 +9,25 @@ export default function ProgressBar (props) {
return (
<View style={{
marginTop: 15,
marginBottom: 15
marginTop : 15,
marginBottom: 15,
}}
>
<View
style={{
height: 5,
overflow: 'hidden',
backgroundColor: '#dee1e3'
height : 5,
overflow : 'hidden',
backgroundColor: '#dee1e3',
}}
>
<View style={{
height: 5,
height : 5,
backgroundColor: progress === 100 ? colorGreen : colorBlue,
width: progress + '%'
width : `${progress}%`,
}}
/>
</View>
<Text>{progress ? progress + '%' : null}</Text>
<Text>{progress ? `${progress}%` : null}</Text>
</View>
)
}

View file

@ -15,11 +15,11 @@ export default function SelectFiles (props) {
const styles = StyleSheet.create({
button: {
backgroundColor: '#cc0077',
padding: 15
padding : 15,
},
text: {
color: '#fff',
color : '#fff',
textAlign: 'center',
fontSize: 17
}
fontSize : 17,
},
})

View file

@ -1,6 +1,6 @@
module.exports = function (api) {
api.cache(true)
return {
presets: ['babel-preset-expo']
presets: ['babel-preset-expo'],
}
}

View file

@ -17,8 +17,8 @@ class TusFileReader {
end = Math.min(end, this.size)
const options = {
encoding: Expo.FileSystem.EncodingTypes.Base64,
length: end - start,
position: start
length : end - start,
position: start,
}
Expo.FileSystem.readAsStringAsync(this.file.uri, options).then((data) => {
cb(null, base64.toByteArray(data))

View file

@ -17,15 +17,15 @@ function counter (state = 0, action) {
}
const reducer = combineReducers({
counter: counter,
counter,
// You don't have to use the `uppy` key. But if you don't,
// you need to provide a custom `selector` to the `uppyReduxStore` call below.
uppy: uppyReduxStore.reducer
uppy: uppyReduxStore.reducer,
})
let enhancer = applyMiddleware(
uppyReduxStore.middleware(),
logger
logger,
)
if (window.__REDUX_DEVTOOLS_EXTENSION__) {
enhancer = compose(enhancer, window.__REDUX_DEVTOOLS_EXTENSION__())
@ -60,8 +60,8 @@ document.querySelector('#incrementAsync').onclick = () => {
// Uppy using the same store
const uppy = new Uppy({
id: 'redux',
store: uppyReduxStore({ store: store }),
id : 'redux',
store: uppyReduxStore({ store }),
// If we had placed our `reducer` elsewhere in Redux, eg. under an `uppy` key in the state for a profile page,
// we'd do something like:
//
@ -70,12 +70,12 @@ const uppy = new Uppy({
// id: 'avatar',
// selector: state => state.pages.profile.uppy
// }),
debug: true
debug: true,
})
uppy.use(Dashboard, {
target: '#app',
inline: true,
width: 400
width : 400,
})
uppy.use(Tus, { endpoint: 'https://tusd.tusdemo.net/' })

View file

@ -1,5 +1,5 @@
module.exports = {
plugins: [
require('postcss-import')()
]
require('postcss-import')(),
],
}

View file

@ -21,32 +21,32 @@ function serve () {
if (server) return
server = require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
shell: true,
})
process.on('SIGTERM', toExit)
process.on('exit', toExit)
}
},
}
}
export default {
input: 'src/main.ts',
input : 'src/main.ts',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js'
format : 'iife',
name : 'app',
file : 'public/build/bundle.js',
},
plugins: [
svelte({
preprocess: sveltePreprocess({
postcss: true
postcss: true,
}),
compilerOptions: {
// enable run-time checks when not in production
dev: !production
}
dev: !production,
},
}),
// we'll extract any component CSS out into
// a separate file - better for performance
@ -59,12 +59,12 @@ export default {
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ['svelte', '@uppy/core']
dedupe : ['svelte', '@uppy/core'],
}),
commonjs(),
typescript({
sourceMap: !production,
inlineSources: !production
sourceMap : !production,
inlineSources: !production,
}),
// In dev mode, call `npm run start` once
@ -77,9 +77,9 @@ export default {
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser()
production && terser(),
],
watch: {
clearScreen: false
}
clearScreen: false,
},
}

View file

@ -26,7 +26,8 @@ class MarkdownTextarea {
this.uploadLine.classList.add('mdtxt-upload')
this.uploadLine.appendChild(
document.createTextNode('Upload an attachment'))
document.createTextNode('Upload an attachment'),
)
}
install () {
@ -104,15 +105,15 @@ class MarkdownTextarea {
uploadFiles (files) {
robodog.upload({
waitForEncoding: true,
params: {
auth: { key: TRANSLOADIT_EXAMPLE_KEY },
template_id: TRANSLOADIT_EXAMPLE_TEMPLATE
}
params : {
auth : { key: TRANSLOADIT_EXAMPLE_KEY },
template_id: TRANSLOADIT_EXAMPLE_TEMPLATE,
},
}).then((result) => {
// Was cancelled
if (result == null) return
this.insertAttachments(
this.matchFilesAndThumbs(result.results)
this.matchFilesAndThumbs(result.results),
)
}).catch((err) => {
console.error(err)
@ -123,15 +124,15 @@ class MarkdownTextarea {
pickFiles () {
robodog.pick({
waitForEncoding: true,
params: {
auth: { key: TRANSLOADIT_EXAMPLE_KEY },
template_id: TRANSLOADIT_EXAMPLE_TEMPLATE
}
params : {
auth : { key: TRANSLOADIT_EXAMPLE_KEY },
template_id: TRANSLOADIT_EXAMPLE_TEMPLATE,
},
}).then((result) => {
// Was cancelled
if (result == null) return
this.insertAttachments(
this.matchFilesAndThumbs(result.results)
this.matchFilesAndThumbs(result.results),
)
}).catch((err) => {
console.error(err)
@ -141,7 +142,8 @@ class MarkdownTextarea {
}
const textarea = new MarkdownTextarea(
document.querySelector('#new textarea'))
document.querySelector('#new textarea'),
)
textarea.install()
function renderSnippet (title, text) {
@ -173,8 +175,8 @@ function loadSnippets () {
document.querySelector('#new').addEventListener('submit', (event) => {
event.preventDefault()
const title = event.target.querySelector('input[name="title"]').value ||
'Unnamed Snippet'
const title = event.target.querySelector('input[name="title"]').value
|| 'Unnamed Snippet'
const text = textarea.element.value
saveSnippet(title, text)

View file

@ -21,18 +21,18 @@ const TEMPLATE_ID = 'bbc273f69e0c4694a5a9d1b587abc1bc'
*/
const formUppy = robodog.form('#test-form', {
debug: true,
fields: ['message'],
debug : true,
fields : ['message'],
restrictions: {
allowedFileTypes: ['.png']
allowedFileTypes: ['.png'],
},
waitForEncoding: true,
params: {
auth: { key: TRANSLOADIT_KEY },
template_id: TEMPLATE_ID
params : {
auth : { key: TRANSLOADIT_KEY },
template_id: TEMPLATE_ID,
},
modal: true,
progressBar: '#test-form .progress'
modal : true,
progressBar: '#test-form .progress',
})
formUppy.on('error', (err) => {
@ -48,30 +48,30 @@ formUppy.on('upload-error', (file, err) => {
window.formUppy = formUppy
const formUppyWithDashboard = robodog.form('#dashboard-form', {
debug: true,
fields: ['message'],
debug : true,
fields : ['message'],
restrictions: {
allowedFileTypes: ['.png']
allowedFileTypes: ['.png'],
},
waitForEncoding: true,
note: 'Only PNG files please!',
params: {
auth: { key: TRANSLOADIT_KEY },
template_id: TEMPLATE_ID
note : 'Only PNG files please!',
params : {
auth : { key: TRANSLOADIT_KEY },
template_id: TEMPLATE_ID,
},
dashboard: '#dashboard-form .dashboard'
dashboard: '#dashboard-form .dashboard',
})
window.formUppyWithDashboard = formUppyWithDashboard
const dashboard = robodog.dashboard('#dashboard', {
debug: true,
debug : true,
waitForEncoding: true,
note: 'Images will be resized with Transloadit',
params: {
auth: { key: TRANSLOADIT_KEY },
template_id: TEMPLATE_ID
}
note : 'Images will be resized with Transloadit',
params : {
auth : { key: TRANSLOADIT_KEY },
template_id: TEMPLATE_ID,
},
})
window.dashboard = dashboard
@ -83,16 +83,16 @@ window.dashboard = dashboard
function openModal () {
robodog.pick({
restrictions: {
allowedFileTypes: ['.png']
allowedFileTypes: ['.png'],
},
waitForEncoding: true,
params: {
auth: { key: TRANSLOADIT_KEY },
template_id: TEMPLATE_ID
params : {
auth : { key: TRANSLOADIT_KEY },
template_id: TEMPLATE_ID,
},
providers: [
'webcam'
]
'webcam',
],
// if providers need custom config
// webcam: {
// option: 'whatever'
@ -111,10 +111,10 @@ window.doUpload = (event) => {
const errorEl = document.querySelector('#upload-error')
robodog.upload(event.target.files, {
waitForEncoding: true,
params: {
auth: { key: TRANSLOADIT_KEY },
template_id: TEMPLATE_ID
}
params : {
auth : { key: TRANSLOADIT_KEY },
template_id: TEMPLATE_ID,
},
}).then((result) => {
resultEl.classList.remove('hidden')
errorEl.classList.add('hidden')

View file

@ -7,20 +7,20 @@ const app = express()
app.use(bodyParser.json())
app.use(session({
secret: 'some-secret',
resave: true,
saveUninitialized: true
secret : 'some-secret',
resave : true,
saveUninitialized: true,
}))
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', req.headers.origin || '*')
res.setHeader(
'Access-Control-Allow-Methods',
'GET, POST, OPTIONS, PUT, PATCH, DELETE'
'GET, POST, OPTIONS, PUT, PATCH, DELETE',
)
res.setHeader(
'Access-Control-Allow-Headers',
'Authorization, Origin, Content-Type, Accept'
'Authorization, Origin, Content-Type, Accept',
)
next()
})
@ -35,38 +35,36 @@ app.get('/', (req, res) => {
const uppyOptions = {
providerOptions: {
drive: {
key: 'your google key',
secret: 'your google secret'
key : 'your google key',
secret: 'your google secret',
},
instagram: {
key: 'your instagram key',
secret: 'your instagram secret'
key : 'your instagram key',
secret: 'your instagram secret',
},
dropbox: {
key: 'your dropbox key',
secret: 'your dropbox secret'
key : 'your dropbox key',
secret: 'your dropbox secret',
},
box: {
key: 'your box key',
secret: 'your box secret'
}
key : 'your box key',
secret: 'your box secret',
},
// you can also add options for additional providers here
},
server: {
host: 'localhost:3020',
protocol: 'http'
host : 'localhost:3020',
protocol: 'http',
},
filePath: './output',
secret: 'some-secret',
debug: true
secret : 'some-secret',
debug : true,
}
app.use(companion.app(uppyOptions))
// handle 404
app.use((req, res, next) => {
return res.status(404).json({ message: 'Not Found' })
})
app.use((req, res, next) => res.status(404).json({ message: 'Not Found' }))
// handle server errors
app.use((err, req, res, next) => {

View file

@ -1,5 +1,5 @@
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
]
'@vue/cli-plugin-babel/preset',
],
}

View file

@ -4,5 +4,5 @@ import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App)
render: (h) => h(App),
}).$mount('#app')

View file

@ -4,19 +4,19 @@ const XHRUpload = require('@uppy/xhr-upload')
const uppy = new Uppy({
debug: true,
meta: { something: 'xyz' }
meta : { something: 'xyz' },
})
uppy.use(Dashboard, {
target: '#app',
inline: true,
hideRetryButton: true,
hideCancelButton: true
target : '#app',
inline : true,
hideRetryButton : true,
hideCancelButton: true,
})
uppy.use(XHRUpload, {
bundle: true,
endpoint: 'http://localhost:9967/upload',
bundle : true,
endpoint : 'http://localhost:9967/upload',
metaFields: ['something'],
fieldName: 'files'
fieldName : 'files',
})

View file

@ -3,7 +3,7 @@ var cors = require('cors')
var multer = require('multer')
var upload = multer({
storage: multer.memoryStorage()
storage: multer.memoryStorage(),
})
app.use(cors())
@ -13,9 +13,9 @@ app.listen(9967)
function uploadRoute (req, res) {
res.json({
files: req.files.map(function (file) {
files: req.files.map((file) => {
delete file.buffer
return file
})
}),
})
}

View file

@ -4,7 +4,7 @@ const delay = require('@uppy/utils/lib/delay')
const MB = 1024 * 1024
const defaultOptions = {
limit: 1,
limit : 1,
retryDelays: [0, 1000, 3000, 5000],
getChunkSize (file) {
return Math.ceil(file.size / 10000)
@ -15,7 +15,7 @@ const defaultOptions = {
onSuccess () {},
onError (err) {
throw err
}
},
}
function ensureInt (value) {
@ -32,7 +32,7 @@ class MultipartUploader {
constructor (file, options) {
this.options = {
...defaultOptions,
...options
...options,
}
// Use default `getChunkSize` if it was null or something
if (!this.options.getChunkSize) {
@ -95,21 +95,20 @@ class MultipartUploader {
this.chunks = chunks
this.chunkState = chunks.map(() => ({
uploaded: 0,
busy: false,
done: false
busy : false,
done : false,
}))
}
_createUpload () {
this.createdPromise = Promise.resolve().then(() =>
this.options.createMultipartUpload()
)
this.options.createMultipartUpload())
return this.createdPromise.then((result) => {
if (this._aborted()) throw createAbortError()
const valid = typeof result === 'object' && result &&
typeof result.uploadId === 'string' &&
typeof result.key === 'string'
const valid = typeof result === 'object' && result
&& typeof result.uploadId === 'string'
&& typeof result.key === 'string'
if (!valid) {
throw new TypeError('AwsS3/Multipart: Got incorrect result from `createMultipartUpload()`, expected an object `{ uploadId, key }`.')
}
@ -128,9 +127,8 @@ class MultipartUploader {
return Promise.resolve().then(() =>
this.options.listParts({
uploadId: this.uploadId,
key: this.key
})
).then((parts) => {
key : this.key,
})).then((parts) => {
if (this._aborted()) throw createAbortError()
parts.forEach((part) => {
@ -138,15 +136,15 @@ class MultipartUploader {
this.chunkState[i] = {
uploaded: ensureInt(part.Size),
etag: part.ETag,
done: true
etag : part.ETag,
done : true,
}
// Only add if we did not yet know about this part.
if (!this.parts.some((p) => p.PartNumber === part.PartNumber)) {
this.parts.push({
PartNumber: part.PartNumber,
ETag: part.ETag
ETag : part.ETag,
})
}
})
@ -211,9 +209,8 @@ class MultipartUploader {
if (shouldRetry(err) && retryAttempt < retryDelays.length) {
return delay(retryDelays[retryAttempt], { signal })
.then(() => doAttempt(retryAttempt + 1))
} else {
throw err
}
throw err
})
return doAttempt(0).then((result) => {
@ -231,9 +228,9 @@ class MultipartUploader {
this.partsInProgress += 1
},
attempt: () => this._uploadPart(index),
after: () => {
after : () => {
this.partsInProgress -= 1
}
},
})
}
@ -243,14 +240,13 @@ class MultipartUploader {
return Promise.resolve().then(() =>
this.options.prepareUploadPart({
key: this.key,
key : this.key,
uploadId: this.uploadId,
body,
number: index + 1
})
).then((result) => {
const valid = typeof result === 'object' && result &&
typeof result.url === 'string'
number : index + 1,
})).then((result) => {
const valid = typeof result === 'object' && result
&& typeof result.url === 'string'
if (!valid) {
throw new TypeError('AwsS3/Multipart: Got incorrect result from `prepareUploadPart()`, expected an object `{ url }`.')
}
@ -279,7 +275,7 @@ class MultipartUploader {
const part = {
PartNumber: index + 1,
ETag: etag
ETag : etag,
}
this.parts.push(part)
@ -369,11 +365,10 @@ class MultipartUploader {
return Promise.resolve().then(() =>
this.options.completeMultipartUpload({
key: this.key,
key : this.key,
uploadId: this.uploadId,
parts: this.parts
})
).then((result) => {
parts : this.parts,
})).then((result) => {
this.options.onSuccess(result)
}, (err) => {
this._onError(err)
@ -385,8 +380,8 @@ class MultipartUploader {
this.createdPromise.then(() => {
this.options.abortMultipartUpload({
key: this.key,
uploadId: this.uploadId
key : this.key,
uploadId: this.uploadId,
})
}, () => {
// if the creation failed we do not need to abort

View file

@ -26,14 +26,14 @@ module.exports = class AwsS3Multipart extends Plugin {
this.client = new RequestClient(uppy, opts)
const defaultOptions = {
timeout: 30 * 1000,
limit: 0,
retryDelays: [0, 1000, 3000, 5000],
createMultipartUpload: this.createMultipartUpload.bind(this),
listParts: this.listParts.bind(this),
prepareUploadPart: this.prepareUploadPart.bind(this),
abortMultipartUpload: this.abortMultipartUpload.bind(this),
completeMultipartUpload: this.completeMultipartUpload.bind(this)
timeout : 30 * 1000,
limit : 0,
retryDelays : [0, 1000, 3000, 5000],
createMultipartUpload : this.createMultipartUpload.bind(this),
listParts : this.listParts.bind(this),
prepareUploadPart : this.prepareUploadPart.bind(this),
abortMultipartUpload : this.abortMultipartUpload.bind(this),
completeMultipartUpload: this.completeMultipartUpload.bind(this),
}
this.opts = { ...defaultOptions, ...opts }
@ -80,7 +80,7 @@ module.exports = class AwsS3Multipart extends Plugin {
const metadata = {}
Object.keys(file.meta).map(key => {
Object.keys(file.meta).map((key) => {
if (file.meta[key] != null) {
metadata[key] = file.meta[key].toString()
}
@ -88,8 +88,8 @@ module.exports = class AwsS3Multipart extends Plugin {
return this.client.post('s3/multipart', {
filename: file.name,
type: file.type,
metadata
type : file.type,
metadata,
}).then(assertServerError)
}
@ -134,17 +134,17 @@ module.exports = class AwsS3Multipart extends Plugin {
this.uppy.setFileState(file.id, {
s3Multipart: {
...cFile.s3Multipart,
key: data.key,
uploadId: data.uploadId
}
key : data.key,
uploadId: data.uploadId,
},
})
}
const onProgress = (bytesUploaded, bytesTotal) => {
this.uppy.emit('upload-progress', file, {
uploader: this,
bytesUploaded: bytesUploaded,
bytesTotal: bytesTotal
bytesUploaded,
bytesTotal,
})
}
@ -160,9 +160,9 @@ module.exports = class AwsS3Multipart extends Plugin {
const onSuccess = (result) => {
const uploadResp = {
body: {
...result
...result,
},
uploadURL: result.location
uploadURL: result.location,
}
queuedRequest.done()
@ -171,7 +171,7 @@ module.exports = class AwsS3Multipart extends Plugin {
this.uppy.emit('upload-success', file, uploadResp)
if (result.location) {
this.uppy.log('Download ' + upload.file.name + ' from ' + result.location)
this.uppy.log(`Download ${upload.file.name} from ${result.location}`)
}
resolve(upload)
@ -188,12 +188,12 @@ module.exports = class AwsS3Multipart extends Plugin {
const upload = new Uploader(file.data, {
// .bind to pass the file object to each handler.
createMultipartUpload: this.opts.createMultipartUpload.bind(this, file),
listParts: this.opts.listParts.bind(this, file),
prepareUploadPart: this.opts.prepareUploadPart.bind(this, file),
createMultipartUpload : this.opts.createMultipartUpload.bind(this, file),
listParts : this.opts.listParts.bind(this, file),
prepareUploadPart : this.opts.prepareUploadPart.bind(this, file),
completeMultipartUpload: this.opts.completeMultipartUpload.bind(this, file),
abortMultipartUpload: this.opts.abortMultipartUpload.bind(this, file),
getChunkSize: this.opts.getChunkSize ? this.opts.getChunkSize.bind(this) : null,
abortMultipartUpload : this.opts.abortMultipartUpload.bind(this, file),
getChunkSize : this.opts.getChunkSize ? this.opts.getChunkSize.bind(this) : null,
onStart,
onProgress,
@ -201,9 +201,9 @@ module.exports = class AwsS3Multipart extends Plugin {
onSuccess,
onPartComplete,
limit: this.opts.limit || 5,
limit : this.opts.limit || 5,
retryDelays: this.opts.retryDelays || [],
...file.s3Multipart
...file.s3Multipart,
})
this.uploaders[file.id] = upload
@ -285,21 +285,20 @@ module.exports = class AwsS3Multipart extends Plugin {
{
...file.remote.body,
protocol: 's3-multipart',
size: file.data.size,
metadata: file.meta
}
size : file.data.size,
metadata: file.meta,
},
).then((res) => {
this.uppy.setFileState(file.id, { serverToken: res.token })
file = this.uppy.getFile(file.id)
return file
}).then((file) => {
return this.connectToServerSocket(file)
}).then(() => {
}).then((file) => this.connectToServerSocket(file)).then(() => {
resolve()
}).catch((err) => {
this.uppy.emit('upload-error', file, err)
reject(err)
})
.catch((err) => {
this.uppy.emit('upload-error', file, err)
reject(err)
})
})
}
@ -384,7 +383,7 @@ module.exports = class AwsS3Multipart extends Plugin {
socket.on('success', (data) => {
const uploadResp = {
uploadURL: data.url
uploadURL: data.url,
}
this.uppy.emit('upload-success', file, uploadResp)
@ -474,8 +473,8 @@ module.exports = class AwsS3Multipart extends Plugin {
this.uppy.setState({
capabilities: {
...capabilities,
resumableUploads: true
}
resumableUploads: true,
},
})
this.uppy.addUploader(this.upload)
}
@ -485,8 +484,8 @@ module.exports = class AwsS3Multipart extends Plugin {
this.uppy.setState({
capabilities: {
...capabilities,
resumableUploads: false
}
resumableUploads: false,
},
})
this.uppy.removeUploader(this.upload)
}

View file

@ -40,7 +40,7 @@ module.exports = class MiniXHRUpload {
validateStatus (status, responseText, response) {
return status >= 200 && status < 300
},
...opts
...opts,
}
this.requests = opts.__queue
@ -56,7 +56,7 @@ module.exports = class MiniXHRUpload {
...this.opts,
...(overrides || {}),
...(file.xhrUpload || {}),
headers: {}
headers: {},
}
Object.assign(opts.headers, this.opts.headers)
if (overrides) {
@ -174,9 +174,9 @@ module.exports = class MiniXHRUpload {
if (ev.lengthComputable) {
this.uppy.emit('upload-progress', file, {
uploader: this,
uploader : this,
bytesUploaded: ev.loaded,
bytesTotal: ev.total
bytesTotal : ev.total,
})
}
})
@ -197,7 +197,7 @@ module.exports = class MiniXHRUpload {
const uploadResp = {
status: ev.target.status,
body,
uploadURL
uploadURL,
}
this.uppy.emit('upload-success', file, uploadResp)
@ -207,18 +207,17 @@ module.exports = class MiniXHRUpload {
}
return resolve(file)
} else {
const body = opts.getResponseData(xhr.responseText, xhr)
const error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr))
const response = {
status: ev.target.status,
body
}
this.uppy.emit('upload-error', file, error, response)
return reject(error)
}
const body = opts.getResponseData(xhr.responseText, xhr)
const error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr))
const response = {
status: ev.target.status,
body,
}
this.uppy.emit('upload-error', file, error, response)
return reject(error)
})
xhr.addEventListener('error', (ev) => {
@ -287,13 +286,13 @@ module.exports = class MiniXHRUpload {
const client = new Client(this.uppy, file.remote.providerOptions)
client.post(file.remote.url, {
...file.remote.body,
endpoint: opts.endpoint,
size: file.data.size,
fieldname: opts.fieldName,
metadata: fields,
httpMethod: opts.method,
endpoint : opts.endpoint,
size : file.data.size,
fieldname : opts.fieldName,
metadata : fields,
httpMethod : opts.method,
useFormData: opts.formData,
headers: opts.headers
headers : opts.headers,
}).then((res) => {
const token = res.token
const host = getSocketHost(file.remote.companionUrl)
@ -331,7 +330,7 @@ module.exports = class MiniXHRUpload {
const uploadResp = {
status: data.response.status,
body,
uploadURL
uploadURL,
}
this.uppy.emit('upload-success', file, uploadResp)

View file

@ -81,15 +81,15 @@ module.exports = class AwsS3 extends Plugin {
this.defaultLocale = {
strings: {
timedOut: 'Upload stalled for %{seconds} seconds, aborting.'
}
timedOut: 'Upload stalled for %{seconds} seconds, aborting.',
},
}
const defaultOptions = {
timeout: 30 * 1000,
limit: 0,
metaFields: [], // have to opt in
getUploadParameters: this.getUploadParameters.bind(this)
timeout : 30 * 1000,
limit : 0,
metaFields : [], // have to opt in
getUploadParameters: this.getUploadParameters.bind(this),
}
this.opts = { ...defaultOptions, ...opts }
@ -132,9 +132,9 @@ module.exports = class AwsS3 extends Plugin {
}
validateParameters (file, params) {
const valid = typeof params === 'object' && params &&
typeof params.url === 'string' &&
(typeof params.fields === 'object' || params.fields == null)
const valid = typeof params === 'object' && params
&& typeof params.url === 'string'
&& (typeof params.fields === 'object' || params.fields == null)
if (!valid) {
const err = new TypeError(`AwsS3: got incorrect result from 'getUploadParameters()' for file '${file.name}', expected an object '{ url, method, fields, headers }' but got '${JSON.stringify(params)}' instead.\nSee https://uppy.io/docs/aws-s3/#getUploadParameters-file for more on the expected format.`)
@ -173,9 +173,7 @@ module.exports = class AwsS3 extends Plugin {
this.uppy.emit('upload-started', file)
})
const getUploadParameters = this.requests.wrapPromiseFunction((file) => {
return this.opts.getUploadParameters(file)
})
const getUploadParameters = this.requests.wrapPromiseFunction((file) => this.opts.getUploadParameters(file))
const numberOfFiles = fileIDs.length
@ -191,13 +189,13 @@ module.exports = class AwsS3 extends Plugin {
method = 'post',
url,
fields,
headers
headers,
} = params
const xhrOpts = {
method,
formData: method.toLowerCase() === 'post',
endpoint: url,
metaFields: fields ? Object.keys(fields) : []
formData : method.toLowerCase() === 'post',
endpoint : url,
metaFields: fields ? Object.keys(fields) : [],
}
if (headers) {
@ -205,8 +203,8 @@ module.exports = class AwsS3 extends Plugin {
}
this.uppy.setFileState(file.id, {
meta: { ...file.meta, ...fields },
xhrUpload: xhrOpts
meta : { ...file.meta, ...fields },
xhrUpload: xhrOpts,
})
return this._uploader.uploadFile(file.id, index, numberOfFiles)
@ -260,9 +258,9 @@ module.exports = class AwsS3 extends Plugin {
// Some S3 alternatives do not reply with an absolute URL.
// Eg DigitalOcean Spaces uses /$bucketName/xyz
location: resolveUrl(xhr.responseURL, getXmlValue(content, 'Location')),
bucket: getXmlValue(content, 'Bucket'),
key: getXmlValue(content, 'Key'),
etag: getXmlValue(content, 'ETag')
bucket : getXmlValue(content, 'Bucket'),
key : getXmlValue(content, 'Key'),
etag : getXmlValue(content, 'ETag'),
}
}
@ -279,14 +277,14 @@ module.exports = class AwsS3 extends Plugin {
}
const xhrOptions = {
fieldName: 'file',
fieldName : 'file',
responseUrlFieldName: 'location',
timeout: this.opts.timeout,
timeout : this.opts.timeout,
// Share the rate limiting queue with XHRUpload.
__queue: this.requests,
responseType: 'text',
getResponseData: this.opts.getResponseData || defaultGetResponseData,
getResponseError: defaultGetResponseError
__queue : this.requests,
responseType : 'text',
getResponseData : this.opts.getResponseData || defaultGetResponseData,
getResponseError : defaultGetResponseError,
}
// Only for MiniXHRUpload, remove once we can depend on XHRUpload directly again

View file

@ -1,6 +1,6 @@
require('whatwg-fetch')
const Core = require('@uppy/core')
const AwsS3 = require('./')
const AwsS3 = require('.')
describe('AwsS3', () => {
it('Registers AwsS3 upload plugin', () => {
@ -27,8 +27,8 @@ describe('AwsS3', () => {
const file = {
meta: {
name: 'foo.jpg',
type: 'image/jpg'
}
type: 'image/jpg',
},
}
expect(() => awsS3.opts.getUploadParameters(file)).not.toThrow()

View file

@ -5,59 +5,59 @@ describe('AwsS3', () => {
it('returns true for XML documents', () => {
const content = '<?xml version="1.0" encoding="UTF-8"?><Key>image.jpg</Key>'
expect(isXml(content, {
getResponseHeader: () => 'application/xml'
getResponseHeader: () => 'application/xml',
})).toEqual(true)
expect(isXml(content, {
getResponseHeader: () => 'text/xml'
getResponseHeader: () => 'text/xml',
})).toEqual(true)
expect(isXml(content, {
getResponseHeader: () => 'text/xml; charset=utf-8'
getResponseHeader: () => 'text/xml; charset=utf-8',
})).toEqual(true)
expect(isXml(content, {
getResponseHeader: () => 'application/xml; charset=iso-8859-1'
getResponseHeader: () => 'application/xml; charset=iso-8859-1',
})).toEqual(true)
})
it('returns true for GCS XML documents', () => {
const content = '<?xml version="1.0" encoding="UTF-8"?><Key>image.jpg</Key>'
expect(isXml(content, {
getResponseHeader: () => 'text/html'
getResponseHeader: () => 'text/html',
})).toEqual(true)
expect(isXml(content, {
getResponseHeader: () => 'text/html; charset=utf8'
getResponseHeader: () => 'text/html; charset=utf8',
})).toEqual(true)
})
it('returns true for remote response objects', () => {
const content = '<?xml version="1.0" encoding="UTF-8"?><Key>image.jpg</Key>'
expect(isXml(content, {
headers: { 'content-type': 'application/xml' }
headers: { 'content-type': 'application/xml' },
})).toEqual(true)
expect(isXml(content, {
headers: { 'content-type': 'application/xml' }
headers: { 'content-type': 'application/xml' },
})).toEqual(true)
expect(isXml(content, {
headers: { 'content-type': 'text/html' }
headers: { 'content-type': 'text/html' },
})).toEqual(true)
})
it('returns false when content-type is missing', () => {
const content = '<?xml version="1.0" encoding="UTF-8"?><Key>image.jpg</Key>'
expect(isXml(content, {
getResponseHeader: () => null
getResponseHeader: () => null,
})).toEqual(false)
expect(isXml(content, {
headers: { 'content-type': null }
headers: { 'content-type': null },
})).toEqual(false)
expect(isXml(content, {
headers: {}
headers: {},
})).toEqual(false)
})
it('returns false for HTML documents', () => {
const content = '<!DOCTYPE html><html>'
expect(isXml(content, {
getResponseHeader: () => 'text/html'
getResponseHeader: () => 'text/html',
})).toEqual(false)
})
})

View file

@ -24,10 +24,10 @@ module.exports = class Box extends Plugin {
)
this.provider = new Provider(uppy, {
companionUrl: this.opts.companionUrl,
companionUrl : this.opts.companionUrl,
companionHeaders: this.opts.companionHeaders || this.opts.serverHeaders,
provider: 'box',
pluginId: this.id
provider : 'box',
pluginId : this.id,
})
this.onFirstRender = this.onFirstRender.bind(this)
@ -36,7 +36,7 @@ module.exports = class Box extends Plugin {
install () {
this.view = new ProviderViews(this, {
provider: this.provider
provider: this.provider,
})
const target = this.opts.target

View file

@ -1,5 +1,3 @@
'use strict'
class AuthError extends Error {
constructor () {
super('Authorization required')

View file

@ -1,12 +1,8 @@
'use strict'
const qsStringify = require('qs-stringify')
const RequestClient = require('./RequestClient')
const tokenStorage = require('./tokenStorage')
const _getName = (id) => {
return id.split('-').map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join(' ')
}
const _getName = (id) => id.split('-').map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join(' ')
module.exports = class Provider extends RequestClient {
constructor (uppy, opts) {
@ -30,10 +26,10 @@ module.exports = class Provider extends RequestClient {
if (this.companionKeysParams) {
authHeaders['uppy-credentials-params'] = btoa(
JSON.stringify({ params: this.companionKeysParams })
JSON.stringify({ params: this.companionKeysParams }),
)
}
return Object.assign({}, headers, authHeaders)
return { ...headers, ...authHeaders }
})
}
@ -90,7 +86,7 @@ module.exports = class Provider extends RequestClient {
return this.get(`${this.id}/logout`)
.then((response) => Promise.all([
response,
this.uppy.getPlugin(this.pluginId).storage.removeItem(this.tokenKey)
this.uppy.getPlugin(this.pluginId).storage.removeItem(this.tokenKey),
])).then(([response]) => response)
}
@ -98,7 +94,7 @@ module.exports = class Provider extends RequestClient {
plugin.type = 'acquirer'
plugin.files = []
if (defaultOpts) {
plugin.opts = Object.assign({}, defaultOpts, opts)
plugin.opts = { ...defaultOpts, ...opts }
}
if (opts.serverUrl || opts.serverPattern) {

View file

@ -1,5 +1,3 @@
'use strict'
const AuthError = require('./AuthError')
const fetchWithNetworkError = require('@uppy/utils/lib/fetchWithNetworkError')
@ -27,9 +25,9 @@ module.exports = class RequestClient {
get defaultHeaders () {
return {
Accept: 'application/json',
'Content-Type': 'application/json',
'Uppy-Versions': `@uppy/companion-client=${RequestClient.VERSION}`
Accept : 'application/json',
'Content-Type' : 'application/json',
'Uppy-Versions': `@uppy/companion-client=${RequestClient.VERSION}`,
}
}
@ -37,7 +35,7 @@ module.exports = class RequestClient {
const userHeaders = this.opts.companionHeaders || this.opts.serverHeaders || {}
return Promise.resolve({
...this.defaultHeaders,
...userHeaders
...userHeaders,
})
}
@ -59,9 +57,7 @@ module.exports = class RequestClient {
// Store the self-identified domain name for the Companion instance we just hit.
if (headers.has('i-am') && headers.get('i-am') !== companion[host]) {
this.uppy.setState({
companion: Object.assign({}, companion, {
[host]: headers.get('i-am')
})
companion: { ...companion, [host]: headers.get('i-am') },
})
}
return response
@ -97,7 +93,7 @@ module.exports = class RequestClient {
}
return fetch(this._getUrl(path), {
method: 'OPTIONS'
method: 'OPTIONS',
})
.then((response) => {
if (response.headers.has('access-control-allow-headers')) {
@ -133,9 +129,9 @@ module.exports = class RequestClient {
return this.preflightAndHeaders(path)
.then((headers) =>
fetchWithNetworkError(this._getUrl(path), {
method: 'get',
headers: headers,
credentials: this.opts.companionCookiesRule || 'same-origin'
method : 'get',
headers,
credentials: this.opts.companionCookiesRule || 'same-origin',
}))
.then(this._getPostResponseFunc(skipPostResponse))
.then((res) => this._json(res))
@ -149,10 +145,10 @@ module.exports = class RequestClient {
return this.preflightAndHeaders(path)
.then((headers) =>
fetchWithNetworkError(this._getUrl(path), {
method: 'post',
headers: headers,
method : 'post',
headers,
credentials: this.opts.companionCookiesRule || 'same-origin',
body: JSON.stringify(data)
body : JSON.stringify(data),
}))
.then(this._getPostResponseFunc(skipPostResponse))
.then((res) => this._json(res))
@ -166,10 +162,10 @@ module.exports = class RequestClient {
return this.preflightAndHeaders(path)
.then((headers) =>
fetchWithNetworkError(`${this.hostname}/${path}`, {
method: 'delete',
headers: headers,
method : 'delete',
headers,
credentials: this.opts.companionCookiesRule || 'same-origin',
body: data ? JSON.stringify(data) : null
body : data ? JSON.stringify(data) : null,
}))
.then(this._getPostResponseFunc(skipPostResponse))
.then((res) => this._json(res))

View file

@ -1,10 +1,6 @@
'use strict'
const RequestClient = require('./RequestClient')
const _getName = (id) => {
return id.split('-').map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join(' ')
}
const _getName = (id) => id.split('-').map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join(' ')
module.exports = class SearchProvider extends RequestClient {
constructor (uppy, opts) {

View file

@ -56,7 +56,7 @@ module.exports = class UppySocket {
this.socket.send(JSON.stringify({
action,
payload
payload,
}))
}

View file

@ -40,8 +40,8 @@ describe('Socket', () => {
expect(UppySocket.name).toEqual('UppySocket')
expect(
new UppySocket({
target: 'foo'
}) instanceof UppySocket
target: 'foo',
}) instanceof UppySocket,
)
})
@ -58,7 +58,7 @@ describe('Socket', () => {
uppySocket.send('bar', 'boo')
expect(webSocketSendSpy.mock.calls.length).toEqual(1)
expect(webSocketSendSpy.mock.calls[0]).toEqual([
JSON.stringify({ action: 'bar', payload: 'boo' })
JSON.stringify({ action: 'bar', payload: 'boo' }),
])
})
@ -78,7 +78,7 @@ describe('Socket', () => {
uppySocket.send('moo', 'baa')
expect(uppySocket._queued).toEqual([
{ action: 'bar', payload: 'boo' },
{ action: 'moo', payload: 'baa' }
{ action: 'moo', payload: 'baa' },
])
expect(webSocketSendSpy.mock.calls.length).toEqual(0)
@ -87,10 +87,10 @@ describe('Socket', () => {
expect(uppySocket._queued).toEqual([])
expect(webSocketSendSpy.mock.calls.length).toEqual(2)
expect(webSocketSendSpy.mock.calls[0]).toEqual([
JSON.stringify({ action: 'bar', payload: 'boo' })
JSON.stringify({ action: 'bar', payload: 'boo' }),
])
expect(webSocketSendSpy.mock.calls[1]).toEqual([
JSON.stringify({ action: 'moo', payload: 'baa' })
JSON.stringify({ action: 'moo', payload: 'baa' }),
])
})
@ -124,10 +124,10 @@ describe('Socket', () => {
webSocketInstance.triggerOpen()
webSocketInstance.onmessage({
data: JSON.stringify({ action: 'hi', payload: 'ho' })
data: JSON.stringify({ action: 'hi', payload: 'ho' }),
})
expect(emitterListenerMock.mock.calls).toEqual([
['ho', undefined, undefined, undefined, undefined, undefined]
['ho', undefined, undefined, undefined, undefined, undefined],
])
})
@ -150,8 +150,8 @@ describe('Socket', () => {
undefined,
undefined,
undefined,
undefined
]
undefined,
],
])
})
@ -167,7 +167,7 @@ describe('Socket', () => {
expect(emitterListenerMock.mock.calls.length).toEqual(1)
expect(emitterListenerMock.mock.calls).toEqual([
['ho', undefined, undefined, undefined, undefined, undefined]
['ho', undefined, undefined, undefined, undefined, undefined],
])
})
})

View file

@ -1,5 +1,3 @@
'use strict'
/**
* Manages communications with Companion
*/
@ -13,5 +11,5 @@ module.exports = {
RequestClient,
Provider,
SearchProvider,
Socket
Socket,
}

View file

@ -1,22 +1,14 @@
'use strict'
/**
* This module serves as an Async wrapper for LocalStorage
*/
module.exports.setItem = (key, value) => {
return new Promise((resolve) => {
localStorage.setItem(key, value)
resolve()
})
}
module.exports.setItem = (key, value) => new Promise((resolve) => {
localStorage.setItem(key, value)
resolve()
})
module.exports.getItem = (key) => {
return Promise.resolve(localStorage.getItem(key))
}
module.exports.getItem = (key) => Promise.resolve(localStorage.getItem(key))
module.exports.removeItem = (key) => {
return new Promise((resolve) => {
localStorage.removeItem(key)
resolve()
})
}
module.exports.removeItem = (key) => new Promise((resolve) => {
localStorage.removeItem(key)
resolve()
})

View file

@ -56,9 +56,9 @@ module.exports = class Plugin {
...plugins,
[this.id]: {
...plugins[this.id],
...update
}
}
...update,
},
},
})
}
@ -161,15 +161,15 @@ module.exports = class Plugin {
let message = `Invalid target option given to ${callerPluginName}.`
if (typeof target === 'function') {
message += ' The given target is not a Plugin class. ' +
'Please check that you\'re not specifying a React Component instead of a plugin. ' +
'If you are using @uppy/* packages directly, make sure you have only 1 version of @uppy/core installed: ' +
'run `npm ls @uppy/core` on the command line and verify that all the versions match and are deduped correctly.'
message += ' The given target is not a Plugin class. '
+ 'Please check that you\'re not specifying a React Component instead of a plugin. '
+ 'If you are using @uppy/* packages directly, make sure you have only 1 version of @uppy/core installed: '
+ 'run `npm ls @uppy/core` on the command line and verify that all the versions match and are deduped correctly.'
} else {
message += 'If you meant to target an HTML element, please make sure that the element exists. ' +
'Check that the <script> tag initializing Uppy is right before the closing </body> tag at the end of the page. ' +
'(see https://github.com/transloadit/uppy/issues/1042)\n\n' +
'If you meant to target a plugin, please confirm that your `import` statements or `require` calls are correct.'
message += 'If you meant to target an HTML element, please make sure that the element exists. '
+ 'Check that the <script> tag initializing Uppy is right before the closing </body> tag at the end of the page. '
+ '(see https://github.com/transloadit/uppy/issues/1042)\n\n'
+ 'If you meant to target a plugin, please confirm that your `import` statements or `require` calls are correct.'
}
throw new Error(message)
}

View file

@ -11,7 +11,8 @@ const generateFileID = require('@uppy/utils/lib/generateFileID')
const findIndex = require('@uppy/utils/lib/findIndex')
const supportsUploadProgress = require('./supportsUploadProgress')
const { justErrorsLogger, debugLogger } = require('./loggers')
const Plugin = require('./Plugin') // Exported from here.
const Plugin = require('./Plugin')
// Exported from here.
class RestrictionError extends Error {
constructor (...args) {
super(...args)
@ -37,80 +38,80 @@ class Uppy {
strings: {
addBulkFilesFailed: {
0: 'Failed to add %{smart_count} file due to an internal error',
1: 'Failed to add %{smart_count} files due to internal errors'
1: 'Failed to add %{smart_count} files due to internal errors',
},
youCanOnlyUploadX: {
0: 'You can only upload %{smart_count} file',
1: 'You can only upload %{smart_count} files'
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'
1: 'You have to select at least %{smart_count} files',
},
// The default `exceedsSize2` string only combines the `exceedsSize` string (%{backwardsCompat}) with the size.
// Locales can override `exceedsSize2` to specify a different word order. This is for backwards compat with
// Uppy 1.9.x and below which did a naive concatenation of `exceedsSize2 + size` instead of using a locale-specific
// substitution.
// TODO: In 2.0 `exceedsSize2` should be removed in and `exceedsSize` updated to use substitution.
exceedsSize2: '%{backwardsCompat} %{size}',
exceedsSize: 'This file exceeds maximum allowed size of',
inferiorSize: 'This file is smaller than the allowed size of %{size}',
exceedsSize2 : '%{backwardsCompat} %{size}',
exceedsSize : 'This file exceeds maximum allowed size of',
inferiorSize : 'This file is smaller than the allowed size of %{size}',
youCanOnlyUploadFileTypes: 'You can only upload: %{types}',
noNewAlreadyUploading: 'Cannot add new files: already uploading',
noDuplicates: 'Cannot add the duplicate file \'%{fileName}\', it already exists',
companionError: 'Connection with Companion failed',
companionUnauthorizeHint: 'To unauthorize to your %{provider} account, please go to %{url}',
failedToUpload: 'Failed to upload %{file}',
noInternetConnection: 'No Internet connection',
connectedToInternet: 'Connected to the Internet',
noNewAlreadyUploading : 'Cannot add new files: already uploading',
noDuplicates : 'Cannot add the duplicate file \'%{fileName}\', it already exists',
companionError : 'Connection with Companion failed',
companionUnauthorizeHint : 'To unauthorize to your %{provider} account, please go to %{url}',
failedToUpload : 'Failed to upload %{file}',
noInternetConnection : 'No Internet connection',
connectedToInternet : 'Connected to the Internet',
// Strings for remote providers
noFilesFound: 'You have no files or folders here',
selectX: {
noFilesFound : 'You have no files or folders here',
selectX : {
0: 'Select %{smart_count}',
1: 'Select %{smart_count}'
1: 'Select %{smart_count}',
},
selectAllFilesFromFolderNamed: 'Select all files from folder %{name}',
selectAllFilesFromFolderNamed : 'Select all files from folder %{name}',
unselectAllFilesFromFolderNamed: 'Unselect all files from folder %{name}',
selectFileNamed: 'Select file %{name}',
unselectFileNamed: 'Unselect file %{name}',
openFolderNamed: 'Open folder %{name}',
cancel: 'Cancel',
logOut: 'Log out',
filter: 'Filter',
resetFilter: 'Reset filter',
loading: 'Loading...',
authenticateWithTitle: 'Please authenticate with %{pluginName} to select files',
authenticateWith: 'Connect to %{pluginName}',
searchImages: 'Search for images',
enterTextToSearch: 'Enter text to search for images',
backToSearch: 'Back to Search',
emptyFolderAdded: 'No files were added from empty folder',
folderAdded: {
selectFileNamed : 'Select file %{name}',
unselectFileNamed : 'Unselect file %{name}',
openFolderNamed : 'Open folder %{name}',
cancel : 'Cancel',
logOut : 'Log out',
filter : 'Filter',
resetFilter : 'Reset filter',
loading : 'Loading...',
authenticateWithTitle : 'Please authenticate with %{pluginName} to select files',
authenticateWith : 'Connect to %{pluginName}',
searchImages : 'Search for images',
enterTextToSearch : 'Enter text to search for images',
backToSearch : 'Back to Search',
emptyFolderAdded : 'No files were added from empty folder',
folderAdded : {
0: 'Added %{smart_count} file from %{folder}',
1: 'Added %{smart_count} files from %{folder}'
}
}
1: 'Added %{smart_count} files from %{folder}',
},
},
}
const defaultOptions = {
id: 'uppy',
autoProceed: false,
id : 'uppy',
autoProceed : false,
allowMultipleUploads: true,
debug: false,
restrictions: {
maxFileSize: null,
minFileSize: null,
debug : false,
restrictions : {
maxFileSize : null,
minFileSize : null,
maxTotalFileSize: null,
maxNumberOfFiles: null,
minNumberOfFiles: null,
allowedFileTypes: null
allowedFileTypes: null,
},
meta: {},
meta : {},
onBeforeFileAdded: (currentFile, files) => currentFile,
onBeforeUpload: (files) => files,
store: DefaultStore(),
logger: justErrorsLogger,
infoTimeout: 5000
onBeforeUpload : (files) => files,
store : DefaultStore(),
logger : justErrorsLogger,
infoTimeout : 5000,
}
// Merge default options with the ones set by user,
@ -120,8 +121,8 @@ class Uppy {
...opts,
restrictions: {
...defaultOptions.restrictions,
...(opts && opts.restrictions)
}
...(opts && opts.restrictions),
},
}
// Support debug: true for backwards-compatability, unless logger is set in opts
@ -134,9 +135,9 @@ class Uppy {
this.log(`Using Core v${this.constructor.VERSION}`)
if (this.opts.restrictions.allowedFileTypes &&
this.opts.restrictions.allowedFileTypes !== null &&
!Array.isArray(this.opts.restrictions.allowedFileTypes)) {
if (this.opts.restrictions.allowedFileTypes
&& this.opts.restrictions.allowedFileTypes !== null
&& !Array.isArray(this.opts.restrictions.allowedFileTypes)) {
throw new TypeError('`restrictions.allowedFileTypes` must be an array')
}
@ -186,22 +187,22 @@ class Uppy {
this.store = this.opts.store
this.setState({
plugins: {},
files: {},
plugins : {},
files : {},
currentUploads: {},
allowNewUpload: true,
capabilities: {
uploadProgress: supportsUploadProgress(),
capabilities : {
uploadProgress : supportsUploadProgress(),
individualCancellation: true,
resumableUploads: false
resumableUploads : false,
},
totalProgress: 0,
meta: { ...this.opts.meta },
info: {
meta : { ...this.opts.meta },
info : {
isHidden: true,
type: 'info',
message: ''
}
type : 'info',
message : '',
},
})
this._storeUnsubscribe = this.store.subscribe((prevState, nextState, patch) => {
@ -247,7 +248,7 @@ class Uppy {
*
*/
updateAll (state) {
this.iteratePlugins(plugin => {
this.iteratePlugins((plugin) => {
plugin.update(state)
})
}
@ -286,9 +287,7 @@ class Uppy {
}
this.setState({
files: Object.assign({}, this.getState().files, {
[fileID]: Object.assign({}, this.getState().files[fileID], state)
})
files: { ...this.getState().files, [fileID]: { ...this.getState().files[fileID], ...state } },
})
}
@ -305,8 +304,8 @@ class Uppy {
...newOpts,
restrictions: {
...this.opts.restrictions,
...(newOpts && newOpts.restrictions)
}
...(newOpts && newOpts.restrictions),
},
}
if (newOpts.meta) {
@ -326,22 +325,22 @@ class Uppy {
resetProgress () {
const defaultProgress = {
percentage: 0,
bytesUploaded: 0,
percentage : 0,
bytesUploaded : 0,
uploadComplete: false,
uploadStarted: null
uploadStarted : null,
}
const files = Object.assign({}, this.getState().files)
const files = { ...this.getState().files }
const updatedFiles = {}
Object.keys(files).forEach(fileID => {
const updatedFile = Object.assign({}, files[fileID])
updatedFile.progress = Object.assign({}, updatedFile.progress, defaultProgress)
Object.keys(files).forEach((fileID) => {
const updatedFile = { ...files[fileID] }
updatedFile.progress = { ...updatedFile.progress, ...defaultProgress }
updatedFiles[fileID] = updatedFile
})
this.setState({
files: updatedFiles,
totalProgress: 0
files : updatedFiles,
totalProgress: 0,
})
this.emit('reset-progress')
@ -381,34 +380,30 @@ class Uppy {
}
setMeta (data) {
const updatedMeta = Object.assign({}, this.getState().meta, data)
const updatedFiles = Object.assign({}, this.getState().files)
const updatedMeta = { ...this.getState().meta, ...data }
const updatedFiles = { ...this.getState().files }
Object.keys(updatedFiles).forEach((fileID) => {
updatedFiles[fileID] = Object.assign({}, updatedFiles[fileID], {
meta: Object.assign({}, updatedFiles[fileID].meta, data)
})
updatedFiles[fileID] = { ...updatedFiles[fileID], meta: { ...updatedFiles[fileID].meta, ...data } }
})
this.log('Adding metadata:')
this.log(data)
this.setState({
meta: updatedMeta,
files: updatedFiles
meta : updatedMeta,
files: updatedFiles,
})
}
setFileMeta (fileID, data) {
const updatedFiles = Object.assign({}, this.getState().files)
const updatedFiles = { ...this.getState().files }
if (!updatedFiles[fileID]) {
this.log('Was trying to set metadata for a file that has been removed: ', fileID)
return
}
const newMeta = Object.assign({}, updatedFiles[fileID].meta, data)
updatedFiles[fileID] = Object.assign({}, updatedFiles[fileID], {
meta: newMeta
})
const newMeta = { ...updatedFiles[fileID].meta, ...data }
updatedFiles[fileID] = { ...updatedFiles[fileID], meta: newMeta }
this.setState({ files: updatedFiles })
}
@ -441,12 +436,12 @@ class Uppy {
try {
this._checkRestrictions(file, files)
return {
result: true
result: true,
}
} catch (err) {
return {
result: false,
reason: err.message
reason: err.message,
}
}
}
@ -499,7 +494,7 @@ class Uppy {
if (totalFilesSize > maxTotalFileSize) {
throw new RestrictionError(this.i18n('exceedsSize2', {
backwardsCompat: this.i18n('exceedsSize'),
size: prettierBytes(maxTotalFileSize)
size : prettierBytes(maxTotalFileSize),
}))
}
}
@ -509,7 +504,7 @@ class Uppy {
if (file.size > maxFileSize) {
throw new RestrictionError(this.i18n('exceedsSize2', {
backwardsCompat: this.i18n('exceedsSize'),
size: prettierBytes(maxFileSize)
size : prettierBytes(maxFileSize),
}))
}
}
@ -518,7 +513,7 @@ class Uppy {
if (minFileSize && file.size != null) {
if (file.size < minFileSize) {
throw new RestrictionError(this.i18n('inferiorSize', {
size: prettierBytes(minFileSize)
size: prettierBytes(minFileSize),
}))
}
}
@ -555,7 +550,7 @@ class Uppy {
// as they are expected and shown in the UI.
let logMessageWithDetails = message
if (details) {
logMessageWithDetails += ' ' + details
logMessageWithDetails += ` ${details}`
}
if (err.isRestriction) {
this.log(logMessageWithDetails)
@ -567,7 +562,7 @@ class Uppy {
// Sometimes informer has to be shown manually by the developer,
// for example, in `onBeforeFileAdded`.
if (showInformer) {
this.info({ message: message, details: details }, 'error', this.opts.infoTimeout)
this.info({ message, details }, 'error', this.opts.infoTimeout)
}
if (throwErr) {
@ -609,7 +604,7 @@ class Uppy {
if (file.name) {
fileName = file.name
} else if (fileType.split('/')[0] === 'image') {
fileName = fileType.split('/')[0] + '.' + fileType.split('/')[1]
fileName = `${fileType.split('/')[0]}.${fileType.split('/')[1]}`
} else {
fileName = 'noname'
}
@ -629,31 +624,31 @@ class Uppy {
// `null` means the size is unknown.
const size = isFinite(file.data.size) ? file.data.size : null
const newFile = {
source: file.source || '',
id: fileID,
name: fileName,
source : file.source || '',
id : fileID,
name : fileName,
extension: fileExtension || '',
meta: {
meta : {
...this.getState().meta,
...meta
...meta,
},
type: fileType,
data: file.data,
type : fileType,
data : file.data,
progress: {
percentage: 0,
bytesUploaded: 0,
bytesTotal: size,
percentage : 0,
bytesUploaded : 0,
bytesTotal : size,
uploadComplete: false,
uploadStarted: null
uploadStarted : null,
},
size: size,
isRemote: isRemote,
remote: file.remote || '',
preview: file.preview
size,
isRemote,
remote : file.remote || '',
preview: file.preview,
}
try {
const filesArray = Object.keys(files).map(i => files[i])
const filesArray = Object.keys(files).map((i) => files[i])
this._checkRestrictions(newFile, filesArray)
} catch (err) {
this._showOrLogErrorAndThrow(err, { file: newFile })
@ -693,8 +688,8 @@ class Uppy {
this.setState({
files: {
...files,
[newFile.id]: newFile
}
[newFile.id]: newFile,
},
})
this.emit('file-added', newFile)
@ -743,7 +738,7 @@ class Uppy {
if (newFiles.length > 5) {
this.log(`Added batch of ${newFiles.length} files`)
} else {
Object.keys(newFiles).forEach(fileID => {
Object.keys(newFiles).forEach((fileID) => {
this.log(`Added file: ${newFiles[fileID].name}\n id: ${newFiles[fileID].id}\n type: ${newFiles[fileID].type}`)
})
}
@ -760,7 +755,7 @@ class Uppy {
this.info({
message: this.i18n('addBulkFilesFailed', { smart_count: errors.length }),
details: message
details: message,
}, 'error', this.opts.infoTimeout)
const err = new Error(message)
@ -798,7 +793,7 @@ class Uppy {
updatedUploads[uploadID] = {
...currentUploads[uploadID],
fileIDs: newFileIDs
fileIDs: newFileIDs,
}
})
@ -808,7 +803,7 @@ class Uppy {
const stateUpdate = {
currentUploads: updatedUploads,
files: updatedFiles
files : updatedFiles,
}
// If all files were removed - allow new uploads!
@ -837,8 +832,8 @@ class Uppy {
}
pauseResume (fileID) {
if (!this.getState().capabilities.resumableUploads ||
this.getFile(fileID).uploadComplete) {
if (!this.getState().capabilities.resumableUploads
|| this.getFile(fileID).uploadComplete) {
return
}
@ -846,7 +841,7 @@ class Uppy {
const isPaused = !wasPaused
this.setFileState(fileID, {
isPaused: isPaused
isPaused,
})
this.emit('upload-pause', fileID, isPaused)
@ -855,16 +850,12 @@ class Uppy {
}
pauseAll () {
const updatedFiles = Object.assign({}, this.getState().files)
const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => {
return !updatedFiles[file].progress.uploadComplete &&
updatedFiles[file].progress.uploadStarted
})
const updatedFiles = { ...this.getState().files }
const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => !updatedFiles[file].progress.uploadComplete
&& updatedFiles[file].progress.uploadStarted)
inProgressUpdatedFiles.forEach((file) => {
const updatedFile = Object.assign({}, updatedFiles[file], {
isPaused: true
})
const updatedFile = { ...updatedFiles[file], isPaused: true }
updatedFiles[file] = updatedFile
})
@ -873,17 +864,16 @@ class Uppy {
}
resumeAll () {
const updatedFiles = Object.assign({}, this.getState().files)
const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => {
return !updatedFiles[file].progress.uploadComplete &&
updatedFiles[file].progress.uploadStarted
})
const updatedFiles = { ...this.getState().files }
const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => !updatedFiles[file].progress.uploadComplete
&& updatedFiles[file].progress.uploadStarted)
inProgressUpdatedFiles.forEach((file) => {
const updatedFile = Object.assign({}, updatedFiles[file], {
const updatedFile = {
...updatedFiles[file],
isPaused: false,
error: null
})
error : null,
}
updatedFiles[file] = updatedFile
})
this.setState({ files: updatedFiles })
@ -892,21 +882,20 @@ class Uppy {
}
retryAll () {
const updatedFiles = Object.assign({}, this.getState().files)
const filesToRetry = Object.keys(updatedFiles).filter(file => {
return updatedFiles[file].error
})
const updatedFiles = { ...this.getState().files }
const filesToRetry = Object.keys(updatedFiles).filter((file) => updatedFiles[file].error)
filesToRetry.forEach((file) => {
const updatedFile = Object.assign({}, updatedFiles[file], {
const updatedFile = {
...updatedFiles[file],
isPaused: false,
error: null
})
error : null,
}
updatedFiles[file] = updatedFile
})
this.setState({
files: updatedFiles,
error: null
error: null,
})
this.emit('retry-all', filesToRetry)
@ -914,12 +903,12 @@ class Uppy {
if (filesToRetry.length === 0) {
return Promise.resolve({
successful: [],
failed: []
failed : [],
})
}
const uploadID = this._createUpload(filesToRetry, {
forceAllowNewUpload: true // create new upload even if allowNewUpload: false
forceAllowNewUpload: true, // create new upload even if allowNewUpload: false
})
return this._runUpload(uploadID)
}
@ -936,20 +925,20 @@ class Uppy {
this.setState({
totalProgress: 0,
error: null
error : null,
})
}
retryUpload (fileID) {
this.setFileState(fileID, {
error: null,
isPaused: false
error : null,
isPaused: false,
})
this.emit('upload-retry', fileID)
const uploadID = this._createUpload([fileID], {
forceAllowNewUpload: true // create new upload even if allowNewUpload: false
forceAllowNewUpload: true, // create new upload even if allowNewUpload: false
})
return this._runUpload(uploadID)
}
@ -970,13 +959,13 @@ class Uppy {
progress: {
...this.getFile(file.id).progress,
bytesUploaded: data.bytesUploaded,
bytesTotal: data.bytesTotal,
percentage: canHavePercentage
bytesTotal : data.bytesTotal,
percentage : canHavePercentage
// TODO(goto-bus-stop) flooring this should probably be the choice of the UI?
// we get more accurate calculations if we don't round this at all.
? Math.round(data.bytesUploaded / data.bytesTotal * 100)
: 0
}
: 0,
},
})
this._calculateTotalProgress()
@ -987,11 +976,9 @@ class Uppy {
// multiplied by 100 and the summ of individual progress of each file
const files = this.getFiles()
const inProgress = files.filter((file) => {
return file.progress.uploadStarted ||
file.progress.preprocess ||
file.progress.postprocess
})
const inProgress = files.filter((file) => file.progress.uploadStarted
|| file.progress.preprocess
|| file.progress.postprocess)
if (inProgress.length === 0) {
this.emit('progress', 0)
@ -1004,17 +991,13 @@ class Uppy {
if (sizedFiles.length === 0) {
const progressMax = inProgress.length * 100
const currentProgress = unsizedFiles.reduce((acc, file) => {
return acc + file.progress.percentage
}, 0)
const currentProgress = unsizedFiles.reduce((acc, file) => acc + file.progress.percentage, 0)
const totalProgress = Math.round(currentProgress / progressMax * 100)
this.setState({ totalProgress })
return
}
let totalSize = sizedFiles.reduce((acc, file) => {
return acc + file.progress.bytesTotal
}, 0)
let totalSize = sizedFiles.reduce((acc, file) => acc + file.progress.bytesTotal, 0)
const averageSize = totalSize / sizedFiles.length
totalSize += averageSize * unsizedFiles.length
@ -1052,7 +1035,7 @@ class Uppy {
}
if (error.details) {
errorMsg += ' ' + error.details
errorMsg += ` ${error.details}`
}
this.setState({ error: errorMsg })
@ -1065,12 +1048,12 @@ class Uppy {
}
if (error.details) {
errorMsg += ' ' + error.details
errorMsg += ` ${error.details}`
}
this.setFileState(file.id, {
error: errorMsg,
response
response,
})
this.setState({ error: error.message })
@ -1079,15 +1062,15 @@ class Uppy {
const newError = new Error(error.message)
newError.details = error.message
if (error.details) {
newError.details += ' ' + error.details
newError.details += ` ${error.details}`
}
newError.message = this.i18n('failedToUpload', { file: file.name })
this._showOrLogErrorAndThrow(newError, {
throwErr: false
throwErr: false,
})
} else {
this._showOrLogErrorAndThrow(error, {
throwErr: false
throwErr: false,
})
}
})
@ -1103,12 +1086,12 @@ class Uppy {
}
this.setFileState(file.id, {
progress: {
uploadStarted: Date.now(),
uploadStarted : Date.now(),
uploadComplete: false,
percentage: 0,
bytesUploaded: 0,
bytesTotal: file.size
}
percentage : 0,
bytesUploaded : 0,
bytesTotal : file.size,
},
})
})
@ -1122,17 +1105,18 @@ class Uppy {
const currentProgress = this.getFile(file.id).progress
this.setFileState(file.id, {
progress: Object.assign({}, currentProgress, {
progress: {
...currentProgress,
postprocess: this.postProcessors.length > 0 ? {
mode: 'indeterminate'
mode: 'indeterminate',
} : null,
uploadComplete: true,
percentage: 100,
bytesUploaded: currentProgress.bytesTotal
}),
response: uploadResp,
percentage : 100,
bytesUploaded : currentProgress.bytesTotal,
},
response : uploadResp,
uploadURL: uploadResp.uploadURL,
isPaused: false
isPaused : false,
})
this._calculateTotalProgress()
@ -1144,9 +1128,7 @@ class Uppy {
return
}
this.setFileState(file.id, {
progress: Object.assign({}, this.getFile(file.id).progress, {
preprocess: progress
})
progress: { ...this.getFile(file.id).progress, preprocess: progress },
})
})
@ -1155,13 +1137,11 @@ class Uppy {
this.log(`Not setting progress for a file that has been removed: ${file.id}`)
return
}
const files = Object.assign({}, this.getState().files)
files[file.id] = Object.assign({}, files[file.id], {
progress: Object.assign({}, files[file.id].progress)
})
const files = { ...this.getState().files }
files[file.id] = { ...files[file.id], progress: { ...files[file.id].progress } }
delete files[file.id].progress.preprocess
this.setState({ files: files })
this.setState({ files })
})
this.on('postprocess-progress', (file, progress) => {
@ -1170,9 +1150,7 @@ class Uppy {
return
}
this.setFileState(file.id, {
progress: Object.assign({}, this.getState().files[file.id].progress, {
postprocess: progress
})
progress: { ...this.getState().files[file.id].progress, postprocess: progress },
})
})
@ -1182,20 +1160,20 @@ class Uppy {
return
}
const files = {
...this.getState().files
...this.getState().files,
}
files[file.id] = {
...files[file.id],
progress: {
...files[file.id].progress
}
...files[file.id].progress,
},
}
delete files[file.id].progress.postprocess
// TODO should we set some kind of `fullyComplete` property on the file object
// so it's easier to see that the file is upload…fully complete…rather than
// what we have to do now (`uploadComplete && !postprocess`)
this.setState({ files: files })
this.setState({ files })
})
this.on('restored', () => {
@ -1212,10 +1190,9 @@ class Uppy {
}
updateOnlineStatus () {
const online =
typeof window.navigator.onLine !== 'undefined'
? window.navigator.onLine
: true
const online = typeof window.navigator.onLine !== 'undefined'
? window.navigator.onLine
: true
if (!online) {
this.emit('is-offline')
this.info(this.i18n('noInternetConnection'), 'error', 0)
@ -1243,8 +1220,8 @@ class Uppy {
*/
use (Plugin, opts) {
if (typeof Plugin !== 'function') {
const msg = `Expected a plugin class, but got ${Plugin === null ? 'null' : typeof Plugin}.` +
' Please verify that the plugin was imported and spelled correctly.'
const msg = `Expected a plugin class, but got ${Plugin === null ? 'null' : typeof Plugin}.`
+ ' Please verify that the plugin was imported and spelled correctly.'
throw new TypeError(msg)
}
@ -1263,9 +1240,9 @@ class Uppy {
const existsPluginAlready = this.getPlugin(pluginId)
if (existsPluginAlready) {
const msg = `Already found a plugin named '${existsPluginAlready.id}'. ` +
`Tried to use: '${pluginId}'.\n` +
'Uppy plugins must have unique `id` options. See https://uppy.io/docs/plugins/#id.'
const msg = `Already found a plugin named '${existsPluginAlready.id}'. `
+ `Tried to use: '${pluginId}'.\n`
+ 'Uppy plugins must have unique `id` options. See https://uppy.io/docs/plugins/#id.'
throw new Error(msg)
}
@ -1302,7 +1279,7 @@ class Uppy {
* @param {Function} method that will be run on each plugin
*/
iteratePlugins (method) {
Object.keys(this.plugins).forEach(pluginType => {
Object.keys(this.plugins).forEach((pluginType) => {
this.plugins[pluginType].forEach(method)
})
}
@ -1324,7 +1301,7 @@ class Uppy {
// list.indexOf failed here, because Vue3 converted the plugin instance
// to a Proxy object, which failed the strict comparison test:
// obj !== objProxy
const index = findIndex(list, item => item.id === instance.id)
const index = findIndex(list, (item) => item.id === instance.id)
if (index !== -1) {
list.splice(index, 1)
this.plugins[instance.type] = list
@ -1334,8 +1311,8 @@ class Uppy {
const updatedState = {
plugins: {
...state.plugins,
[instance.id]: undefined
}
[instance.id]: undefined,
},
}
this.setState(updatedState)
}
@ -1370,10 +1347,10 @@ class Uppy {
this.setState({
info: {
isHidden: false,
type: type,
message: isComplexMessage ? message.message : message,
details: isComplexMessage ? message.details : null
}
type,
message : isComplexMessage ? message.message : message,
details : isComplexMessage ? message.details : null,
},
})
this.emit('info-visible')
@ -1389,11 +1366,9 @@ class Uppy {
}
hideInfo () {
const newInfo = Object.assign({}, this.getState().info, {
isHidden: true
})
const newInfo = { ...this.getState().info, isHidden: true }
this.setState({
info: newInfo
info: newInfo,
})
this.emit('info-hidden')
}
@ -1444,7 +1419,7 @@ class Uppy {
*/
_createUpload (fileIDs, opts = {}) {
const {
forceAllowNewUpload = false // uppy.retryAll sets this to true — when retrying we want to ignore `allowNewUpload: false`
forceAllowNewUpload = false, // uppy.retryAll sets this to true — when retrying we want to ignore `allowNewUpload: false`
} = opts
const { allowNewUpload, currentUploads } = this.getState()
@ -1456,7 +1431,7 @@ class Uppy {
this.emit('upload', {
id: uploadID,
fileIDs: fileIDs
fileIDs,
})
this.setState({
@ -1465,11 +1440,11 @@ class Uppy {
currentUploads: {
...currentUploads,
[uploadID]: {
fileIDs: fileIDs,
step: 0,
result: {}
}
}
fileIDs,
step : 0,
result: {},
},
},
})
return uploadID
@ -1493,13 +1468,9 @@ class Uppy {
return
}
const currentUploads = this.getState().currentUploads
const currentUpload = Object.assign({}, currentUploads[uploadID], {
result: Object.assign({}, currentUploads[uploadID].result, data)
})
const currentUpload = { ...currentUploads[uploadID], result: { ...currentUploads[uploadID].result, ...data } }
this.setState({
currentUploads: Object.assign({}, currentUploads, {
[uploadID]: currentUpload
})
currentUploads: { ...currentUploads, [uploadID]: currentUpload },
})
}
@ -1513,7 +1484,7 @@ class Uppy {
delete currentUploads[uploadID]
this.setState({
currentUploads: currentUploads
currentUploads,
})
}
@ -1529,7 +1500,7 @@ class Uppy {
const steps = [
...this.preProcessors,
...this.uploaders,
...this.postProcessors
...this.postProcessors,
]
let lastStep = Promise.resolve()
steps.forEach((fn, step) => {
@ -1547,22 +1518,20 @@ class Uppy {
const updatedUpload = {
...currentUpload,
step
step,
}
this.setState({
currentUploads: {
...currentUploads,
[uploadID]: updatedUpload
}
[uploadID]: updatedUpload,
},
})
// TODO give this the `updatedUpload` object as its only parameter maybe?
// Otherwise when more metadata may be added to the upload this would keep getting more parameters
return fn(updatedUpload.fileIDs, uploadID)
}).then((result) => {
return null
})
}).then((result) => null)
})
// Not returning the `catch`ed promise, because we still want to return a rejected
@ -1648,7 +1617,7 @@ class Uppy {
// Updating files in state, because uploader plugins receive file IDs,
// and then fetch the actual file object from state
this.setState({
files: files
files,
})
}
@ -1676,7 +1645,7 @@ class Uppy {
})
.catch((err) => {
this._showOrLogErrorAndThrow(err, {
showInformer: false
showInformer: false,
})
})
}

File diff suppressed because it is too large Load diff

View file

@ -4,8 +4,8 @@ const getTimeStamp = require('@uppy/utils/lib/getTimeStamp')
// default if logger is not set or debug: false
const justErrorsLogger = {
debug: (...args) => {},
warn: (...args) => {},
error: (...args) => console.error(`[Uppy] [${getTimeStamp()}]`, ...args)
warn : (...args) => {},
error: (...args) => console.error(`[Uppy] [${getTimeStamp()}]`, ...args),
}
// Print logs to console with namespace + timestamp,
@ -16,11 +16,11 @@ const debugLogger = {
const debug = console.debug || console.log
debug.call(console, `[Uppy] [${getTimeStamp()}]`, ...args)
},
warn: (...args) => console.warn(`[Uppy] [${getTimeStamp()}]`, ...args),
error: (...args) => console.error(`[Uppy] [${getTimeStamp()}]`, ...args)
warn : (...args) => console.warn(`[Uppy] [${getTimeStamp()}]`, ...args),
error: (...args) => console.error(`[Uppy] [${getTimeStamp()}]`, ...args),
}
module.exports = {
justErrorsLogger,
debugLogger
debugLogger,
}

View file

@ -34,7 +34,7 @@ class AddFiles extends Component {
// Support both the old word-order-insensitive string `poweredBy` and the new word-order-sensitive string `poweredBy2`
const linkText = this.props.i18nArray('poweredBy2', {
backwardsCompat: this.props.i18n('poweredBy'),
uppy: uppyBranding
uppy : uppyBranding,
})
return (
@ -50,8 +50,7 @@ class AddFiles extends Component {
)
}
renderHiddenInput = (isFolder, refCallback) => {
return (
renderHiddenInput = (isFolder, refCallback) => (
<input
class="uppy-Dashboard-input"
hidden
@ -65,11 +64,9 @@ class AddFiles extends Component {
accept={this.props.allowedFileTypes}
ref={refCallback}
/>
)
}
)
renderMyDeviceAcquirer = () => {
return (
renderMyDeviceAcquirer = () => (
<div
class="uppy-DashboardTab"
role="presentation"
@ -92,8 +89,7 @@ class AddFiles extends Component {
<div class="uppy-DashboardTab-name">{this.props.i18n('myDevice')}</div>
</button>
</div>
)
}
)
renderBrowseButton = (text, onClickFn) => {
const numberOfAcquirers = this.props.acquirers.length
@ -172,8 +168,7 @@ class AddFiles extends Component {
)
}
renderAcquirer = (acquirer) => {
return (
renderAcquirer = (acquirer) => (
<div
class="uppy-DashboardTab"
role="presentation"
@ -193,8 +188,7 @@ class AddFiles extends Component {
<div class="uppy-DashboardTab-name">{acquirer.name}</div>
</button>
</div>
)
}
)
renderAcquirers = (acquirers) => {
// Group last two buttons, so we dont end up with

View file

@ -2,8 +2,7 @@ const { h } = require('preact')
const classNames = require('classnames')
const AddFiles = require('./AddFiles')
const AddFilesPanel = (props) => {
return (
const AddFilesPanel = (props) => (
<div
class={classNames('uppy-Dashboard-AddFilesPanel', props.className)}
data-uppy-panelType="AddFiles"
@ -22,7 +21,6 @@ const AddFilesPanel = (props) => {
</div>
<AddFiles {...props} />
</div>
)
}
)
module.exports = AddFilesPanel

View file

@ -23,22 +23,22 @@ module.exports = function Dashboard (props) {
const isSizeMD = props.containerWidth > WIDTH_MD
const wrapperClassName = classNames({
'uppy-Root': props.isTargetDOMEl
'uppy-Root': props.isTargetDOMEl,
})
const dashboardClassName = classNames({
'uppy-Dashboard': true,
'uppy-Dashboard--isDisabled': props.disabled,
'uppy-Dashboard--animateOpenClose': props.animateOpenClose,
'uppy-Dashboard--isClosing': props.isClosing,
'uppy-Dashboard--isDraggingOver': props.isDraggingOver,
'uppy-Dashboard--modal': !props.inline,
'uppy-size--md': props.containerWidth > WIDTH_MD,
'uppy-size--lg': props.containerWidth > WIDTH_LG,
'uppy-size--xl': props.containerWidth > WIDTH_XL,
'uppy-size--height-md': props.containerHeight > HEIGHT_MD,
'uppy-Dashboard' : true,
'uppy-Dashboard--isDisabled' : props.disabled,
'uppy-Dashboard--animateOpenClose' : props.animateOpenClose,
'uppy-Dashboard--isClosing' : props.isClosing,
'uppy-Dashboard--isDraggingOver' : props.isDraggingOver,
'uppy-Dashboard--modal' : !props.inline,
'uppy-size--md' : props.containerWidth > WIDTH_MD,
'uppy-size--lg' : props.containerWidth > WIDTH_LG,
'uppy-size--xl' : props.containerWidth > WIDTH_XL,
'uppy-size--height-md' : props.containerHeight > HEIGHT_MD,
'uppy-Dashboard--isAddFilesPanelVisible': props.showAddFilesPanel,
'uppy-Dashboard--isInnerWrapVisible': props.areInsidesReadyToBeVisible
'uppy-Dashboard--isInnerWrapVisible' : props.areInsidesReadyToBeVisible,
})
// Important: keep these in sync with the percent width values in `src/components/FileItem/index.scss`.
@ -78,8 +78,8 @@ module.exports = function Dashboard (props) {
aria-modal={!props.inline && 'true'}
role={!props.inline && 'dialog'}
style={{
width: props.inline && props.width ? props.width : '',
height: props.inline && props.height ? props.height : ''
width : props.inline && props.width ? props.width : '',
height: props.inline && props.height ? props.height : '',
}}
>
@ -128,9 +128,7 @@ module.exports = function Dashboard (props) {
</Slide>
<div class="uppy-Dashboard-progressindicators">
{props.progressindicators.map((target) => {
return props.getPlugin(target.id).render(props.state)
})}
{props.progressindicators.map((target) => props.getPlugin(target.id).render(props.state))}
</div>
</div>
</div>

View file

@ -14,7 +14,7 @@ function EditorPanel (props) {
<div class="uppy-DashboardContent-bar">
<div class="uppy-DashboardContent-title" role="heading" aria-level="1">
{props.i18nArray('editing', {
file: <span class="uppy-DashboardContent-titleFile">{file.meta ? file.meta.name : file.name}</span>
file: <span class="uppy-DashboardContent-titleFile">{file.meta ? file.meta.name : file.name}</span>,
})}
</div>
<button
@ -26,9 +26,7 @@ function EditorPanel (props) {
</button>
</div>
<div class="uppy-DashboardContent-panelBody">
{props.editors.map((target) => {
return props.getPlugin(target.id).render(props.state)
})}
{props.editors.map((target) => props.getPlugin(target.id).render(props.state))}
</div>
</div>
)

View file

@ -17,7 +17,7 @@ class FileCard extends Component {
})
this.state = {
formState: storedMetaData
formState: storedMetaData,
}
}
@ -34,8 +34,8 @@ class FileCard extends Component {
this.setState({
formState: {
...this.state.formState,
[name]: newVal
}
[name]: newVal,
},
})
}
@ -51,7 +51,7 @@ class FileCard extends Component {
renderMetaFields = () => {
const metaFields = this.props.metaFields || []
const fieldCSSClasses = {
text: 'uppy-u-reset uppy-c-textInput uppy-Dashboard-FileCard-input'
text: 'uppy-u-reset uppy-c-textInput uppy-Dashboard-FileCard-input',
}
return metaFields.map((field) => {
@ -61,9 +61,9 @@ class FileCard extends Component {
<label class="uppy-Dashboard-FileCard-label" for={id}>{field.name}</label>
{field.render !== undefined
? field.render({
value: this.state.formState[field.id],
value : this.state.formState[field.id],
onChange: (newVal) => this.updateMeta(newVal, field.id),
fieldCSSClasses: fieldCSSClasses
fieldCSSClasses,
}, h)
: (
<input
@ -75,7 +75,7 @@ class FileCard extends Component {
onkeyup={this.saveOnEnter}
onkeydown={this.saveOnEnter}
onkeypress={this.saveOnEnter}
oninput={ev => this.updateMeta(ev.target.value, field.id)}
oninput={(ev) => this.updateMeta(ev.target.value, field.id)}
data-uppy-super-focusable
/>
)}
@ -100,7 +100,7 @@ class FileCard extends Component {
<div class="uppy-DashboardContent-bar">
<div class="uppy-DashboardContent-title" role="heading" aria-level="1">
{this.props.i18nArray('editing', {
file: <span class="uppy-DashboardContent-titleFile">{file.meta ? file.meta.name : file.name}</span>
file: <span class="uppy-DashboardContent-titleFile">{file.meta ? file.meta.name : file.name}</span>,
})}
</div>
<button
@ -114,8 +114,8 @@ class FileCard extends Component {
<div class="uppy-Dashboard-FileCard-inner">
<div class="uppy-Dashboard-FileCard-preview" style={{ backgroundColor: getFileTypeIcon(file.type).color }}>
<FilePreview file={file} />
{showEditButton &&
<button
{showEditButton
&& <button
type="button"
class="uppy-u-reset uppy-c-btn uppy-Dashboard-FileCard-edit"
onClick={() => this.props.openFileEditor(file)}

View file

@ -7,17 +7,17 @@ function EditButton ({
metaFields,
canEditFile,
i18n,
onClick
onClick,
}) {
if (
(!uploadInProgressOrComplete && metaFields && metaFields.length > 0) ||
(!uploadInProgressOrComplete && canEditFile(file))
(!uploadInProgressOrComplete && metaFields && metaFields.length > 0)
|| (!uploadInProgressOrComplete && canEditFile(file))
) {
return (
<button
class="uppy-u-reset uppy-Dashboard-Item-action uppy-Dashboard-Item-action--edit"
type="button"
aria-label={i18n('editFile') + ' ' + file.meta.name}
aria-label={`${i18n('editFile')} ${file.meta.name}`}
title={i18n('editFile')}
onclick={() => onClick()}
>
@ -91,7 +91,7 @@ module.exports = function Buttons (props) {
toggleFileCard,
openFileEditor,
log,
info
info,
} = props
const editAction = () => {

View file

@ -8,10 +8,10 @@ const renderAcquirerIcon = (acquirer, props) =>
</span>
const renderFileSource = (props) => (
props.file.source &&
props.file.source !== props.id &&
<div class="uppy-Dashboard-Item-sourceIcon">
{props.acquirers.map(acquirer => {
props.file.source
&& props.file.source !== props.id
&& <div class="uppy-Dashboard-Item-sourceIcon">
{props.acquirers.map((acquirer) => {
if (acquirer.id === props.file.source) {
return renderAcquirerIcon(acquirer, props)
}
@ -41,8 +41,8 @@ const renderFileName = (props) => {
}
const renderFileSize = (props) => (
props.file.data.size &&
<div class="uppy-Dashboard-Item-statusSize">
props.file.data.size
&& <div class="uppy-Dashboard-Item-statusSize">
{prettierBytes(props.file.data.size)}
</div>
)

View file

@ -9,9 +9,9 @@ module.exports = function FilePreviewAndLink (props) {
style={{ backgroundColor: getFileTypeIcon(props.file.type).color }}
>
{
props.showLinkToFileUploadResult &&
props.file.uploadURL &&
<a
props.showLinkToFileUploadResult
&& props.file.uploadURL
&& <a
class="uppy-Dashboard-Item-previewLink"
href={props.file.uploadURL}
rel="noreferrer noopener"

View file

@ -29,7 +29,7 @@ function progressIndicatorTitle (props) {
return props.i18n('resumeUpload')
}
return props.i18n('pauseUpload')
} else if (props.individualCancellation) {
} if (props.individualCancellation) {
return props.i18n('cancelUpload')
}

View file

@ -43,13 +43,13 @@ module.exports = class FileItem extends Component {
}
const dashboardItemClass = classNames({
'uppy-Dashboard-Item': true,
'is-inprogress': uploadInProgress,
'is-processing': isProcessing,
'is-complete': isUploaded,
'is-error': !!error,
'is-resumable': this.props.resumableUploads,
'is-noIndividualCancellation': !this.props.individualCancellation
'uppy-Dashboard-Item' : true,
'is-inprogress' : uploadInProgress,
'is-processing' : isProcessing,
'is-complete' : isUploaded,
'is-error' : !!error,
'is-resumable' : this.props.resumableUploads,
'is-noIndividualCancellation': !this.props.individualCancellation,
})
return (

View file

@ -22,7 +22,7 @@ module.exports = (props) => {
const noFiles = props.totalFileCount === 0
const dashboardFilesClass = classNames(
'uppy-Dashboard-files',
{ 'uppy-Dashboard-files--noFiles': noFiles }
{ 'uppy-Dashboard-files--noFiles': noFiles },
)
// It's not great that this is hardcoded!
@ -35,32 +35,32 @@ module.exports = (props) => {
const fileProps = {
// FIXME This is confusing, it's actually the Dashboard's plugin ID
id: props.id,
error: props.error,
id : props.id,
error : props.error,
// TODO move this to context
i18n: props.i18n,
log: props.log,
info: props.info,
i18n : props.i18n,
log : props.log,
info : props.info,
// features
acquirers: props.acquirers,
resumableUploads: props.resumableUploads,
individualCancellation: props.individualCancellation,
acquirers : props.acquirers,
resumableUploads : props.resumableUploads,
individualCancellation : props.individualCancellation,
// visual options
hideRetryButton: props.hideRetryButton,
hidePauseResumeButton: props.hidePauseResumeButton,
hideCancelButton: props.hideCancelButton,
showLinkToFileUploadResult: props.showLinkToFileUploadResult,
hideRetryButton : props.hideRetryButton,
hidePauseResumeButton : props.hidePauseResumeButton,
hideCancelButton : props.hideCancelButton,
showLinkToFileUploadResult : props.showLinkToFileUploadResult,
showRemoveButtonAfterComplete: props.showRemoveButtonAfterComplete,
isWide: props.isWide,
metaFields: props.metaFields,
isWide : props.isWide,
metaFields : props.metaFields,
// callbacks
retryUpload: props.retryUpload,
pauseUpload: props.pauseUpload,
cancelUpload: props.cancelUpload,
toggleFileCard: props.toggleFileCard,
removeFile: props.removeFile,
handleRequestThumbnail: props.handleRequestThumbnail,
handleCancelThumbnail: props.handleCancelThumbnail
retryUpload : props.retryUpload,
pauseUpload : props.pauseUpload,
cancelUpload : props.cancelUpload,
toggleFileCard : props.toggleFileCard,
removeFile : props.removeFile,
handleRequestThumbnail : props.handleRequestThumbnail,
handleCancelThumbnail : props.handleCancelThumbnail,
}
const rows = chunks(Object.keys(props.files), props.itemsPerRow)

View file

@ -18,7 +18,7 @@ module.exports = function FilePreview (props) {
return (
<div class="uppy-Dashboard-Item-previewIconWrap">
<span class="uppy-Dashboard-Item-previewIcon" style={{ color: color }}>{icon}</span>
<span class="uppy-Dashboard-Item-previewIcon" style={{ color }}>{icon}</span>
<svg aria-hidden="true" focusable="false" class="uppy-Dashboard-Item-previewIconBg" width="58" height="76" viewBox="0 0 58 76">
<rect fill="#FFF" width="58" height="76" rx="3" fill-rule="evenodd" />
</svg>

View file

@ -1,13 +1,13 @@
const { h } = require('preact')
const uploadStates = {
STATE_ERROR: 'error',
STATE_WAITING: 'waiting',
STATE_PREPROCESSING: 'preprocessing',
STATE_UPLOADING: 'uploading',
STATE_ERROR : 'error',
STATE_WAITING : 'waiting',
STATE_PREPROCESSING : 'preprocessing',
STATE_UPLOADING : 'uploading',
STATE_POSTPROCESSING: 'postprocessing',
STATE_COMPLETE: 'complete',
STATE_PAUSED: 'paused'
STATE_COMPLETE : 'complete',
STATE_PAUSED : 'paused',
}
function getUploadingState (isAllErrored, isAllComplete, isAllPaused, files = {}) {
@ -50,7 +50,7 @@ function UploadStatus (props) {
props.isAllErrored,
props.isAllComplete,
props.isAllPaused,
props.files
props.files,
)
switch (uploadingState) {

View file

@ -19,7 +19,7 @@ class Slide extends Component {
this.state = {
cachedChildren: null,
className: ''
className : '',
}
}
@ -30,7 +30,7 @@ class Slide extends Component {
if (cachedChildren === child) return
const patch = {
cachedChildren: child
cachedChildren: child,
}
// Enter transition
@ -46,7 +46,7 @@ class Slide extends Component {
this.base.getBoundingClientRect()
this.setState({
className: `${transitionName}-enter ${transitionName}-enter-active`
className: `${transitionName}-enter ${transitionName}-enter-active`,
})
this.enterTimeout = setTimeout(() => {
@ -65,13 +65,13 @@ class Slide extends Component {
this.enterTimeout = undefined
this.animationFrame = requestAnimationFrame(() => {
this.setState({
className: `${transitionName}-leave ${transitionName}-leave-active`
className: `${transitionName}-leave ${transitionName}-leave-active`,
})
this.leaveTimeout = setTimeout(() => {
this.setState({
cachedChildren: null,
className: ''
className : '',
})
}, duration)
})
@ -88,7 +88,7 @@ class Slide extends Component {
}
return cloneElement(cachedChildren, {
className: classNames(className, cachedChildren.attributes.className)
className: classNames(className, cachedChildren.attributes.className),
})
}
}

View file

@ -29,26 +29,26 @@
const { h, Component } = require('preact')
const STYLE_INNER = {
position: 'relative',
position : 'relative',
// Disabled for our use case: the wrapper elements around FileList already deal with overflow,
// and this additional property would hide things that we want to show.
//
// overflow: 'hidden',
width: '100%',
minHeight: '100%'
width : '100%',
minHeight: '100%',
}
const STYLE_CONTENT = {
position: 'absolute',
top: 0,
left: 0,
top : 0,
left : 0,
// Because the `top` value gets set to some offset, this `height` being 100% would make the scrollbar
// stretch far beyond the content. For our use case, the content div actually can get its height from
// the elements inside it, so we don't need to specify a `height` property at all.
//
// height: '100%',
width: '100%',
overflow: 'visible'
width : '100%',
overflow: 'visible',
}
class VirtualList extends Component {
@ -61,14 +61,14 @@ class VirtualList extends Component {
this.state = {
offset: 0,
height: 0
height: 0,
}
}
resize () {
if (this.state.height !== this.base.offsetHeight) {
this.setState({
height: this.base.offsetHeight
height: this.base.offsetHeight,
})
}
}
@ -79,7 +79,7 @@ class VirtualList extends Component {
handleScroll = () => {
this.setState({
offset: this.base.scrollTop
offset: this.base.scrollTop,
})
if (this.props.sync) {
this.forceUpdate()
@ -94,8 +94,8 @@ class VirtualList extends Component {
componentDidUpdate () {
// Maintain focus when rows are added and removed.
if (this.focusElement && this.focusElement.parentNode &&
document.activeElement !== this.focusElement) {
if (this.focusElement && this.focusElement.parentNode
&& document.activeElement !== this.focusElement) {
this.focusElement.focus()
}
this.focusElement = null

View file

@ -51,52 +51,52 @@ module.exports = class Dashboard extends Plugin {
this.defaultLocale = {
strings: {
closeModal: 'Close Modal',
importFrom: 'Import from %{name}',
addingMoreFiles: 'Adding more files',
addMoreFiles: 'Add more files',
dashboardWindowTitle: 'File Uploader Window (Press escape to close)',
dashboardTitle: 'File Uploader',
copyLinkToClipboardSuccess: 'Link copied to clipboard',
closeModal : 'Close Modal',
importFrom : 'Import from %{name}',
addingMoreFiles : 'Adding more files',
addMoreFiles : 'Add more files',
dashboardWindowTitle : 'File Uploader Window (Press escape to close)',
dashboardTitle : 'File Uploader',
copyLinkToClipboardSuccess : 'Link copied to clipboard',
copyLinkToClipboardFallback: 'Copy the URL below',
copyLink: 'Copy link',
fileSource: 'File source: %{name}',
done: 'Done',
back: 'Back',
addMore: 'Add more',
removeFile: 'Remove file',
editFile: 'Edit file',
editing: 'Editing %{file}',
finishEditingFile: 'Finish editing file',
saveChanges: 'Save changes',
cancel: 'Cancel',
myDevice: 'My Device',
dropPasteFiles: 'Drop files here, paste or %{browseFiles}',
dropPasteFolders: 'Drop files here, paste or %{browseFolders}',
dropPasteBoth: 'Drop files here, paste, %{browseFiles} or %{browseFolders}',
dropPasteImportFiles: 'Drop files here, paste, %{browseFiles} or import from:',
dropPasteImportFolders: 'Drop files here, paste, %{browseFolders} or import from:',
dropPasteImportBoth: 'Drop files here, paste, %{browseFiles}, %{browseFolders} or import from:',
dropHint: 'Drop your files here',
browseFiles: 'browse files',
browseFolders: 'browse folders',
uploadComplete: 'Upload complete',
uploadPaused: 'Upload paused',
resumeUpload: 'Resume upload',
pauseUpload: 'Pause upload',
retryUpload: 'Retry upload',
cancelUpload: 'Cancel upload',
xFilesSelected: {
copyLink : 'Copy link',
fileSource : 'File source: %{name}',
done : 'Done',
back : 'Back',
addMore : 'Add more',
removeFile : 'Remove file',
editFile : 'Edit file',
editing : 'Editing %{file}',
finishEditingFile : 'Finish editing file',
saveChanges : 'Save changes',
cancel : 'Cancel',
myDevice : 'My Device',
dropPasteFiles : 'Drop files here, paste or %{browseFiles}',
dropPasteFolders : 'Drop files here, paste or %{browseFolders}',
dropPasteBoth : 'Drop files here, paste, %{browseFiles} or %{browseFolders}',
dropPasteImportFiles : 'Drop files here, paste, %{browseFiles} or import from:',
dropPasteImportFolders : 'Drop files here, paste, %{browseFolders} or import from:',
dropPasteImportBoth : 'Drop files here, paste, %{browseFiles}, %{browseFolders} or import from:',
dropHint : 'Drop your files here',
browseFiles : 'browse files',
browseFolders : 'browse folders',
uploadComplete : 'Upload complete',
uploadPaused : 'Upload paused',
resumeUpload : 'Resume upload',
pauseUpload : 'Pause upload',
retryUpload : 'Retry upload',
cancelUpload : 'Cancel upload',
xFilesSelected : {
0: '%{smart_count} file selected',
1: '%{smart_count} files selected'
1: '%{smart_count} files selected',
},
uploadingXFiles: {
0: 'Uploading %{smart_count} file',
1: 'Uploading %{smart_count} files'
1: 'Uploading %{smart_count} files',
},
processingXFiles: {
0: 'Processing %{smart_count} file',
1: 'Processing %{smart_count} files'
1: 'Processing %{smart_count} files',
},
// The default `poweredBy2` string only combines the `poweredBy` string (%{backwardsCompat}) with the size.
// Locales can override `poweredBy2` to specify a different word order. This is for backwards compat with
@ -104,50 +104,50 @@ module.exports = class Dashboard extends Plugin {
// substitution.
// TODO: In 2.0 `poweredBy2` should be removed in and `poweredBy` updated to use substitution.
poweredBy2: '%{backwardsCompat} %{uppy}',
poweredBy: 'Powered by'
}
poweredBy : 'Powered by',
},
}
// set default options
const defaultOptions = {
target: 'body',
metaFields: [],
trigger: '#uppy-select-files',
inline: false,
width: 750,
height: 550,
thumbnailWidth: 280,
thumbnailType: 'image/jpeg',
target : 'body',
metaFields : [],
trigger : '#uppy-select-files',
inline : false,
width : 750,
height : 550,
thumbnailWidth : 280,
thumbnailType : 'image/jpeg',
waitForThumbnailsBeforeUpload: false,
defaultPickerIcon,
showLinkToFileUploadResult: true,
showProgressDetails: false,
hideUploadButton: false,
hideCancelButton: false,
hideRetryButton: false,
hidePauseResumeButton: false,
hideProgressAfterFinish: false,
doneButtonHandler: () => {
showLinkToFileUploadResult : true,
showProgressDetails : false,
hideUploadButton : false,
hideCancelButton : false,
hideRetryButton : false,
hidePauseResumeButton : false,
hideProgressAfterFinish : false,
doneButtonHandler : () => {
this.uppy.reset()
this.requestCloseModal()
},
note: null,
closeModalOnClickOutside: false,
closeAfterFinish: false,
disableStatusBar: false,
disableInformer: false,
disableThumbnailGenerator: false,
note : null,
closeModalOnClickOutside : false,
closeAfterFinish : false,
disableStatusBar : false,
disableInformer : false,
disableThumbnailGenerator : false,
disablePageScrollWhenModalOpen: true,
animateOpenClose: true,
fileManagerSelectionType: 'files',
proudlyDisplayPoweredByUppy: true,
onRequestCloseModal: () => this.closeModal(),
showSelectedFiles: true,
showRemoveButtonAfterComplete: false,
browserBackButtonClose: false,
theme: 'light',
autoOpenFileEditor: false,
disabled: false
animateOpenClose : true,
fileManagerSelectionType : 'files',
proudlyDisplayPoweredByUppy : true,
onRequestCloseModal : () => this.closeModal(),
showSelectedFiles : true,
showRemoveButtonAfterComplete : false,
browserBackButtonClose : false,
theme : 'light',
autoOpenFileEditor : false,
disabled : false,
}
// merge default options with the ones set by user
@ -178,10 +178,10 @@ module.exports = class Dashboard extends Plugin {
removeTarget = (plugin) => {
const pluginState = this.getPluginState()
// filter out the one we want to remove
const newTargets = pluginState.targets.filter(target => target.id !== plugin.id)
const newTargets = pluginState.targets.filter((target) => target.id !== plugin.id)
this.setPluginState({
targets: newTargets
targets: newTargets,
})
}
@ -190,18 +190,18 @@ module.exports = class Dashboard extends Plugin {
const callerPluginName = plugin.title || callerPluginId
const callerPluginType = plugin.type
if (callerPluginType !== 'acquirer' &&
callerPluginType !== 'progressindicator' &&
callerPluginType !== 'editor') {
if (callerPluginType !== 'acquirer'
&& callerPluginType !== 'progressindicator'
&& callerPluginType !== 'editor') {
const msg = 'Dashboard: can only be targeted by plugins of types: acquirer, progressindicator, editor'
this.uppy.log(msg, 'error')
return
}
const target = {
id: callerPluginId,
id : callerPluginId,
name: callerPluginName,
type: callerPluginType
type: callerPluginType,
}
const state = this.getPluginState()
@ -209,7 +209,7 @@ module.exports = class Dashboard extends Plugin {
newTargets.push(target)
this.setPluginState({
targets: newTargets
targets: newTargets,
})
return this.el
@ -220,15 +220,15 @@ module.exports = class Dashboard extends Plugin {
activePickerPanel: false,
showAddFilesPanel: false,
activeOverlayType: null,
fileCardFor: null,
showFileEditor: false
fileCardFor : null,
showFileEditor : false,
}
const current = this.getPluginState()
if (current.activePickerPanel === update.activePickerPanel &&
current.showAddFilesPanel === update.showAddFilesPanel &&
current.showFileEditor === update.showFileEditor &&
current.activeOverlayType === update.activeOverlayType) {
if (current.activePickerPanel === update.activePickerPanel
&& current.showAddFilesPanel === update.showAddFilesPanel
&& current.showFileEditor === update.showFileEditor
&& current.activeOverlayType === update.activeOverlayType) {
// avoid doing a state update if nothing changed
return
}
@ -239,13 +239,11 @@ module.exports = class Dashboard extends Plugin {
showPanel = (id) => {
const { targets } = this.getPluginState()
const activePickerPanel = targets.filter((target) => {
return target.type === 'acquirer' && target.id === id
})[0]
const activePickerPanel = targets.filter((target) => target.type === 'acquirer' && target.id === id)[0]
this.setPluginState({
activePickerPanel: activePickerPanel,
activeOverlayType: 'PickerPanel'
activePickerPanel,
activeOverlayType: 'PickerPanel',
})
}
@ -263,9 +261,9 @@ module.exports = class Dashboard extends Plugin {
const editors = this._getEditors(targets)
this.setPluginState({
showFileEditor: true,
fileCardFor: file.id || null,
activeOverlayType: 'FileEditor'
showFileEditor : true,
fileCardFor : file.id || null,
activeOverlayType: 'FileEditor',
})
editors.forEach((editor) => {
@ -287,7 +285,7 @@ module.exports = class Dashboard extends Plugin {
if (this.opts.animateOpenClose && this.getPluginState().isClosing) {
const handler = () => {
this.setPluginState({
isHidden: false
isHidden: false,
})
this.el.removeEventListener('animationend', handler, false)
resolve()
@ -295,7 +293,7 @@ module.exports = class Dashboard extends Plugin {
this.el.addEventListener('animationend', handler, false)
} else {
this.setPluginState({
isHidden: false
isHidden: false,
})
resolve()
}
@ -314,7 +312,7 @@ module.exports = class Dashboard extends Plugin {
closeModal = (opts = {}) => {
const {
manualClose = true // Whether the modal is being closed by the user (`true`) or by other means (e.g. browser back button)
manualClose = true, // Whether the modal is being closed by the user (`true`) or by other means (e.g. browser back button)
} = opts
const { isHidden, isClosing } = this.getPluginState()
@ -331,12 +329,12 @@ module.exports = class Dashboard extends Plugin {
if (this.opts.animateOpenClose) {
this.setPluginState({
isClosing: true
isClosing: true,
})
const handler = () => {
this.setPluginState({
isHidden: true,
isClosing: false
isHidden : true,
isClosing: false,
})
this.superFocus.cancel()
@ -348,7 +346,7 @@ module.exports = class Dashboard extends Plugin {
this.el.addEventListener('animationend', handler, false)
} else {
this.setPluginState({
isHidden: true
isHidden: true,
})
this.superFocus.cancel()
@ -375,9 +373,7 @@ module.exports = class Dashboard extends Plugin {
return promise
}
isModalOpen = () => {
return !this.getPluginState().isHidden || false
}
isModalOpen = () => !this.getPluginState().isHidden || false
requestCloseModal = () => {
if (this.opts.onRequestCloseModal) {
@ -391,8 +387,8 @@ module.exports = class Dashboard extends Plugin {
this.uppy.setState({
capabilities: {
...capabilities,
darkMode: isDarkModeOn
}
darkMode: isDarkModeOn,
},
})
}
@ -411,29 +407,29 @@ module.exports = class Dashboard extends Plugin {
}
this.setPluginState({
fileCardFor: show ? fileID : null,
activeOverlayType: show ? 'FileCard' : null
fileCardFor : show ? fileID : null,
activeOverlayType: show ? 'FileCard' : null,
})
}
toggleAddFilesPanel = (show) => {
this.setPluginState({
showAddFilesPanel: show,
activeOverlayType: show ? 'AddFiles' : null
activeOverlayType: show ? 'AddFiles' : null,
})
}
addFiles = (files) => {
const descriptors = files.map((file) => ({
source: this.id,
name: file.name,
type: file.type,
data: file,
meta: {
name : file.name,
type : file.type,
data : file,
meta : {
// path of the file relative to the ancestor directory the user selected.
// e.g. 'docs/Old Prague/airbnb.pdf'
relativePath: file.relativePath || null
}
relativePath: file.relativePath || null,
},
}))
try {
@ -459,9 +455,9 @@ module.exports = class Dashboard extends Plugin {
this.uppy.log(`[Dashboard] resized: ${width} / ${height}`, 'debug')
this.setPluginState({
containerWidth: width,
containerHeight: height,
areInsidesReadyToBeVisible: true
containerWidth : width,
containerHeight : height,
areInsidesReadyToBeVisible: true,
})
})
this.resizeObserver.observe(this.el.querySelector('.uppy-Dashboard-inner'))
@ -472,14 +468,14 @@ module.exports = class Dashboard extends Plugin {
const isModalAndClosed = !this.opts.inline && pluginState.isHidden
if (
// if ResizeObserver hasn't yet fired,
!pluginState.areInsidesReadyToBeVisible &&
!pluginState.areInsidesReadyToBeVisible
// and it's not due to the modal being closed
!isModalAndClosed
&& !isModalAndClosed
) {
this.uppy.log("[Dashboard] resize event didn't fire on time: defaulted to mobile layout", 'debug')
this.setPluginState({
areInsidesReadyToBeVisible: true
areInsidesReadyToBeVisible: true,
})
}
}, 1000)
@ -533,7 +529,7 @@ module.exports = class Dashboard extends Plugin {
// Push to history so that the page is not lost on browser back button press
history.pushState({
...history.state,
[this.modalName]: true
[this.modalName]: true,
}, '')
}
@ -711,7 +707,7 @@ module.exports = class Dashboard extends Plugin {
if (this.opts.trigger && !this.opts.inline) {
const showModalTrigger = findAllDOMElements(this.opts.trigger)
if (showModalTrigger) {
showModalTrigger.forEach(trigger => trigger.addEventListener('click', this.openModal))
showModalTrigger.forEach((trigger) => trigger.addEventListener('click', this.openModal))
} else {
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')
}
@ -743,7 +739,7 @@ module.exports = class Dashboard extends Plugin {
removeEvents = () => {
const showModalTrigger = findAllDOMElements(this.opts.trigger)
if (!this.opts.inline && showModalTrigger) {
showModalTrigger.forEach(trigger => trigger.removeEventListener('click', this.openModal))
showModalTrigger.forEach((trigger) => trigger.removeEventListener('click', this.openModal))
}
this.stopListeningToResize()
@ -776,17 +772,17 @@ module.exports = class Dashboard extends Plugin {
if (
// If update is connected to showing the Informer - let the screen reader calmly read it.
isInformerHidden &&
(
isInformerHidden
&& (
// 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)
isModal ||
isModal
// If we are already inside of Uppy, or
isFocusInUppy ||
|| isFocusInUppy
// If we are not focused on anything BUT we have already, at least once, focused on uppy
// 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'.
// 2. We only focus when focus is nowhere AND this.ifFocusedOnUppyRecently, to avoid focus jumps if we do something else on the page.
// [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.
(isFocusNowhere && this.ifFocusedOnUppyRecently)
|| (isFocusNowhere && this.ifFocusedOnUppyRecently)
)
) {
this.superFocus(this.el, this.getPluginState().activeOverlayType)
@ -821,8 +817,8 @@ module.exports = class Dashboard extends Plugin {
const plugin = this.uppy.getPlugin(target.id)
return {
...target,
icon: plugin.icon || this.opts.defaultPickerIcon,
render: plugin.render
icon : plugin.icon || this.opts.defaultPickerIcon,
render: plugin.render,
}
}
@ -835,23 +831,17 @@ module.exports = class Dashboard extends Plugin {
return plugin.isSupported()
}
_getAcquirers = memoize((targets) => {
return targets
.filter(target => target.type === 'acquirer' && this._isTargetSupported(target))
.map(this._attachRenderFunctionToTarget)
})
_getAcquirers = memoize((targets) => targets
.filter((target) => target.type === 'acquirer' && this._isTargetSupported(target))
.map(this._attachRenderFunctionToTarget))
_getProgressIndicators = memoize((targets) => {
return targets
.filter(target => target.type === 'progressindicator')
.map(this._attachRenderFunctionToTarget)
})
_getProgressIndicators = memoize((targets) => targets
.filter((target) => target.type === 'progressindicator')
.map(this._attachRenderFunctionToTarget))
_getEditors = memoize((targets) => {
return targets
.filter(target => target.type === 'editor')
.map(this._attachRenderFunctionToTarget)
})
_getEditors = memoize((targets) => targets
.filter((target) => target.type === 'editor')
.map(this._attachRenderFunctionToTarget))
render = (state) => {
const pluginState = this.getPluginState()
@ -859,50 +849,34 @@ module.exports = class Dashboard extends Plugin {
// TODO: move this to Core, to share between Status Bar and Dashboard
// (and any other plugin that might need it, too)
const newFiles = Object.keys(files).filter((file) => {
return !files[file].progress.uploadStarted
})
const newFiles = Object.keys(files).filter((file) => !files[file].progress.uploadStarted)
const uploadStartedFiles = Object.keys(files).filter((file) => {
return files[file].progress.uploadStarted
})
const uploadStartedFiles = Object.keys(files).filter((file) => files[file].progress.uploadStarted)
const pausedFiles = Object.keys(files).filter((file) => {
return files[file].isPaused
})
const pausedFiles = Object.keys(files).filter((file) => files[file].isPaused)
const completeFiles = Object.keys(files).filter((file) => {
return files[file].progress.uploadComplete
})
const completeFiles = Object.keys(files).filter((file) => files[file].progress.uploadComplete)
const erroredFiles = Object.keys(files).filter((file) => {
return files[file].error
})
const erroredFiles = Object.keys(files).filter((file) => files[file].error)
const inProgressFiles = Object.keys(files).filter((file) => {
return !files[file].progress.uploadComplete &&
files[file].progress.uploadStarted
})
const inProgressFiles = Object.keys(files).filter((file) => !files[file].progress.uploadComplete
&& files[file].progress.uploadStarted)
const inProgressNotPausedFiles = inProgressFiles.filter((file) => {
return !files[file].isPaused
})
const inProgressNotPausedFiles = inProgressFiles.filter((file) => !files[file].isPaused)
const processingFiles = Object.keys(files).filter((file) => {
return files[file].progress.preprocess || files[file].progress.postprocess
})
const processingFiles = Object.keys(files).filter((file) => files[file].progress.preprocess || files[file].progress.postprocess)
const isUploadStarted = uploadStartedFiles.length > 0
const isAllComplete = state.totalProgress === 100 &&
completeFiles.length === Object.keys(files).length &&
processingFiles.length === 0
const isAllComplete = state.totalProgress === 100
&& completeFiles.length === Object.keys(files).length
&& processingFiles.length === 0
const isAllErrored = isUploadStarted &&
erroredFiles.length === uploadStartedFiles.length
const isAllErrored = isUploadStarted
&& erroredFiles.length === uploadStartedFiles.length
const isAllPaused = inProgressFiles.length !== 0 &&
pausedFiles.length === inProgressFiles.length
const isAllPaused = inProgressFiles.length !== 0
&& pausedFiles.length === inProgressFiles.length
const acquirers = this._getAcquirers(pluginState.targets)
const progressindicators = this._getProgressIndicators(pluginState.targets)
@ -922,7 +896,7 @@ module.exports = class Dashboard extends Plugin {
return DashboardUI({
state,
isHidden: pluginState.isHidden,
isHidden : pluginState.isHidden,
files,
newFiles,
uploadStartedFiles,
@ -935,76 +909,76 @@ module.exports = class Dashboard extends Plugin {
isAllComplete,
isAllErrored,
isAllPaused,
totalFileCount: Object.keys(files).length,
totalProgress: state.totalProgress,
totalFileCount : Object.keys(files).length,
totalProgress : state.totalProgress,
allowNewUpload,
acquirers,
theme,
disabled: this.opts.disabled,
direction: this.opts.direction,
activePickerPanel: pluginState.activePickerPanel,
showFileEditor: pluginState.showFileEditor,
disableAllFocusableElements: this.disableAllFocusableElements,
animateOpenClose: this.opts.animateOpenClose,
isClosing: pluginState.isClosing,
getPlugin: this.uppy.getPlugin,
progressindicators: progressindicators,
editors: editors,
autoProceed: this.uppy.opts.autoProceed,
id: this.id,
closeModal: this.requestCloseModal,
handleClickOutside: this.handleClickOutside,
handleInputChange: this.handleInputChange,
handlePaste: this.handlePaste,
inline: this.opts.inline,
showPanel: this.showPanel,
hideAllPanels: this.hideAllPanels,
log: this.uppy.log,
i18n: this.i18n,
i18nArray: this.i18nArray,
removeFile: this.uppy.removeFile,
uppy: this.uppy,
info: this.uppy.info,
note: this.opts.note,
metaFields: pluginState.metaFields,
resumableUploads: capabilities.resumableUploads || false,
individualCancellation: capabilities.individualCancellation,
isMobileDevice: capabilities.isMobileDevice,
pauseUpload: this.uppy.pauseResume,
retryUpload: this.uppy.retryUpload,
cancelUpload: this.cancelUpload,
cancelAll: this.uppy.cancelAll,
fileCardFor: pluginState.fileCardFor,
toggleFileCard: this.toggleFileCard,
toggleAddFilesPanel: this.toggleAddFilesPanel,
showAddFilesPanel: pluginState.showAddFilesPanel,
saveFileCard: this.saveFileCard,
openFileEditor: this.openFileEditor,
canEditFile: this.canEditFile,
width: this.opts.width,
height: this.opts.height,
showLinkToFileUploadResult: this.opts.showLinkToFileUploadResult,
fileManagerSelectionType: this.opts.fileManagerSelectionType,
proudlyDisplayPoweredByUppy: this.opts.proudlyDisplayPoweredByUppy,
hideCancelButton: this.opts.hideCancelButton,
hideRetryButton: this.opts.hideRetryButton,
hidePauseResumeButton: this.opts.hidePauseResumeButton,
disabled : this.opts.disabled,
direction : this.opts.direction,
activePickerPanel : pluginState.activePickerPanel,
showFileEditor : pluginState.showFileEditor,
disableAllFocusableElements : this.disableAllFocusableElements,
animateOpenClose : this.opts.animateOpenClose,
isClosing : pluginState.isClosing,
getPlugin : this.uppy.getPlugin,
progressindicators,
editors,
autoProceed : this.uppy.opts.autoProceed,
id : this.id,
closeModal : this.requestCloseModal,
handleClickOutside : this.handleClickOutside,
handleInputChange : this.handleInputChange,
handlePaste : this.handlePaste,
inline : this.opts.inline,
showPanel : this.showPanel,
hideAllPanels : this.hideAllPanels,
log : this.uppy.log,
i18n : this.i18n,
i18nArray : this.i18nArray,
removeFile : this.uppy.removeFile,
uppy : this.uppy,
info : this.uppy.info,
note : this.opts.note,
metaFields : pluginState.metaFields,
resumableUploads : capabilities.resumableUploads || false,
individualCancellation : capabilities.individualCancellation,
isMobileDevice : capabilities.isMobileDevice,
pauseUpload : this.uppy.pauseResume,
retryUpload : this.uppy.retryUpload,
cancelUpload : this.cancelUpload,
cancelAll : this.uppy.cancelAll,
fileCardFor : pluginState.fileCardFor,
toggleFileCard : this.toggleFileCard,
toggleAddFilesPanel : this.toggleAddFilesPanel,
showAddFilesPanel : pluginState.showAddFilesPanel,
saveFileCard : this.saveFileCard,
openFileEditor : this.openFileEditor,
canEditFile : this.canEditFile,
width : this.opts.width,
height : this.opts.height,
showLinkToFileUploadResult : this.opts.showLinkToFileUploadResult,
fileManagerSelectionType : this.opts.fileManagerSelectionType,
proudlyDisplayPoweredByUppy : this.opts.proudlyDisplayPoweredByUppy,
hideCancelButton : this.opts.hideCancelButton,
hideRetryButton : this.opts.hideRetryButton,
hidePauseResumeButton : this.opts.hidePauseResumeButton,
showRemoveButtonAfterComplete: this.opts.showRemoveButtonAfterComplete,
containerWidth: pluginState.containerWidth,
containerHeight: pluginState.containerHeight,
areInsidesReadyToBeVisible: pluginState.areInsidesReadyToBeVisible,
isTargetDOMEl: this.isTargetDOMEl,
parentElement: this.el,
allowedFileTypes: this.uppy.opts.restrictions.allowedFileTypes,
maxNumberOfFiles: this.uppy.opts.restrictions.maxNumberOfFiles,
showSelectedFiles: this.opts.showSelectedFiles,
handleRequestThumbnail: this.handleRequestThumbnail,
handleCancelThumbnail: this.handleCancelThumbnail,
containerWidth : pluginState.containerWidth,
containerHeight : pluginState.containerHeight,
areInsidesReadyToBeVisible : pluginState.areInsidesReadyToBeVisible,
isTargetDOMEl : this.isTargetDOMEl,
parentElement : this.el,
allowedFileTypes : this.uppy.opts.restrictions.allowedFileTypes,
maxNumberOfFiles : this.uppy.opts.restrictions.maxNumberOfFiles,
showSelectedFiles : this.opts.showSelectedFiles,
handleRequestThumbnail : this.handleRequestThumbnail,
handleCancelThumbnail : this.handleCancelThumbnail,
// drag props
isDraggingOver: pluginState.isDraggingOver,
handleDragOver: this.handleDragOver,
handleDragLeave: this.handleDragLeave,
handleDrop: this.handleDrop
isDraggingOver : pluginState.isDraggingOver,
handleDragOver : this.handleDragOver,
handleDragLeave : this.handleDragLeave,
handleDrop : this.handleDrop,
})
}
@ -1028,17 +1002,17 @@ module.exports = class Dashboard extends Plugin {
install = () => {
// Set default state for Dashboard
this.setPluginState({
isHidden: true,
fileCardFor: null,
activeOverlayType: null,
showAddFilesPanel: false,
activePickerPanel: false,
showFileEditor: false,
metaFields: this.opts.metaFields,
targets: [],
isHidden : true,
fileCardFor : null,
activeOverlayType : null,
showAddFilesPanel : false,
activePickerPanel : false,
showFileEditor : false,
metaFields : this.opts.metaFields,
targets : [],
// We'll make them visible once .containerWidth is determined
areInsidesReadyToBeVisible: false,
isDraggingOver: false
isDraggingOver : false,
})
const { inline, closeAfterFinish } = this.opts
@ -1066,34 +1040,34 @@ module.exports = class Dashboard extends Plugin {
if (!this.opts.disableStatusBar) {
this.uppy.use(StatusBar, {
id: `${this.id}:StatusBar`,
target: this,
hideUploadButton: this.opts.hideUploadButton,
hideRetryButton: this.opts.hideRetryButton,
id : `${this.id}:StatusBar`,
target : this,
hideUploadButton : this.opts.hideUploadButton,
hideRetryButton : this.opts.hideRetryButton,
hidePauseResumeButton: this.opts.hidePauseResumeButton,
hideCancelButton: this.opts.hideCancelButton,
showProgressDetails: this.opts.showProgressDetails,
hideAfterFinish: this.opts.hideProgressAfterFinish,
locale: this.opts.locale,
doneButtonHandler: this.opts.doneButtonHandler
hideCancelButton : this.opts.hideCancelButton,
showProgressDetails : this.opts.showProgressDetails,
hideAfterFinish : this.opts.hideProgressAfterFinish,
locale : this.opts.locale,
doneButtonHandler : this.opts.doneButtonHandler,
})
}
if (!this.opts.disableInformer) {
this.uppy.use(Informer, {
id: `${this.id}:Informer`,
target: this
id : `${this.id}:Informer`,
target: this,
})
}
if (!this.opts.disableThumbnailGenerator) {
this.uppy.use(ThumbnailGenerator, {
id: `${this.id}:ThumbnailGenerator`,
thumbnailWidth: this.opts.thumbnailWidth,
thumbnailType: this.opts.thumbnailType,
id : `${this.id}:ThumbnailGenerator`,
thumbnailWidth : this.opts.thumbnailWidth,
thumbnailType : this.opts.thumbnailType,
waitForThumbnailsBeforeUpload: this.opts.waitForThumbnailsBeforeUpload,
// If we don't block on thumbnails, we can lazily generate them
lazy: !this.opts.waitForThumbnailsBeforeUpload
lazy : !this.opts.waitForThumbnailsBeforeUpload,
})
}

View file

@ -21,7 +21,7 @@ describe('Dashboard', () => {
expect(() => {
core.use(DashboardPlugin, {
inline: true,
target: 'body'
target: 'body',
})
}).not.toThrow()
@ -33,7 +33,7 @@ describe('Dashboard', () => {
expect(() => {
core.use(DashboardPlugin, {
inline: true,
target: 'body'
target: 'body',
})
core.use(GoogleDrivePlugin, { target: DashboardPlugin, companionUrl: 'https://fake.uppy.io/' })
}).not.toThrow()
@ -47,9 +47,9 @@ describe('Dashboard', () => {
expect(() => {
core.use(DashboardPlugin, {
inline: true,
target: 'body',
plugins: ['GoogleDrive']
inline : true,
target : 'body',
plugins: ['GoogleDrive'],
})
}).not.toThrow()
@ -60,15 +60,15 @@ describe('Dashboard', () => {
const core = new Core()
core.use(DashboardPlugin, {
inline: true,
target: 'body'
target: 'body',
})
core.getPlugin('Dashboard').setOptions({
width: 300
width: 300,
})
expect(
core.getPlugin('Dashboard').opts.width
core.getPlugin('Dashboard').opts.width,
).toEqual(300)
})
@ -76,19 +76,19 @@ describe('Dashboard', () => {
const core = new Core()
core.use(DashboardPlugin, {
inline: true,
target: 'body'
target: 'body',
})
core.setOptions({
locale: {
strings: {
myDevice: 'Май дивайс'
}
}
myDevice: 'Май дивайс',
},
},
})
expect(
core.getPlugin('Dashboard').i18n('myDevice')
core.getPlugin('Dashboard').i18n('myDevice'),
).toEqual('Май дивайс')
})
})

View file

@ -14,16 +14,16 @@ module.exports = function copyToClipboard (textToCopy, fallbackString) {
return new Promise((resolve) => {
const textArea = document.createElement('textarea')
textArea.setAttribute('style', {
position: 'fixed',
top: 0,
left: 0,
width: '2em',
height: '2em',
padding: 0,
border: 'none',
outline: 'none',
boxShadow: 'none',
background: 'transparent'
position : 'fixed',
top : 0,
left : 0,
width : '2em',
height : '2em',
padding : 0,
border : 'none',
outline : 'none',
boxShadow : 'none',
background: 'transparent',
})
textArea.value = textToCopy

View file

@ -66,7 +66,7 @@ function iconText () {
module.exports = function getIconByMime (fileType) {
const defaultChoice = {
color: '#838999',
icon: iconFile()
icon : iconFile(),
}
if (!fileType) return defaultChoice
@ -78,7 +78,7 @@ module.exports = function getIconByMime (fileType) {
if (fileTypeGeneral === 'text') {
return {
color: '#5a5e69',
icon: iconText()
icon : iconText(),
}
}
@ -86,7 +86,7 @@ module.exports = function getIconByMime (fileType) {
if (fileTypeGeneral === 'image') {
return {
color: '#686de0',
icon: iconImage()
icon : iconImage(),
}
}
@ -94,7 +94,7 @@ module.exports = function getIconByMime (fileType) {
if (fileTypeGeneral === 'audio') {
return {
color: '#068dbb',
icon: iconAudio()
icon : iconAudio(),
}
}
@ -102,7 +102,7 @@ module.exports = function getIconByMime (fileType) {
if (fileTypeGeneral === 'video') {
return {
color: '#19af67',
icon: iconVideo()
icon : iconVideo(),
}
}
@ -110,7 +110,7 @@ module.exports = function getIconByMime (fileType) {
if (fileTypeGeneral === 'application' && fileTypeSpecific === 'pdf') {
return {
color: '#e25149',
icon: iconPDF()
icon : iconPDF(),
}
}
@ -119,7 +119,7 @@ module.exports = function getIconByMime (fileType) {
if (fileTypeGeneral === 'application' && archiveTypes.indexOf(fileTypeSpecific) !== -1) {
return {
color: '#00C469',
icon: iconArchive()
icon : iconArchive(),
}
}

View file

@ -5,8 +5,8 @@
function ignoreEvent (ev) {
const tagName = ev.target.tagName
if (tagName === 'INPUT' ||
tagName === 'TEXTAREA') {
if (tagName === 'INPUT'
|| tagName === 'TEXTAREA') {
ev.stopPropagation()
return
}

View file

@ -61,5 +61,5 @@ module.exports = {
// User can close the overlay (click 'Done') if they want to travel away from Uppy.
trapFocus(event, activeOverlayType, dashboardEl)
}
}
},
}

View file

@ -21,17 +21,17 @@ module.exports = class DragDrop extends Plugin {
this.defaultLocale = {
strings: {
dropHereOr: 'Drop files here or %{browse}',
browse: 'browse'
}
browse : 'browse',
},
}
// Default options
const defaultOpts = {
target: null,
target : null,
inputName: 'files[]',
width: '100%',
height: '100%',
note: null
width : '100%',
height : '100%',
note : null,
}
// Merge default options with the ones set by user
@ -67,14 +67,14 @@ module.exports = class DragDrop extends Plugin {
addFiles (files) {
const descriptors = files.map((file) => ({
source: this.id,
name: file.name,
type: file.type,
data: file,
meta: {
name : file.name,
type : file.type,
data : file,
meta : {
// path of the file relative to the ancestor directory the user selected.
// e.g. 'docs/Old Prague/airbnb.pdf'
relativePath: file.relativePath || null
}
relativePath: file.relativePath || null,
},
}))
try {
@ -166,7 +166,7 @@ module.exports = class DragDrop extends Plugin {
return (
<div class="uppy-DragDrop-label">
{this.i18nArray('dropHereOr', {
browse: <span class="uppy-DragDrop-browse">{this.i18n('browse')}</span>
browse: <span class="uppy-DragDrop-browse">{this.i18n('browse')}</span>,
})}
</div>
)
@ -187,8 +187,8 @@ module.exports = class DragDrop extends Plugin {
`
const dragDropStyle = {
width: this.opts.width,
height: this.opts.height
width : this.opts.width,
height: this.opts.height,
}
return (
@ -213,7 +213,7 @@ module.exports = class DragDrop extends Plugin {
install () {
this.setPluginState({
isDraggingOver: false
isDraggingOver: false,
})
const target = this.opts.target
if (target) {

View file

@ -21,12 +21,12 @@ module.exports = class Dropbox extends Plugin {
)
this.provider = new Provider(uppy, {
companionUrl: this.opts.companionUrl,
companionHeaders: this.opts.companionHeaders || this.opts.serverHeaders,
companionKeysParams: this.opts.companionKeysParams,
companionUrl : this.opts.companionUrl,
companionHeaders : this.opts.companionHeaders || this.opts.serverHeaders,
companionKeysParams : this.opts.companionKeysParams,
companionCookiesRule: this.opts.companionCookiesRule,
provider: 'dropbox',
pluginId: this.id
provider : 'dropbox',
pluginId : this.id,
})
this.onFirstRender = this.onFirstRender.bind(this)
@ -35,7 +35,7 @@ module.exports = class Dropbox extends Plugin {
install () {
this.view = new ProviderViews(this, {
provider: this.provider
provider: this.provider,
})
const target = this.opts.target
@ -52,7 +52,7 @@ module.exports = class Dropbox extends Plugin {
onFirstRender () {
return Promise.all([
this.provider.fetchPreAuthToken(),
this.view.getFolder()
this.view.getFolder(),
])
}

View file

@ -21,12 +21,12 @@ module.exports = class Facebook extends Plugin {
)
this.provider = new Provider(uppy, {
companionUrl: this.opts.companionUrl,
companionHeaders: this.opts.companionHeaders || this.opts.serverHeaders,
companionKeysParams: this.opts.companionKeysParams,
companionUrl : this.opts.companionUrl,
companionHeaders : this.opts.companionHeaders || this.opts.serverHeaders,
companionKeysParams : this.opts.companionKeysParams,
companionCookiesRule: this.opts.companionCookiesRule,
provider: 'facebook',
pluginId: this.id
provider : 'facebook',
pluginId : this.id,
})
this.onFirstRender = this.onFirstRender.bind(this)
@ -35,7 +35,7 @@ module.exports = class Facebook extends Plugin {
install () {
this.view = new ProviderViews(this, {
provider: this.provider
provider: this.provider,
})
const target = this.opts.target
@ -52,7 +52,7 @@ module.exports = class Facebook extends Plugin {
onFirstRender () {
return Promise.all([
this.provider.fetchPreAuthToken(),
this.view.getFolder()
this.view.getFolder(),
])
}

View file

@ -17,15 +17,15 @@ module.exports = class FileInput extends Plugin {
// The same key is used for the same purpose by @uppy/robodog's `form()` API, but our
// locale pack scripts can't access it in Robodog. If it is updated here, it should
// also be updated there!
chooseFiles: 'Choose files'
}
chooseFiles: 'Choose files',
},
}
// Default options
const defaultOptions = {
target: null,
pretty: true,
inputName: 'files[]'
target : null,
pretty : true,
inputName: 'files[]',
}
// Merge default options with the ones set by user
@ -53,9 +53,9 @@ module.exports = class FileInput extends Plugin {
addFiles (files) {
const descriptors = files.map((file) => ({
source: this.id,
name: file.name,
type: file.type,
data: file
name : file.name,
type : file.type,
data : file,
}))
try {
@ -86,12 +86,12 @@ module.exports = class FileInput extends Plugin {
render (state) {
/* http://tympanus.net/codrops/2015/09/15/styling-customizing-file-inputs-smart-way/ */
const hiddenInputStyle = {
width: '0.1px',
height: '0.1px',
opacity: 0,
width : '0.1px',
height : '0.1px',
opacity : 0,
overflow: 'hidden',
position: 'absolute',
zIndex: -1
zIndex : -1,
}
const restrictions = this.uppy.opts.restrictions
@ -109,8 +109,8 @@ module.exports = class FileInput extends Plugin {
accept={accept}
ref={(input) => { this.input = input }}
/>
{this.opts.pretty &&
<button
{this.opts.pretty
&& <button
class="uppy-FileInput-btn"
type="button"
onclick={this.handleClick}

View file

@ -19,13 +19,13 @@ module.exports = class Form extends Plugin {
// set default options
const defaultOptions = {
target: null,
resultName: 'uppyResult',
getMetaFromForm: true,
addResultToForm: true,
multipleResults: false,
submitOnSuccess: false,
triggerUploadOnSubmit: false
target : null,
resultName : 'uppyResult',
getMetaFromForm : true,
addResultToForm : true,
multipleResults : false,
submitOnSuccess : false,
triggerUploadOnSubmit: false,
}
// merge default options with the ones set by user

View file

@ -1,6 +1,7 @@
const prettierBytes = require('@transloadit/prettier-bytes')
const indexedDB = typeof window !== 'undefined' &&
(window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB)
const indexedDB = typeof window !== 'undefined'
&& (window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB)
const isSupported = !!indexedDB
@ -67,19 +68,18 @@ function waitForRequest (request) {
let cleanedUp = false
class IndexedDBStore {
constructor (opts) {
this.opts = Object.assign({
dbName: DB_NAME,
storeName: 'default',
expires: DEFAULT_EXPIRY, // 24 hours
maxFileSize: 10 * 1024 * 1024, // 10 MB
maxTotalSize: 300 * 1024 * 1024 // 300 MB
}, opts)
this.opts = {
dbName : DB_NAME,
storeName : 'default',
expires : DEFAULT_EXPIRY, // 24 hours
maxFileSize : 10 * 1024 * 1024, // 10 MB
maxTotalSize: 300 * 1024 * 1024, // 300 MB
...opts,
}
this.name = this.opts.storeName
const createConnection = () => {
return connect(this.opts.dbName)
}
const createConnection = () => connect(this.opts.dbName)
if (!cleanedUp) {
cleanedUp = true
@ -123,8 +123,8 @@ class IndexedDBStore {
.get(this.key(fileID))
return waitForRequest(request)
}).then((result) => ({
id: result.data.fileID,
data: result.data.data
id : result.data.fileID,
data: result.data.data,
}))
}
@ -172,11 +172,11 @@ class IndexedDBStore {
}).then((db) => {
const transaction = db.transaction([STORE_NAME], 'readwrite')
const request = transaction.objectStore(STORE_NAME).add({
id: this.key(file.id),
fileID: file.id,
store: this.name,
id : this.key(file.id),
fileID : file.id,
store : this.name,
expires: Date.now() + this.opts.expires,
data: file.data
data : file.data,
})
return waitForRequest(request)
})
@ -212,7 +212,8 @@ class IndexedDBStore {
console.log(
'[IndexedDBStore] Deleting record', entry.fileID,
'of size', prettierBytes(entry.data.size),
'- expired on', new Date(entry.expires))
'- expired on', new Date(entry.expires),
)
cursor.delete() // Ignoring return value … it's not terrible if this goes wrong.
cursor.continue()
} else {

View file

@ -26,9 +26,10 @@ function maybeParse (str) {
let cleanedUp = false
module.exports = class MetaDataStore {
constructor (opts) {
this.opts = Object.assign({
expires: 24 * 60 * 60 * 1000 // 24 hours
}, opts)
this.opts = {
expires: 24 * 60 * 60 * 1000, // 24 hours
...opts,
}
this.name = `uppyState:${opts.storeName}`
if (!cleanedUp) {
@ -60,7 +61,7 @@ module.exports = class MetaDataStore {
const expires = Date.now() + this.opts.expires
const state = JSON.stringify({
metadata,
expires
expires,
})
localStorage.setItem(this.name, state)
}

View file

@ -40,9 +40,9 @@ function removeFile (store, fileID) {
function getFiles (store) {
sendMessageToAllClients({
type: 'uppy/ALL_FILES',
store: store,
files: getCache(store)
type : 'uppy/ALL_FILES',
store,
files: getCache(store),
})
}

View file

@ -20,24 +20,25 @@ module.exports = class GoldenRetriever extends Plugin {
this.title = 'Golden Retriever'
const defaultOptions = {
expires: 24 * 60 * 60 * 1000, // 24 hours
serviceWorker: false
expires : 24 * 60 * 60 * 1000, // 24 hours
serviceWorker: false,
}
this.opts = Object.assign({}, defaultOptions, opts)
this.opts = { ...defaultOptions, ...opts }
this.MetaDataStore = new MetaDataStore({
expires: this.opts.expires,
storeName: uppy.getID()
expires : this.opts.expires,
storeName: uppy.getID(),
})
this.ServiceWorkerStore = null
if (this.opts.serviceWorker) {
this.ServiceWorkerStore = new ServiceWorkerStore({ storeName: uppy.getID() })
}
this.IndexedDBStore = new IndexedDBStore(Object.assign(
{ expires: this.opts.expires },
this.opts.indexedDB || {},
{ storeName: uppy.getID() }))
this.IndexedDBStore = new IndexedDBStore({
expires : this.opts.expires,
...this.opts.indexedDB || {},
storeName: uppy.getID(),
})
this.saveFilesStateToLocalStorage = this.saveFilesStateToLocalStorage.bind(this)
this.loadFilesStateFromLocalStorage = this.loadFilesStateFromLocalStorage.bind(this)
@ -53,7 +54,7 @@ module.exports = class GoldenRetriever extends Plugin {
this.uppy.log('[GoldenRetriever] Recovered some state from Local Storage')
this.uppy.setState({
currentUploads: savedState.currentUploads || {},
files: savedState.files || {}
files : savedState.files || {},
})
this.savedPluginData = savedState.pluginData
@ -101,7 +102,7 @@ module.exports = class GoldenRetriever extends Plugin {
saveFilesStateToLocalStorage () {
const filesToSave = Object.assign(
this.getWaitingFiles(),
this.getUploadingFiles()
this.getUploadingFiles(),
)
const pluginData = {}
@ -114,9 +115,9 @@ module.exports = class GoldenRetriever extends Plugin {
const { currentUploads } = this.uppy.getState()
this.MetaDataStore.save({
currentUploads: currentUploads,
currentUploads,
files: filesToSave,
pluginData: pluginData
pluginData,
})
}
@ -155,7 +156,7 @@ module.exports = class GoldenRetriever extends Plugin {
onBlobsLoaded (blobs) {
const obsoleteBlobs = []
const updatedFiles = Object.assign({}, this.uppy.getState().files)
const updatedFiles = { ...this.uppy.getState().files }
Object.keys(blobs).forEach((fileID) => {
const originalFile = this.uppy.getFile(fileID)
if (!originalFile) {
@ -166,15 +167,15 @@ module.exports = class GoldenRetriever extends Plugin {
const cachedData = blobs[fileID]
const updatedFileData = {
data: cachedData,
isRestored: true
data : cachedData,
isRestored: true,
}
const updatedFile = Object.assign({}, originalFile, updatedFileData)
const updatedFile = { ...originalFile, ...updatedFileData }
updatedFiles[fileID] = updatedFile
})
this.uppy.setState({
files: updatedFiles
files: updatedFiles,
})
this.uppy.emit('restored', this.savedPluginData)

View file

@ -22,12 +22,12 @@ module.exports = class GoogleDrive extends Plugin {
)
this.provider = new Provider(uppy, {
companionUrl: this.opts.companionUrl,
companionHeaders: this.opts.companionHeaders || this.opts.serverHeaders,
companionKeysParams: this.opts.companionKeysParams,
companionUrl : this.opts.companionUrl,
companionHeaders : this.opts.companionHeaders || this.opts.serverHeaders,
companionKeysParams : this.opts.companionKeysParams,
companionCookiesRule: this.opts.companionCookiesRule,
provider: 'drive',
pluginId: this.id
provider : 'drive',
pluginId : this.id,
})
this.onFirstRender = this.onFirstRender.bind(this)
@ -36,7 +36,7 @@ module.exports = class GoogleDrive extends Plugin {
install () {
this.view = new DriveProviderViews(this, {
provider: this.provider
provider: this.provider,
})
const target = this.opts.target
@ -53,7 +53,7 @@ module.exports = class GoogleDrive extends Plugin {
onFirstRender () {
return Promise.all([
this.provider.fetchPreAuthToken(),
this.view.getFolder('root', '/')
this.view.getFolder('root', '/'),
])
}

Some files were not shown because too many files have changed in this diff Show more