1
0
mirror of https://github.com/ascribe/onion.git synced 2024-12-22 09:23:13 +01:00

Merge with master

This commit is contained in:
Brett Sun 2016-02-08 14:08:54 +01:00
commit 8fce04125f
197 changed files with 7046 additions and 3319 deletions

3
.env-template Normal file
View File

@ -0,0 +1,3 @@
SAUCE_USERNAME=ascribe
SAUCE_ACCESS_KEY=
SAUCE_DEFAULT_URL=

View File

@ -2,7 +2,7 @@
"parser": "babel-eslint",
"env": {
"browser": true,
"es6": true
"es6": true,
},
"rules": {
"new-cap": [2, {newIsCap: true, capIsNew: false}],

11
.gitignore vendored
View File

@ -16,9 +16,14 @@ webapp-dependencies.txt
pids
logs
results
build/*
gemini-coverage/*
gemini-report/*
test/gemini/screenshots/*
node_modules/*
build
.DS_Store
.env

View File

@ -1,18 +1,19 @@
Introduction
============
Onion is the web client for Ascribe. The idea is to have a well documented,
easy to test, easy to hack, JavaScript application.
Onion is the web client for Ascribe. The idea is to have a well documented, modern, easy to test, easy to hack, JavaScript application.
The code is JavaScript ECMA 6.
The code is JavaScript 2015 / ECMAScript 6.
Getting started
===============
Install some nice extension for Chrom(e|ium):
- [React Developer Tools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi)
- [Alt Developer Tools](https://github.com/goatslacker/alt-devtool)
```bash
git clone git@github.com:ascribe/onion.git
cd onion
@ -32,48 +33,69 @@ Additionally, to work on the white labeling functionality, you need to edit your
127.0.0.1 lumenus.localhost.com
127.0.0.1 portfolioreview.localhost.com
127.0.0.1 23vivi.localhost.com
127.0.0.1 polline.localhost.com
127.0.0.1 artcity.localhost.com
```
JavaScript Code Conventions
===========================
For this project, we're using:
* 4 Spaces
* We use ES6
* ES6
* We don't use ES6's class declaration for React components because it does not support Mixins as well as Autobinding ([Blog post about it](http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding))
* We don't use camel case for file naming but in everything Javascript related
* We use `let` instead of `var`: [SA Post](http://stackoverflow.com/questions/762011/javascript-let-keyword-vs-var-keyword)
* We don't use Javascript's `Date` object, as its interface introduced bugs previously and we're including `momentjs` for other dependencies anyways
* We use `momentjs` instead of Javascript's `Date` object, as the native `Date` interface previously introduced bugs and we're including `momentjs` for other dependencies anyway
Branch names
=====================
Since we moved to Github, we cannot create branch names automatically with JIRA anymore.
To not lose context, but still be able to switch branches quickly using a ticket's number, we're recommending the following rules when naming our branches in onion.
Make sure to check out the [style guide](https://github.com/ascribe/javascript).
```
AD-<JIRA-ticket-id>-brief-and-sane-description-of-the-ticket
```
Linting
-------
where `brief-and-sane-description-of-the-ticket` does not need to equal to the ticket's title.
This allows JIRA to still track branches and pull-requests while allowing us to keep our peace of mind.
We use [ESLint](https://github.com/eslint/eslint) with our own [custom ruleset](.eslintrc).
Example
-------------
**JIRA ticket name:** `AD-1242 - Frontend caching for simple endpoints to measure perceived page load <more useless information>`
**Github branch name:** `AD-1242-caching-solution-for-stores`
SCSS Code Conventions
=====================
Install [lint-scss](https://github.com/brigade/scss-lint), check the [editor integration docs](https://github.com/brigade/scss-lint#editor-integration) to integrate the lint in your editor.
Some interesting links:
* [Improving Sass code quality on theguardian.com](https://www.theguardian.com/info/developer-blog/2014/may/13/improving-sass-code-quality-on-theguardiancom)
Branch names
============
To allow Github and JIRA to track branches while still allowing us to switch branches quickly using a ticket's number (and keep our peace of mind), we have the following rules for naming branches:
```
// For issues logged in Github:
AG-<Github-issue-id>-brief-and-sane-description-of-the-ticket
// For issues logged in JIRA:
AD-<JIRA-ticket-id>-brief-and-sane-description-of-the-ticket
```
where `brief-and-sane-description-of-the-ticket` does not need to equal to the issue or ticket's title.
Example
-------
**JIRA ticket name:** `AD-1242 - Frontend caching for simple endpoints to measure perceived page load <more useless information>`
**Github branch name:** `AD-1242-caching-solution-for-stores`
Testing
===============
=======
Unit Testing
------------
We're using Facebook's jest to do testing as it integrates nicely with react.js as well.
Tests are always created per directory by creating a `__tests__` folder. To test a specific file, a `<file_name>_tests.js` file needs to be created.
@ -83,7 +105,24 @@ This is due to the fact that jest's function mocking and ES6 module syntax are [
Therefore, to require a module in your test file, you need to use CommonJS's `require` syntax. Except for this, all tests can be written in ES6 syntax.
## Workflow
Visual Regression Testing
-------------------------
We're using [Gemini](https://github.com/gemini-testing/gemini) for visual regression tests because it supports both PhantomJS2 and SauceLabs.
See the [helper docs](test/gemini/README.md) for information on installing Gemini, its dependencies, and running and writing tests.
Integration Testing
-------------------
We're using [Sauce Labs](https://saucelabs.com/home) with [WD.js](https://github.com/admc/wd) for integration testing across browser grids with Selenium.
See the [helper docs](test/integration/README.md) for information on each part of the test stack and how to run and write tests.
Workflow
========
Generally, when you're runing `gulp serve`, all tests are being run.
If you want to test exclusively (without having the obnoxious ES6Linter warnings), you can just run `gulp jest:watch`.
@ -134,9 +173,16 @@ A: Easily by starting the your gulp process with the following command:
ONION_BASE_URL='/' ONION_SERVER_URL='http://localhost.com:8000/' gulp serve
```
Or, by adding these two your environment variables:
```
ONION_BASE_URL='/'
ONION_SERVER_URL='http://localhost.com:8000/'
```
Q: I want to know all dependencies that get bundled into the live build.
A: ```browserify -e js/app.js --list > webapp-dependencies.txt```
Reading list
============
@ -149,7 +195,6 @@ Start here
- [alt.js](http://alt.js.org/)
- [alt.js readme](https://github.com/goatslacker/alt)
Moar stuff
----------

View File

@ -97,7 +97,8 @@ gulp.task('browser-sync', function() {
proxy: 'http://localhost:4000',
port: 3000,
open: false, // does not open the browser-window anymore (handled manually)
ghostMode: false
ghostMode: false,
notify: false // stop showing the browsersync pop up
});
});

View File

@ -28,12 +28,10 @@ class ContractListActions {
}
changeContract(contract){
changeContract(contract) {
return Q.Promise((resolve, reject) => {
OwnershipFetcher.changeContract(contract)
.then((res) => {
resolve(res);
})
.then(resolve)
.catch((err)=> {
console.logGlobal(err);
reject(err);
@ -41,13 +39,11 @@ class ContractListActions {
});
}
removeContract(contractId){
return Q.Promise( (resolve, reject) => {
removeContract(contractId) {
return Q.Promise((resolve, reject) => {
OwnershipFetcher.deleteContract(contractId)
.then((res) => {
resolve(res);
})
.catch( (err) => {
.then(resolve)
.catch((err) => {
console.logGlobal(err);
reject(err);
});

View File

@ -39,7 +39,7 @@ class EditionListActions {
return Q.Promise((resolve, reject) => {
EditionListFetcher
.fetch({ pieceId, page, itemsToFetch, orderBy, orderAsc, filterBy })
.fetch({ pieceId, page, orderBy, orderAsc, filterBy, pageSize: itemsToFetch })
.then((res) => {
if (res && !res.editions) {
throw new Error('Piece has no editions to fetch.');

View File

@ -0,0 +1,13 @@
'use strict';
import { alt } from '../alt';
class ErrorQueueActions {
constructor() {
this.generateActions(
'shiftErrorQueue'
);
}
}
export default alt.createActions(ErrorQueueActions);

View File

@ -8,9 +8,8 @@ class EventActions {
this.generateActions(
'applicationWillBoot',
'applicationDidBoot',
'profileDidLoad',
//'userDidLogin',
//'userDidLogout',
'userDidAuthenticate',
'userDidLogout',
'routeDidChange'
);
}

View File

@ -0,0 +1,14 @@
'use strict';
import { altThirdParty } from '../alt';
class FacebookActions {
constructor() {
this.generateActions(
'sdkReady'
);
}
}
export default altThirdParty.createActions(FacebookActions);

View File

@ -1,34 +0,0 @@
'use strict';
import { alt } from '../alt';
import Q from 'q';
import PrizeListFetcher from '../fetchers/prize_list_fetcher';
class PrizeListActions {
constructor() {
this.generateActions(
'updatePrizeList'
);
}
fetchPrizeList() {
return Q.Promise((resolve, reject) => {
PrizeListFetcher
.fetch()
.then((res) => {
this.actions.updatePrizeList({
prizeList: res.prizes,
prizeListCount: res.count
});
resolve(res);
})
.catch((err) => {
console.logGlobal(err);
reject(err);
});
});
}
}
export default alt.createActions(PrizeListActions);

View File

@ -1,6 +1,6 @@
'use strict';
import { altUser } from '../alt';
import { alt } from '../alt';
class UserActions {
@ -15,4 +15,4 @@ class UserActions {
}
}
export default altUser.createActions(UserActions);
export default alt.createActions(UserActions);

View File

@ -4,5 +4,4 @@ import Alt from 'alt';
export let alt = new Alt();
export let altThirdParty = new Alt();
export let altUser = new Alt();
export let altWhitelabel = new Alt();

View File

@ -7,9 +7,7 @@ import React from 'react';
import { Router, Redirect } from 'react-router';
import history from './history';
/* eslint-disable */
import fetch from 'isomorphic-fetch';
/* eslint-enable */
import ApiUrls from './constants/api_urls';
@ -18,44 +16,27 @@ import getRoutes from './routes';
import requests from './utils/requests';
import { updateApiUrls } from './constants/api_urls';
import { getSubdomainSettings } from './utils/constants_utils';
import { getDefaultSubdomainSettings, getSubdomainSettings } from './utils/constants_utils';
import { initLogging } from './utils/error_utils';
import { getSubdomain } from './utils/general_utils';
import EventActions from './actions/event_actions';
/* eslint-disable */
// You can comment out the modules you don't need
// import DebugHandler from './third_party/debug';
import GoogleAnalyticsHandler from './third_party/ga';
import RavenHandler from './third_party/raven';
import IntercomHandler from './third_party/intercom';
import NotificationsHandler from './third_party/notifications';
import FacebookHandler from './third_party/facebook';
/* eslint-enable */
// import DebugHandler from './third_party/debug_handler';
import FacebookHandler from './third_party/facebook_handler';
import GoogleAnalyticsHandler from './third_party/ga_handler';
import IntercomHandler from './third_party/intercom_handler';
import NotificationsHandler from './third_party/notifications_handler';
import RavenHandler from './third_party/raven_handler';
initLogging();
let headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
requests.defaults({
urlMap: ApiUrls,
http: {
headers: headers,
credentials: 'include'
}
});
class AppGateway {
const AppGateway = {
start() {
let settings;
let subdomain = getSubdomain();
try {
settings = getSubdomainSettings(subdomain);
const subdomain = getSubdomain();
const settings = getSubdomainSettings(subdomain);
AppConstants.whitelabel = settings;
updateApiUrls(settings.type, subdomain);
this.load(settings);
@ -63,28 +44,25 @@ class AppGateway {
// if there are no matching subdomains, we're routing
// to the default frontend
console.logGlobal(err);
this.load();
this.load(getDefaultSubdomainSettings());
}
}
},
load(settings) {
let type = 'default';
let subdomain = 'www';
const { subdomain, type } = settings;
let redirectRoute = (<Redirect from="/" to="/collection" />);
if (settings) {
type = settings.type;
subdomain = settings.subdomain;
}
if (subdomain) {
// Some whitelabels have landing pages so we should not automatically redirect from / to /collection.
// Only www and cc do not have a landing page.
if (subdomain !== 'cc') {
redirectRoute = null;
}
// www and cc do not have a landing page
if(subdomain && subdomain !== 'cc') {
redirectRoute = null;
// Adds a client specific class to the body for whitelabel styling
window.document.body.classList.add('client--' + subdomain);
}
// Adds a client specific class to the body for whitelabel styling
window.document.body.classList.add('client--' + subdomain);
// Send the applicationWillBoot event to the third-party stores
EventActions.applicationWillBoot(settings);
@ -102,8 +80,21 @@ class AppGateway {
// Send the applicationDidBoot event to the third-party stores
EventActions.applicationDidBoot(settings);
}
}
};
let ag = new AppGateway();
ag.start();
// Initialize pre-start components
initLogging();
requests.defaults({
urlMap: ApiUrls,
http: {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
credentials: 'include'
}
});
// And bootstrap app
AppGateway.start();

90
js/components/app_base.js Normal file
View File

@ -0,0 +1,90 @@
'use strict';
import React from 'react';
import classNames from 'classnames';
import { History } from 'react-router';
import UserActions from '../actions/user_actions';
import UserStore from '../stores/user_store';
import WhitelabelActions from '../actions/whitelabel_actions';
import WhitelabelStore from '../stores/whitelabel_store';
import GlobalNotification from './global_notification';
import AppConstants from '../constants/application_constants';
import { mergeOptions } from '../utils/general_utils';
export default function AppBase(App) {
return React.createClass({
displayName: 'AppBase',
propTypes: {
children: React.PropTypes.element.isRequired,
history: React.PropTypes.object.isRequired,
location: React.PropTypes.object.isRequired,
routes: React.PropTypes.arrayOf(React.PropTypes.object).isRequired
},
getInitialState() {
return mergeOptions(
UserStore.getState(),
WhitelabelStore.getState()
);
},
mixins: [History],
componentDidMount() {
UserStore.listen(this.onChange);
WhitelabelStore.listen(this.onChange);
UserActions.fetchCurrentUser();
WhitelabelActions.fetchWhitelabel();
this.history.locationQueue.push(this.props.location);
},
componentWillReceiveProps(nextProps) {
const { locationQueue } = this.history;
locationQueue.unshift(nextProps.location);
// Limit the number of locations to keep in memory to avoid too much memory usage
if (locationQueue.length > AppConstants.locationThreshold) {
locationQueue.length = AppConstants.locationThreshold;
}
},
componentWillUnmount() {
UserStore.unlisten(this.onChange);
WhitelabelActions.unlisten(this.onChange);
},
onChange(state) {
this.setState(state);
},
render() {
const { routes } = this.props;
const { currentUser, whitelabel } = this.state;
// The second element of the routes prop given to us by react-router is always the
// active second-level component object (ie. after App).
const activeRoute = routes[1];
return (
<div>
<App
{...this.props}
activeRoute={activeRoute}
currentUser={currentUser}
whitelabel={whitelabel} />
<GlobalNotification />
<div id="modal" className="container" />
</div>
);
}
});
};

View File

@ -0,0 +1,34 @@
'use strict';
import React from 'react';
import { omitFromObject } from '../utils/general_utils';
const AppRouteWrapper = React.createClass({
propTypes: {
children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element),
React.PropTypes.element
]).isRequired
},
render() {
const propsToPropagate = omitFromObject(this.props, ['children']);
let childrenWithProps = this.props.children;
// If there are more props given, propagate them into the child routes by cloning the routes
if (Object.keys(propsToPropagate).length) {
childrenWithProps = React.Children.map(this.props.children, (child) => {
return React.cloneElement(child, propsToPropagate);
});
}
return (
<div className="container ascribe-body">
{childrenWithProps}
</div>
);
}
});
export default AppRouteWrapper;

View File

@ -1,14 +1,17 @@
'use strict';
import React from 'react';
import { Link } from 'react-router';
import { getLangText } from '../../utils/lang_utils';
let AccordionList = React.createClass({
propTypes: {
className: React.PropTypes.string,
children: React.PropTypes.arrayOf(React.PropTypes.element).isRequired,
loadingElement: React.PropTypes.element,
loadingElement: React.PropTypes.element.isRequired,
className: React.PropTypes.string,
count: React.PropTypes.number,
itemList: React.PropTypes.arrayOf(React.PropTypes.object),
search: React.PropTypes.string,
@ -22,7 +25,7 @@ let AccordionList = React.createClass({
render() {
const { search } = this.props;
if(this.props.itemList && this.props.itemList.length > 0) {
if (this.props.itemList && this.props.itemList.length > 0) {
return (
<div className={this.props.className}>
{this.props.children}
@ -36,7 +39,7 @@ let AccordionList = React.createClass({
</p>
<p className="text-center">
{getLangText('To register one, click')}&nbsp;
<a href="register_piece">{getLangText('here')}</a>!
<Link to="/register_piece">{getLangText('here')}</Link>!
</p>
</div>
);

View File

@ -21,16 +21,15 @@ let AccordionListItem = React.createClass({
},
render() {
const { linkData,
const { badge,
buttons,
children,
className,
thumbnail,
heading,
linkData,
subheading,
subsubheading,
buttons,
badge,
children } = this.props;
thumbnail } = this.props;
return (
<div className="row">

View File

@ -34,11 +34,10 @@ let AccordionListItemPiece = React.createClass({
},
getLinkData() {
let { piece } = this.props;
const { piece } = this.props;
if(piece && piece.first_edition) {
if (piece && piece.first_edition) {
return `/editions/${piece.first_edition.bitcoin_id}`;
} else {
return `/pieces/${piece.id}`;
}

View File

@ -1,4 +1,4 @@
'use strict'
'use strict';
import React from 'react';

View File

@ -7,20 +7,19 @@ import Glyphicon from 'react-bootstrap/lib/Glyphicon';
import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger';
import Tooltip from 'react-bootstrap/lib/Tooltip';
import AccordionListItemPiece from './accordion_list_item_piece';
import AccordionListItemEditionWidget from './accordion_list_item_edition_widget';
import CreateEditionsForm from '../ascribe_forms/create_editions_form';
import PieceListActions from '../../actions/piece_list_actions';
import PieceListStore from '../../stores/piece_list_store';
import WhitelabelStore from '../../stores/whitelabel_store';
import EditionListActions from '../../actions/edition_list_actions';
import GlobalNotificationModel from '../../models/global_notification_model';
import GlobalNotificationActions from '../../actions/global_notification_actions';
import PieceListActions from '../../actions/piece_list_actions';
import PieceListStore from '../../stores/piece_list_store';
import AccordionListItemPiece from './accordion_list_item_piece';
import AccordionListItemEditionWidget from './accordion_list_item_edition_widget';
import CreateEditionsForm from '../ascribe_forms/create_editions_form';
import AclProxy from '../acl_proxy';
import { getLangText } from '../../utils/lang_utils';
@ -29,50 +28,51 @@ import { mergeOptions } from '../../utils/general_utils';
let AccordionListItemWallet = React.createClass({
propTypes: {
className: React.PropTypes.string,
content: React.PropTypes.object,
thumbnailPlaceholder: React.PropTypes.func,
content: React.PropTypes.object.isRequired,
whitelabel: React.PropTypes.object.isRequired,
children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element),
React.PropTypes.element
])
]),
className: React.PropTypes.string,
thumbnailPlaceholder: React.PropTypes.func
},
getInitialState() {
return mergeOptions(
PieceListStore.getState(),
{
showCreateEditionsDialog: false
},
PieceListStore.getState(),
WhitelabelStore.getState()
}
);
},
componentDidMount() {
PieceListStore.listen(this.onChange);
WhitelabelStore.listen(this.onChange);
},
componentWillUnmount() {
PieceListStore.unlisten(this.onChange);
WhitelabelStore.unlisten(this.onChange);
},
onChange(state) {
this.setState(state);
},
getGlyphicon(){
if ((this.props.content.notifications && this.props.content.notifications.length > 0)){
getGlyphicon() {
if (this.props.content.notifications && this.props.content.notifications.length) {
return (
<OverlayTrigger
delay={500}
placement="left"
overlay={<Tooltip>{getLangText('You have actions pending')}</Tooltip>}>
<Glyphicon glyph='bell' color="green"/>
</OverlayTrigger>);
<Glyphicon glyph='bell' color="green" />
</OverlayTrigger>
);
} else {
return null;
}
return null;
},
toggleCreateEditionsDialog() {
@ -93,7 +93,7 @@ let AccordionListItemWallet = React.createClass({
PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
EditionListActions.toggleEditionList(pieceId);
const notification = new GlobalNotificationModel('Editions successfully created', 'success', 10000);
const notification = new GlobalNotificationModel(getLangText('Editions successfully created'), 'success', 10000);
GlobalNotificationActions.appendGlobalNotification(notification);
},
@ -111,13 +111,15 @@ let AccordionListItemWallet = React.createClass({
},
getLicences() {
const { content, whitelabel } = this.props;
// convert this to acl_view_licences later
if (this.state.whitelabel && this.state.whitelabel.name === 'Creative Commons France') {
if (whitelabel.name === 'Creative Commons France') {
return (
<span>
<span>, </span>
<a href={this.props.content.license_type.url} target="_blank">
{getLangText('%s license', this.props.content.license_type.code)}
<a href={content.license_type.url} target="_blank">
{getLangText('%s license', content.license_type.code)}
</a>
</span>
);

View File

@ -2,36 +2,42 @@
import React from 'react';
import Header from '../components/header';
import Footer from '../components/footer';
import GlobalNotification from './global_notification';
import AppBase from './app_base';
import AppRouteWrapper from './app_route_wrapper';
import Footer from './footer';
import Header from './header';
let AscribeApp = React.createClass({
propTypes: {
children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element),
React.PropTypes.element
]),
routes: React.PropTypes.arrayOf(React.PropTypes.object)
activeRoute: React.PropTypes.object.isRequired,
children: React.PropTypes.element.isRequired,
routes: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
// Provided from AppBase
currentUser: React.PropTypes.object,
whitelabel: React.PropTypes.object
},
render() {
let { children, routes } = this.props;
const { activeRoute, children, currentUser, routes, whitelabel } = this.props;
return (
<div className="container ascribe-default-app">
<Header routes={routes} />
{/* Routes are injected here */}
<div className="ascribe-body">
<div className="ascribe-app ascribe-default-app">
<Header
currentUser={currentUser}
routes={routes}
whitelabel={whitelabel} />
<AppRouteWrapper
currentUser={currentUser}
whitelabel={whitelabel}>
{/* Routes are injected here */}
{children}
</div>
<Footer />
<GlobalNotification />
<div id="modal" className="container"></div>
</AppRouteWrapper>
<Footer activeRoute={activeRoute} />
</div>
);
}
});
export default AscribeApp;
export default AppBase(AscribeApp);

View File

@ -2,9 +2,6 @@
import React from 'react/addons';
import UserActions from '../../actions/user_actions';
import UserStore from '../../stores/user_store';
import ConsignButton from './acls/consign_button';
import EmailButton from './acls/email_button';
import LoanButton from './acls/loan_button';
@ -12,50 +9,44 @@ import LoanRequestButton from './acls/loan_request_button';
import TransferButton from './acls/transfer_button';
import UnconsignButton from './acls/unconsign_button';
import { mergeOptions } from '../../utils/general_utils';
import { selectFromObject } from '../../utils/general_utils';
let AclButtonList = React.createClass({
propTypes: {
className: React.PropTypes.string,
availableAcls: React.PropTypes.object.isRequired,
currentUser: React.PropTypes.object.isRequired,
handleSuccess: React.PropTypes.func.isRequired,
pieceOrEditions: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.array
]).isRequired,
availableAcls: React.PropTypes.object.isRequired,
buttonsStyle: React.PropTypes.object,
handleSuccess: React.PropTypes.func.isRequired,
children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element),
React.PropTypes.element
])
]),
className: React.PropTypes.string
},
getInitialState() {
return mergeOptions(
UserStore.getState(),
{
buttonListSize: 0
}
);
return {
buttonListSize: 0
}
},
componentDidMount() {
UserStore.listen(this.onChange);
UserActions.fetchCurrentUser.defer();
window.addEventListener('resize', this.handleResize);
window.dispatchEvent(new Event('resize'));
},
componentDidUpdate(prevProps) {
if(prevProps.availableAcls && prevProps.availableAcls !== this.props.availableAcls) {
if (prevProps.availableAcls && prevProps.availableAcls !== this.props.availableAcls) {
window.dispatchEvent(new Event('resize'));
}
},
componentWillUnmount() {
UserStore.unlisten(this.onChange);
window.removeEventListener('resize', this.handleResize);
},
@ -65,10 +56,6 @@ let AclButtonList = React.createClass({
});
},
onChange(state) {
this.setState(state);
},
renderChildren() {
const { children } = this.props;
const { buttonListSize } = this.state;
@ -79,42 +66,28 @@ let AclButtonList = React.createClass({
},
render() {
const { className,
const { availableAcls,
buttonsStyle,
availableAcls,
pieceOrEditions,
handleSuccess } = this.props;
className,
currentUser,
handleSuccess,
pieceOrEditions } = this.props;
const { currentUser } = this.state;
const buttonProps = selectFromObject(this.props, [
'availableAcls',
'currentUser',
'handleSuccess',
'pieceOrEditions'
]);
return (
<div className={className}>
<span ref="buttonList" style={buttonsStyle}>
<EmailButton
availableAcls={availableAcls}
pieceOrEditions={pieceOrEditions}
currentUser={currentUser}
handleSuccess={handleSuccess} />
<TransferButton
availableAcls={availableAcls}
pieceOrEditions={pieceOrEditions}
currentUser={currentUser}
handleSuccess={handleSuccess}/>
<ConsignButton
availableAcls={availableAcls}
pieceOrEditions={pieceOrEditions}
currentUser={currentUser}
handleSuccess={handleSuccess} />
<UnconsignButton
availableAcls={availableAcls}
pieceOrEditions={pieceOrEditions}
currentUser={currentUser}
handleSuccess={handleSuccess} />
<LoanButton
availableAcls={availableAcls}
pieceOrEditions={pieceOrEditions}
currentUser={currentUser}
handleSuccess={handleSuccess} />
<EmailButton {...buttonProps} />
<TransferButton {...buttonProps} />
<ConsignButton {...buttonProps} />
<UnconsignButton {...buttonProps} />
<LoanButton {...buttonProps} />
{this.renderChildren()}
</span>
</div>

View File

@ -14,7 +14,7 @@ import AppConstants from '../../../constants/application_constants';
import { AclInformationText } from '../../../constants/acl_information_text';
export default function ({ action, displayName, title, tooltip }) {
export default function AclButton({ action, displayName, title, tooltip }) {
if (AppConstants.aclList.indexOf(action) < 0) {
console.warn('Your specified aclName did not match a an acl class.');
}
@ -24,23 +24,20 @@ export default function ({ action, displayName, title, tooltip }) {
propTypes: {
availableAcls: React.PropTypes.object.isRequired,
buttonAcceptName: React.PropTypes.string,
buttonAcceptClassName: React.PropTypes.string,
currentUser: React.PropTypes.object,
email: React.PropTypes.string,
pieceOrEditions: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.array
]).isRequired,
handleSuccess: React.PropTypes.func.isRequired,
className: React.PropTypes.string
buttonAcceptName: React.PropTypes.string,
buttonAcceptClassName: React.PropTypes.string,
currentUser: React.PropTypes.object,
email: React.PropTypes.string,
handleSuccess: React.PropTypes.func
},
sanitizeAction() {
if (this.props.buttonAcceptName) {
return this.props.buttonAcceptName;
}
return AclInformationText.titles[action];
return this.props.buttonAcceptName || AclInformationText.titles[action];
},
render() {

View File

@ -15,10 +15,12 @@ let UnConsignRequestButton = React.createClass({
propTypes: {
currentUser: React.PropTypes.object.isRequired,
edition: React.PropTypes.object.isRequired,
handleSuccess: React.PropTypes.func.isRequired
handleSuccess: React.PropTypes.func
},
render: function () {
const { currentUser, edition, handleSuccess } = this.props;
return (
<ModalWrapper
trigger={
@ -26,17 +28,18 @@ let UnConsignRequestButton = React.createClass({
REQUEST UNCONSIGN
</Button>
}
handleSuccess={this.props.handleSuccess}
handleSuccess={handleSuccess}
title='Request to Un-Consign'>
<UnConsignRequestForm
url={ApiUrls.ownership_unconsigns_request}
id={{'bitcoin_id': this.props.edition.bitcoin_id}}
id={{'bitcoin_id': edition.bitcoin_id}}
message={`${getLangText('Hi')},
${getLangText('I request you to un-consign')} \" ${this.props.edition.title} \".
${getLangText('I request you to un-consign')} \" ${edition.title} \".
${getLangText('Truly yours')},
${this.props.currentUser.username}`}/>
${currentUser.username}`
} />
</ModalWrapper>
);
}

View File

@ -8,23 +8,23 @@ import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
import HistoryIterator from './history_iterator';
import EditionActions from '../../actions/edition_actions';
import MediaContainer from './media_container';
import CollapsibleParagraph from './../ascribe_collapsible/collapsible_paragraph';
import Form from './../ascribe_forms/form';
import Property from './../ascribe_forms/property';
import DetailProperty from './detail_property';
import LicenseDetail from './license_detail';
import FurtherDetails from './further_details';
import EditionActionPanel from './edition_action_panel';
import AclProxy from '../acl_proxy';
import FurtherDetails from './further_details';
import HistoryIterator from './history_iterator';
import LicenseDetail from './license_detail';
import MediaContainer from './media_container';
import Note from './note';
import CollapsibleParagraph from '../ascribe_collapsible/collapsible_paragraph';
import Form from '../ascribe_forms/form';
import Property from '../ascribe_forms/property';
import AclProxy from '../acl_proxy';
import ApiUrls from '../../constants/api_urls';
import AscribeSpinner from '../ascribe_spinner';
@ -36,11 +36,13 @@ import { getLangText } from '../../utils/lang_utils';
*/
let Edition = React.createClass({
propTypes: {
currentUser: React.PropTypes.object.isRequired,
edition: React.PropTypes.object.isRequired,
whitelabel: React.PropTypes.object.isRequired,
actionPanelButtonListType: React.PropTypes.func,
furtherDetailsType: React.PropTypes.func,
edition: React.PropTypes.object,
coaError: React.PropTypes.object,
currentUser: React.PropTypes.object,
furtherDetailsType: React.PropTypes.func,
loadEdition: React.PropTypes.func
},
@ -56,56 +58,56 @@ let Edition = React.createClass({
currentUser,
edition,
furtherDetailsType: FurtherDetailsType,
loadEdition } = this.props;
loadEdition,
whitelabel } = this.props;
return (
<Row>
<Col md={6} className="ascribe-print-col-left">
<MediaContainer
content={edition}
currentUser={currentUser} />
currentUser={currentUser}
refreshObject={loadEdition} />
</Col>
<Col md={6} className="ascribe-edition-details ascribe-print-col-right">
<div className="ascribe-detail-header">
<hr className="hidden-print" style={{marginTop: 0}}/>
<hr className="hidden-print" style={{marginTop: 0}} />
<h1 className="ascribe-detail-title">{edition.title}</h1>
<DetailProperty label="BY" value={edition.artist_name} />
<DetailProperty label="CREATED BY" value={edition.artist_name} />
<DetailProperty label="DATE" value={Moment(edition.date_created, 'YYYY-MM-DD').year()} />
<hr/>
<hr />
</div>
<EditionSummary
actionPanelButtonListType={actionPanelButtonListType}
edition={edition}
currentUser={currentUser}
handleSuccess={loadEdition}/>
handleSuccess={loadEdition}
whitelabel={whitelabel} />
<CollapsibleParagraph
title={getLangText('Certificate of Authenticity')}
show={edition.acl.acl_coa === true}>
<CoaDetails
coa={edition.coa}
coaError={coaError}
editionId={edition.bitcoin_id}/>
editionId={edition.bitcoin_id} />
</CollapsibleParagraph>
<CollapsibleParagraph
title={getLangText('Provenance/Ownership History')}
show={edition.ownership_history && edition.ownership_history.length > 0}>
<HistoryIterator
history={edition.ownership_history} />
show={edition.ownership_history && edition.ownership_history.length}>
<HistoryIterator history={edition.ownership_history} />
</CollapsibleParagraph>
<CollapsibleParagraph
title={getLangText('Consignment History')}
show={edition.consign_history && edition.consign_history.length > 0}>
<HistoryIterator
history={edition.consign_history} />
<HistoryIterator history={edition.consign_history} />
</CollapsibleParagraph>
<CollapsibleParagraph
title={getLangText('Loan History')}
show={edition.loan_history && edition.loan_history.length > 0}>
<HistoryIterator
history={edition.loan_history} />
<HistoryIterator history={edition.loan_history} />
</CollapsibleParagraph>
<CollapsibleParagraph
@ -119,7 +121,7 @@ let Edition = React.createClass({
editable={true}
successMessage={getLangText('Private note saved')}
url={ApiUrls.note_private_edition}
currentUser={currentUser}/>
currentUser={currentUser} />
<Note
id={() => {return {'bitcoin_id': edition.bitcoin_id}; }}
label={getLangText('Personal note (public)')}
@ -129,13 +131,11 @@ let Edition = React.createClass({
show={!!edition.public_note || !!edition.acl.acl_edit}
successMessage={getLangText('Public edition note saved')}
url={ApiUrls.note_public_edition}
currentUser={currentUser}/>
currentUser={currentUser} />
</CollapsibleParagraph>
<CollapsibleParagraph
title={getLangText('Further Details')}
show={edition.acl.acl_edit ||
Object.keys(edition.extra_data).length > 0 ||
edition.other_data.length > 0}>
show={edition.acl.acl_edit || Object.keys(edition.extra_data).length || edition.other_data.length}>
<FurtherDetailsType
editable={edition.acl.acl_edit}
pieceId={edition.parent}
@ -143,10 +143,8 @@ let Edition = React.createClass({
otherData={edition.other_data}
handleSuccess={loadEdition} />
</CollapsibleParagraph>
<CollapsibleParagraph
title={getLangText('SPOOL Details')}>
<SpoolDetails
edition={edition} />
<CollapsibleParagraph title={getLangText('SPOOL Details')}>
<SpoolDetails edition={edition} />
</CollapsibleParagraph>
</Col>
</Row>
@ -157,60 +155,56 @@ let Edition = React.createClass({
let EditionSummary = React.createClass({
propTypes: {
currentUser: React.PropTypes.object.isRequired,
edition: React.PropTypes.object.isRequired,
whitelabel: React.PropTypes.object.isRequired,
actionPanelButtonListType: React.PropTypes.func,
edition: React.PropTypes.object,
currentUser: React.PropTypes.object,
handleSuccess: React.PropTypes.func
},
handleSuccess() {
this.props.handleSuccess();
},
getStatus() {
const { status } = this.props.edition;
getStatus(){
let status = null;
if (this.props.edition.status.length > 0){
let statusStr = this.props.edition.status.join(', ').replace(/_/g, ' ');
status = <DetailProperty label="STATUS" value={ statusStr }/>;
if (this.props.edition.pending_new_owner && this.props.edition.acl.acl_withdraw_transfer){
status = (
<DetailProperty label="STATUS" value={ statusStr } />
);
}
}
return status;
return status.length ? (
<DetailProperty
label="STATUS"
value={status.join(', ').replace(/_/g, ' ')} />
) : null;
},
render() {
let { actionPanelButtonListType, edition, currentUser } = this.props;
const { actionPanelButtonListType, currentUser, edition, handleSuccess, whitelabel } = this.props;
return (
<div className="ascribe-detail-header">
<DetailProperty
label={getLangText('EDITION')}
value={ edition.edition_number + ' ' + getLangText('of') + ' ' + edition.num_editions} />
value={edition.edition_number + ' ' + getLangText('of') + ' ' + edition.num_editions} />
<DetailProperty
label={getLangText('ID')}
value={ edition.bitcoin_id }
value={edition.bitcoin_id}
ellipsis={true} />
<DetailProperty
label={getLangText('OWNER')}
value={ edition.owner } />
<LicenseDetail license={edition.license_type}/>
value={edition.owner} />
<LicenseDetail license={edition.license_type} />
{this.getStatus()}
{/*
`acl_view` is always available in `edition.acl`, therefore if it has
no more than 1 key, we're hiding the `DetailProperty` actions as otherwise
`AclInformation` would show up
*/}
<AclProxy show={currentUser && currentUser.email && Object.keys(edition.acl).length > 1}>
<AclProxy show={currentUser.email && Object.keys(edition.acl).length > 1}>
<DetailProperty
label={getLangText('ACTIONS')}
className="hidden-print">
<EditionActionPanel
actionPanelButtonListType={actionPanelButtonListType}
edition={edition}
currentUser={currentUser}
handleSuccess={this.handleSuccess} />
edition={edition}
handleSuccess={handleSuccess}
whitelabel={whitelabel} />
</DetailProperty>
</AclProxy>
<hr/>
@ -359,4 +353,5 @@ let SpoolDetails = React.createClass({
}
});
export default Edition;

View File

@ -36,9 +36,11 @@ import { getLangText } from '../../utils/lang_utils';
*/
let EditionActionPanel = React.createClass({
propTypes: {
currentUser: React.PropTypes.object.isRequired,
edition: React.PropTypes.object.isRequired,
whitelabel: React.PropTypes.object.isRequired,
actionPanelButtonListType: React.PropTypes.func,
edition: React.PropTypes.object,
currentUser: React.PropTypes.object,
handleSuccess: React.PropTypes.func
},
@ -87,38 +89,41 @@ let EditionActionPanel = React.createClass({
handleSuccess(response) {
this.refreshCollection();
this.props.handleSuccess();
if (response){
let notification = new GlobalNotificationModel(response.notification, 'success');
if (response) {
const notification = new GlobalNotificationModel(response.notification, 'success');
GlobalNotificationActions.appendGlobalNotification(notification);
}
if (typeof this.props.handleSuccess === 'function') {
this.props.handleSuccess();
}
},
render() {
const { actionPanelButtonListType: ActionPanelButtonListType,
currentUser,
edition } = this.props;
edition,
whitelabel } = this.props;
if (edition &&
edition.notifications &&
edition.notifications.length > 0){
if (edition.notifications && edition.notifications.length) {
return (
<ListRequestActions
pieceOrEditions={[edition]}
currentUser={currentUser}
handleSuccess={this.handleSuccess}
notifications={edition.notifications}/>);
}
else {
notifications={edition.notifications}
pieceOrEditions={[edition]}
handleSuccess={this.handleSuccess} />);
} else {
return (
<Row>
<Col md={12}>
<ActionPanelButtonListType
className="ascribe-button-list"
availableAcls={edition.acl}
className="ascribe-button-list"
currentUser={currentUser}
handleSuccess={this.handleSuccess}
pieceOrEditions={[edition]}
handleSuccess={this.handleSuccess}>
whitelabel={whitelabel}>
<AclProxy
aclObject={edition.acl}
aclName="acl_withdraw_transfer">

View File

@ -9,16 +9,12 @@ import { ResourceNotFoundError } from '../../models/errors';
import EditionActions from '../../actions/edition_actions';
import EditionStore from '../../stores/edition_store';
import UserActions from '../../actions/user_actions';
import UserStore from '../../stores/user_store';
import Edition from './edition';
import AscribeSpinner from '../ascribe_spinner';
import { getLangText } from '../../utils/lang_utils';
import { setDocumentTitle } from '../../utils/dom_utils';
import { mergeOptions } from '../../utils/general_utils';
/**
@ -28,24 +24,26 @@ let EditionContainer = React.createClass({
propTypes: {
actionPanelButtonListType: React.PropTypes.func,
furtherDetailsType: React.PropTypes.func,
// Provided from AscribeApp
currentUser: React.PropTypes.object.isRequired,
whitelabel: React.PropTypes.object.isRequired,
// Provided from router
location: React.PropTypes.object,
params: React.PropTypes.object
},
mixins: [History, ReactError],
getInitialState() {
return mergeOptions(
EditionStore.getInitialState(),
UserStore.getState()
);
return EditionStore.getInitialState();
},
componentDidMount() {
EditionStore.listen(this.onChange);
UserStore.listen(this.onChange);
this.loadEdition();
UserActions.fetchCurrentUser();
},
// This is done to update the container when the user clicks on the prev or next
@ -68,19 +66,10 @@ let EditionContainer = React.createClass({
componentWillUnmount() {
window.clearInterval(this.state.timerId);
EditionStore.unlisten(this.onChange);
UserStore.unlisten(this.onChange);
},
onChange(state) {
this.setState(state);
if(state && state.edition && state.edition.digital_work) {
let isEncoding = state.edition.digital_work.isEncoding;
if (state.edition.digital_work.mime === 'video' && typeof isEncoding === 'number' && isEncoding !== 100 && !this.state.timerId) {
let timerId = window.setInterval(() => EditionActions.fetchEdition(this.props.params.editionId), 10000);
this.setState({timerId: timerId});
}
}
},
loadEdition(editionId = this.props.params.editionId) {
@ -88,8 +77,8 @@ let EditionContainer = React.createClass({
},
render() {
const { edition, currentUser, coaMeta } = this.state;
const { actionPanelButtonListType, furtherDetailsType } = this.props;
const { actionPanelButtonListType, currentUser, furtherDetailsType, whitelabel } = this.props;
const { edition, coaMeta } = this.state;
if (edition.id) {
setDocumentTitle(`${edition.artist_name}, ${edition.title}`);
@ -97,11 +86,12 @@ let EditionContainer = React.createClass({
return (
<Edition
actionPanelButtonListType={actionPanelButtonListType}
furtherDetailsType={furtherDetailsType}
edition={edition}
coaError={coaMeta.err}
currentUser={currentUser}
loadEdition={this.loadEdition} />
edition={edition}
furtherDetailsType={furtherDetailsType}
loadEdition={this.loadEdition}
whitelabel={whitelabel} />
);
} else {
return (

View File

@ -58,39 +58,42 @@ let FurtherDetails = React.createClass({
},
render() {
const { editable, extraData, otherData, pieceId } = this.props;
return (
<Row>
<Col md={12} className="ascribe-edition-personal-note">
<PieceExtraDataForm
name='artist_contact_info'
title='Artist Contact Info'
convertLinks
editable={editable}
extraData={extraData}
handleSuccess={this.showNotification}
editable={this.props.editable}
pieceId={this.props.pieceId}
extraData={this.props.extraData} />
pieceId={pieceId} />
<PieceExtraDataForm
name='display_instructions'
title='Display Instructions'
editable={editable}
extraData={extraData}
handleSuccess={this.showNotification}
editable={this.props.editable}
pieceId={this.props.pieceId}
extraData={this.props.extraData} />
pieceId={pieceId} />
<PieceExtraDataForm
name='technology_details'
title='Technology Details'
editable={editable}
extraData={extraData}
handleSuccess={this.showNotification}
editable={this.props.editable}
pieceId={this.props.pieceId}
extraData={this.props.extraData} />
pieceId={pieceId} />
<Form>
<FurtherDetailsFileuploader
submitFile={this.submitFile}
setIsUploadReady={this.setIsUploadReady}
isReadyForFormSubmission={formSubmissionValidation.atLeastOneUploadedFile}
editable={this.props.editable}
editable={editable}
overrideForm={true}
pieceId={this.props.pieceId}
otherData={this.props.otherData}
pieceId={pieceId}
otherData={otherData}
multiple={true} />
</Form>
</Col>

View File

@ -8,62 +8,93 @@ import ReactS3FineUploader from './../ascribe_uploader/react_s3_fine_uploader';
import ApiUrls from '../../constants/api_urls';
import AppConstants from '../../constants/application_constants';
import { validationTypes } from '../../constants/uploader_constants';
import { getCookie } from '../../utils/fetch_api_utils';
import { getLangText } from '../../utils/lang_utils';
const { func, bool, number, object, string, arrayOf } = React.PropTypes;
let FurtherDetailsFileuploader = React.createClass({
propTypes: {
label: React.PropTypes.string,
pieceId: React.PropTypes.number,
otherData: React.PropTypes.arrayOf(React.PropTypes.object),
setIsUploadReady: React.PropTypes.func,
submitFile: React.PropTypes.func,
onValidationFailed: React.PropTypes.func,
isReadyForFormSubmission: React.PropTypes.func,
editable: React.PropTypes.bool,
multiple: React.PropTypes.bool
pieceId: number.isRequired,
editable: bool,
label: string,
otherData: arrayOf(object),
// Props for ReactS3FineUploader
areAssetsDownloadable: bool,
isReadyForFormSubmission: func,
submitFile: func, // TODO: rename to onSubmitFile
onValidationFailed: func,
multiple: bool,
setIsUploadReady: func, //TODO: rename to setIsUploaderValidated
showErrorPrompt: bool,
validation: ReactS3FineUploader.propTypes.validation
},
getDefaultProps() {
return {
areAssetsDownloadable: true,
label: getLangText('Additional files'),
multiple: false
multiple: false,
validation: validationTypes.additionalData
};
},
render() {
const { editable,
isReadyForFormSubmission,
multiple,
onValidationFailed,
otherData,
pieceId,
setIsUploadReady,
showErrorPrompt,
submitFile,
validation } = this.props;
// Essentially there a three cases important to the fileuploader
//
// 1. there is no other_data => do not show the fileuploader at all (where otherData is now an array)
// 2. there is other_data, but user has no edit rights => show fileuploader but without action buttons
// 3. both other_data and editable are defined or true => show fileuploader with all action buttons
if (!this.props.editable && (!this.props.otherData || this.props.otherData.length === 0)) {
if (!editable && (!otherData || otherData.length === 0)) {
return null;
}
let otherDataIds = this.props.otherData ? this.props.otherData.map((data) => data.id).join() : null;
let otherDataIds = otherData ? otherData.map((data) => data.id).join() : null;
return (
<Property
name="other_data_key"
label={this.props.label}>
<ReactS3FineUploader
areAssetsDownloadable
areAssetsEditable={editable}
createBlobRoutine={{
url: ApiUrls.blob_otherdatas,
pieceId: pieceId
}}
deleteFile={{
enabled: true,
method: 'DELETE',
endpoint: AppConstants.serverUrl + 's3/delete',
customHeaders: {
'X-CSRFToken': getCookie(AppConstants.csrftoken)
}
}}
isReadyForFormSubmission={isReadyForFormSubmission}
keyRoutine={{
url: AppConstants.serverUrl + 's3/key/',
fileClass: 'otherdata',
pieceId: this.props.pieceId
pieceId: pieceId
}}
createBlobRoutine={{
url: ApiUrls.blob_otherdatas,
pieceId: this.props.pieceId
}}
validation={AppConstants.fineUploader.validation.additionalData}
submitFile={this.props.submitFile}
onValidationFailed={this.props.onValidationFailed}
setIsUploadReady={this.props.setIsUploadReady}
isReadyForFormSubmission={this.props.isReadyForFormSubmission}
multiple={multiple}
onValidationFailed={onValidationFailed}
setIsUploadReady={setIsUploadReady}
session={{
endpoint: AppConstants.serverUrl + 'api/blob/otherdatas/fineuploader_session/',
customHeaders: {
@ -83,17 +114,9 @@ let FurtherDetailsFileuploader = React.createClass({
'X-CSRFToken': getCookie(AppConstants.csrftoken)
}
}}
deleteFile={{
enabled: true,
method: 'DELETE',
endpoint: AppConstants.serverUrl + 's3/delete',
customHeaders: {
'X-CSRFToken': getCookie(AppConstants.csrftoken)
}
}}
areAssetsDownloadable={true}
areAssetsEditable={this.props.editable}
multiple={this.props.multiple} />
submitFile={submitFile}
showErrorPrompt={showErrorPrompt}
validation={validation} />
</Property>
);
}

View File

@ -14,18 +14,22 @@ import CollapsibleButton from './../ascribe_collapsible/collapsible_button';
import AclProxy from '../acl_proxy';
import { getLangText } from '../../utils/lang_utils.js';
import { getLangText } from '../../utils/lang_utils';
import { extractFileExtensionFromString } from '../../utils/file_utils';
const EMBED_IFRAME_HEIGHT = {
video: 315,
audio: 62
};
const ENCODE_UPDATE_TIME = 5000;
let MediaContainer = React.createClass({
propTypes: {
content: React.PropTypes.object,
currentUser: React.PropTypes.object,
refreshObject: React.PropTypes.func
content: React.PropTypes.object.isRequired,
refreshObject: React.PropTypes.func.isRequired,
currentUser: React.PropTypes.object
},
getInitialState() {
@ -35,14 +39,16 @@ let MediaContainer = React.createClass({
},
componentDidMount() {
if (!this.props.content.digital_work) {
return;
}
const { content: { digital_work: digitalWork }, refreshObject } = this.props;
const isEncoding = this.props.content.digital_work.isEncoding;
if (this.props.content.digital_work.mime === 'video' && typeof isEncoding === 'number' && isEncoding !== 100 && !this.state.timerId) {
let timerId = window.setInterval(this.props.refreshObject, 10000);
this.setState({timerId: timerId});
if (digitalWork) {
const isEncoding = digitalWork.isEncoding;
if (digitalWork.mime === 'video' && typeof isEncoding === 'number' && isEncoding !== 100 && !this.state.timerId) {
this.setState({
timerId: window.setInterval(refreshObject, ENCODE_UPDATE_TIME)
});
}
}
},
@ -64,6 +70,16 @@ let MediaContainer = React.createClass({
// content was registered by the current user.
const didUserRegisterContent = currentUser && (currentUser.username === content.user_registered);
// We want to show the file's extension as a label of the download button.
// We can however not only use `extractFileExtensionFromString` on the url for that
// as files might be saved on S3 without a file extension which leads
// `extractFileExtensionFromString` to extract everything starting from the top level
// domain: e.g. '.net/live/<hash>'.
// Therefore, we extract the file's name (last part of url, separated with a slash)
// and try to extract the file extension from there.
const fileName = content.digital_work.url.split('/').pop();
const fileExtension = extractFileExtensionFromString(fileName);
let thumbnail = content.thumbnail.thumbnail_sizes && content.thumbnail.thumbnail_sizes['600x600'] ?
content.thumbnail.thumbnail_sizes['600x600'] : content.thumbnail.url_safe;
let mimetype = content.digital_work.mime;
@ -93,7 +109,7 @@ let MediaContainer = React.createClass({
{'<iframe width="560" height="' + height + '" src="https://embed.ascribe.io/content/'
+ content.bitcoin_id + '" frameborder="0" allowfullscreen></iframe>'}
</pre>
}/>
} />
);
}
return (
@ -120,7 +136,11 @@ let MediaContainer = React.createClass({
className="ascribe-margin-1px"
href={content.digital_work.url}
target="_blank">
{getLangText('Download')} .{mimetype} <Glyphicon glyph="cloud-download"/>
{/*
If it turns out that `fileExtension` is an empty string, we're just
using the label 'file'.
*/}
{getLangText('Download')} .{fileExtension || 'file'} <Glyphicon glyph="cloud-download" />
</Button>
</AclProxy>
{embed}

View File

@ -2,64 +2,68 @@
import React from 'react';
import GlobalNotificationModel from '../../models/global_notification_model';
import GlobalNotificationActions from '../../actions/global_notification_actions';
import Form from './../ascribe_forms/form';
import Property from './../ascribe_forms/property';
import InputTextAreaToggable from './../ascribe_forms/input_textarea_toggable';
import GlobalNotificationModel from '../../models/global_notification_model';
import GlobalNotificationActions from '../../actions/global_notification_actions';
import { getLangText } from '../../utils/lang_utils';
let Note = React.createClass({
propTypes: {
url: React.PropTypes.string,
id: React.PropTypes.func,
label: React.PropTypes.string,
currentUser: React.PropTypes.object,
currentUser: React.PropTypes.object.isRequired,
id: React.PropTypes.func.isRequired,
url: React.PropTypes.string.isRequired,
defaultValue: React.PropTypes.string,
editable: React.PropTypes.bool,
show: React.PropTypes.bool,
label: React.PropTypes.string,
placeholder: React.PropTypes.string,
show: React.PropTypes.bool,
successMessage: React.PropTypes.string
},
getDefaultProps() {
return {
editable: true,
show: true,
placeholder: getLangText('Enter a note'),
show: true,
successMessage: getLangText('Note saved')
};
},
showNotification(){
let notification = new GlobalNotificationModel(this.props.successMessage, 'success');
showNotification() {
const notification = new GlobalNotificationModel(this.props.successMessage, 'success');
GlobalNotificationActions.appendGlobalNotification(notification);
},
render() {
if ((!!this.props.currentUser.username && this.props.editable || !this.props.editable ) && this.props.show) {
const { currentUser, defaultValue, editable, id, label, placeholder, show, url } = this.props;
if ((!!currentUser.username && editable || !editable ) && show) {
return (
<Form
url={this.props.url}
getFormData={this.props.id}
url={url}
getFormData={id}
handleSuccess={this.showNotification}
disabled={!this.props.editable}>
disabled={!editable}>
<Property
name='note'
label={this.props.label}>
label={label}>
<InputTextAreaToggable
rows={1}
defaultValue={this.props.defaultValue}
placeholder={this.props.placeholder}/>
defaultValue={defaultValue}
placeholder={placeholder} />
</Property>
<hr />
</Form>
);
} else {
return null;
}
return null;
}
});
export default Note;
export default Note;

View File

@ -15,19 +15,19 @@ import MediaContainer from './media_container';
*/
let Piece = React.createClass({
propTypes: {
piece: React.PropTypes.object,
piece: React.PropTypes.object.isRequired,
buttons: React.PropTypes.object,
currentUser: React.PropTypes.object,
header: React.PropTypes.object,
subheader: React.PropTypes.object,
buttons: React.PropTypes.object,
children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element),
React.PropTypes.element
])
},
updateObject() {
updatePiece() {
return PieceActions.fetchPiece(this.props.piece.id);
},
@ -40,7 +40,7 @@ let Piece = React.createClass({
<MediaContainer
content={piece}
currentUser={currentUser}
refreshObject={this.updateObject} />
refreshObject={this.updatePiece} />
</Col>
<Col md={6} className="ascribe-edition-details ascribe-print-col-right">
{header}

View File

@ -7,39 +7,35 @@ import Moment from 'moment';
import ReactError from '../../mixins/react_error';
import { ResourceNotFoundError } from '../../models/errors';
import EditionListActions from '../../actions/edition_list_actions';
import GlobalNotificationModel from '../../models/global_notification_model';
import GlobalNotificationActions from '../../actions/global_notification_actions';
import PieceActions from '../../actions/piece_actions';
import PieceStore from '../../stores/piece_store';
import PieceListActions from '../../actions/piece_list_actions';
import PieceListStore from '../../stores/piece_list_store';
import UserActions from '../../actions/user_actions';
import UserStore from '../../stores/user_store';
import EditionListActions from '../../actions/edition_list_actions';
import Piece from './piece';
import CollapsibleParagraph from './../ascribe_collapsible/collapsible_paragraph';
import FurtherDetails from './further_details';
import DetailProperty from './detail_property';
import LicenseDetail from './license_detail';
import HistoryIterator from './history_iterator';
import LicenseDetail from './license_detail';
import Note from './note';
import Piece from './piece';
import AclButtonList from './../ascribe_buttons/acl_button_list';
import CreateEditionsForm from '../ascribe_forms/create_editions_form';
import AclInformation from '../ascribe_buttons/acl_information';
import CreateEditionsButton from '../ascribe_buttons/create_editions_button';
import DeleteButton from '../ascribe_buttons/delete_button';
import AclInformation from '../ascribe_buttons/acl_information';
import AclProxy from '../acl_proxy';
import CollapsibleParagraph from './../ascribe_collapsible/collapsible_paragraph';
import CreateEditionsForm from '../ascribe_forms/create_editions_form';
import ListRequestActions from '../ascribe_forms/list_form_request_actions';
import GlobalNotificationModel from '../../models/global_notification_model';
import GlobalNotificationActions from '../../actions/global_notification_actions';
import Note from './note';
import AclProxy from '../acl_proxy';
import ApiUrls from '../../constants/api_urls';
import AscribeSpinner from '../ascribe_spinner';
@ -54,6 +50,13 @@ import { setDocumentTitle } from '../../utils/dom_utils';
let PieceContainer = React.createClass({
propTypes: {
furtherDetailsType: React.PropTypes.func,
// Provided from AscribeApp
currentUser: React.PropTypes.object.isRequired,
whitelabel: React.PropTypes.object,
// Provided from router
location: React.PropTypes.object,
params: React.PropTypes.object
},
@ -67,7 +70,6 @@ let PieceContainer = React.createClass({
getInitialState() {
return mergeOptions(
UserStore.getState(),
PieceListStore.getState(),
PieceStore.getInitialState(),
{
@ -77,12 +79,10 @@ let PieceContainer = React.createClass({
},
componentDidMount() {
UserStore.listen(this.onChange);
PieceListStore.listen(this.onChange);
PieceStore.listen(this.onChange);
this.loadPiece();
UserActions.fetchCurrentUser();
},
// This is done to update the container when the user clicks on the prev or next
@ -105,7 +105,6 @@ let PieceContainer = React.createClass({
componentWillUnmount() {
PieceStore.unlisten(this.onChange);
UserStore.unlisten(this.onChange);
PieceListStore.unlisten(this.onChange);
},
@ -207,15 +206,17 @@ let PieceContainer = React.createClass({
},
getActions() {
const { piece, currentUser } = this.state;
const { piece } = this.state;
const { currentUser } = this.props;
if (piece.notifications && piece.notifications.length > 0) {
return (
<ListRequestActions
pieceOrEditions={piece}
currentUser={currentUser}
handleSuccess={this.loadPiece}
notifications={piece.notifications} />);
notifications={piece.notifications}
pieceOrEditions={piece} />
);
} else {
return (
<AclProxy
@ -229,8 +230,9 @@ let PieceContainer = React.createClass({
label={getLangText('ACTIONS')}
className="hidden-print">
<AclButtonList
className="ascribe-button-list"
availableAcls={piece.acl}
className="ascribe-button-list"
currentUser={currentUser}
pieceOrEditions={piece}
handleSuccess={this.loadPiece}>
<CreateEditionsButton
@ -255,8 +257,8 @@ let PieceContainer = React.createClass({
},
render() {
const { furtherDetailsType: FurtherDetailsType } = this.props;
const { currentUser, piece } = this.state;
const { currentUser, furtherDetailsType: FurtherDetailsType } = this.props;
const { piece } = this.state;
if (piece.id) {
setDocumentTitle(`${piece.artist_name}, ${piece.title}`);
@ -269,7 +271,7 @@ let PieceContainer = React.createClass({
<div className="ascribe-detail-header">
<hr className="hidden-print" style={{marginTop: 0}} />
<h1 className="ascribe-detail-title">{piece.title}</h1>
<DetailProperty label="BY" value={piece.artist_name} />
<DetailProperty label="CREATED BY" value={piece.artist_name} />
<DetailProperty label="DATE" value={Moment(piece.date_created, 'YYYY-MM-DD').year() } />
{piece.num_editions > 0 ? <DetailProperty label="EDITIONS" value={ piece.num_editions } /> : null}
<hr/>
@ -277,7 +279,7 @@ let PieceContainer = React.createClass({
}
subheader={
<div className="ascribe-detail-header">
<DetailProperty label={getLangText('REGISTREE')} value={ piece.user_registered } />
<DetailProperty label={getLangText('ASCRIBED BY')} value={ piece.user_registered } />
<DetailProperty label={getLangText('ID')} value={ piece.bitcoin_id } ellipsis={true} />
<LicenseDetail license={piece.license_type} />
</div>

View File

@ -20,16 +20,17 @@ import { getAclFormMessage, getAclFormDataId } from '../../utils/form_utils';
let AclFormFactory = React.createClass({
propTypes: {
action: React.PropTypes.oneOf(AppConstants.aclList).isRequired,
autoFocusProperty: React.PropTypes.string,
currentUser: React.PropTypes.object,
email: React.PropTypes.string,
message: React.PropTypes.string,
labels: React.PropTypes.object,
pieceOrEditions: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.array
]).isRequired,
autoFocusProperty: React.PropTypes.string,
currentUser: React.PropTypes.object,
email: React.PropTypes.string,
handleSuccess: React.PropTypes.func,
message: React.PropTypes.string,
labels: React.PropTypes.object,
showNotification: React.PropTypes.bool
},
@ -104,7 +105,7 @@ let AclFormFactory = React.createClass({
message={formMessage}
id={this.getFormDataId()}
url={this.isPiece() ? ApiUrls.ownership_loans_pieces
: ApiUrls.ownership_loans_editions}
: ApiUrls.ownership_loans_editions}
handleSuccess={showNotification ? this.showSuccessNotification : handleSuccess} />
);
} else if (action === 'acl_loan_request') {
@ -121,7 +122,7 @@ let AclFormFactory = React.createClass({
message={formMessage}
id={this.getFormDataId()}
url={this.isPiece() ? ApiUrls.ownership_shares_pieces
: ApiUrls.ownership_shares_editions}
: ApiUrls.ownership_shares_editions}
handleSuccess={showNotification ? this.showSuccessNotification : handleSuccess} />
);
} else {

View File

@ -19,7 +19,7 @@ let CreateEditionsForm = React.createClass({
pieceId: React.PropTypes.number
},
getFormData(){
getFormData() {
return {
piece_id: parseInt(this.props.pieceId, 10)
};
@ -58,11 +58,12 @@ let CreateEditionsForm = React.createClass({
<input
type="number"
placeholder="(e.g. 32)"
min={1}/>
min={1}
max={100} />
</Property>
</Form>
);
}
});
export default CreateEditionsForm;
export default CreateEditionsForm;

View File

@ -156,7 +156,7 @@ let Form = React.createClass({
for(let ref in this.refs) {
if(this.refs[ref] && typeof this.refs[ref].handleSuccess === 'function'){
this.refs[ref].handleSuccess();
this.refs[ref].handleSuccess(response);
}
}
this.setState({
@ -205,16 +205,15 @@ let Form = React.createClass({
},
getButtons() {
if (this.state.submitted){
if (this.state.submitted) {
return this.props.spinner;
}
if (this.props.buttons){
if (this.props.buttons !== undefined) {
return this.props.buttons;
}
let buttons = null;
if (this.state.edited && !this.props.disabled){
buttons = (
if (this.state.edited && !this.props.disabled) {
return (
<div className="row" style={{margin: 0}}>
<p className="pull-right">
<Button
@ -230,9 +229,9 @@ let Form = React.createClass({
</p>
</div>
);
} else {
return null;
}
return buttons;
},
getErrors() {

View File

@ -122,8 +122,7 @@ let ConsignForm = React.createClass({
<Property
name='contract_agreement'
label={getLangText('Consign Contract')}
className="ascribe-property-collapsible-toggle"
style={{paddingBottom: 0}}>
className="ascribe-property-collapsible-toggle">
<InputContractAgreementCheckbox
createPublicContractAgreement={createPublicContractAgreement}
email={email} />

View File

@ -15,30 +15,30 @@ import { getLangText } from '../../utils/lang_utils';
let CopyrightAssociationForm = React.createClass({
propTypes: {
currentUser: React.PropTypes.object
currentUser: React.PropTypes.object.isRequired
},
handleSubmitSuccess(){
let notification = getLangText('Copyright association updated');
notification = new GlobalNotificationModel(notification, 'success', 10000);
handleSubmitSuccess() {
const notification = new GlobalNotificationModel(getLangText('Copyright association updated'), 'success', 10000);
GlobalNotificationActions.appendGlobalNotification(notification);
},
getProfileFormData(){
return {email: this.props.currentUser.email};
getProfileFormData() {
return { email: this.props.currentUser.email };
},
render() {
let selectedState;
let selectDefaultValue = ' -- ' + getLangText('select an association') + ' -- ';
const { currentUser } = this.props;
const selectDefaultValue = ' -- ' + getLangText('select an association') + ' -- ';
if (this.props.currentUser && this.props.currentUser.profile
&& this.props.currentUser.profile.copyright_association) {
selectedState = AppConstants.copyrightAssociations.indexOf(this.props.currentUser.profile.copyright_association);
selectedState = selectedState !== -1 ? AppConstants.copyrightAssociations[selectedState] : selectDefaultValue;
let selectedState = selectDefaultValue;
if (currentUser.profile && currentUser.profile.copyright_association) {
if (AppConstants.copyrightAssociations.indexOf(currentUser.profile.copyright_association) !== -1) {
selectedState = AppConstants.copyrightAssociations[selectedState];
}
}
if (this.props.currentUser && this.props.currentUser.email){
if (currentUser.email) {
return (
<Form
ref='form'
@ -48,8 +48,7 @@ let CopyrightAssociationForm = React.createClass({
<Property
name="copyright_association"
className="ascribe-property-collapsible-toggle"
label={getLangText('Copyright Association')}
style={{paddingBottom: 0}}>
label={getLangText('Copyright Association')}>
<select defaultValue={selectedState} name="contract">
<option
name={0}
@ -72,9 +71,10 @@ let CopyrightAssociationForm = React.createClass({
<hr />
</Form>
);
} else {
return null;
}
return null;
}
});
export default CopyrightAssociationForm;
export default CopyrightAssociationForm;

View File

@ -2,19 +2,20 @@
import React from 'react';
import Form from '../ascribe_forms/form';
import Property from '../ascribe_forms/property';
import ContractListActions from '../../actions/contract_list_actions';
import GlobalNotificationModel from '../../models/global_notification_model';
import GlobalNotificationActions from '../../actions/global_notification_actions';
import ContractListActions from '../../actions/contract_list_actions';
import AppConstants from '../../constants/application_constants';
import ApiUrls from '../../constants/api_urls';
import InputFineUploader from './input_fineuploader';
import Form from '../ascribe_forms/form';
import Property from '../ascribe_forms/property';
import ApiUrls from '../../constants/api_urls';
import AppConstants from '../../constants/application_constants';
import { validationTypes } from '../../constants/uploader_constants';
import { getLangText } from '../../utils/lang_utils';
import { formSubmissionValidation } from '../ascribe_uploader/react_s3_fine_uploader_utils';
@ -78,8 +79,8 @@ let CreateContractForm = React.createClass({
url: ApiUrls.blob_contracts
}}
validation={{
itemLimit: AppConstants.fineUploader.validation.additionalData.itemLimit,
sizeLimit: AppConstants.fineUploader.validation.additionalData.sizeLimit,
itemLimit: validationTypes.additionalData.itemLimit,
sizeLimit: validationTypes.additionalData.sizeLimit,
allowedExtensions: ['pdf']
}}
areAssetsDownloadable={true}

View File

@ -170,7 +170,7 @@ let LoanForm = React.createClass({
editable={!gallery}
overrideForm={!!gallery}>
<input
value={gallery}
defaultValue={gallery}
type="text"
placeholder={getLangText('Gallery/exhibition (optional)')}/>
</Property>
@ -209,8 +209,7 @@ let LoanForm = React.createClass({
<Property
name='contract_agreement'
label={getLangText('Loan Contract')}
className="ascribe-property-collapsible-toggle"
style={{paddingBottom: 0}}>
className="ascribe-property-collapsible-toggle">
<InputContractAgreementCheckbox
createPublicContractAgreement={createPublicContractAgreement}
email={email} />

View File

@ -6,7 +6,6 @@ import { History } from 'react-router';
import GlobalNotificationModel from '../../models/global_notification_model';
import GlobalNotificationActions from '../../actions/global_notification_actions';
import UserStore from '../../stores/user_store';
import UserActions from '../../actions/user_actions';
import Form from './form';
@ -23,8 +22,6 @@ let LoginForm = React.createClass({
propTypes: {
headerMessage: React.PropTypes.string,
submitMessage: React.PropTypes.string,
redirectOnLoggedIn: React.PropTypes.bool,
redirectOnLoginSuccess: React.PropTypes.bool,
location: React.PropTypes.object
},
@ -32,40 +29,25 @@ let LoginForm = React.createClass({
getDefaultProps() {
return {
headerMessage: getLangText('Enter ascribe'),
submitMessage: getLangText('Log in'),
redirectOnLoggedIn: true,
redirectOnLoginSuccess: true
headerMessage: getLangText('Enter') + ' ascribe',
submitMessage: getLangText('Log in')
};
},
getInitialState() {
return UserStore.getState();
},
componentDidMount() {
UserStore.listen(this.onChange);
},
componentWillUnmount() {
UserStore.unlisten(this.onChange);
},
onChange(state) {
this.setState(state);
},
handleSuccess({ success }){
let notification = new GlobalNotificationModel('Login successful', 'success', 10000);
handleSuccess({ success }) {
const notification = new GlobalNotificationModel(getLangText('Login successful'), 'success', 10000);
GlobalNotificationActions.appendGlobalNotification(notification);
if(success) {
if (success) {
UserActions.fetchCurrentUser(true);
}
},
render() {
let email = this.props.location.query.email || null;
const { headerMessage,
location: { query: { email: emailQuery } },
submitMessage } = this.props;
return (
<Form
className="ascribe-form-bordered"
@ -77,7 +59,7 @@ let LoginForm = React.createClass({
<button
type="submit"
className="btn btn-default btn-wide">
{this.props.submitMessage}
{submitMessage}
</button>}
spinner={
<span className="btn btn-default btn-wide btn-spinner">
@ -85,7 +67,7 @@ let LoginForm = React.createClass({
</span>
}>
<div className="ascribe-form-header">
<h3>{this.props.headerMessage}</h3>
<h3>{headerMessage}</h3>
</div>
<Property
name='email'
@ -93,7 +75,7 @@ let LoginForm = React.createClass({
<input
type="email"
placeholder={getLangText('Enter your email')}
defaultValue={email}
defaultValue={emailQuery}
required/>
</Property>
<Property

View File

@ -16,6 +16,7 @@ let PieceExtraDataForm = React.createClass({
name: React.PropTypes.string.isRequired,
pieceId: React.PropTypes.number.isRequired,
convertLinks: React.PropTypes.bool,
editable: React.PropTypes.bool,
extraData: React.PropTypes.object,
handleSuccess: React.PropTypes.func,
@ -32,7 +33,7 @@ let PieceExtraDataForm = React.createClass({
},
render() {
const { editable, extraData, handleSuccess, name, pieceId, title } = this.props;
const { convertLinks, editable, extraData, handleSuccess, name, pieceId, title } = this.props;
const defaultValue = (extraData && extraData[name]) || null;
if (!defaultValue && !editable) {
@ -42,15 +43,16 @@ let PieceExtraDataForm = React.createClass({
return (
<Form
ref='form'
url={requests.prepareUrl(ApiUrls.piece_extradata, { piece_id: pieceId })}
handleSuccess={handleSuccess}
disabled={!editable}
getFormData={this.getFormData}
disabled={!editable}>
handleSuccess={handleSuccess}
url={requests.prepareUrl(ApiUrls.piece_extradata, { piece_id: pieceId })}>
<Property
name={name}
label={title}>
<InputTextAreaToggable
rows={1}
convertLinks={convertLinks}
defaultValue={defaultValue}
placeholder={getLangText('Fill in%s', ' ') + title}
required />

View File

@ -2,36 +2,40 @@
import React from 'react';
import UserStore from '../../stores/user_store';
import UserActions from '../../actions/user_actions';
import Form from './form';
import Property from './property';
import InputFineUploader from './input_fineuploader';
import UploadButton from '../ascribe_uploader/ascribe_upload_button/upload_button';
import FormSubmitButton from '../ascribe_buttons/form_submit_button';
import { FileStatus } from '../ascribe_uploader/react_s3_fine_uploader_utils';
import UploadButton from '../ascribe_uploader/ascribe_upload_button/upload_button';
import AscribeSpinner from '../ascribe_spinner';
import ApiUrls from '../../constants/api_urls';
import AppConstants from '../../constants/application_constants';
import AscribeSpinner from '../ascribe_spinner';
import { validationParts, validationTypes } from '../../constants/uploader_constants';
import { getLangText } from '../../utils/lang_utils';
import { mergeOptions } from '../../utils/general_utils';
import { formSubmissionValidation } from '../ascribe_uploader/react_s3_fine_uploader_utils';
let RegisterPieceForm = React.createClass({
propTypes: {
currentUser: React.PropTypes.object.isRequired,
headerMessage: React.PropTypes.string,
submitMessage: React.PropTypes.string,
handleSuccess: React.PropTypes.func,
isFineUploaderActive: React.PropTypes.bool,
isFineUploaderEditable: React.PropTypes.bool,
enableLocalHashing: React.PropTypes.bool,
enableSeparateThumbnail: React.PropTypes.bool,
isFineUploaderActive: React.PropTypes.bool,
isFineUploaderEditable: React.PropTypes.bool,
handleSuccess: React.PropTypes.func,
// For this form to work with SlideContainer, we sometimes have to disable it
disabled: React.PropTypes.bool,
location: React.PropTypes.object,
children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element),
@ -48,26 +52,10 @@ let RegisterPieceForm = React.createClass({
};
},
getInitialState(){
return mergeOptions(
{
digitalWorkFile: null
},
UserStore.getState()
);
},
componentDidMount() {
UserStore.listen(this.onChange);
UserActions.fetchCurrentUser();
},
componentWillUnmount() {
UserStore.unlisten(this.onChange);
},
onChange(state) {
this.setState(state);
getInitialState() {
return {
digitalWorkFile: null
}
},
/**
@ -85,7 +73,7 @@ let RegisterPieceForm = React.createClass({
handleChangedDigitalWork(digitalWorkFile) {
if (digitalWorkFile &&
(digitalWorkFile.status === 'deleted' || digitalWorkFile.status === 'canceled')) {
(digitalWorkFile.status === FileStatus.DELETED || digitalWorkFile.status === FileStatus.CANCELED)) {
this.refs.form.refs.thumbnail_file.reset();
// Manually we need to set the ready state for `thumbnailKeyReady` back
@ -104,8 +92,8 @@ let RegisterPieceForm = React.createClass({
fineuploader.setThumbnailForFileId(
digitalWorkFile.id,
// if thumbnail was delete, we delete it from the display as well
thumbnailFile.status !== 'deleted' ? thumbnailFile.url : null
// if thumbnail was deleted, we delete it from the display as well
thumbnailFile.status !== FileStatus.DELETED ? thumbnailFile.url : null
);
},
@ -129,16 +117,16 @@ let RegisterPieceForm = React.createClass({
},
render() {
const { disabled,
const { children,
currentUser,
disabled,
enableLocalHashing,
handleSuccess,
submitMessage,
headerMessage,
isFineUploaderActive,
isFineUploaderEditable,
location,
children,
enableLocalHashing } = this.props;
const { currentUser} = this.state;
submitMessage } = this.props;
const profileHashLocally = currentUser && currentUser.profile ? currentUser.profile.hash_locally : false;
const hashLocally = profileHashLocally && enableLocalHashing;
@ -180,14 +168,15 @@ let RegisterPieceForm = React.createClass({
createBlobRoutine={{
url: ApiUrls.blob_digitalworks
}}
validation={AppConstants.fineUploader.validation.registerWork}
validation={validationTypes.registerWork}
setIsUploadReady={this.setIsUploadReady('digitalWorkKeyReady')}
isReadyForFormSubmission={formSubmissionValidation.atLeastOneUploadedFile}
isFineUploaderActive={isFineUploaderActive}
disabled={!isFineUploaderEditable}
enableLocalHashing={hashLocally}
uploadMethod={location.query.method}
handleChangedFile={this.handleChangedDigitalWork}/>
handleChangedFile={this.handleChangedDigitalWork}
showErrorPrompt />
</Property>
<Property
name="thumbnail_file"
@ -206,9 +195,9 @@ let RegisterPieceForm = React.createClass({
fileClass: 'thumbnail'
}}
validation={{
itemLimit: AppConstants.fineUploader.validation.workThumbnail.itemLimit,
sizeLimit: AppConstants.fineUploader.validation.workThumbnail.sizeLimit,
allowedExtensions: ['png', 'jpg', 'jpeg', 'gif']
itemLimit: validationTypes.workThumbnail.itemLimit,
sizeLimit: validationTypes.workThumbnail.sizeLimit,
allowedExtensions: validationParts.allowedExtensions.images
}}
setIsUploadReady={this.setIsUploadReady('thumbnailKeyReady')}
fileClassToUpload={{
@ -216,9 +205,7 @@ let RegisterPieceForm = React.createClass({
plural: getLangText('Select representative images')
}}
isFineUploaderActive={isFineUploaderActive}
disabled={!isFineUploaderEditable}
enableLocalHashing={enableLocalHashing}
uploadMethod={location.query.method} />
disabled={!isFineUploaderEditable} />
</Property>
<Property
name='artist_name'

View File

@ -21,11 +21,12 @@ import { getLangText } from '../../utils/lang_utils.js';
let RequestActionForm = React.createClass({
propTypes: {
notifications: React.PropTypes.object.isRequired,
pieceOrEditions: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.array
]).isRequired,
notifications: React.PropTypes.object,
currentUser: React.PropTypes.object,
handleSuccess: React.PropTypes.func
},

View File

@ -128,8 +128,7 @@ let SendContractAgreementForm = React.createClass({
<Property
name='appendix'
checkboxLabel={getLangText('Add appendix to the contract')}
expanded={false}
style={{paddingBottom: 0}}>
expanded={false}>
<span>{getLangText('Appendix')}</span>
{/* We're using disabled on a form here as PropertyCollapsible currently
does not support the disabled + overrideForm functionality */}

View File

@ -3,12 +3,11 @@
import React from 'react';
import { History } from 'react-router';
import UserStore from '../../stores/user_store';
import UserActions from '../../actions/user_actions';
import GlobalNotificationModel from '../../models/global_notification_model';
import GlobalNotificationActions from '../../actions/global_notification_actions';
import UserActions from '../../actions/user_actions';
import Form from './form';
import Property from './property';
import InputCheckbox from './input_checkbox';
@ -24,8 +23,12 @@ let SignupForm = React.createClass({
headerMessage: React.PropTypes.string,
submitMessage: React.PropTypes.string,
handleSuccess: React.PropTypes.func,
children: React.PropTypes.element,
location: React.PropTypes.object
location: React.PropTypes.object,
children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element),
React.PropTypes.element,
React.PropTypes.string
])
},
mixins: [History],
@ -37,27 +40,11 @@ let SignupForm = React.createClass({
};
},
getInitialState() {
return UserStore.getState();
},
componentDidMount() {
UserStore.listen(this.onChange);
},
componentWillUnmount() {
UserStore.unlisten(this.onChange);
},
onChange(state) {
this.setState(state);
},
handleSuccess(response) {
if (response.user) {
let notification = new GlobalNotificationModel(getLangText('Sign up successful'), 'success', 50000);
const notification = new GlobalNotificationModel(getLangText('Sign up successful'), 'success', 50000);
GlobalNotificationActions.appendGlobalNotification(notification);
// Refactor this to its own component
this.props.handleSuccess(getLangText('We sent an email to your address') + ' ' + response.user.email + ', ' + getLangText('please confirm') + '.');
} else {
@ -66,18 +53,19 @@ let SignupForm = React.createClass({
},
getFormData() {
if (this.props.location.query.token){
return {token: this.props.location.query.token};
}
return null;
const { token } = this.props.location.query;
return token ? { token } : null;
},
render() {
let tooltipPassword = getLangText('Your password must be at least 10 characters') + '.\n ' +
getLangText('This password is securing your digital property like a bank account') + '.\n ' +
getLangText('Store it in a safe place') + '!';
const { children,
headerMessage,
location: { query: { email: emailQuery } },
submitMessage } = this.props;
let email = this.props.location.query.email || null;
const tooltipPassword = getLangText('Your password must be at least 10 characters') + '.\n ' +
getLangText('This password is securing your digital property like a bank account') + '.\n ' +
getLangText('Store it in a safe place') + '!';
return (
<Form
@ -88,15 +76,16 @@ let SignupForm = React.createClass({
handleSuccess={this.handleSuccess}
buttons={
<button type="submit" className="btn btn-default btn-wide">
{this.props.submitMessage}
</button>}
{submitMessage}
</button>
}
spinner={
<span className="btn btn-default btn-wide btn-spinner">
<AscribeSpinner color="dark-blue" size="md" />
</span>
}>
}>
<div className="ascribe-form-header">
<h3>{this.props.headerMessage}</h3>
<h3>{headerMessage}</h3>
</div>
<Property
name='email'
@ -105,7 +94,7 @@ let SignupForm = React.createClass({
type="email"
placeholder={getLangText('(e.g. andy@warhol.co.uk)')}
autoComplete="on"
defaultValue={email}
defaultValue={emailQuery}
required/>
</Property>
<Property
@ -128,11 +117,10 @@ let SignupForm = React.createClass({
autoComplete="on"
required/>
</Property>
{this.props.children}
{children}
<Property
name="terms"
className="ascribe-property-collapsible-toggle"
style={{paddingBottom: 0}}>
className="ascribe-property-collapsible-toggle">
<InputCheckbox>
<span>
{' ' + getLangText('I agree to the Terms of Service of ascribe') + ' '}

View File

@ -66,8 +66,7 @@ let PieceSubmitToPrizeForm = React.createClass({
</Property>
<Property
name="terms"
className="ascribe-property-collapsible-toggle"
style={{paddingBottom: 0}}>
className="ascribe-property-collapsible-toggle">
<InputCheckbox>
<span>
{' ' + getLangText('I agree to the Terms of Service the art price') + ' '}

View File

@ -18,26 +18,26 @@ import { getLangText } from '../../utils/lang_utils.js';
let TransferForm = React.createClass({
propTypes: {
url: React.PropTypes.string,
id: React.PropTypes.object,
message: React.PropTypes.string,
editions: React.PropTypes.array,
currentUser: React.PropTypes.object,
handleSuccess: React.PropTypes.func
id: React.PropTypes.object.isRequired,
url: React.PropTypes.string.isRequired,
handleSuccess: React.PropTypes.func,
message: React.PropTypes.string
},
getFormData(){
getFormData() {
return this.props.id;
},
render() {
const { handleSuccess, message, url } = this.props;
return (
<Form
ref='form'
url={this.props.url}
url={url}
getFormData={this.getFormData}
handleSuccess={this.props.handleSuccess}
handleSuccess={handleSuccess}
buttons={
<div className="modal-footer">
<p className="pull-right">
@ -70,7 +70,7 @@ let TransferForm = React.createClass({
overrideForm={true}>
<InputTextAreaToggable
rows={1}
defaultValue={this.props.message}
defaultValue={message}
placeholder={getLangText('Enter a message...')}
required />
</Property>

View File

@ -154,7 +154,7 @@ const InputContractAgreementCheckbox = React.createClass({
return (
<div
className="notification-contract-pdf"
style={{paddingBottom: '1em'}}>
style={{paddingBottom: '0.25em'}}>
<embed
className="embed-form"
src={contractUrl}

View File

@ -17,10 +17,7 @@ let InputDate = React.createClass({
},
getInitialState() {
return {
value: null,
value_moment: null
};
return this.getStateFromMoment(this.props.defaultValue);
},
// InputDate needs to support setting a defaultValue from outside.
@ -28,20 +25,30 @@ let InputDate = React.createClass({
// to the outer Property
componentWillReceiveProps(nextProps) {
if(!this.state.value && !this.state.value_moment && nextProps.defaultValue) {
this.handleChange(this.props.defaultValue);
this.handleChange(nextProps.defaultValue);
}
},
handleChange(date) {
let formattedDate = date.format('YYYY-MM-DD');
this.setState({
value: formattedDate,
value_moment: date
});
getStateFromMoment(date) {
const state = {};
if (date) {
state.value = date.format('YYYY-MM-DD');
state.value_moment = date;
}
return state;
},
handleChange(date) {
const newState = this.getStateFromMoment(date);
this.setState(newState);
// Propagate change up by faking event
this.props.onChange({
target: {
value: formattedDate
value: newState.value
}
});
},

View File

@ -10,52 +10,35 @@ import AppConstants from '../../constants/application_constants';
import { getCookie } from '../../utils/fetch_api_utils';
const { func, bool, shape, string, number, arrayOf } = React.PropTypes;
const { func, bool, shape, string, number, element, oneOf, oneOfType, arrayOf } = React.PropTypes;
const InputFineUploader = React.createClass({
propTypes: {
setIsUploadReady: func,
isReadyForFormSubmission: func,
submitFile: func,
fileInputElement: func,
areAssetsDownloadable: bool,
keyRoutine: shape({
url: string,
fileClass: string
}),
createBlobRoutine: shape({
url: string
}),
validation: shape({
itemLimit: number,
sizeLimit: string,
allowedExtensions: arrayOf(string)
}),
// isFineUploaderActive is used to lock react fine uploader in case
// a user is actually not logged in already to prevent him from droping files
// before login in
isFineUploaderActive: bool,
enableLocalHashing: bool,
uploadMethod: string,
// provided by Property
disabled: bool,
onChange: func,
// A class of a file the user has to upload
// Needs to be defined both in singular as well as in plural
fileClassToUpload: shape({
singular: string,
plural: string
}),
handleChangedFile: func,
// Props for ReactS3FineUploader
areAssetsDownloadable: bool,
createBlobRoutine: ReactS3FineUploader.propTypes.createBlobRoutine,
enableLocalHashing: bool,
fileClassToUpload: ReactS3FineUploader.propTypes.fileClassToUpload,
fileInputElement: ReactS3FineUploader.propTypes.fileInputElement,
isReadyForFormSubmission: func,
keyRoutine: ReactS3FineUploader.propTypes.keyRoutine,
handleChangedFile: func, // TODO: rename to onChangedFile
submitFile: func, // TODO: rename to onSubmitFile
onValidationFailed: func,
// Provided by `Property`
onChange: React.PropTypes.func
setIsUploadReady: func, //TODO: rename to setIsUploaderValidated
setWarning: func,
showErrorPrompt: bool,
uploadMethod: oneOf(['hash', 'upload']),
validation: ReactS3FineUploader.propTypes.validation,
},
getDefaultProps() {
@ -99,19 +82,21 @@ const InputFineUploader = React.createClass({
render() {
const { areAssetsDownloadable,
enableLocalHashing,
createBlobRoutine,
enableLocalHashing,
disabled,
fileClassToUpload,
fileInputElement,
handleChangedFile,
isFineUploaderActive,
isReadyForFormSubmission,
keyRoutine,
onValidationFailed,
setIsUploadReady,
setWarning,
showErrorPrompt,
uploadMethod,
validation,
handleChangedFile } = this.props;
validation } = this.props;
let editable = isFineUploaderActive;
// if disabled is actually set by property, we want to override
@ -133,6 +118,8 @@ const InputFineUploader = React.createClass({
isReadyForFormSubmission={isReadyForFormSubmission}
areAssetsDownloadable={areAssetsDownloadable}
areAssetsEditable={editable}
setWarning={setWarning}
showErrorPrompt={showErrorPrompt}
signature={{
endpoint: AppConstants.serverUrl + 's3/signature/',
customHeaders: {
@ -150,7 +137,7 @@ const InputFineUploader = React.createClass({
enableLocalHashing={enableLocalHashing}
uploadMethod={uploadMethod}
fileClassToUpload={fileClassToUpload}
handleChangedFile={handleChangedFile}/>
handleChangedFile={handleChangedFile} />
);
}
});

View File

@ -4,17 +4,20 @@ import React from 'react';
import TextareaAutosize from 'react-textarea-autosize';
import { anchorize } from '../../utils/dom_utils';
let InputTextAreaToggable = React.createClass({
propTypes: {
autoFocus: React.PropTypes.bool,
disabled: React.PropTypes.bool,
rows: React.PropTypes.number.isRequired,
required: React.PropTypes.bool,
convertLinks: React.PropTypes.bool,
defaultValue: React.PropTypes.string,
placeholder: React.PropTypes.string,
disabled: React.PropTypes.bool,
onBlur: React.PropTypes.func,
onChange: React.PropTypes.func
onChange: React.PropTypes.func,
placeholder: React.PropTypes.string,
required: React.PropTypes.bool,
rows: React.PropTypes.number.isRequired
},
getInitialState() {
@ -36,7 +39,7 @@ let InputTextAreaToggable = React.createClass({
componentDidUpdate() {
// If the initial value of state.value is null, we want to set props.defaultValue
// as a value. In all other cases TextareaAutosize.onChange is updating.handleChange already
if(this.state.value === null && this.props.defaultValue) {
if (this.state.value === null && this.props.defaultValue) {
this.setState({
value: this.props.defaultValue
});
@ -49,28 +52,26 @@ let InputTextAreaToggable = React.createClass({
},
render() {
let className = 'form-control ascribe-textarea';
let textarea = null;
const { convertLinks, disabled, onBlur, placeholder, required, rows } = this.props;
const { value } = this.state;
if(!this.props.disabled) {
className = className + ' ascribe-textarea-editable';
textarea = (
if (!disabled) {
return (
<TextareaAutosize
ref='textarea'
className={className}
value={this.state.value}
rows={this.props.rows}
className='form-control ascribe-textarea ascribe-textarea-editable'
value={value}
rows={rows}
maxRows={10}
required={this.props.required}
required={required}
onChange={this.handleChange}
onBlur={this.props.onBlur}
placeholder={this.props.placeholder} />
onBlur={onBlur}
placeholder={placeholder} />
);
} else {
textarea = <pre className="ascribe-pre">{this.state.value}</pre>;
// Can only convert links when not editable, as textarea does not support anchors
return <pre className="ascribe-pre">{convertLinks ? anchorize(value) : value}</pre>;
}
return textarea;
}
});

View File

@ -4,32 +4,35 @@ import React from 'react';
import RequestActionForm from './form_request_action';
let ListRequestActions = React.createClass({
propTypes: {
notifications: React.PropTypes.array.isRequired,
pieceOrEditions: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.array
]).isRequired,
currentUser: React.PropTypes.object,
handleSuccess: React.PropTypes.func.isRequired,
notifications: React.PropTypes.array.isRequired
handleSuccess: React.PropTypes.func
},
render () {
if (this.props.notifications &&
this.props.notifications.length > 0) {
const { currentUser, handleSuccess, notifications, pieceOrEditions } = this.props;
if (notifications.length) {
return (
<div>
{this.props.notifications.map((notification) =>
{notifications.map((notification) =>
<RequestActionForm
currentUser={this.props.currentUser}
pieceOrEditions={ this.props.pieceOrEditions }
currentUser={currentUser}
handleSuccess={handleSuccess}
notifications={notification}
handleSuccess={this.props.handleSuccess}/>)}
pieceOrEditions={pieceOrEditions} />
)}
</div>
);
} else {
return null;
}
return null;
}
});

View File

@ -72,7 +72,8 @@ const Property = React.createClass({
initialValue: null,
value: null,
isFocused: false,
errors: null
errors: null,
hasWarning: false
};
},
@ -218,17 +219,20 @@ const Property = React.createClass({
this.setState({errors: null});
},
setWarning(hasWarning) {
this.setState({ hasWarning });
},
getClassName() {
if(!this.state.expanded && !this.props.checkboxLabel){
if (!this.state.expanded && !this.props.checkboxLabel) {
return 'is-hidden';
}
if(!this.props.editable){
} else if (!this.props.editable) {
return 'is-fixed';
}
if (this.state.errors){
} else if (this.state.errors) {
return 'is-error';
}
if(this.state.isFocused) {
} else if (this.state.hasWarning) {
return 'is-warning';
} else if (this.state.isFocused) {
return 'is-focused';
} else {
return '';
@ -240,7 +244,17 @@ const Property = React.createClass({
},
handleCheckboxToggle() {
this.setExpanded(!this.state.expanded);
const expanded = !this.state.expanded;
this.setExpanded(expanded);
// Reset the value to be the initial value when the checkbox is unticked since the
// user doesn't want to specify their own value.
if (!expanded) {
this.setState({
value: this.state.initialValue
});
}
},
renderChildren(style) {
@ -261,6 +275,7 @@ const Property = React.createClass({
onChange: this.handleChange,
onFocus: this.handleFocus,
onBlur: this.handleBlur,
setWarning: this.setWarning,
disabled: !this.props.editable,
ref: 'input',
name: this.props.name,
@ -284,18 +299,18 @@ const Property = React.createClass({
},
getCheckbox() {
const { checkboxLabel } = this.props;
const { checkboxLabel, name } = this.props;
if(checkboxLabel) {
if (checkboxLabel) {
return (
<div
className="ascribe-property-collapsible-toggle"
onClick={this.handleCheckboxToggle}>
<input
onChange={this.handleCheckboxToggle}
type="checkbox"
name={`${name}-checkbox`}
checked={this.state.expanded}
ref="checkboxCollapsible"/>
onChange={this.handleCheckboxToggle}
type="checkbox" />
<span className="checkbox">{' ' + checkboxLabel}</span>
</div>
);

View File

@ -6,6 +6,10 @@ import Modal from 'react-bootstrap/lib/Modal';
let ModalWrapper = React.createClass({
propTypes: {
children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element),
React.PropTypes.element
]).isRequired,
title: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element),
React.PropTypes.element,
@ -14,11 +18,7 @@ let ModalWrapper = React.createClass({
handleCancel: React.PropTypes.func,
handleSuccess: React.PropTypes.func,
trigger: React.PropTypes.element,
children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element),
React.PropTypes.element
])
trigger: React.PropTypes.element
},
getInitialState() {

View File

@ -84,9 +84,10 @@ let PieceListToolbarFilterWidget = React.createClass({
if (this.props.filterParams && this.props.filterParams.length) {
return (
<DropdownButton
id="ascribe-piece-list-toolbar-filter-widget-dropdown"
pullRight={true}
title={filterIcon}
className="ascribe-piece-list-toolbar-filter-widget">
className="ascribe-piece-list-toolbar-widget">
{/* We iterate over filterParams, to receive the label and then for each
label also iterate over its items, to get all filterable options */}
{this.props.filterParams.map(({ label, items }, i) => {
@ -120,7 +121,7 @@ let PieceListToolbarFilterWidget = React.createClass({
<li
key={itemLabel}
onClick={this.filterBy(param)}
className="filter-widget-item">
className="ascribe-piece-list-toolbar-widget-item">
<div className="checkbox-line">
<span>
{getLangText(itemLabel)}

View File

@ -45,7 +45,7 @@ let PieceListToolbarOrderWidget = React.createClass({
},
render() {
let filterIcon = (
let orderIcon = (
<span>
<span className="ascribe-icon icon-ascribe-sort" aria-hidden="true"></span>
<span style={this.isOrderActive()}>&middot;</span>
@ -55,9 +55,10 @@ let PieceListToolbarOrderWidget = React.createClass({
if (this.props.orderParams && this.props.orderParams.length) {
return (
<DropdownButton
id="ascribe-piece-list-toolbar-order-widget-dropdown"
pullRight={true}
title={filterIcon}
className="ascribe-piece-list-toolbar-filter-widget">
className="ascribe-piece-list-toolbar-widget"
title={orderIcon}>
<li style={{'textAlign': 'center'}}>
<em>{getLangText('Sort by')}:</em>
</li>
@ -66,7 +67,7 @@ let PieceListToolbarOrderWidget = React.createClass({
<li
key={param}
onClick={this.orderBy(param)}
className="filter-widget-item">
className="ascribe-piece-list-toolbar-widget-item">
<div className="checkbox-line">
<span>
{getLangText(param.replace('_', ' '))}

View File

@ -5,7 +5,6 @@ import { RouteContext } from 'react-router';
import history from '../../history';
import UserStore from '../../stores/user_store';
import UserActions from '../../actions/user_actions';
import AppConstants from '../../constants/application_constants';
@ -18,11 +17,11 @@ const WHEN_ENUM = ['loggedIn', 'loggedOut'];
*
* @param {enum/string} options.when ('loggedIn' || 'loggedOut')
*/
export function AuthRedirect({to, when}) {
export function AuthRedirect({ to, when }) {
// validate `when`, must be contained in `WHEN_ENUM`.
// Throw an error otherwise.
if(WHEN_ENUM.indexOf(when) === -1) {
let whenValues = WHEN_ENUM.join(', ');
if (WHEN_ENUM.indexOf(when) === -1) {
const whenValues = WHEN_ENUM.join(', ');
throw new Error(`"when" must be one of: [${whenValues}] got "${when}" instead`);
}
@ -35,23 +34,22 @@ export function AuthRedirect({to, when}) {
//
// So if when === 'loggedIn', we're checking if the user is logged in (and
// vice versa)
let exprToValidate = when === 'loggedIn' ? currentUser && currentUser.email
: currentUser && !currentUser.email;
const isLoggedIn = Object.keys(currentUser).length && currentUser.email;
const exprToValidate = when === 'loggedIn' ? isLoggedIn : !isLoggedIn;
// and redirect if `true`.
if(exprToValidate) {
if (exprToValidate) {
window.setTimeout(() => history.replace({ query, pathname: to }));
return true;
// Otherwise there can also be the case that the backend
// wants to redirect the user to a specific route when the user is logged out already
} else if(!exprToValidate && when === 'loggedIn' && redirect) {
} else if (!exprToValidate && when === 'loggedIn' && redirect) {
delete query.redirect;
window.setTimeout(() => history.replace({ query, pathname: '/' + redirect }));
return true;
} else if(!exprToValidate && when === 'loggedOut' && redirectAuthenticated) {
} else if (!exprToValidate && when === 'loggedOut' && redirectAuthenticated) {
/*
* redirectAuthenticated contains an arbitrary path
* eg pieces/<id>, editions/<bitcoin_id>, collection, settings, ...
@ -64,6 +62,7 @@ export function AuthRedirect({to, when}) {
window.location = AppConstants.baseUrl + redirectAuthenticated;
return true;
}
return false;
};
}
@ -81,6 +80,11 @@ export function ProxyHandler(...redirectFunctions) {
displayName: 'ProxyHandler',
propTypes: {
// Provided from AscribeApp, after the routes have been initialized
currentUser: React.PropTypes.object,
whitelabel: React.PropTypes.object,
// Provided from router
location: object
},
@ -88,43 +92,33 @@ export function ProxyHandler(...redirectFunctions) {
// to use the `Lifecycle` widget in further down nested components
mixins: [RouteContext],
getInitialState() {
return UserStore.getState();
},
componentDidMount() {
UserStore.listen(this.onChange);
UserActions.fetchCurrentUser();
this.evaluateRedirectFunctions();
},
componentDidUpdate() {
if(!UserStore.isLoading()) {
const { currentUser } = this.state;
const { query } = this.props.location;
componentWillReceiveProps(nextProps) {
this.evaluateRedirectFunctions(nextProps);
},
for(let i = 0; i < redirectFunctions.length; i++) {
evaluateRedirectFunctions(props = this.props) {
const { currentUser, location: { query } } = props;
if (UserStore.hasLoaded() && !UserStore.isLoading()) {
for (let i = 0; i < redirectFunctions.length; i++) {
// if a redirectFunction redirects the user,
// it should return `true` and therefore
// stop/avoid the execution of all functions
// that follow
if(redirectFunctions[i](currentUser, query)) {
if (redirectFunctions[i](currentUser, query)) {
break;
}
}
}
},
componentWillUnmount() {
UserStore.unlisten(this.onChange);
},
onChange(state) {
this.setState(state);
},
render() {
return (
<Component {...this.props}/>
<Component {...this.props} />
);
}
});

View File

@ -26,21 +26,23 @@ let AccountSettings = React.createClass({
whitelabel: React.PropTypes.object.isRequired
},
handleSuccess(){
handleSuccess() {
this.props.loadUser(true);
let notification = new GlobalNotificationModel(getLangText('Settings succesfully updated'), 'success', 5000);
const notification = new GlobalNotificationModel(getLangText('Settings succesfully updated'), 'success', 5000);
GlobalNotificationActions.appendGlobalNotification(notification);
},
getFormDataProfile(){
return {'email': this.props.currentUser.email};
getFormDataProfile() {
return { 'email': this.props.currentUser.email };
},
render() {
let content = <AscribeSpinner color='dark-blue' size='lg'/>;
const { currentUser, whitelabel } = this.props;
let content = <AscribeSpinner color='dark-blue' size='lg' />;
let profile = null;
if (this.props.currentUser.username) {
if (currentUser.username) {
content = (
<Form
url={ApiUrls.users_username}
@ -50,7 +52,7 @@ let AccountSettings = React.createClass({
label={getLangText('Username')}>
<input
type="text"
defaultValue={this.props.currentUser.username}
defaultValue={currentUser.username}
placeholder={getLangText('Enter your username')}
required/>
</Property>
@ -61,7 +63,7 @@ let AccountSettings = React.createClass({
editable={false}>
<input
type="text"
defaultValue={this.props.currentUser.email}
defaultValue={currentUser.email}
placeholder={getLangText('Enter your username')}
required/>
</Property>
@ -70,7 +72,7 @@ let AccountSettings = React.createClass({
);
profile = (
<AclProxy
aclObject={this.props.whitelabel}
aclObject={whitelabel}
aclName="acl_view_settings_account_hash">
<Form
url={ApiUrls.users_profile}
@ -78,10 +80,9 @@ let AccountSettings = React.createClass({
getFormData={this.getFormDataProfile}>
<Property
name="hash_locally"
className="ascribe-property-collapsible-toggle"
style={{paddingBottom: 0}}>
className="ascribe-property-collapsible-toggle">
<InputCheckbox
defaultChecked={this.props.currentUser.profile.hash_locally}>
defaultChecked={currentUser.profile.hash_locally}>
<span>
{' ' + getLangText('Enable hash option, e.g. slow connections or to keep piece private')}
</span>
@ -97,9 +98,9 @@ let AccountSettings = React.createClass({
defaultExpanded={true}>
{content}
<AclProxy
aclObject={this.props.whitelabel}
aclObject={whitelabel}
aclName="acl_view_settings_copyright_association">
<CopyrightAssociationForm currentUser={this.props.currentUser}/>
<CopyrightAssociationForm currentUser={currentUser} />
</AclProxy>
{profile}
</CollapsibleParagraph>

View File

@ -8,12 +8,6 @@ import CreateContractForm from '../ascribe_forms/form_create_contract';
import ContractListStore from '../../stores/contract_list_store';
import ContractListActions from '../../actions/contract_list_actions';
import UserStore from '../../stores/user_store';
import UserActions from '../../actions/user_actions';
import WhitelabelStore from '../../stores/whitelabel_store';
import WhitelabelActions from '../../actions/whitelabel_actions';
import ActionPanel from '../ascribe_panel/action_panel';
import ContractSettingsUpdateButton from './contract_settings_update_button';
@ -24,34 +18,29 @@ import AclProxy from '../acl_proxy';
import { getLangText } from '../../utils/lang_utils';
import { setDocumentTitle } from '../../utils/dom_utils';
import { mergeOptions, truncateTextAtCharIndex } from '../../utils/general_utils';
import { truncateTextAtCharIndex } from '../../utils/general_utils';
let ContractSettings = React.createClass({
propTypes: {
// Provided from AscribeApp
currentUser: React.PropTypes.object.isRequired,
whitelabel: React.PropTypes.object.isRequired,
// Provided from router
location: React.PropTypes.object
},
getInitialState(){
return mergeOptions(
ContractListStore.getState(),
UserStore.getState()
);
getInitialState() {
return ContractListStore.getState();
},
componentDidMount() {
ContractListStore.listen(this.onChange);
UserStore.listen(this.onChange);
WhitelabelStore.listen(this.onChange);
WhitelabelActions.fetchWhitelabel();
UserActions.fetchCurrentUser();
ContractListActions.fetchContractList(true);
},
componentWillUnmount() {
WhitelabelStore.unlisten(this.onChange);
UserStore.unlisten(this.onChange);
ContractListStore.unlisten(this.onChange);
},
@ -64,40 +53,40 @@ let ContractSettings = React.createClass({
ContractListActions.removeContract(contract.id)
.then((response) => {
ContractListActions.fetchContractList(true);
let notification = new GlobalNotificationModel(response.notification, 'success', 4000);
const notification = new GlobalNotificationModel(response.notification, 'success', 4000);
GlobalNotificationActions.appendGlobalNotification(notification);
})
.catch((err) => {
let notification = new GlobalNotificationModel(err, 'danger', 10000);
const notification = new GlobalNotificationModel(err, 'danger', 10000);
GlobalNotificationActions.appendGlobalNotification(notification);
});
};
},
getPublicContracts(){
getPublicContracts() {
return this.state.contractList.filter((contract) => contract.is_public);
},
getPrivateContracts(){
getPrivateContracts() {
return this.state.contractList.filter((contract) => !contract.is_public);
},
render() {
let publicContracts = this.getPublicContracts();
let privateContracts = this.getPrivateContracts();
const { currentUser, location, whitelabel } = this.props;
const publicContracts = this.getPublicContracts();
const privateContracts = this.getPrivateContracts();
let createPublicContractForm = null;
setDocumentTitle(getLangText('Contracts settings'));
if(publicContracts.length === 0) {
if (publicContracts.length === 0) {
createPublicContractForm = (
<CreateContractForm
isPublic={true}
fileClassToUpload={{
singular: 'new contract',
plural: 'new contracts'
}}
location={this.props.location}/>
isPublic={true} />
);
}
@ -108,23 +97,21 @@ let ContractSettings = React.createClass({
defaultExpanded={true}>
<AclProxy
aclName="acl_edit_public_contract"
aclObject={this.state.currentUser.acl}>
aclObject={currentUser.acl}>
<div>
{createPublicContractForm}
{publicContracts.map((contract, i) => {
return (
<ActionPanel
key={i}
key={contract.id}
title={contract.name}
content={truncateTextAtCharIndex(contract.name, 120, '(...).pdf')}
buttons={
<div className="pull-right">
<AclProxy
aclObject={this.state.whitelabel}
aclObject={whitelabel}
aclName="acl_update_public_contract">
<ContractSettingsUpdateButton
contract={contract}
location={this.props.location}/>
<ContractSettingsUpdateButton contract={contract} />
</AclProxy>
<a
className="btn btn-default btn-sm margin-left-2px"
@ -147,29 +134,26 @@ let ContractSettings = React.createClass({
</AclProxy>
<AclProxy
aclName="acl_edit_private_contract"
aclObject={this.state.currentUser.acl}>
aclObject={currentUser.acl}>
<div>
<CreateContractForm
isPublic={false}
fileClassToUpload={{
singular: getLangText('new contract'),
plural: getLangText('new contracts')
}}
location={this.props.location}/>
fileClassToUpload={{
singular: getLangText('new contract'),
plural: getLangText('new contracts')
}}
isPublic={false} />
{privateContracts.map((contract, i) => {
return (
<ActionPanel
key={i}
key={contract.id}
title={contract.name}
content={truncateTextAtCharIndex(contract.name, 120, '(...).pdf')}
buttons={
<div className="pull-right">
<AclProxy
aclObject={this.state.whitelabel}
aclObject={whitelabel}
aclName="acl_update_private_contract">
<ContractSettingsUpdateButton
contract={contract}
location={this.props.location}/>
<ContractSettingsUpdateButton contract={contract} />
</AclProxy>
<a
className="btn btn-default btn-sm margin-left-2px"

View File

@ -2,17 +2,18 @@
import React from 'react';
import ReactS3FineUploader from '../ascribe_uploader/react_s3_fine_uploader';
import UploadButton from '../ascribe_uploader/ascribe_upload_button/upload_button';
import AppConstants from '../../constants/application_constants';
import ApiUrls from '../../constants/api_urls';
import ContractListActions from '../../actions/contract_list_actions';
import GlobalNotificationModel from '../../models/global_notification_model';
import GlobalNotificationActions from '../../actions/global_notification_actions';
import ReactS3FineUploader from '../ascribe_uploader/react_s3_fine_uploader';
import UploadButton from '../ascribe_uploader/ascribe_upload_button/upload_button';
import ApiUrls from '../../constants/api_urls';
import AppConstants from '../../constants/application_constants';
import { validationTypes } from '../../constants/uploader_constants';
import { formSubmissionValidation } from '../ascribe_uploader/react_s3_fine_uploader_utils';
import { getCookie } from '../../utils/fetch_api_utils';
import { getLangText } from '../../utils/lang_utils';
@ -24,71 +25,75 @@ let ContractSettingsUpdateButton = React.createClass({
},
submitFile(file) {
let contract = this.props.contract;
// override the blob with the key's value
contract.blob = file.key;
const contract = Object.assign(this.props.contract, { blob: file.key });
// send it to the server
ContractListActions
.changeContract(contract)
.then((res) => {
// Display feedback to the user
let notification = new GlobalNotificationModel(getLangText('Contract %s successfully updated', res.name), 'success', 5000);
const notification = new GlobalNotificationModel(getLangText('Contract %s successfully updated', contract.name), 'success', 5000);
GlobalNotificationActions.appendGlobalNotification(notification);
// and refresh the contract list to get the updated contracs
return ContractListActions.fetchContractList(true);
})
.then(() => {
// Also, reset the fineuploader component so that the user can again 'update' his contract
this.refs.fineuploader.reset();
})
.catch((err) => {
console.logGlobal(err);
let notification = new GlobalNotificationModel(getLangText('Contract could not be updated'), 'success', 5000);
return ContractListActions
.fetchContractList(true)
// Also, reset the fineuploader component if fetch is successful so that the user can again 'update' his contract
.then(this.refs.fineuploader.reset)
.catch((err) => {
const notification = new GlobalNotificationModel(getLangText('Latest contract failed to load'), 'danger', 5000);
GlobalNotificationActions.appendGlobalNotification(notification);
return Promise.reject(err);
});
}, (err) => {
const notification = new GlobalNotificationModel(getLangText('Contract could not be updated'), 'danger', 5000);
GlobalNotificationActions.appendGlobalNotification(notification);
});
return Promise.reject(err);
})
.catch(console.logGlobal);
},
render() {
return (
<ReactS3FineUploader
fileInputElement={UploadButton()}
keyRoutine={{
url: AppConstants.serverUrl + 's3/key/',
fileClass: 'contract'
}}
createBlobRoutine={{
url: ApiUrls.blob_contracts
}}
validation={{
itemLimit: AppConstants.fineUploader.validation.registerWork.itemLimit,
sizeLimit: AppConstants.fineUploader.validation.additionalData.sizeLimit,
allowedExtensions: ['pdf']
}}
setIsUploadReady={() =>{/* So that ReactS3FineUploader is not complaining */}}
signature={{
endpoint: AppConstants.serverUrl + 's3/signature/',
customHeaders: {
'X-CSRFToken': getCookie(AppConstants.csrftoken)
}
}}
deleteFile={{
enabled: true,
method: 'DELETE',
endpoint: AppConstants.serverUrl + 's3/delete',
customHeaders: {
'X-CSRFToken': getCookie(AppConstants.csrftoken)
}
}}
fileClassToUpload={{
singular: getLangText('UPDATE'),
plural: getLangText('UPDATE')
}}
isReadyForFormSubmission={formSubmissionValidation.atLeastOneUploadedFile}
submitFile={this.submitFile} />
ref='fineuploader'
fileInputElement={UploadButton({ showLabel: false })}
keyRoutine={{
url: AppConstants.serverUrl + 's3/key/',
fileClass: 'contract'
}}
createBlobRoutine={{
url: ApiUrls.blob_contracts
}}
validation={{
itemLimit: validationTypes.registerWork.itemLimit,
sizeLimit: validationTypes.additionalData.sizeLimit,
allowedExtensions: ['pdf']
}}
setIsUploadReady={() =>{/* So that ReactS3FineUploader is not complaining */}}
signature={{
endpoint: AppConstants.serverUrl + 's3/signature/',
customHeaders: {
'X-CSRFToken': getCookie(AppConstants.csrftoken)
}
}}
deleteFile={{
enabled: true,
method: 'DELETE',
endpoint: AppConstants.serverUrl + 's3/delete',
customHeaders: {
'X-CSRFToken': getCookie(AppConstants.csrftoken)
}
}}
fileClassToUpload={{
singular: getLangText('UPDATE'),
plural: getLangText('UPDATE')
}}
isReadyForFormSubmission={formSubmissionValidation.atLeastOneUploadedFile}
submitFile={this.submitFile} />
);
}
});

View File

@ -2,12 +2,8 @@
import React from 'react';
import UserStore from '../../stores/user_store';
import UserActions from '../../actions/user_actions';
import WhitelabelStore from '../../stores/whitelabel_store';
import WhitelabelActions from '../../actions/whitelabel_actions';
import AccountSettings from './account_settings';
import BitcoinWalletSettings from './bitcoin_wallet_settings';
import APISettings from './api_settings';
@ -24,56 +20,42 @@ let SettingsContainer = React.createClass({
propTypes: {
children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element),
React.PropTypes.element])
React.PropTypes.element
]),
// Provided from AscribeApp
currentUser: React.PropTypes.object.isRequired,
whitelabel: React.PropTypes.object.isRequired,
// Provided from router
location: React.PropTypes.object
},
getInitialState() {
return mergeOptions(
UserStore.getState(),
WhitelabelStore.getState()
);
},
componentDidMount() {
UserStore.listen(this.onChange);
WhitelabelStore.listen(this.onChange);
WhitelabelActions.fetchWhitelabel();
UserActions.fetchCurrentUser();
},
componentWillUnmount() {
WhitelabelStore.unlisten(this.onChange);
UserStore.unlisten(this.onChange);
},
loadUser(invalidateCache){
loadUser(invalidateCache) {
UserActions.fetchCurrentUser(invalidateCache);
},
onChange(state) {
this.setState(state);
},
render() {
const { children, currentUser, whitelabel } = this.props;
setDocumentTitle(getLangText('Account settings'));
if (this.state.currentUser && this.state.currentUser.username) {
if (currentUser.username) {
return (
<div className="settings-container">
<AccountSettings
currentUser={this.state.currentUser}
currentUser={currentUser}
loadUser={this.loadUser}
whitelabel={this.state.whitelabel}/>
{this.props.children}
whitelabel={whitelabel} />
{children}
<AclProxy
aclObject={this.state.whitelabel}
aclObject={whitelabel}
aclName="acl_view_settings_api">
<APISettings />
</AclProxy>
<WebhookSettings />
<AclProxy
aclObject={this.state.whitelabel}
aclObject={whitelabel}
aclName="acl_view_settings_bitcoin">
<BitcoinWalletSettings />
</AclProxy>

View File

@ -34,7 +34,6 @@ let WebhookSettings = React.createClass({
componentDidMount() {
WebhookStore.listen(this.onChange);
WebhookActions.fetchWebhooks();
WebhookActions.fetchWebhookEvents();
},
componentWillUnmount() {
@ -49,7 +48,7 @@ let WebhookSettings = React.createClass({
return (event) => {
WebhookActions.removeWebhook(webhookId);
let notification = new GlobalNotificationModel(getLangText('Webhook deleted'), 'success', 2000);
const notification = new GlobalNotificationModel(getLangText('Webhook deleted'), 'success', 2000);
GlobalNotificationActions.appendGlobalNotification(notification);
};
},
@ -57,16 +56,16 @@ let WebhookSettings = React.createClass({
handleCreateSuccess() {
this.refs.webhookCreateForm.reset();
WebhookActions.fetchWebhooks(true);
let notification = new GlobalNotificationModel(getLangText('Webhook successfully created'), 'success', 5000);
const notification = new GlobalNotificationModel(getLangText('Webhook successfully created'), 'success', 5000);
GlobalNotificationActions.appendGlobalNotification(notification);
},
getWebhooks(){
let content = <AscribeSpinner color='dark-blue' size='lg'/>;
getWebhooks() {
if (this.state.webhooks) {
content = this.state.webhooks.map(function(webhook, i) {
return this.state.webhooks.map(function(webhook, i) {
const event = webhook.event.split('.')[0];
return (
<ActionPanel
name={webhook.event}
@ -91,11 +90,14 @@ let WebhookSettings = React.createClass({
</button>
</div>
</div>
}/>
} />
);
}, this);
} else {
return (
<AscribeSpinner color='dark-blue' size='lg'/>
);
}
return content;
},
getEvents() {
@ -110,18 +112,18 @@ let WebhookSettings = React.createClass({
<option
name={i}
key={i}
value={ event + '.webhook' }>
{ event.toUpperCase() }
value={event + '.webhook'}>
{event.toUpperCase()}
</option>
);
})}
</select>
</Property>);
} else {
return null;
}
return null;
},
render() {
return (
<CollapsibleParagraph
@ -138,20 +140,19 @@ let WebhookSettings = React.createClass({
a target url.
</p>
</div>
<AclProxy
show={this.state.webhookEvents && this.state.webhookEvents.length}>
<AclProxy show={this.state.webhookEvents && this.state.webhookEvents.length}>
<Form
ref="webhookCreateForm"
url={ApiUrls.webhooks}
handleSuccess={this.handleCreateSuccess}>
{ this.getEvents() }
{this.getEvents()}
<Property
name='target'
label={getLangText('Redirect Url')}>
<input
type="text"
placeholder={getLangText('Enter the url to be triggered')}
required/>
required />
</Property>
<hr />
</Form>
@ -162,4 +163,4 @@ let WebhookSettings = React.createClass({
}
});
export default WebhookSettings;
export default WebhookSettings;

View File

@ -2,6 +2,8 @@
import React from 'react';
import FacebookHandler from '../../third_party/facebook_handler';
import AppConstants from '../../constants/application_constants';
import { InjectInHeadUtils } from '../../utils/inject_utils';
@ -17,24 +19,40 @@ let FacebookShareButton = React.createClass({
};
},
componentDidMount() {
/**
* Ideally we would only use FB.XFBML.parse() on the component that we're
* mounting, but doing this when we first load the FB sdk causes unpredictable behaviour.
* The button sometimes doesn't get initialized, likely because FB hasn't properly
* been initialized yet.
*
* To circumvent this, we always have the sdk parse the entire DOM on the initial load
* (see FacebookHandler) and then use FB.XFBML.parse() on the mounting component later.
*/
InjectInHeadUtils
.inject(AppConstants.facebook.sdkUrl)
.then(() => { FB.XFBML.parse(this.refs.fbShareButton.getDOMNode().parentElement) });
getInitialState() {
return FacebookHandler.getState();
},
shouldComponentUpdate(nextProps) {
return this.props.type !== nextProps.type;
componentDidMount() {
FacebookHandler.listen(this.onChange);
this.loadFacebook();
},
shouldComponentUpdate(nextProps, nextState) {
// Don't update if the props haven't changed or the FB SDK loading status is still the same
return this.props.type !== nextProps.type || nextState.loaded !== this.state.loaded;
},
componentDidUpdate() {
// If the component changes, we need to reparse the share button's XFBML.
// To prevent cases where the Facebook SDK hasn't been loaded yet at this stage,
// let's make sure that it's injected before trying to reparse.
this.loadFacebook();
},
onChange(state) {
this.setState(state);
},
loadFacebook() {
InjectInHeadUtils
.inject(AppConstants.facebook.sdkUrl)
.then(() => {
if (this.state.loaded) {
FB.XFBML.parse(this.refs.fbShareButton.getDOMNode().parent)
}
});
},
render() {

View File

@ -1,29 +1,33 @@
'use strict';
import React from 'react';
import classNames from 'classnames';
import ProgressBar from 'react-bootstrap/lib/ProgressBar';
import FileDragAndDropDialog from './file_drag_and_drop_dialog';
import FileDragAndDropErrorDialog from './file_drag_and_drop_error_dialog';
import FileDragAndDropPreviewIterator from './file_drag_and_drop_preview_iterator';
import { FileStatus } from '../react_s3_fine_uploader_utils';
import { getLangText } from '../../../utils/lang_utils';
// Taken from: https://github.com/fedosejev/react-file-drag-and-drop
let FileDragAndDrop = React.createClass({
propTypes: {
className: React.PropTypes.string,
areAssetsDownloadable: React.PropTypes.bool,
areAssetsEditable: React.PropTypes.bool,
multiple: React.PropTypes.bool,
dropzoneInactive: React.PropTypes.bool,
filesToUpload: React.PropTypes.array,
onDrop: React.PropTypes.func.isRequired,
onDragOver: React.PropTypes.func,
filesToUpload: React.PropTypes.array,
handleDeleteFile: React.PropTypes.func,
handleCancelFile: React.PropTypes.func,
handlePauseFile: React.PropTypes.func,
handleResumeFile: React.PropTypes.func,
multiple: React.PropTypes.bool,
dropzoneInactive: React.PropTypes.bool,
areAssetsDownloadable: React.PropTypes.bool,
areAssetsEditable: React.PropTypes.bool,
handleRetryFiles: React.PropTypes.func,
enableLocalHashing: React.PropTypes.bool,
uploadMethod: React.PropTypes.string,
@ -34,6 +38,12 @@ let FileDragAndDrop = React.createClass({
// to -1 which is code for: aborted
handleCancelHashing: React.PropTypes.func,
showError: React.PropTypes.bool,
errorClass: React.PropTypes.shape({
name: React.PropTypes.string,
prettifiedText: React.PropTypes.string
}),
// A class of a file the user has to upload
// Needs to be defined both in singular as well as in plural
fileClassToUpload: React.PropTypes.shape({
@ -126,64 +136,91 @@ let FileDragAndDrop = React.createClass({
}
},
getErrorDialog(failedFiles) {
const { errorClass } = this.props;
return (
<FileDragAndDropErrorDialog
errorClass={errorClass}
files={failedFiles}
handleRetryFiles={this.props.handleRetryFiles} />
);
},
getPreviewIterator() {
const { areAssetsDownloadable, areAssetsEditable, filesToUpload } = this.props;
return (
<FileDragAndDropPreviewIterator
files={filesToUpload}
handleDeleteFile={this.handleDeleteFile}
handleCancelFile={this.handleCancelFile}
handlePauseFile={this.handlePauseFile}
handleResumeFile={this.handleResumeFile}
areAssetsDownloadable={areAssetsDownloadable}
areAssetsEditable={areAssetsEditable} />
);
},
getUploadDialog() {
const { enableLocalHashing, fileClassToUpload, multiple, uploadMethod } = this.props;
return (
<FileDragAndDropDialog
multipleFiles={multiple}
onClick={this.handleOnClick}
enableLocalHashing={enableLocalHashing}
uploadMethod={uploadMethod}
fileClassToUpload={fileClassToUpload} />
);
},
render: function () {
const { allowedExtensions,
areAssetsDownloadable,
areAssetsEditable,
className,
dropzoneInactive,
enableLocalHashing,
fileClassToUpload,
errorClass,
filesToUpload,
handleCancelHashing,
hashingProgress,
multiple,
uploadMethod } = this.props;
showError } = this.props;
// has files only is true if there are files that do not have the status deleted or canceled
let hasFiles = filesToUpload.filter((file) => file.status !== 'deleted' && file.status !== 'canceled' && file.size !== -1).length > 0;
let updatedClassName = hasFiles ? 'has-files ' : '';
updatedClassName += dropzoneInactive ? 'inactive-dropzone' : 'active-dropzone';
updatedClassName += ' file-drag-and-drop';
// has files only is true if there are files that do not have the status deleted, canceled, or failed
const hasFiles = filesToUpload
.filter((file) => {
return file.status !== FileStatus.DELETED &&
file.status !== FileStatus.CANCELED &&
file.status !== FileStatus.UPLOAD_FAILED &&
file.size !== -1;
})
.length > 0;
const failedFiles = filesToUpload.filter((file) => file.status === FileStatus.UPLOAD_FAILED);
let hasError = showError && errorClass && failedFiles.length > 0;
// if !== -2: triggers a FileDragAndDrop-global spinner
if(hashingProgress !== -2) {
if (hashingProgress !== -2) {
return (
<div className={className}>
<div className="file-drag-and-drop-hashing-dialog">
<p>{getLangText('Computing hash(es)... This may take a few minutes.')}</p>
<p>
<a onClick={handleCancelHashing}> {getLangText('Cancel hashing')}</a>
</p>
<ProgressBar
now={Math.ceil(hashingProgress)}
label="%(percent)s%"
className="ascribe-progress-bar"/>
</div>
<div className="file-drag-and-drop-hashing-dialog">
<p>{getLangText('Computing hash(es)... This may take a few minutes.')}</p>
<p>
<a onClick={handleCancelHashing}> {getLangText('Cancel hashing')}</a>
</p>
<ProgressBar
now={Math.ceil(hashingProgress)}
label="%(percent)s%"
className="ascribe-progress-bar"/>
</div>
);
} else {
return (
<div
className={updatedClassName}
className={classNames('file-drag-and-drop', dropzoneInactive ? 'inactive-dropzone' : 'active-dropzone', { 'has-files': hasFiles })}
onDrag={this.handleDrop}
onDragOver={this.handleDragOver}
onDrop={this.handleDrop}>
<FileDragAndDropDialog
multipleFiles={multiple}
hasFiles={hasFiles}
onClick={this.handleOnClick}
enableLocalHashing={enableLocalHashing}
uploadMethod={uploadMethod}
fileClassToUpload={fileClassToUpload} />
<FileDragAndDropPreviewIterator
files={filesToUpload}
handleDeleteFile={this.handleDeleteFile}
handleCancelFile={this.handleCancelFile}
handlePauseFile={this.handlePauseFile}
handleResumeFile={this.handleResumeFile}
areAssetsDownloadable={areAssetsDownloadable}
areAssetsEditable={areAssetsEditable}/>
{hasError ? this.getErrorDialog(failedFiles) : this.getPreviewIterator()}
{!hasFiles && !hasError ? this.getUploadDialog() : null}
{/*
Opera doesn't trigger simulated click events
if the targeted input has `display:none` set.

View File

@ -9,7 +9,6 @@ import { getCurrentQueryParams } from '../../../utils/url_utils';
let FileDragAndDropDialog = React.createClass({
propTypes: {
hasFiles: React.PropTypes.bool,
multipleFiles: React.PropTypes.bool,
enableLocalHashing: React.PropTypes.bool,
uploadMethod: React.PropTypes.string,
@ -37,90 +36,86 @@ let FileDragAndDropDialog = React.createClass({
render() {
const { enableLocalHashing,
fileClassToUpload,
hasFiles,
multipleFiles,
onClick,
uploadMethod } = this.props;
let dialogElement;
if (hasFiles) {
return null;
} else {
let dialogElement;
if (enableLocalHashing && !uploadMethod) {
const currentQueryParams = getCurrentQueryParams();
if (enableLocalHashing && !uploadMethod) {
const currentQueryParams = getCurrentQueryParams();
const queryParamsHash = Object.assign({}, currentQueryParams);
queryParamsHash.method = 'hash';
const queryParamsHash = Object.assign({}, currentQueryParams);
queryParamsHash.method = 'hash';
const queryParamsUpload = Object.assign({}, currentQueryParams);
queryParamsUpload.method = 'upload';
const queryParamsUpload = Object.assign({}, currentQueryParams);
queryParamsUpload.method = 'upload';
dialogElement = (
<div className="present-options">
<p className="file-drag-and-drop-dialog-title">{getLangText('Would you rather')}</p>
{/*
The frontend in live is hosted under /app,
Since `Link` is appending that base url, if its defined
by itself, we need to make sure to not set it at this point.
Otherwise it will be appended twice.
*/}
<Link
to={`/${window.location.pathname.split('/').pop()}`}
query={queryParamsHash}>
<span className="btn btn-default btn-sm">
{getLangText('Hash your work')}
</span>
</Link>
<span> or </span>
<Link
to={`/${window.location.pathname.split('/').pop()}`}
query={queryParamsUpload}>
<span className="btn btn-default btn-sm">
{getLangText('Upload and hash your work')}
</span>
</Link>
</div>
);
} else {
if (multipleFiles) {
dialogElement = [
this.getDragDialog(fileClassToUpload.plural),
<span
className="btn btn-default"
onClick={onClick}>
{getLangText('choose %s to upload', fileClassToUpload.plural)}
dialogElement = (
<div className="present-options">
<p className="file-drag-and-drop-dialog-title">{getLangText('Would you rather')}</p>
{/*
The frontend in live is hosted under /app,
Since `Link` is appending that base url, if its defined
by itself, we need to make sure to not set it at this point.
Otherwise it will be appended twice.
*/}
<Link
to={`/${window.location.pathname.split('/').pop()}`}
query={queryParamsHash}>
<span className="btn btn-default btn-sm">
{getLangText('Hash your work')}
</span>
];
} else {
const dialog = uploadMethod === 'hash' ? getLangText('choose a %s to hash', fileClassToUpload.singular)
: getLangText('choose a %s to upload', fileClassToUpload.singular);
</Link>
dialogElement = [
this.getDragDialog(fileClassToUpload.singular),
<span
className="btn btn-default"
onClick={onClick}>
{dialog}
<span> {getLangText('or')} </span>
<Link
to={`/${window.location.pathname.split('/').pop()}`}
query={queryParamsUpload}>
<span className="btn btn-default btn-sm">
{getLangText('Upload and hash your work')}
</span>
];
}
}
return (
<div className="file-drag-and-drop-dialog">
<div className="hidden-print">
{dialogElement}
</div>
{/* Hide the uploader and just show that there's been on files uploaded yet when printing */}
<p className="text-align-center visible-print">
{getLangText('No files uploaded')}
</p>
</Link>
</div>
);
} else {
if (multipleFiles) {
dialogElement = [
this.getDragDialog(fileClassToUpload.plural),
(<span
key='mutlipleFilesBtn'
className="btn btn-default"
onClick={onClick}>
{getLangText('choose %s to upload', fileClassToUpload.plural)}
</span>)
];
} else {
const dialog = uploadMethod === 'hash' ? getLangText('choose a %s to hash', fileClassToUpload.singular)
: getLangText('choose a %s to upload', fileClassToUpload.singular);
dialogElement = [
this.getDragDialog(fileClassToUpload.singular),
(<span
key='singleFileBtn'
className="btn btn-default"
onClick={onClick}>
{dialog}
</span>)
];
}
}
return (
<div className="file-drag-and-drop-dialog">
<div className="hidden-print">
{dialogElement}
</div>
{/* Hide the uploader and just show that there's been on files uploaded yet when printing */}
<p className="text-align-center visible-print">
{getLangText('No files uploaded')}
</p>
</div>
);
}
});

View File

@ -0,0 +1,86 @@
'use strict';
import React from 'react';
import classNames from 'classnames';
import { ErrorClasses } from '../../../constants/error_constants';
import { getLangText } from '../../../utils/lang_utils';
let FileDragAndDropErrorDialog = React.createClass({
propTypes: {
errorClass: React.PropTypes.shape({
name: React.PropTypes.string,
prettifiedText: React.PropTypes.string
}).isRequired,
files: React.PropTypes.array.isRequired,
handleRetryFiles: React.PropTypes.func.isRequired
},
getRetryButton(text, openIntercom) {
return (
<button
type="button"
className='btn btn-default'
onClick={() => {
if (openIntercom) {
window.Intercom('showNewMessage', getLangText("I'm having trouble uploading my file."));
}
this.retryAllFiles()
}}>
{getLangText(text)}
</button>
);
},
getContactUsDetail() {
return (
<div className='file-drag-and-drop-error'>
<h4>{getLangText('Let us help you')}</h4>
<p>{getLangText('Still having problems? Send us a message.')}</p>
{this.getRetryButton('Contact us', true)}
</div>
);
},
getErrorDetail(multipleFiles) {
const { errorClass: { prettifiedText }, files } = this.props;
return (
<div className='file-drag-and-drop-error'>
<div className={classNames('file-drag-and-drop-error-detail', { 'file-drag-and-drop-error-detail-multiple-files': multipleFiles })}>
<h4>{getLangText(multipleFiles ? 'Some files did not upload correctly'
: 'Error uploading the file!')}
</h4>
<p>{prettifiedText}</p>
{this.getRetryButton('Retry')}
</div>
<span className={classNames('file-drag-and-drop-error-icon-container', { 'file-drag-and-drop-error-icon-container-multiple-files': multipleFiles })}>
<span className='ascribe-icon icon-ascribe-thin-cross'></span>
</span>
<div className='file-drag-and-drop-error-file-names'>
<ul>
{files.map((file) => (<li key={file.id} className='file-name'>{file.originalName}</li>))}
</ul>
</div>
</div>
);
},
retryAllFiles() {
const { files, handleRetryFiles } = this.props;
handleRetryFiles(files.map(file => file.id));
},
render() {
const { errorClass: { name: errorName }, files } = this.props;
const multipleFiles = files.length > 1;
const contactUs = errorName === ErrorClasses.upload.contactUs.name;
return contactUs ? this.getContactUsDetail() : this.getErrorDetail(multipleFiles);
}
});
export default FileDragAndDropErrorDialog;

View File

@ -5,6 +5,7 @@ import React from 'react';
import FileDragAndDropPreviewImage from './file_drag_and_drop_preview_image';
import FileDragAndDropPreviewOther from './file_drag_and_drop_preview_other';
import { FileStatus } from '../react_s3_fine_uploader_utils';
import { getLangText } from '../../../utils/lang_utils';
import { truncateTextAtCharIndex } from '../../../utils/general_utils';
import { extractFileExtensionFromString } from '../../../utils/file_utils';
@ -23,27 +24,30 @@ const FileDragAndDropPreview = React.createClass({
s3Url: string,
s3UrlSafe: string
}).isRequired,
areAssetsDownloadable: bool,
areAssetsEditable: bool,
handleDeleteFile: func,
handleCancelFile: func,
handlePauseFile: func,
handleResumeFile: func,
areAssetsDownloadable: bool,
areAssetsEditable: bool,
numberOfDisplayedFiles: number
},
toggleUploadProcess() {
if(this.props.file.status === 'uploading') {
this.props.handlePauseFile(this.props.file.id);
} else if(this.props.file.status === 'paused') {
this.props.handleResumeFile(this.props.file.id);
const { file, handlePauseFile, handleResumeFile } = this.props;
if (file.status === FileStatus.UPLOADING) {
handlePauseFile(file.id);
} else if (file.status === FileStatus.PAUSED) {
handleResumeFile(file.id);
}
},
handleDeleteFile() {
const { handleDeleteFile,
handleCancelFile,
file } = this.props;
const { file,
handleDeleteFile,
handleCancelFile } = this.props;
// `handleDeleteFile` is optional, so if its not submitted, don't run it
//
// For delete though, we only want to trigger it, when we're sure that
@ -51,16 +55,16 @@ const FileDragAndDropPreview = React.createClass({
// deleted using an HTTP DELETE request.
if (handleDeleteFile &&
file.progress === 100 &&
(file.status === 'upload successful' || file.status === 'online') &&
(file.status === FileStatus.UPLOAD_SUCCESSFUL || file.status === FileStatus.ONLINE) &&
file.s3UrlSafe) {
handleDeleteFile(file.id);
} else if(handleCancelFile) {
} else if (handleCancelFile) {
handleCancelFile(file.id);
}
},
handleDownloadFile() {
if(this.props.file.s3Url) {
if (this.props.file.s3Url) {
// This simply opens a new browser tab with the url provided
open(this.props.file.s3Url);
}
@ -69,7 +73,7 @@ const FileDragAndDropPreview = React.createClass({
getFileName() {
const { numberOfDisplayedFiles, file } = this.props;
if(numberOfDisplayedFiles === 1) {
if (numberOfDisplayedFiles === 1) {
return (
<span className="file-name">
{truncateTextAtCharIndex(file.name, 30, '(...).' + extractFileExtensionFromString(file.name))}
@ -81,7 +85,7 @@ const FileDragAndDropPreview = React.createClass({
},
getRemoveButton() {
if(this.props.areAssetsEditable) {
if (this.props.areAssetsEditable) {
return (
<div className="delete-file">
<span
@ -107,7 +111,7 @@ const FileDragAndDropPreview = React.createClass({
// Decide whether an image or a placeholder picture should be displayed
// If a file has its `thumbnailUrl` defined, then we display it also as an image
if(file.type.split('/')[0] === 'image' || file.thumbnailUrl) {
if (file.type.split('/')[0] === 'image' || file.thumbnailUrl) {
previewElement = (
<FileDragAndDropPreviewImage
onClick={this.handleDeleteFile}
@ -123,7 +127,7 @@ const FileDragAndDropPreview = React.createClass({
<FileDragAndDropPreviewOther
onClick={this.handleDeleteFile}
progress={file.progress}
type={file.type.split('/')[1]}
type={extractFileExtensionFromString(file.name)}
toggleUploadProcess={this.toggleUploadProcess}
areAssetsDownloadable={areAssetsDownloadable}
downloadUrl={file.s3UrlSafe}

View File

@ -56,9 +56,9 @@ const FileDragAndDropPreviewOther = React.createClass({
target="_blank"
className="glyphicon glyphicon-download action-file"
aria-hidden="true"
title={getLangText('Download file')}/>
title={getLangText('Download file')} />
);
} else if(progress >= 0 && progress < 100) {
} else if (progress >= 0 && progress < 100) {
actionSymbol = (
<div className="spinner-file">
<AscribeSpinner color='dark-blue' size='md' />
@ -66,22 +66,19 @@ const FileDragAndDropPreviewOther = React.createClass({
);
} else {
actionSymbol = (
<span className='ascribe-icon icon-ascribe-ok action-file'/>
<span className='ascribe-icon icon-ascribe-ok action-file' />
);
}
return (
<div
className="file-drag-and-drop-preview">
<div className="file-drag-and-drop-preview">
<ProgressBar
now={Math.ceil(progress)}
style={style}
className="ascribe-progress-bar ascribe-progress-bar-xs"/>
<div className="file-drag-and-drop-preview-table-wrapper">
<div className="file-drag-and-drop-preview-other">
{actionSymbol}
<p style={style}>{'.' + type}</p>
</div>
className="ascribe-progress-bar ascribe-progress-bar-xs" />
<div className="file-drag-and-drop-preview-other">
{actionSymbol}
<p style={style}>{'.' + (type ? type : 'file')}</p>
</div>
</div>
);

View File

@ -1,15 +1,16 @@
'use strict';
import React from 'react';
import classNames from 'classnames';
import { displayValidProgressFilesFilter } from '../react_s3_fine_uploader_utils';
import { displayValidProgressFilesFilter, FileStatus } from '../react_s3_fine_uploader_utils';
import { getLangText } from '../../../utils/lang_utils';
import { truncateTextAtCharIndex } from '../../../utils/general_utils';
const { func, array, bool, shape, string } = React.PropTypes;
export default function UploadButton({ className = 'btn btn-default btn-sm' } = {}) {
export default function UploadButton({ className = 'btn btn-default btn-sm', showLabel = true } = {}) {
return React.createClass({
displayName: 'UploadButton',
@ -57,11 +58,11 @@ export default function UploadButton({ className = 'btn btn-default btn-sm' } =
},
getUploadingFiles(filesToUpload = this.props.filesToUpload) {
return filesToUpload.filter((file) => file.status === 'uploading');
return filesToUpload.filter((file) => file.status === FileStatus.UPLOADING);
},
getUploadedFile() {
return this.props.filesToUpload.filter((file) => file.status === 'upload successful')[0];
return this.props.filesToUpload.filter((file) => file.status === FileStatus.UPLOAD_SUCCESSFUL)[0];
},
clearSelection() {
@ -119,28 +120,28 @@ export default function UploadButton({ className = 'btn btn-default btn-sm' } =
},
getUploadedFileLabel() {
const uploadedFile = this.getUploadedFile();
const uploadingFiles = this.getUploadingFiles();
if (showLabel) {
const uploadedFile = this.getUploadedFile();
const uploadingFiles = this.getUploadingFiles();
if(uploadingFiles.length) {
return (
<span>
{' ' + truncateTextAtCharIndex(uploadingFiles[0].name, 40) + ' '}
[<a onClick={this.onClickRemove}>{getLangText('cancel upload')}</a>]
</span>
);
} else if(uploadedFile) {
return (
<span>
<span className='ascribe-icon icon-ascribe-ok'/>
{' ' + truncateTextAtCharIndex(uploadedFile.name, 40) + ' '}
[<a onClick={this.onClickRemove}>{getLangText('remove')}</a>]
</span>
);
} else {
return (
<span>{getLangText('No file chosen')}</span>
);
if (uploadingFiles.length) {
return (
<span>
{' ' + truncateTextAtCharIndex(uploadingFiles[0].name, 40) + ' '}
[<a onClick={this.onClickRemove}>{getLangText('cancel upload')}</a>]
</span>
);
} else if (uploadedFile) {
return (
<span>
<span className='ascribe-icon icon-ascribe-ok'/>
{' ' + truncateTextAtCharIndex(uploadedFile.name, 40) + ' '}
[<a onClick={this.onClickRemove}>{getLangText('remove')}</a>]
</span>
);
} else {
return <span>{getLangText('No file chosen')}</span>;
}
}
},
@ -156,7 +157,7 @@ export default function UploadButton({ className = 'btn btn-default btn-sm' } =
* Therefore the wrapping component needs to be an `anchor` tag instead of a `button`
*/
return (
<div className="upload-button-wrapper">
<div className={classNames('ascribe-upload-button', {'ascribe-upload-button-has-label': showLabel})}>
{/*
The button needs to be of `type="button"` as it would
otherwise submit the form its in.

View File

@ -8,14 +8,18 @@ import S3Fetcher from '../../fetchers/s3_fetcher';
import FileDragAndDrop from './ascribe_file_drag_and_drop/file_drag_and_drop';
import ErrorQueueStore from '../../stores/error_queue_store';
import GlobalNotificationModel from '../../models/global_notification_model';
import GlobalNotificationActions from '../../actions/global_notification_actions';
import AppConstants from '../../constants/application_constants';
import { ErrorClasses, testErrorAgainstAll } from '../../constants/error_constants';
import { RETRY_ATTEMPT_TO_SHOW_CONTACT_US } from '../../constants/uploader_constants';
import { computeHashOfFile } from '../../utils/file_utils';
import { displayValidFilesFilter, transformAllowedExtensionsToInputAcceptProp } from './react_s3_fine_uploader_utils';
import { displayValidFilesFilter, FileStatus, transformAllowedExtensionsToInputAcceptProp } from './react_s3_fine_uploader_utils';
import { getCookie } from '../../utils/fetch_api_utils';
import { computeHashOfFile, extractFileExtensionFromString } from '../../utils/file_utils';
import { getLangText } from '../../utils/lang_utils';
@ -33,80 +37,18 @@ const { shape,
const ReactS3FineUploader = React.createClass({
propTypes: {
keyRoutine: shape({
url: string,
fileClass: string,
pieceId: number
}),
createBlobRoutine: shape({
url: string,
pieceId: number
}),
handleChangedFile: func, // is for when a file is dropped or selected
submitFile: func, // is for when a file has been successfully uploaded, TODO: rename to handleSubmitFile
onValidationFailed: func,
autoUpload: bool,
debug: bool,
objectProperties: shape({
acl: string
}),
request: shape({
endpoint: string,
accessKey: string,
params: shape({
csrfmiddlewaretoken: string
})
}),
signature: shape({
endpoint: string
}).isRequired,
uploadSuccess: shape({
method: string,
endpoint: string,
params: shape({
isBrowserPreviewCapable: any, // maybe fix this later
bitcoin_ID_noPrefix: string
})
}),
cors: shape({
expected: bool
}),
chunking: shape({
enabled: bool
}),
resume: shape({
enabled: bool
}),
deleteFile: shape({
enabled: bool,
method: string,
endpoint: string,
customHeaders: object
}).isRequired,
session: shape({
customHeaders: object,
endpoint: string,
params: object,
refreshOnRequests: bool
}),
validation: shape({
itemLimit: number,
sizeLimit: string,
allowedExtensions: arrayOf(string)
}),
messages: shape({
unsupportedBrowser: string
}),
formatFileName: func,
multiple: bool,
retry: shape({
enableAuto: bool
}),
setIsUploadReady: func,
isReadyForFormSubmission: func,
areAssetsDownloadable: bool,
areAssetsEditable: bool,
defaultErrorMessage: string,
errorNotificationMessage: string,
handleChangedFile: func, // for when a file is dropped or selected, TODO: rename to onChangedFile
submitFile: func, // for when a file has been successfully uploaded, TODO: rename to onSubmitFile
onValidationFailed: func,
setWarning: func, // for when the parent component wants to be notified of uploader warnings (ie. upload failed)
showErrorPrompt: bool,
// Handle form validation
setIsUploadReady: func, //TODO: rename to setIsUploaderValidated
isReadyForFormSubmission: func,
// We encountered some cases where people had difficulties to upload their
// works to ascribe due to a slow internet connection.
@ -135,13 +77,94 @@ const ReactS3FineUploader = React.createClass({
fileInputElement: oneOfType([
func,
element
])
]),
// S3 helpers
createBlobRoutine: shape({
url: string,
pieceId: number
}),
keyRoutine: shape({
url: string,
fileClass: string,
pieceId: number
}),
// FineUploader options
debug: bool,
autoUpload: bool,
chunking: shape({
enabled: bool
}),
cors: shape({
expected: bool
}),
deleteFile: shape({
enabled: bool,
method: string,
endpoint: string,
customHeaders: object
}).isRequired,
formatFileName: func,
messages: shape({
unsupportedBrowser: string
}),
multiple: bool,
objectProperties: shape({
acl: string
}),
request: shape({
endpoint: string,
accessKey: string,
params: shape({
csrfmiddlewaretoken: string
})
}),
resume: shape({
enabled: bool
}),
retry: shape({
enableAuto: bool
}),
session: shape({
customHeaders: object,
endpoint: string,
params: object,
refreshOnRequests: bool
}),
signature: shape({
endpoint: string
}).isRequired,
uploadSuccess: shape({
method: string,
endpoint: string,
params: shape({
isBrowserPreviewCapable: any, // maybe fix this later
bitcoin_ID_noPrefix: string
})
}),
validation: shape({
itemLimit: number,
sizeLimit: number,
allowedExtensions: arrayOf(string)
})
},
getDefaultProps() {
return {
errorNotificationMessage: getLangText('Oops, we had a problem uploading your file. Please contact us if this happens repeatedly.'),
showErrorPrompt: false,
fileClassToUpload: {
singular: getLangText('file'),
plural: getLangText('files')
},
fileInputElement: FileDragAndDrop,
// FineUploader options
autoUpload: true,
debug: false,
multiple: false,
objectProperties: {
acl: 'public-read',
bucket: 'ascribe0'
@ -178,27 +201,25 @@ const ReactS3FineUploader = React.createClass({
messages: {
unsupportedBrowser: '<h3>' + getLangText('Upload is not functional in IE7 as IE7 has no support for CORS!') + '</h3>'
},
formatFileName: function(name){// fix maybe
formatFileName: function(name) { // fix maybe
if (name !== undefined && name.length > 26) {
name = name.slice(0, 15) + '...' + name.slice(-15);
}
return name;
},
multiple: false,
defaultErrorMessage: getLangText('Unexpected error. Please contact us if this happens repeatedly.'),
fileClassToUpload: {
singular: getLangText('file'),
plural: getLangText('files')
},
fileInputElement: FileDragAndDrop
}
};
},
getInitialState() {
return {
filesToUpload: [],
uploader: new fineUploader.s3.FineUploaderBasic(this.propsToConfig()),
uploader: this.createNewFineUploader(),
csrfToken: getCookie(AppConstants.csrftoken),
errorState: {
manualRetryAttempt: 0,
errorClass: null
},
uploadInProgress: false,
// -1: aborted
// -2: uninitialized
@ -216,7 +237,7 @@ const ReactS3FineUploader = React.createClass({
let potentiallyNewCSRFToken = getCookie(AppConstants.csrftoken);
if(this.state.csrfToken !== potentiallyNewCSRFToken) {
this.setState({
uploader: new fineUploader.s3.FineUploaderBasic(this.propsToConfig()),
uploader: this.createNewFineUploader(),
csrfToken: potentiallyNewCSRFToken
});
}
@ -229,8 +250,12 @@ const ReactS3FineUploader = React.createClass({
this.state.uploader.cancelAll();
},
createNewFineUploader() {
return new fineUploader.s3.FineUploaderBasic(this.propsToConfig());
},
propsToConfig() {
let objectProperties = this.props.objectProperties;
const objectProperties = Object.assign({}, this.props.objectProperties);
objectProperties.key = this.requestKey;
return {
@ -251,6 +276,7 @@ const ReactS3FineUploader = React.createClass({
multiple: this.props.multiple,
retry: this.props.retry,
callbacks: {
onAllComplete: this.onAllComplete,
onComplete: this.onComplete,
onCancel: this.onCancel,
onProgress: this.onProgress,
@ -274,26 +300,13 @@ const ReactS3FineUploader = React.createClass({
// proclaim that upload is not ready
this.props.setIsUploadReady(false);
// reset any warnings propagated to parent
this.setWarning(false);
// reset internal data structures of component
this.setState(this.getInitialState());
},
// Cancel uploads and clear previously selected files on the input element
cancelUploads(id) {
typeof id !== 'undefined' ? this.state.uploader.cancel(id) : this.state.uploader.cancelAll();
// Reset the file input element to clear the previously selected files so that
// the user can reselect them again.
this.clearFileSelection();
},
clearFileSelection() {
const { fileInput } = this.refs;
if (fileInput && typeof fileInput.clearSelection === 'function') {
fileInput.clearSelection();
}
},
requestKey(fileId) {
let filename = this.state.uploader.getName(fileId);
let uuid = this.state.uploader.getUuid(fileId);
@ -335,7 +348,7 @@ const ReactS3FineUploader = React.createClass({
// if createBlobRoutine is not defined,
// we're progressing right away without posting to S3
// so that this can be done manually by the form
if(!createBlobRoutine) {
if (!createBlobRoutine) {
// still we warn the user of this component
console.warn('createBlobRoutine was not defined for ReactS3FineUploader. Continuing without creating the blob on the server.');
resolve();
@ -384,6 +397,151 @@ const ReactS3FineUploader = React.createClass({
});
},
// Cancel uploads and clear previously selected files on the input element
cancelUploads(id) {
typeof id !== 'undefined' ? this.state.uploader.cancel(id) : this.state.uploader.cancelAll();
// Reset the file input element to clear the previously selected files so that
// the user can reselect them again.
this.clearFileSelection();
},
checkFormSubmissionReady() {
const { isReadyForFormSubmission, setIsUploadReady } = this.props;
// since the form validation props isReadyForFormSubmission and setIsUploadReady
// are optional, we'll only trigger them when they're actually defined
if (typeof isReadyForFormSubmission === 'function' && typeof setIsUploadReady === 'function') {
// set uploadReady to true if the uploader's ready for submission
setIsUploadReady(isReadyForFormSubmission(this.state.filesToUpload));
} else {
console.warn('You didn\'t define the functions isReadyForFormSubmission and/or setIsUploadReady in as a prop in react-s3-fine-uploader');
}
},
clearFileSelection() {
const { fileInput } = this.refs;
if (fileInput && typeof fileInput.clearSelection === 'function') {
fileInput.clearSelection();
}
},
getAllowedExtensions() {
const { validation: { allowedExtensions } = {} } = this.props;
if (allowedExtensions && allowedExtensions.length) {
return transformAllowedExtensionsToInputAcceptProp(allowedExtensions);
} else {
return null;
}
},
getUploadErrorClass({ type = 'upload', reason, xhr }) {
const { manualRetryAttempt } = this.state.errorState;
let matchedErrorClass;
if ('onLine' in window.navigator && !window.navigator.onLine) {
// If the user's offline, this is definitely the most important error to show.
// TODO: use a better mechanism for checking network state, ie. offline.js
matchedErrorClass = ErrorClasses.upload.offline;
} else if (manualRetryAttempt === RETRY_ATTEMPT_TO_SHOW_CONTACT_US) {
// Use the contact us error class if they've retried a number of times
// and are still unsuccessful
matchedErrorClass = ErrorClasses.upload.contactUs;
} else {
matchedErrorClass = testErrorAgainstAll({ type, reason, xhr });
if (!matchedErrorClass) {
// If none found, show the next error message in the queue for upload errors
matchedErrorClass = ErrorQueueStore.getNextError('upload');
}
}
return matchedErrorClass;
},
getXhrErrorComment(xhr) {
if (xhr) {
return {
response: xhr.response,
url: xhr.responseURL,
status: xhr.status,
statusText: xhr.statusText
};
}
},
isDropzoneInactive() {
const { areAssetsEditable, enableLocalHashing, multiple, showErrorPrompt, uploadMethod } = this.props;
const { errorState, filesToUpload } = this.state;
const filesToDisplay = filesToUpload.filter((file) => {
return file.status !== FileStatus.DELETED &&
file.status !== FileStatus.CANCELED &&
file.status !== FileStatus.UPLOAD_FAILED &&
file.size !== -1;
});
return (enableLocalHashing && !uploadMethod) ||
!areAssetsEditable ||
(showErrorPrompt && errorState.errorClass) ||
(!multiple && filesToDisplay.length > 0);
},
isFileValid(file) {
const { validation: { allowedExtensions, sizeLimit = 0 }, onValidationFailed } = this.props;
const fileExt = extractFileExtensionFromString(file.name);
if (file.size > sizeLimit) {
const fileSizeInMegaBytes = sizeLimit / 1000000;
const notification = new GlobalNotificationModel(getLangText('A file you submitted is bigger than ' + fileSizeInMegaBytes + 'MB.'), 'danger', 5000);
GlobalNotificationActions.appendGlobalNotification(notification);
if (typeof onValidationFailed === 'function') {
onValidationFailed(file);
}
return false;
} else if (allowedExtensions && !allowedExtensions.includes(fileExt)) {
const notification = new GlobalNotificationModel(getLangText(`The file you've submitted is of an invalid file format: Valid format(s): ${allowedExtensions.join(', ')}`), 'danger', 5000);
GlobalNotificationActions.appendGlobalNotification(notification);
return false;
} else {
return true;
}
},
selectValidFiles(files) {
return Array.from(files).reduce((validFiles, file) => {
if (this.isFileValid(file)) {
validFiles.push(file);
}
return validFiles;
}, []);
},
// This method has been made promise-based to immediately afterwards
// call a callback function (instantly after this.setState went through)
// This is e.g. needed when showing/hiding the optional thumbnail upload
// field in the registration form
setStatusOfFile(fileId, status) {
return Q.Promise((resolve) => {
let changeSet = {};
if (status === FileStatus.DELETED || status === FileStatus.CANCELED || status === FileStatus.UPLOAD_FAILED) {
changeSet.progress = { $set: 0 };
}
changeSet.status = { $set: status };
let filesToUpload = React.addons.update(this.state.filesToUpload, { [fileId]: changeSet });
this.setState({ filesToUpload }, resolve);
});
},
setThumbnailForFileId(fileId, url) {
const { filesToUpload } = this.state;
@ -399,8 +557,13 @@ const ReactS3FineUploader = React.createClass({
}
},
/* FineUploader specific callback function handlers */
setWarning(hasWarning) {
if (typeof this.props.setWarning === 'function') {
this.props.setWarning(hasWarning);
}
},
/* FineUploader specific callback function handlers */
onUploadChunk(id, name, chunkData) {
let chunks = this.state.chunks;
@ -429,7 +592,14 @@ const ReactS3FineUploader = React.createClass({
this.setState({ startedChunks });
}
},
onAllComplete(succeed, failed) {
if (this.state.uploadInProgress) {
this.setState({
uploadInProgress: false
});
}
},
onComplete(id, name, res, xhr) {
@ -441,12 +611,12 @@ const ReactS3FineUploader = React.createClass({
xhr: this.getXhrErrorComment(xhr)
});
// onError will catch any errors, so we can ignore them here
} else if (!res.error || res.success) {
} else if (!res.error && res.success) {
let files = this.state.filesToUpload;
// Set the state of the completed file to 'upload successful' in order to
// remove it from the GUI
files[id].status = 'upload successful';
files[id].status = FileStatus.UPLOAD_SUCCESSFUL;
files[id].key = this.state.uploader.getKey(id);
let filesToUpload = React.addons.update(this.state.filesToUpload, { $set: files });
@ -455,29 +625,14 @@ const ReactS3FineUploader = React.createClass({
// Only after the blob has been created server-side, we can make the form submittable.
this.createBlob(files[id])
.then(() => {
// since the form validation props isReadyForFormSubmission, setIsUploadReady and submitFile
// are optional, we'll only trigger them when they're actually defined
if(this.props.submitFile) {
if (typeof this.props.submitFile === 'function') {
this.props.submitFile(files[id]);
} else {
console.warn('You didn\'t define submitFile as a prop in react-s3-fine-uploader');
}
// for explanation, check comment of if statement above
if(this.props.isReadyForFormSubmission && this.props.setIsUploadReady) {
// also, lets check if after the completion of this upload,
// the form is ready for submission or not
if(this.props.isReadyForFormSubmission(this.state.filesToUpload)) {
// if so, set uploadstatus to true
this.props.setIsUploadReady(true);
} else {
this.props.setIsUploadReady(false);
}
} else {
console.warn('You didn\'t define the functions isReadyForFormSubmission and/or setIsUploadReady in as a prop in react-s3-fine-uploader');
}
})
.catch(this.onErrorPromiseProxy);
this.checkFormSubmissionReady();
});
}
},
@ -493,50 +648,51 @@ const ReactS3FineUploader = React.createClass({
},
onError(id, name, errorReason, xhr) {
const { errorNotificationMessage, showErrorPrompt } = this.props;
const { chunks, filesToUpload } = this.state;
console.logGlobal(errorReason, {
files: this.state.filesToUpload,
chunks: this.state.chunks,
files: filesToUpload,
chunks: chunks,
xhr: this.getXhrErrorComment(xhr)
});
this.props.setIsUploadReady(true);
this.cancelUploads();
let notificationMessage;
let notification = new GlobalNotificationModel(errorReason || this.props.defaultErrorMessage, 'danger', 5000);
GlobalNotificationActions.appendGlobalNotification(notification);
},
if (showErrorPrompt) {
this.setStatusOfFile(id, FileStatus.UPLOAD_FAILED);
getXhrErrorComment(xhr) {
if (xhr) {
return {
response: xhr.response,
url: xhr.responseURL,
status: xhr.status,
statusText: xhr.statusText
};
}
},
// If we've already found an error on this upload, just ignore other errors
// that pop up. They'll likely pop up again when the user retries.
if (!this.state.errorState.errorClass) {
notificationMessage = errorNotificationMessage;
isFileValid(file) {
if (file.size > this.props.validation.sizeLimit) {
const fileSizeInMegaBytes = this.props.validation.sizeLimit / 1000000;
const errorState = React.addons.update(this.state.errorState, {
errorClass: {
$set: this.getUploadErrorClass({
reason: errorReason,
xhr
})
}
});
const notification = new GlobalNotificationModel(getLangText('A file you submitted is bigger than ' + fileSizeInMegaBytes + 'MB.'), 'danger', 5000);
GlobalNotificationActions.appendGlobalNotification(notification);
if (typeof this.props.onValidationFailed === 'function') {
this.props.onValidationFailed(file);
this.setState({ errorState });
this.setWarning(true);
}
return false;
} else {
return true;
notificationMessage = errorReason || errorNotificationMessage;
this.cancelUploads();
}
if (notificationMessage) {
const notification = new GlobalNotificationModel(notificationMessage, 'danger', 5000);
GlobalNotificationActions.appendGlobalNotification(notification);
}
},
onCancel(id) {
// when a upload is canceled, we need to update this components file array
this.setStatusOfFile(id, 'canceled')
this.setStatusOfFile(id, FileStatus.CANCELED)
.then(() => {
if(typeof this.props.handleChangedFile === 'function') {
this.props.handleChangedFile(this.state.filesToUpload[id]);
@ -546,17 +702,18 @@ const ReactS3FineUploader = React.createClass({
let notification = new GlobalNotificationModel(getLangText('File upload canceled'), 'success', 5000);
GlobalNotificationActions.appendGlobalNotification(notification);
// since the form validation props isReadyForFormSubmission, setIsUploadReady and submitFile
// are optional, we'll only trigger them when they're actually defined
if(this.props.isReadyForFormSubmission && this.props.setIsUploadReady) {
if(this.props.isReadyForFormSubmission(this.state.filesToUpload)) {
// if so, set uploadstatus to true
this.props.setIsUploadReady(true);
} else {
this.props.setIsUploadReady(false);
}
} else {
console.warn('You didn\'t define the functions isReadyForFormSubmission and/or setIsUploadReady in as a prop in react-s3-fine-uploader');
this.checkFormSubmissionReady();
// FineUploader's onAllComplete event doesn't fire if all files are cancelled
// so we need to double check if this is the last file getting cancelled.
//
// Because we're calling FineUploader.getInProgress() in a cancel callback,
// the current file getting cancelled is still considered to be in progress
// so there will be one file left in progress when we're cancelling the last file.
if (this.state.uploader.getInProgress() === 1) {
this.setState({
uploadInProgress: false
});
}
return true;
@ -576,7 +733,7 @@ const ReactS3FineUploader = React.createClass({
// fetch blobs for images
response = response.map((file) => {
file.url = file.s3UrlSafe;
file.status = 'online';
file.status = FileStatus.ONLINE;
file.progress = 100;
return file;
});
@ -604,7 +761,7 @@ const ReactS3FineUploader = React.createClass({
onDeleteComplete(id, xhr, isError) {
if(isError) {
this.setStatusOfFile(id, 'online');
this.setStatusOfFile(id, FileStatus.ONLINE);
let notification = new GlobalNotificationModel(getLangText('There was an error deleting your file.'), 'danger', 10000);
GlobalNotificationActions.appendGlobalNotification(notification);
@ -613,29 +770,16 @@ const ReactS3FineUploader = React.createClass({
GlobalNotificationActions.appendGlobalNotification(notification);
}
// since the form validation props isReadyForFormSubmission, setIsUploadReady and submitFile
// are optional, we'll only trigger them when they're actually defined
if(this.props.isReadyForFormSubmission && this.props.setIsUploadReady) {
// also, lets check if after the completion of this upload,
// the form is ready for submission or not
if(this.props.isReadyForFormSubmission(this.state.filesToUpload)) {
// if so, set uploadstatus to true
this.props.setIsUploadReady(true);
} else {
this.props.setIsUploadReady(false);
}
} else {
console.warn('You didn\'t define the functions isReadyForFormSubmission and/or setIsUploadReady in as a prop in react-s3-fine-uploader');
}
this.checkFormSubmissionReady();
},
handleDeleteFile(fileId) {
// We set the files state to 'deleted' immediately, so that the user is not confused with
// the unresponsiveness of the UI
//
// If there is an error during the deletion, we will just change the status back to 'online'
// If there is an error during the deletion, we will just change the status back to FileStatus.ONLINE
// and display an error message
this.setStatusOfFile(fileId, 'deleted')
this.setStatusOfFile(fileId, FileStatus.DELETED)
.then(() => {
if(typeof this.props.handleChangedFile === 'function') {
this.props.handleChangedFile(this.state.filesToUpload[fileId]);
@ -651,7 +795,7 @@ const ReactS3FineUploader = React.createClass({
// To check which files are already uploaded from previous sessions we check their status.
// If they are, it is "online"
if(this.state.filesToUpload[fileId].status !== 'online') {
if(this.state.filesToUpload[fileId].status !== FileStatus.ONLINE) {
// delete file from server
this.state.uploader.deleteFile(fileId);
// this is being continued in onDeleteFile, as
@ -670,9 +814,16 @@ const ReactS3FineUploader = React.createClass({
this.cancelUploads(fileId);
},
handleCancelHashing() {
// Every progress tick of the hashing function in handleUploadFile there is a
// check if this.state.hashingProgress is -1. If so, there is an error thrown that cancels
// the hashing of all files immediately.
this.setState({ hashingProgress: -1 });
},
handlePauseFile(fileId) {
if(this.state.uploader.pauseUpload(fileId)) {
this.setStatusOfFile(fileId, 'paused');
this.setStatusOfFile(fileId, FileStatus.PAUSED);
} else {
throw new Error(getLangText('File upload could not be paused.'));
}
@ -680,12 +831,35 @@ const ReactS3FineUploader = React.createClass({
handleResumeFile(fileId) {
if(this.state.uploader.continueUpload(fileId)) {
this.setStatusOfFile(fileId, 'uploading');
this.setStatusOfFile(fileId, FileStatus.UPLOADING);
} else {
throw new Error(getLangText('File upload could not be resumed.'));
}
},
handleRetryFiles(fileIds) {
let filesToUpload = this.state.filesToUpload;
if (fileIds.constructor !== Array) {
fileIds = [ fileIds ];
}
fileIds.forEach((fileId) => {
this.state.uploader.retry(fileId);
filesToUpload = React.addons.update(filesToUpload, { [fileId]: { status: { $set: FileStatus.UPLOADING } } });
});
this.setState({
// Reset the error class along with the retry
errorState: {
manualRetryAttempt: this.state.errorState.manualRetryAttempt + 1
},
filesToUpload
});
this.setWarning(false);
},
handleUploadFile(files) {
// While files are being uploaded, the form cannot be ready
// for submission
@ -698,15 +872,8 @@ const ReactS3FineUploader = React.createClass({
return;
}
// validate each submitted file if it fits the file size
let validFiles = [];
for(let i = 0; i < files.length; i++) {
if(this.isFileValid(files[i])) {
validFiles.push(files[i]);
}
}
// override standard files list with only valid files
files = validFiles;
// Select only the submitted files that fit the file size and allowed extensions
files = this.selectValidFiles(files);
// if multiple is set to false and user drops multiple files into the dropzone,
// take the first one and notify user that only one file can be submitted
@ -813,17 +980,13 @@ const ReactS3FineUploader = React.createClass({
if(files.length > 0) {
this.state.uploader.addFiles(files);
this.synchronizeFileLists(files);
this.setState({
uploadInProgress: true
});
}
}
},
handleCancelHashing() {
// Every progress tick of the hashing function in handleUploadFile there is a
// check if this.state.hashingProgress is -1. If so, there is an error thrown that cancels
// the hashing of all files immediately.
this.setState({ hashingProgress: -1 });
},
// ReactFineUploader is essentially just a react layer around s3 fineuploader.
// However, since we need to display the status of a file (progress, uploading) as well as
// be able to execute actions on a currently uploading file we need to exactly sync the file list
@ -860,12 +1023,12 @@ const ReactS3FineUploader = React.createClass({
//
// If the user deletes one of those files, then fineuploader will still keep it in his
// files array but with key, progress undefined and size === -1 but
// status === 'upload successful'.
// status === FileStatus.UPLOAD_SUCCESSFUL.
// This poses a problem as we depend on the amount of files that have
// status === 'upload successful', therefore once the file is synced,
// we need to tag its status as 'deleted' (which basically happens here)
// status === FileStatus.UPLOAD_SUCCESSFUL, therefore once the file is synced,
// we need to tag its status as FileStatus.DELETED (which basically happens here)
if(oldAndNewFiles[i].size === -1 && (!oldAndNewFiles[i].progress || oldAndNewFiles[i].progress === 0)) {
oldAndNewFiles[i].status = 'deleted';
oldAndNewFiles[i].status = FileStatus.DELETED;
}
if(oldAndNewFiles[i].originalName === oldFiles[j].name) {
@ -893,55 +1056,19 @@ const ReactS3FineUploader = React.createClass({
});
},
// This method has been made promise-based to immediately afterwards
// call a callback function (instantly after this.setState went through)
// This is e.g. needed when showing/hiding the optional thumbnail upload
// field in the registration form
setStatusOfFile(fileId, status) {
return Q.Promise((resolve) => {
let changeSet = {};
if(status === 'deleted' || status === 'canceled') {
changeSet.progress = { $set: 0 };
}
changeSet.status = { $set: status };
let filesToUpload = React.addons.update(this.state.filesToUpload, { [fileId]: changeSet });
this.setState({ filesToUpload }, resolve);
});
},
isDropzoneInactive() {
const filesToDisplay = this.state.filesToUpload.filter((file) => file.status !== 'deleted' && file.status !== 'canceled' && file.size !== -1);
if ((this.props.enableLocalHashing && !this.props.uploadMethod) || !this.props.areAssetsEditable || !this.props.multiple && filesToDisplay.length > 0) {
return true;
} else {
return false;
}
},
getAllowedExtensions() {
let { validation } = this.props;
if(validation && validation.allowedExtensions && validation.allowedExtensions.length > 0) {
return transformAllowedExtensionsToInputAcceptProp(validation.allowedExtensions);
} else {
return null;
}
},
render() {
const {
multiple,
areAssetsDownloadable,
areAssetsEditable,
enableLocalHashing,
fileClassToUpload,
fileInputElement: FileInputElement,
uploadMethod } = this.props;
const { errorState: { errorClass }, filesToUpload, uploadInProgress } = this.state;
const { areAssetsDownloadable,
areAssetsEditable,
enableLocalHashing,
fileClassToUpload,
fileInputElement: FileInputElement,
multiple,
showErrorPrompt,
uploadMethod } = this.props;
// Only show the error state once all files are finished
const showError = !uploadInProgress && showErrorPrompt && errorClass != null;
const props = {
multiple,
@ -950,12 +1077,16 @@ const ReactS3FineUploader = React.createClass({
enableLocalHashing,
uploadMethod,
fileClassToUpload,
filesToUpload,
uploadInProgress,
errorClass,
showError,
onDrop: this.handleUploadFile,
filesToUpload: this.state.filesToUpload,
handleDeleteFile: this.handleDeleteFile,
handleCancelFile: this.handleCancelFile,
handlePauseFile: this.handlePauseFile,
handleResumeFile: this.handleResumeFile,
handleRetryFiles: this.handleRetryFiles,
handleCancelHashing: this.handleCancelHashing,
dropzoneInactive: this.isDropzoneInactive(),
hashingProgress: this.state.hashingProgress,

View File

@ -1,7 +1,15 @@
'use strict';
import fineUploader from 'fineUploader';
import MimeTypes from '../../constants/mime_types';
// Re-export qq.status from FineUploader with an additional online
// state that we use to keep track of files from S3.
export const FileStatus = Object.assign({}, fineUploader.status, {
ONLINE: 'online'
});
export const formSubmissionValidation = {
/**
* Returns a boolean if there has been at least one file uploaded
@ -10,8 +18,13 @@ export const formSubmissionValidation = {
* @return {boolean}
*/
atLeastOneUploadedFile(files) {
files = files.filter((file) => file.status !== 'deleted' && file.status !== 'canceled');
if (files.length > 0 && files[0].status === 'upload successful') {
files = files.filter((file) => {
return file.status !== FileStatus.DELETED &&
file.status !== FileStatus.CANCELED &&
file.status != FileStatus.UPLOADED_FAILED
});
if (files.length && files[0].status === FileStatus.UPLOAD_SUCCESSFUL) {
return true;
} else {
return false;
@ -25,32 +38,32 @@ export const formSubmissionValidation = {
* @return {boolean} [description]
*/
fileOptional(files) {
let uploadingFiles = files.filter((file) => file.status === 'submitting');
const uploadingFiles = files.filter((file) => file.status === FileStatus.SUBMITTING);
if (uploadingFiles.length === 0) {
return true;
} else {
return false;
}
return uploadFiles.length === 0;
}
};
/**
* Filter function for filtering all deleted and canceled files
* Filter function for filtering all deleted, canceled, and failed files
* @param {object} file A file from filesToUpload that has status as a prop.
* @return {boolean}
*/
export function displayValidFilesFilter(file) {
return file.status !== 'deleted' && file.status !== 'canceled';
return file.status !== FileStatus.DELETED &&
file.status !== FileStatus.CANCELED &&
file.status !== FileStatus.UPLOAD_FAILED;
}
/**
* Filter function for filtering all files except for deleted and canceled files
* Filter function for filtering all files except for deleted, canceled, and failed files
* @param {object} file A file from filesToUpload that has status as a prop.
* @return {boolean}
*/
export function displayRemovedFilesFilter(file) {
return file.status === 'deleted' || file.status === 'canceled';
return file.status === FileStatus.DELETED ||
file.status === FileStatus.CANCELED ||
file.status === FileStatus.UPLOAD_FAILED;
}
@ -60,7 +73,10 @@ export function displayRemovedFilesFilter(file) {
* @return {boolean}
*/
export function displayValidProgressFilesFilter(file) {
return file.status !== 'deleted' && file.status !== 'canceled' && file.status !== 'online';
return file.status !== FileStatus.DELETED &&
file.status !== FileStatus.CANCELED &&
file.status !== FileStatus.UPLOAD_FAILED &&
file.status !== FileStatus.ONLINE;
}
@ -77,7 +93,7 @@ export function displayValidProgressFilesFilter(file) {
export function transformAllowedExtensionsToInputAcceptProp(allowedExtensions) {
// Get the mime type of the extension if it's defined or add a dot in front of the extension
// This is important for Safari as it doesn't understand just the extension.
let prefixedAllowedExtensions = allowedExtensions.map((ext) => {
const prefixedAllowedExtensions = allowedExtensions.map((ext) => {
return MimeTypes[ext] || ('.' + ext);
});

View File

@ -18,6 +18,11 @@ import { setDocumentTitle } from '../utils/dom_utils';
let CoaVerifyContainer = React.createClass({
propTypes: {
// Provided from AscribeApp
currentUser: React.PropTypes.object,
whitelabel: React.PropTypes.object,
// Provided from router
location: React.PropTypes.object
},
@ -27,7 +32,7 @@ let CoaVerifyContainer = React.createClass({
return (
<div className="ascribe-login-wrapper">
<br/>
<br />
<div className="ascribe-login-text ascribe-login-header">
{getLangText('Verify your Certificate of Authenticity')}
</div>
@ -37,7 +42,7 @@ let CoaVerifyContainer = React.createClass({
signature={signature}/>
<br />
<br />
{getLangText('ascribe is using the following public key for verification')}:
{getLangText('ascribe is using the following public key for verification')}:
<br />
<pre>
-----BEGIN PUBLIC KEY-----
@ -60,9 +65,8 @@ let CoaVerifyForm = React.createClass({
},
handleSuccess(response){
let notification = null;
if (response.verdict) {
notification = new GlobalNotificationModel(getLangText('Certificate of Authenticity successfully verified'), 'success');
const notification = new GlobalNotificationModel(getLangText('Certificate of Authenticity successfully verified'), 'success');
GlobalNotificationActions.appendGlobalNotification(notification);
}
},
@ -71,46 +75,44 @@ let CoaVerifyForm = React.createClass({
const { message, signature } = this.props;
return (
<div>
<Form
url={ApiUrls.coa_verify}
handleSuccess={this.handleSuccess}
buttons={
<button
type="submit"
className="btn btn-default btn-wide">
{getLangText('Verify your Certificate of Authenticity')}
</button>}
spinner={
<span className="btn btn-default btn-wide btn-spinner">
<AscribeSpinner color="dark-blue" size="md" />
</span>
}>
<Property
name='message'
label={getLangText('Message')}>
<input
type="text"
placeholder={getLangText('Copy paste the message on the bottom of your Certificate of Authenticity')}
autoComplete="on"
defaultValue={message}
name="username"
required/>
</Property>
<Property
name='signature'
label="Signature"
editable={true}
overrideForm={true}>
<InputTextAreaToggable
rows={3}
placeholder={getLangText('Copy paste the signature on the bottom of your Certificate of Authenticity')}
defaultValue={signature}
required/>
</Property>
<hr />
</Form>
</div>
<Form
url={ApiUrls.coa_verify}
handleSuccess={this.handleSuccess}
buttons={
<button
type="submit"
className="btn btn-default btn-wide">
{getLangText('Verify your Certificate of Authenticity')}
</button>
}
spinner={
<span className="btn btn-default btn-wide btn-spinner">
<AscribeSpinner color="dark-blue" size="md" />
</span>
}>
<Property
name='message'
label={getLangText('Message')}>
<input
type="text"
placeholder={getLangText('Copy paste the message on the bottom of your Certificate of Authenticity')}
autoComplete="on"
defaultValue={message}
required />
</Property>
<Property
name='signature'
label="Signature"
editable={true}
overrideForm={true}>
<InputTextAreaToggable
rows={3}
placeholder={getLangText('Copy paste the signature on the bottom of your Certificate of Authenticity')}
defaultValue={signature}
required />
</Property>
<hr />
</Form>
);
}
});

View File

@ -1,21 +1,42 @@
'use strict';
import React from 'react';
import { History } from 'react-router';
import { getLangText } from '../utils/lang_utils';
let ErrorNotFoundPage = React.createClass({
propTypes: {
message: React.PropTypes.string
message: React.PropTypes.string,
// Provided from AscribeApp
currentUser: React.PropTypes.object,
whitelabel: React.PropTypes.object,
// Provided from router
location: React.PropTypes.object
},
mixins: [History],
getDefaultProps() {
return {
message: getLangText("Oops, the page you are looking for doesn't exist.")
};
},
componentDidMount() {
// The previous page, if any, is the second item in the locationQueue
const { locationQueue: [ , previousPage ] } = this.history;
if (previousPage) {
console.logGlobal('Page not found', {
previousPath: previousPage.pathname
});
}
},
render() {
return (
<div className="row">
@ -32,4 +53,4 @@ let ErrorNotFoundPage = React.createClass({
}
});
export default ErrorNotFoundPage;
export default ErrorNotFoundPage;

View File

@ -5,8 +5,12 @@ import React from 'react';
import { getLangText } from '../utils/lang_utils';
let Footer = React.createClass({
propTypes: {
activeRoute: React.PropTypes.object.isRequired
},
render() {
return (
return !this.props.activeRoute.hideFooter ? (
<div className="ascribe-footer hidden-print">
<p className="ascribe-sub-sub-statement">
<br />
@ -24,7 +28,7 @@ let Footer = React.createClass({
<a href="https://www.linkedin.com/company/4816284?trk=vsrp_companies_res_name&trkInfo=VSRPsearchId%3A122827941425632318075%2CVSRPtargetId%3A4816284%2CVSRPcmpt%3Aprimary" className="social social-linked-in" target="_blank"></a>
</p>
</div>
);
) : null;
}
});

View File

@ -14,74 +14,52 @@ import NavItem from 'react-bootstrap/lib/NavItem';
import LinkContainer from 'react-router-bootstrap/lib/LinkContainer';
import AclProxy from './acl_proxy';
import EventActions from '../actions/event_actions';
import UserActions from '../actions/user_actions';
import UserStore from '../stores/user_store';
import WhitelabelActions from '../actions/whitelabel_actions';
import WhitelabelStore from '../stores/whitelabel_store';
import PieceListStore from '../stores/piece_list_store';
import AclProxy from './acl_proxy';
import HeaderNotifications from './header_notification';
import HeaderNotificationDebug from './header_notification_debug';
import NavRoutesLinks from './nav_routes_links';
import { mergeOptions } from '../utils/general_utils';
import { getLangText } from '../utils/lang_utils';
import { constructHead } from '../utils/dom_utils';
let Header = React.createClass({
propTypes: {
routes: React.PropTypes.arrayOf(React.PropTypes.object)
currentUser: React.PropTypes.object.isRequired,
routes: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
whitelabel: React.PropTypes.object.isRequired
},
getInitialState() {
return mergeOptions(
WhitelabelStore.getState(),
UserStore.getState()
);
return PieceListStore.getState();
},
componentDidMount() {
UserStore.listen(this.onChange);
UserActions.fetchCurrentUser.defer();
WhitelabelStore.listen(this.onChange);
WhitelabelActions.fetchWhitelabel.defer();
// Listen to the piece list store, but don't fetch immediately to avoid
// conflicts with routes that may need to wait to load the piece list
PieceListStore.listen(this.onChange);
// react-bootstrap 0.25.1 has a bug in which it doesn't
// close the mobile expanded navigation after a click by itself.
// To get rid of this, we set the state of the component ourselves.
history.listen(this.onRouteChange);
if (this.state.currentUser && this.state.currentUser.email) {
EventActions.profileDidLoad.defer(this.state.currentUser);
}
},
componentWillUpdate(nextProps, nextState) {
const { currentUser: { email: curEmail } = {} } = this.state;
const { currentUser: { email: nextEmail } = {} } = nextState;
if (nextEmail && curEmail !== nextEmail) {
EventActions.profileDidLoad.defer(nextState.currentUser);
}
},
componentWillUnmount() {
UserStore.unlisten(this.onChange);
WhitelabelStore.unlisten(this.onChange);
PieceListStore.unlisten(this.onChange);
//history.unlisten(this.onRouteChange);
},
onChange(state) {
this.setState(state);
},
getLogo() {
let { whitelabel } = this.state;
const { whitelabel } = this.props;
if (whitelabel.head) {
constructHead(whitelabel.head);
@ -93,19 +71,19 @@ let Header = React.createClass({
<img className="img-brand" src={whitelabel.logo} alt="Whitelabel brand"/>
</Link>
);
} else {
return (
<span>
<Link className="icon-ascribe-logo" to="/collection"/>
</span>
);
}
return (
<span>
<Link className="icon-ascribe-logo" to="/collection"/>
</span>
);
},
getPoweredBy(){
getPoweredBy() {
return (
<AclProxy
aclObject={this.state.whitelabel}
aclObject={this.props.whitelabel}
aclName="acl_view_powered_by">
<li>
<a className="pull-right ascribe-powered-by" href="https://www.ascribe.io/" target="_blank">
@ -117,10 +95,6 @@ let Header = React.createClass({
);
},
onChange(state) {
this.setState(state);
},
onMenuItemClick() {
/*
This is a hack to make the dropdown close after clicking on an item
@ -156,59 +130,70 @@ let Header = React.createClass({
},
render() {
const { currentUser, routes } = this.props;
const { unfilteredPieceListCount } = this.state;
let account;
let signup;
let navRoutesLinks;
if (this.state.currentUser.username){
if (currentUser.username) {
account = (
<DropdownButton
ref='dropdownbutton'
id="nav-route-user-dropdown"
eventKey="1"
title={this.state.currentUser.username}>
title={currentUser.username}>
<LinkContainer
to="/settings"
onClick={this.onMenuItemClick}>
<MenuItem
eventKey="2">
<MenuItem eventKey="2">
{getLangText('Account Settings')}
</MenuItem>
</LinkContainer>
<AclProxy
aclObject={this.state.currentUser.acl}
aclObject={currentUser.acl}
aclName="acl_view_settings_contract">
<LinkContainer
to="/contract_settings"
onClick={this.onMenuItemClick}>
<MenuItem
eventKey="2">
<MenuItem eventKey="2">
{getLangText('Contract Settings')}
</MenuItem>
</LinkContainer>
</AclProxy>
<MenuItem divider />
<LinkContainer
to="/logout">
<MenuItem
eventKey="3">
<LinkContainer to="/logout">
<MenuItem eventKey="3">
{getLangText('Log out')}
</MenuItem>
</LinkContainer>
</DropdownButton>
);
navRoutesLinks = <NavRoutesLinks routes={this.props.routes} userAcl={this.state.currentUser.acl} navbar right/>;
}
else {
// Let's assume that if the piece list hasn't loaded yet (ie. when unfilteredPieceListCount === -1)
// then the user has pieces
// FIXME: this doesn't work that well as the user may not load their piece list
// until much later, so we would show the 'Collection' header as available until
// they actually click on it and get redirected to piece registration.
navRoutesLinks = (
<NavRoutesLinks
navbar
right
hasPieces={!!unfilteredPieceListCount}
routes={routes}
userAcl={currentUser.acl} />
);
} else {
account = (
<LinkContainer
to="/login">
<LinkContainer to="/login">
<NavItem>
{getLangText('LOGIN')}
</NavItem>
</LinkContainer>
);
signup = (
<LinkContainer
to="/signup">
<LinkContainer to="/signup">
<NavItem>
{getLangText('SIGNUP')}
</NavItem>
@ -224,13 +209,12 @@ let Header = React.createClass({
toggleNavKey={0}
fixedTop={true}
className="hidden-print">
<CollapsibleNav
eventKey={0}>
<CollapsibleNav eventKey={0}>
<Nav navbar left>
{this.getPoweredBy()}
</Nav>
<Nav navbar right>
<HeaderNotificationDebug show={false}/>
<HeaderNotificationDebug show={false} />
{account}
{signup}
</Nav>

View File

@ -11,16 +11,12 @@ import Nav from 'react-bootstrap/lib/Nav';
import NotificationActions from '../actions/notification_actions';
import NotificationStore from '../stores/notification_store';
import { mergeOptions } from '../utils/general_utils';
import { getLangText } from '../utils/lang_utils';
let HeaderNotifications = React.createClass({
getInitialState() {
return mergeOptions(
NotificationStore.getState()
);
return NotificationStore.getState();
},
componentDidMount() {
@ -62,7 +58,7 @@ let HeaderNotifications = React.createClass({
this.refs.dropdownbutton.setDropdownState(false);
},
getPieceNotifications(){
getPieceNotifications() {
if (this.state.pieceListNotifications && this.state.pieceListNotifications.length > 0) {
return (
<div>
@ -87,7 +83,7 @@ let HeaderNotifications = React.createClass({
return null;
},
getEditionNotifications(){
getEditionNotifications() {
if (this.state.editionListNotifications && this.state.editionListNotifications.length > 0) {
return (
<div>
@ -114,7 +110,7 @@ let HeaderNotifications = React.createClass({
render() {
if ((this.state.pieceListNotifications && this.state.pieceListNotifications.length > 0) ||
(this.state.editionListNotifications && this.state.editionListNotifications.length > 0)){
(this.state.editionListNotifications && this.state.editionListNotifications.length > 0)) {
let numNotifications = 0;
if (this.state.pieceListNotifications && this.state.pieceListNotifications.length > 0) {
numNotifications += this.state.pieceListNotifications.length;
@ -125,7 +121,8 @@ let HeaderNotifications = React.createClass({
return (
<Nav navbar right>
<DropdownButton
ref='dropdownbutton'
ref='dropdownButton'
id="header-notification-dropdown"
eventKey="1"
title={
<span>

View File

@ -11,19 +11,12 @@ import { setDocumentTitle } from '../utils/dom_utils';
let LoginContainer = React.createClass({
propTypes: {
message: React.PropTypes.string,
redirectOnLoggedIn: React.PropTypes.bool,
redirectOnLoginSuccess: React.PropTypes.bool,
onLogin: React.PropTypes.func,
location: React.PropTypes.object
},
// Provided from AscribeApp
currentUser: React.PropTypes.object,
whitelabel: React.PropTypes.object,
getDefaultProps() {
return {
message: getLangText('Enter') + ' ascribe',
redirectOnLoggedIn: true,
redirectOnLoginSuccess: true
};
// Provided from router
location: React.PropTypes.object
},
render() {
@ -31,12 +24,7 @@ let LoginContainer = React.createClass({
return (
<div className="ascribe-login-wrapper">
<LoginForm
redirectOnLoggedIn={this.props.redirectOnLoggedIn}
redirectOnLoginSuccess={this.props.redirectOnLoginSuccess}
message={this.props.message}
onLogin={this.props.onLogin}
location={this.props.location}/>
<LoginForm location={this.props.location} />
<div className="ascribe-login-text">
{getLangText('Not an ascribe user')}&#63; <Link to="/signup">{getLangText('Sign up')}...</Link><br/>
{getLangText('Forgot my password')}&#63; <Link to="/password_reset">{getLangText('Rescue me')}...</Link>

View File

@ -6,23 +6,25 @@ import { History } from 'react-router';
import AscribeSpinner from './ascribe_spinner';
import UserActions from '../actions/user_actions';
import { alt, altWhitelabel, altUser, altThirdParty } from '../alt';
import { getLangText } from '../utils/lang_utils';
import { setDocumentTitle } from '../utils/dom_utils';
let LogoutContainer = React.createClass({
propTypes: {
// Provided from AscribeApp
currentUser: React.PropTypes.object,
whitelabel: React.PropTypes.object,
// Provided from router
location: React.PropTypes.object
},
mixins: [History],
componentDidMount() {
UserActions.logoutCurrentUser();
alt.flush();
altWhitelabel.flush();
altUser.flush();
altThirdParty.flush();
// kill intercom (with fire)
window.Intercom('shutdown');
},
render() {

View File

@ -11,14 +11,33 @@ import AclProxy from './acl_proxy';
import { sanitizeList } from '../utils/general_utils';
const DISABLE_ENUM = ['hasPieces', 'noPieces'];
let NavRoutesLinks = React.createClass({
propTypes: {
hasPieces: React.PropTypes.bool,
routes: React.PropTypes.arrayOf(React.PropTypes.object),
userAcl: React.PropTypes.object
},
isRouteDisabled(disableOn) {
const { hasPieces } = this.props;
if (disableOn) {
if (!DISABLE_ENUM.includes(disableOn)) {
throw new Error(`"disableOn" must be one of: [${DISABLE_ENUM.join(', ')}] got "${disableOn}" instead`);
}
if (disableOn === 'hasPieces') {
return hasPieces;
} else if (disableOn === 'noPieces') {
return !hasPieces;
}
}
},
/**
* This method generales a bunch of react-bootstrap specific links
* This method generates a bunch of react-bootstrap specific links
* from the routes we defined in one of the specific routes.js file
*
* We can define a headerTitle as well as a aclName and according to that the
@ -29,48 +48,50 @@ let NavRoutesLinks = React.createClass({
* @return {Array} Array of ReactElements that can be displayed to the user
*/
extractLinksFromRoutes(node, userAcl, i) {
if(!node) {
if (!node) {
return;
}
let links = node.childRoutes.map((child, j) => {
let childrenFn = null;
let { aclName, headerTitle, path, childRoutes } = child;
// If the node has children that could be rendered, then we want
// to execute this function again with the child as the root
//
// Otherwise we'll just pass childrenFn as false
if(child.childRoutes && child.childRoutes.length > 0) {
childrenFn = this.extractLinksFromRoutes(child, userAcl, i++);
}
const links = node.childRoutes.map((child, j) => {
const { aclName, disableOn, headerTitle, path, childRoutes } = child;
// We validate if the user has set the title correctly,
// otherwise we're not going to render his route
if(headerTitle && typeof headerTitle === 'string') {
if (headerTitle && typeof headerTitle === 'string') {
let nestedChildren = null;
// If the node has children that could be rendered, then we want
// to execute this function again with the child as the root
//
// Otherwise we'll just pass nestedChildren as false
if (child.childRoutes && child.childRoutes.length) {
nestedChildren = this.extractLinksFromRoutes(child, userAcl, i++);
}
const navLinkProps = {
headerTitle,
children: nestedChildren,
depth: i,
disabled: this.isRouteDisabled(disableOn),
routePath: `/${path}`
};
// if there is an aclName present on the route definition,
// we evaluate it against the user's acl
if(aclName && typeof aclName !== 'undefined') {
if (aclName && typeof aclName !== 'undefined') {
return (
<AclProxy
key={j}
aclName={aclName}
aclObject={this.props.userAcl}>
<NavRoutesLinksLink
headerTitle={headerTitle}
routePath={'/' + path}
depth={i}
children={childrenFn}/>
<NavRoutesLinksLink {...navLinkProps} />
</AclProxy>
);
} else {
return (
<NavRoutesLinksLink
key={j}
headerTitle={headerTitle}
routePath={'/' + path}
depth={i}
children={childrenFn}/>
{...navLinkProps} />
);
}
} else {
@ -84,7 +105,7 @@ let NavRoutesLinks = React.createClass({
},
render() {
let {routes, userAcl} = this.props;
const {routes, userAcl} = this.props;
return (
<Nav {...this.props}>
@ -94,4 +115,4 @@ let NavRoutesLinks = React.createClass({
}
});
export default NavRoutesLinks;
export default NavRoutesLinks;

View File

@ -11,40 +11,46 @@ import LinkContainer from 'react-router-bootstrap/lib/LinkContainer';
let NavRoutesLinksLink = React.createClass({
propTypes: {
headerTitle: React.PropTypes.string,
routePath: React.PropTypes.string,
children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element),
React.PropTypes.element
]),
depth: React.PropTypes.number
disabled: React.PropTypes.bool,
depth: React.PropTypes.number,
headerTitle: React.PropTypes.string,
routePath: React.PropTypes.string
},
render() {
let { children, headerTitle, depth, routePath } = this.props;
const { children, headerTitle, depth, disabled, routePath } = this.props;
// if the route has children, we're returning a DropdownButton that will get filled
// with MenuItems
if(children) {
if (children) {
return (
<DropdownButton title={headerTitle}>
<DropdownButton
disabled={disabled}
id={`nav-route-${headerTitle.toLowerCase()}-dropdown`}
title={headerTitle}>
{children}
</DropdownButton>
);
} else {
if(depth === 1) {
if (depth === 1) {
// if the node's child is actually a node of level one (a child of a node), we're
// returning a DropdownButton matching MenuItem
return (
<LinkContainer to={routePath}>
<LinkContainer
disabled={disabled}
to={routePath}>
<MenuItem>{headerTitle}</MenuItem>
</LinkContainer>
);
} else if(depth === 0) {
} else if (depth === 0) {
return (
<LinkContainer to={routePath}>
<LinkContainer
disabled={disabled}
to={routePath}>
<NavItem>{headerTitle}</NavItem>
</LinkContainer>
);
@ -55,4 +61,4 @@ let NavRoutesLinksLink = React.createClass({
}
});
export default NavRoutesLinksLink;
export default NavRoutesLinksLink;

View File

@ -16,52 +16,44 @@ import { setDocumentTitle } from '../utils/dom_utils';
let PasswordResetContainer = React.createClass({
propTypes: {
// Provided from AscribeApp
currentUser: React.PropTypes.object,
whitelabel: React.PropTypes.object,
// Provided from router
location: React.PropTypes.object
},
getInitialState() {
return {isRequested: false};
return { isRequested: false };
},
handleRequestSuccess(email) {
this.setState({isRequested: email});
this.setState({ isRequested: !!email });
},
render() {
let { location } = this.props;
const { email: emailQuery, token: tokenQuery } = this.props.location.query;
const { isRequested } = this.state;
if (location.query.email && location.query.token) {
if (emailQuery && tokenQuery) {
return (
<div>
<PasswordResetForm
email={location.query.email}
token={location.query.token}/>
<PasswordResetForm
email={emailQuery}
token={tokenQuery} />
);
} else if (!isRequested) {
return (
<PasswordRequestResetForm handleRequestSuccess={this.handleRequestSuccess} />
);
} else {
return (
<div className="ascribe-login-text ascribe-login-header">
{getLangText('If your email address exists in our database, you will receive a password recovery link in a few minutes.')}
</div>
);
}
else {
if (this.state.isRequested === false) {
return (
<div>
<PasswordRequestResetForm
handleRequestSuccess={this.handleRequestSuccess}/>
</div>
);
}
else if (this.state.isRequested) {
return (
<div>
<div className="ascribe-login-text ascribe-login-header">
{getLangText('If your email address exists in our database, you will receive a password recovery link in a few minutes.')}
</div>
</div>
);
}
else {
return <span />;
}
}
}
}
});
let PasswordRequestResetForm = React.createClass({
@ -70,9 +62,10 @@ let PasswordRequestResetForm = React.createClass({
},
handleSuccess() {
let notificationText = getLangText('If your email address exists in our database, you will receive a password recovery link in a few minutes.');
let notification = new GlobalNotificationModel(notificationText, 'success', 50000);
const notificationText = getLangText('If your email address exists in our database, you will receive a password recovery link in a few minutes.');
const notification = new GlobalNotificationModel(notificationText, 'success', 50000);
GlobalNotificationActions.appendGlobalNotification(notification);
this.props.handleRequestSuccess(this.refs.form.refs.email.state.value);
},
@ -90,12 +83,13 @@ let PasswordRequestResetForm = React.createClass({
type="submit"
className="btn btn-default btn-wide">
{getLangText('Reset your password')}
</button>}
</button>
}
spinner={
<span className="btn btn-default btn-wide btn-spinner">
<AscribeSpinner color="dark-blue" size="md" />
</span>
}>
}>
<div className="ascribe-form-header">
<h3>{getLangText('Reset your password')}</h3>
</div>
@ -149,12 +143,13 @@ let PasswordResetForm = React.createClass({
type="submit"
className="btn btn-default btn-wide">
{getLangText('Reset your password')}
</button>}
</button>
}
spinner={
<span className="btn btn-default btn-wide btn-spinner">
<AscribeSpinner color="dark-blue" size="md" />
</span>
}>
}>
<div className="ascribe-form-header">
<h3>{getLangText('Reset the password for')} {this.props.email}</h3>
</div>

View File

@ -36,13 +36,22 @@ let PieceList = React.createClass({
accordionListItemType: React.PropTypes.func,
bulkModalButtonListType: React.PropTypes.func,
canLoadPieceList: React.PropTypes.bool,
redirectTo: React.PropTypes.string,
redirectTo: React.PropTypes.shape({
pathname: React.PropTypes.string,
query: React.PropTypes.object
}),
shouldRedirect: React.PropTypes.func,
customSubmitButton: React.PropTypes.element,
customThumbnailPlaceholder: React.PropTypes.func,
filterParams: React.PropTypes.array,
orderParams: React.PropTypes.array,
orderBy: React.PropTypes.string,
// Provided from AscribeApp
currentUser: React.PropTypes.object.isRequired,
whitelabel: React.PropTypes.object.isRequired,
// Provided from router
location: React.PropTypes.object
},
@ -53,7 +62,6 @@ let PieceList = React.createClass({
accordionListItemType: AccordionListItemWallet,
bulkModalButtonListType: AclButtonList,
canLoadPieceList: true,
orderParams: ['artist_name', 'title'],
filterParams: [{
label: getLangText('Show works I can'),
items: [
@ -61,7 +69,13 @@ let PieceList = React.createClass({
'acl_consign',
'acl_create_editions'
]
}]
}],
orderParams: ['artist_name', 'title'],
redirectTo: {
pathname: '/register_piece',
query: null
},
shouldRedirect: (pieceCount) => !pieceCount
};
},
@ -85,7 +99,7 @@ let PieceList = React.createClass({
PieceListStore.listen(this.onChange);
EditionListStore.listen(this.onChange);
let page = this.props.location.query.page || 1;
const page = this.props.location.query.page || 1;
if (this.props.canLoadPieceList && (this.state.pieceList.length === 0 || this.state.page !== page)) {
this.loadPieceList({ page });
}
@ -118,10 +132,16 @@ let PieceList = React.createClass({
const { location: { query }, redirectTo, shouldRedirect } = this.props;
const { unfilteredPieceListCount } = this.state;
if (redirectTo && unfilteredPieceListCount === 0 &&
if (redirectTo && redirectTo.pathname &&
(typeof shouldRedirect === 'function' && shouldRedirect(unfilteredPieceListCount))) {
// FIXME: hack to redirect out of the dispatch cycle
window.setTimeout(() => this.history.push({ query, pathname: redirectTo }), 0);
window.setTimeout(() => this.history.push({
// Occasionally, the back end also sets query parameters for Onion.
// We need to consider this by merging all passed query parameters, as we'll
// otherwise end up in a 404 screen
query: Object.assign({}, query, redirectTo.query),
pathname: redirectTo.pathname
}), 0);
}
},
@ -161,8 +181,8 @@ let PieceList = React.createClass({
},
getPagination() {
let currentPage = parseInt(this.props.location.query.page, 10) || 1;
let totalPages = Math.ceil(this.state.pieceListCount / this.state.pageSize);
const currentPage = parseInt(this.props.location.query.page, 10) || 1;
const totalPages = Math.ceil(this.state.pieceListCount / this.state.pageSize);
if (this.state.pieceListCount > 20) {
return (
@ -189,8 +209,7 @@ let PieceList = React.createClass({
});
// first we need to apply the filter on the piece list
this
.loadPieceList({ page: 1, filterBy })
this.loadPieceList({ page: 1, filterBy })
.then(() => {
// but also, we need to filter all the open edition lists
this.state.pieceList
@ -225,23 +244,22 @@ let PieceList = React.createClass({
},
fetchSelectedPieceEditionList() {
let filteredPieceIdList = Object.keys(this.state.editionList)
.filter((pieceId) => {
return this.state.editionList[pieceId]
.filter((edition) => edition.selected).length > 0;
});
const filteredPieceIdList = Object.keys(this.state.editionList)
.filter((pieceId) => {
return this.state.editionList[pieceId]
.filter((edition) => edition.selected)
.length;
});
return filteredPieceIdList;
},
fetchSelectedEditionList() {
let selectedEditionList = [];
Object
.keys(this.state.editionList)
.forEach((pieceId) => {
let filteredEditionsForPiece = this.state.editionList[pieceId].filter((edition) => edition.selected);
selectedEditionList = selectedEditionList.concat(filteredEditionsForPiece);
});
const selectedEditionList = Object.keys(this.state.editionList)
.reduce((selectedList, pieceId) => {
const selectedEditionsForPiece = this.state.editionList[pieceId]
.filter((edition) => edition.selected);
return selectedList.concat(selectedEditionsForPiece);
}, []);
return selectedEditionList;
},
@ -253,7 +271,7 @@ let PieceList = React.createClass({
this.fetchSelectedPieceEditionList()
.forEach((pieceId) => {
EditionListActions.refreshEditionList({pieceId});
EditionListActions.refreshEditionList({ pieceId });
});
EditionListActions.clearAllEditionSelections();
},
@ -261,10 +279,12 @@ let PieceList = React.createClass({
render() {
const { accordionListItemType: AccordionListItemType,
bulkModalButtonListType: BulkModalButtonListType,
currentUser,
customSubmitButton,
customThumbnailPlaceholder,
filterParams,
orderParams } = this.props;
orderParams,
whitelabel } = this.props;
const loadingElement = <AscribeSpinner color='dark-blue' size='lg'/>;
@ -272,6 +292,7 @@ let PieceList = React.createClass({
const availableAcls = getAvailableAcls(selectedEditions, (aclName) => aclName !== 'acl_view');
setDocumentTitle(getLangText('Collection'));
return (
<div>
<PieceListToolbar
@ -284,12 +305,7 @@ let PieceList = React.createClass({
orderBy={this.state.orderBy}
applyFilterBy={this.applyFilterBy}
applyOrderBy={this.applyOrderBy}>
{customSubmitButton ?
customSubmitButton :
<button className="btn btn-default btn-ascribe-add">
<span className="icon-ascribe icon-ascribe-add" />
</button>
}
{customSubmitButton}
</PieceListToolbar>
<PieceListBulkModal
availableAcls={availableAcls}
@ -297,17 +313,19 @@ let PieceList = React.createClass({
className="ascribe-piece-list-bulk-modal">
<BulkModalButtonListType
availableAcls={availableAcls}
pieceOrEditions={selectedEditions}
currentUser={currentUser}
handleSuccess={this.handleAclSuccess}
pieceOrEditions={selectedEditions}
whitelabel={whitelabel}
className="text-center ascribe-button-list collapse-group">
<DeleteButton
handleSuccess={this.handleAclSuccess}
editions={selectedEditions}/>
editions={selectedEditions} />
</BulkModalButtonListType>
</PieceListBulkModal>
<PieceListFilterDisplay
filterBy={this.state.filterBy}
filterParams={filterParams}/>
filterParams={filterParams} />
<AccordionList
className="ascribe-accordion-list"
changeOrder={this.accordionChangeOrder}
@ -320,13 +338,15 @@ let PieceList = React.createClass({
page={this.state.page}
pageSize={this.state.pageSize}
loadingElement={loadingElement}>
{this.state.pieceList.map((piece, i) => {
{this.state.pieceList.map((piece) => {
return (
<AccordionListItemType
key={piece.id}
className="col-xs-12 col-sm-10 col-md-8 col-lg-8 col-sm-offset-1 col-md-offset-2 col-lg-offset-2 ascribe-accordion-list-item"
content={piece}
currentUser={currentUser}
thumbnailPlaceholder={customThumbnailPlaceholder}
key={i}>
whitelabel={whitelabel}>
<AccordionListItemTableEditions
className="ascribe-accordion-list-item-table col-xs-12 col-sm-10 col-md-8 col-lg-8 col-sm-offset-1 col-md-offset-2 col-lg-offset-2"
parentId={piece.id} />

View File

@ -6,27 +6,20 @@ import { History } from 'react-router';
import Col from 'react-bootstrap/lib/Col';
import Row from 'react-bootstrap/lib/Row';
import WhitelabelActions from '../actions/whitelabel_actions';
import WhitelabelStore from '../stores/whitelabel_store';
import PieceListStore from '../stores/piece_list_store';
import PieceListActions from '../actions/piece_list_actions';
import UserStore from '../stores/user_store';
import GlobalNotificationModel from '../models/global_notification_model';
import GlobalNotificationActions from '../actions/global_notification_actions';
import Property from './ascribe_forms/property';
import RegisterPieceForm from './ascribe_forms/form_register_piece';
import { mergeOptions } from '../utils/general_utils';
import { getLangText } from '../utils/lang_utils';
import { setDocumentTitle } from '../utils/dom_utils';
let RegisterPiece = React.createClass( {
propTypes: {
headerMessage: React.PropTypes.string,
submitMessage: React.PropTypes.string,
@ -35,30 +28,27 @@ let RegisterPiece = React.createClass( {
React.PropTypes.element,
React.PropTypes.string
]),
// Provided from AscribeApp
currentUser: React.PropTypes.object,
whitelabel: React.PropTypes.object.isRequired,
// Provided from router
location: React.PropTypes.object
},
mixins: [History],
getInitialState(){
return mergeOptions(
UserStore.getState(),
WhitelabelStore.getState(),
PieceListStore.getState()
);
return PieceListStore.getState();
},
componentDidMount() {
PieceListStore.listen(this.onChange);
UserStore.listen(this.onChange);
WhitelabelStore.listen(this.onChange);
WhitelabelActions.fetchWhitelabel();
},
componentWillUnmount() {
PieceListStore.unlisten(this.onChange);
UserStore.unlisten(this.onChange);
WhitelabelStore.unlisten(this.onChange);
},
onChange(state) {
@ -79,7 +69,9 @@ let RegisterPiece = React.createClass( {
},
getSpecifyEditions() {
if (this.state.whitelabel && this.state.whitelabel.acl_create_editions || Object.keys(this.state.whitelabel).length === 0) {
const { whitelabel } = this.props;
if (whitelabel.acl_create_editions || Object.keys(whitelabel).length) {
return (
<Property
name="num_editions"
@ -89,7 +81,8 @@ let RegisterPiece = React.createClass( {
<input
type="number"
placeholder="(e.g. 32)"
min={0}/>
min={1}
max={100} />
</Property>
);
}
@ -104,8 +97,7 @@ let RegisterPiece = React.createClass( {
<RegisterPieceForm
{...this.props}
isFineUploaderActive={true}
handleSuccess={this.handleSuccess}
location={this.props.location}>
handleSuccess={this.handleSuccess}>
{this.props.children}
{this.getSpecifyEditions()}
</RegisterPieceForm>

View File

@ -11,6 +11,11 @@ import { setDocumentTitle } from '../utils/dom_utils';
let SignupContainer = React.createClass({
propTypes: {
// Provided from AscribeApp
currentUser: React.PropTypes.object,
whitelabel: React.PropTypes.object,
// Provided from router
location: React.PropTypes.object
},
@ -21,7 +26,7 @@ let SignupContainer = React.createClass({
};
},
handleSuccess(message){
handleSuccess(message) {
this.setState({
submitted: true,
message: message
@ -29,14 +34,17 @@ let SignupContainer = React.createClass({
},
render() {
const { location } = this.props;
const { message, submitted } = this.state;
setDocumentTitle(getLangText('Sign up'));
if (this.state.submitted){
if (submitted) {
return (
<div className="ascribe-login-wrapper">
<br/>
<div className="ascribe-login-text ascribe-login-header">
{this.state.message}
{message}
</div>
</div>
);
@ -45,7 +53,7 @@ let SignupContainer = React.createClass({
<div className="ascribe-login-wrapper">
<SignupForm
handleSuccess={this.handleSuccess}
location={this.props.location}/>
location={location}/>
<div className="ascribe-login-text">
{getLangText('Already an ascribe user')}&#63; <Link to="/login">{getLangText('Log in')}...</Link><br/>
</div>

View File

@ -3,19 +3,21 @@
import React from 'react';
import { History } from 'react-router';
import GlobalNotificationModel from '../../../../../../models/global_notification_model';
import GlobalNotificationActions from '../../../../../../actions/global_notification_actions';
import Form from '../../../../../ascribe_forms/form';
import Property from '../../../../../ascribe_forms/property';
import InputTextAreaToggable from '../../../../../ascribe_forms/input_textarea_toggable';
import UploadButton from '../../../../../ascribe_uploader/ascribe_upload_button/upload_button';
import InputFineuploader from '../../../../../ascribe_forms/input_fineuploader';
import UploadButton from '../../../../../ascribe_uploader/ascribe_upload_button/upload_button';
import AscribeSpinner from '../../../../../ascribe_spinner';
import GlobalNotificationModel from '../../../../../../models/global_notification_model';
import GlobalNotificationActions from '../../../../../../actions/global_notification_actions';
import AppConstants from '../../../../../../constants/application_constants';
import ApiUrls from '../../../../../../constants/api_urls';
import AppConstants from '../../../../../../constants/application_constants';
import { validationParts, validationTypes } from '../../../../../../constants/uploader_constants';
import requests from '../../../../../../utils/requests';
@ -30,9 +32,8 @@ const { object } = React.PropTypes;
const PRRegisterPieceForm = React.createClass({
propTypes: {
location: object,
history: object,
currentUser: object
currentUser: object.isRequired,
location: object
},
mixins: [History],
@ -193,11 +194,12 @@ const PRRegisterPieceForm = React.createClass({
render() {
const { location } = this.props;
const maxThumbnailSize = validationTypes.workThumbnail.sizeLimit / 1000000;
return (
<div className="register-piece--form">
<Form
buttons={{}}
buttons={null}
className="ascribe-form-bordered"
ref="registerPieceForm">
<Property
@ -234,7 +236,7 @@ const PRRegisterPieceForm = React.createClass({
</Property>
</Form>
<Form
buttons={{}}
buttons={null}
className="ascribe-form-bordered"
ref="additionalDataForm">
<Property
@ -286,7 +288,7 @@ const PRRegisterPieceForm = React.createClass({
</Property>
</Form>
<Form
buttons={{}}
buttons={null}
className="ascribe-form-bordered"
ref="uploadersForm">
<Property
@ -304,8 +306,8 @@ const PRRegisterPieceForm = React.createClass({
fileClass: 'digitalwork'
}}
validation={{
itemLimit: AppConstants.fineUploader.validation.registerWork.itemLimit,
sizeLimit: AppConstants.fineUploader.validation.additionalData.sizeLimit,
itemLimit: validationTypes.registerWork.itemLimit,
sizeLimit: validationTypes.additionalData.sizeLimit,
allowedExtensions: ['pdf']
}}
location={location}
@ -317,7 +319,7 @@ const PRRegisterPieceForm = React.createClass({
</Property>
<Property
name="thumbnailKey"
label={getLangText('Featured Cover photo (max 5MB)')}>
label={`${getLangText('Featured Cover photo')} (max ${maxThumbnailSize}MB)`}>
<InputFineuploader
fileInputElement={UploadButton()}
createBlobRoutine={{
@ -330,9 +332,9 @@ const PRRegisterPieceForm = React.createClass({
fileClass: 'thumbnail'
}}
validation={{
itemLimit: AppConstants.fineUploader.validation.workThumbnail.itemLimit,
sizeLimit: AppConstants.fineUploader.validation.workThumbnail.sizeLimit,
allowedExtensions: ['png', 'jpg', 'jpeg', 'gif']
itemLimit: validationTypes.workThumbnail.itemLimit,
sizeLimit: validationTypes.workThumbnail.sizeLimit,
allowedExtensions: validationParts.allowedExtensions.images
}}
location={location}
fileClassToUpload={{
@ -355,8 +357,8 @@ const PRRegisterPieceForm = React.createClass({
fileClass: 'otherdata'
}}
validation={{
itemLimit: AppConstants.fineUploader.validation.registerWork.itemLimit,
sizeLimit: AppConstants.fineUploader.validation.additionalData.sizeLimit
itemLimit: validationParts.itemLimit.single,
sizeLimit: validationTypes.additionalData.sizeLimit
}}
location={location}
fileClassToUpload={{
@ -377,9 +379,9 @@ const PRRegisterPieceForm = React.createClass({
fileClass: 'otherdata'
}}
validation={{
itemLimit: AppConstants.fineUploader.validation.registerWork.itemLimit,
sizeLimit: AppConstants.fineUploader.validation.additionalData.sizeLimit,
allowedExtensions: ['png', 'jpg', 'jpeg', 'gif']
itemLimit: validationParts.itemLimit.single,
sizeLimit: validationTypes.additionalData.sizeLimit,
allowedExtensions: validationParts.allowedExtensions.images
}}
location={location}
fileClassToUpload={{
@ -390,12 +392,11 @@ const PRRegisterPieceForm = React.createClass({
</Property>
</Form>
<Form
buttons={{}}
buttons={null}
className="ascribe-form-bordered">
<Property
name="terms"
className="ascribe-property-collapsible-toggle"
style={{paddingBottom: 0}}>
className="ascribe-property-collapsible-toggle">
<span>
{getLangText('By submitting this form, you agree to the') + ' '}
<a

View File

@ -12,7 +12,7 @@ const PRHero = React.createClass({
propTypes: {
currentUser: React.PropTypes.shape({
email: React.PropTypes.object
})
}).isRequired
},
render() {

View File

@ -3,45 +3,41 @@
import React from 'react';
import { History } from 'react-router';
import PrizeActions from '../../simple_prize/actions/prize_actions';
import PrizeStore from '../../simple_prize/stores/prize_store';
import Button from 'react-bootstrap/lib/Button';
import ButtonGroup from 'react-bootstrap/lib/ButtonGroup';
import LinkContainer from 'react-router-bootstrap/lib/LinkContainer';
import UserStore from '../../../../../stores/user_store';
import UserActions from '../../../../../actions/user_actions';
import PrizeActions from '../../simple_prize/actions/prize_actions';
import PrizeStore from '../../simple_prize/stores/prize_store';
import { mergeOptions, omitFromObject } from '../../../../../utils/general_utils';
import { omitFromObject } from '../../../../../utils/general_utils';
import { getLangText } from '../../../../../utils/lang_utils';
const PRLanding = React.createClass({
propTypes: {
// Provided from PrizeApp
currentUser: React.PropTypes.object,
whitelabel: React.PropTypes.object,
// Provided from router
location: React.PropTypes.object
},
mixins: [History],
getInitialState() {
return mergeOptions(
PrizeStore.getState(),
UserStore.getState()
);
return PrizeStore.getState();
},
componentDidMount() {
const { location } = this.props;
UserStore.listen(this.onChange);
PrizeStore.listen(this.onChange);
UserActions.fetchCurrentUser();
PrizeActions.fetchPrize();
if (location && location.query && location.query.redirect) {
if (location.query.redirect) {
window.setTimeout(() => this.history.replace({
pathname: `/${location.query.redirect}`,
query: omitFromObject(location.query, ['redirect'])
@ -50,7 +46,6 @@ const PRLanding = React.createClass({
},
componentWillUnmount() {
UserStore.unlisten(this.onChange);
PrizeStore.unlisten(this.onChange);
},
@ -59,7 +54,7 @@ const PRLanding = React.createClass({
},
getButtons() {
if (this.state.prize && this.state.prize.active){
if (this.state.prize && this.state.prize.active) {
return (
<ButtonGroup className="enter" bsSize="large" vertical>
<LinkContainer to="/signup">
@ -78,39 +73,37 @@ const PRLanding = React.createClass({
</LinkContainer>
</ButtonGroup>
);
}
return (
<ButtonGroup className="enter" bsSize="large" vertical>
<a className="btn btn-default" href="https://www.ascribe.io/app/signup">
{getLangText('Sign up to ascribe')}
</a>
} else {
return (
<ButtonGroup className="enter" bsSize="large" vertical>
<a className="btn btn-default" href="https://www.ascribe.io/app/signup">
{getLangText('Sign up to ascribe')}
</a>
<p>
{getLangText('or, already an ascribe user?')}
</p>
<LinkContainer to="/login">
<Button>
{getLangText('Log in')}
</Button>
</LinkContainer>
</ButtonGroup>
);
<p>
{getLangText('or, already an ascribe user?')}
</p>
<LinkContainer to="/login">
<Button>
{getLangText('Log in')}
</Button>
</LinkContainer>
</ButtonGroup>
);
}
},
getTitle() {
if (this.state.prize && this.state.prize.active){
return (
<p>
{getLangText('This is the submission page for Portfolio Review 2016.')}
</p>
);
}
const { prize } = this.state;
return (
<p>
{getLangText('Submissions for Portfolio Review 2016 are now closed.')}
{getLangText(prize && prize.active ? 'This is the submission page for Portfolio Review 2016.'
: 'Submissions for Portfolio Review 2016 are now closed.')}
</p>
);
},
render() {
return (
<div className="container">

View File

@ -6,9 +6,6 @@ import { Link, History } from 'react-router';
import Col from 'react-bootstrap/lib/Col';
import Row from 'react-bootstrap/lib/Row';
import UserStore from '../../../../../stores/user_store';
import UserActions from '../../../../../actions/user_actions';
import PRRegisterPieceForm from './pr_forms/pr_register_piece_form';
import { getLangText } from '../../../../../utils/lang_utils';
@ -20,43 +17,31 @@ const { object } = React.PropTypes;
const PRRegisterPiece = React.createClass({
propTypes: {
// Provided from PrizeApp
currentUser: React.PropTypes.object.isRequired,
whitelabel: React.PropTypes.object,
// Provided from router
location: object
},
mixins: [History],
getInitialState() {
return UserStore.getState();
},
componentDidMount() {
UserStore.listen(this.onChange);
UserActions.fetchCurrentUser();
},
componentDidUpdate() {
const { currentUser } = this.state;
if(currentUser && currentUser.email) {
const { currentUser } = this.props;
if (currentUser.email) {
const submittedPieceId = getCookie(currentUser.email);
if(submittedPieceId) {
if (submittedPieceId) {
this.history.push(`/pieces/${submittedPieceId}`);
}
}
},
componentWillUnmount() {
UserStore.unlisten(this.onChange);
},
onChange(state) {
this.setState(state);
},
render() {
const { currentUser } = this.state;
const { location } = this.props;
const { currentUser, location } = this.props;
setDocumentTitle(getLangText('Submit to Portfolio Review'));
return (
<Row>
<Col xs={6}>
@ -77,7 +62,7 @@ const PRRegisterPiece = React.createClass({
<Col xs={6}>
<PRRegisterPieceForm
location={location}
currentUser={currentUser}/>
currentUser={currentUser} />
</Col>
</Row>
);

View File

@ -1,90 +1,73 @@
'use strict';
import React from 'react';
import GlobalNotification from '../../../global_notification';
import Hero from './components/pr_hero';
import Header from '../../../header';
import classNames from 'classnames';
import EventActions from '../../../../actions/event_actions';
import UserStore from '../../../../stores/user_store';
import UserActions from '../../../../actions/user_actions';
import Hero from './components/pr_hero';
import AppBase from '../../../app_base';
import AppRouteWrapper from '../../../app_route_wrapper';
import Footer from '../../../footer';
import Header from '../../../header';
import { getSubdomain } from '../../../../utils/general_utils';
import { getCookie } from '../../../../utils/fetch_api_utils';
let PRApp = React.createClass({
propTypes: {
children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element),
React.PropTypes.element
]),
history: React.PropTypes.object,
routes: React.PropTypes.arrayOf(React.PropTypes.object)
},
activeRoute: React.PropTypes.object.isRequired,
children: React.PropTypes.element.isRequired,
history: React.PropTypes.object.isRequired,
routes: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
getInitialState() {
return UserStore.getState();
},
componentDidMount() {
UserStore.listen(this.onChange);
UserActions.fetchCurrentUser();
if (this.state.currentUser && this.state.currentUser.email) {
EventActions.profileDidLoad.defer(this.state.currentUser);
}
},
componentWillUpdate(nextProps, nextState) {
const { currentUser: { email: curEmail } = {} } = this.state;
const { currentUser: { email: nextEmail } = {} } = nextState;
if (nextEmail && curEmail !== nextEmail) {
EventActions.profileDidLoad.defer(nextState.currentUser);
}
},
componentWillUnmount() {
UserStore.unlisten(this.onChange);
},
onChange(state) {
this.setState(state);
// Provided from AppBase
currentUser: React.PropTypes.object,
whitelabel: React.PropTypes.object
},
render() {
const { history, children, routes } = this.props;
const { currentUser } = this.state;
const { activeRoute, children, currentUser, history, routes, whitelabel } = this.props;
const subdomain = getSubdomain();
const path = activeRoute && activeRoute.path;
let style = {};
let subdomain = getSubdomain();
let header;
if (currentUser && currentUser.email && history.isActive(`/pieces/${getCookie(currentUser.email)}`)) {
header = <Hero currentUser={currentUser} />;
header = (<Hero currentUser={currentUser} />);
style = { paddingTop: '0 !important' };
} else if(currentUser && (currentUser.is_admin || currentUser.is_jury || currentUser.is_judge)) {
header = <Header routes={routes} />;
} else if (currentUser && (currentUser.is_admin || currentUser.is_jury || currentUser.is_judge)) {
header = (
<Header
currentUser={currentUser}
routes={routes}
whitelabel={whitelabel}
/>
);
} else {
style = { paddingTop: '0 !important' };
}
return (
<div>
<div
style={style}
className={classNames('ascribe-app', 'ascribe-prize-app', `route--${(path ? path.split('/')[0] : 'landing')}`)}>
{header}
<div
style={style}
className={'container ascribe-prize-app client--' + subdomain}>
<AppRouteWrapper
currentUser={currentUser}
whitelabel={whitelabel}>
{/* Routes are injected here */}
{children}
<GlobalNotification />
<div id="modal" className="container"></div>
</div>
</AppRouteWrapper>
<Footer activeRoute={activeRoute} />
</div>
);
}
});
export default PRApp;
export default AppBase(PRApp);

View File

@ -31,74 +31,116 @@ import { AuthPrizeRoleRedirect } from './portfolioreview/components/pr_routes/pr
const ROUTES = {
sluice: (
<Route path='/' component={SPApp}>
<IndexRoute component={SPLanding} />
<IndexRoute
component={ProxyHandler(AuthRedirect({to: '/collection', when: 'loggedIn'}))(SPLanding)}
hideFooter />
<Route
path='login'
component={ProxyHandler(AuthRedirect({to: '/collection', when: 'loggedIn'}))(SPLoginContainer)} />
component={ProxyHandler(AuthRedirect({to: '/collection', when: 'loggedIn'}))(SPLoginContainer)}
hideFooter />
<Route
path='logout'
component={ProxyHandler(AuthRedirect({to: '/', when: 'loggedOut'}))(LogoutContainer)}/>
component={ProxyHandler(AuthRedirect({to: '/', when: 'loggedOut'}))(LogoutContainer)}
hideFooter />
<Route
path='signup'
component={ProxyHandler(AuthRedirect({to: '/collection', when: 'loggedIn'}))(SPSignupContainer)} />
component={ProxyHandler(AuthRedirect({to: '/collection', when: 'loggedIn'}))(SPSignupContainer)}
hideFooter />
<Route
path='password_reset'
component={ProxyHandler(AuthRedirect({to: '/collection', when: 'loggedIn'}))(PasswordResetContainer)} />
component={ProxyHandler(AuthRedirect({to: '/collection', when: 'loggedIn'}))(PasswordResetContainer)}
hideFooter />
<Route
path='settings'
component={ProxyHandler(AuthRedirect({to: '/login', when: 'loggedOut'}))(SPSettingsContainer)}/>
component={ProxyHandler(AuthRedirect({to: '/login', when: 'loggedOut'}))(SPSettingsContainer)}
hideFooter />
<Route
path='register_piece'
component={ProxyHandler(AuthRedirect({to: '/login', when: 'loggedOut'}))(SPRegisterPiece)}
headerTitle='+ NEW WORK'/>
headerTitle='+ NEW WORK'
hideFooter />
<Route
path='collection'
component={ProxyHandler(AuthRedirect({to: '/login', when: 'loggedOut'}))(SPPieceList)}
headerTitle='COLLECTION'/>
<Route path='pieces/:pieceId' component={SluicePieceContainer} />
<Route path='editions/:editionId' component={EditionContainer} />
<Route path='verify' component={CoaVerifyContainer} />
<Route path='*' component={ErrorNotFoundPage} />
headerTitle='COLLECTION'
hideFooter />
<Route
path='pieces/:pieceId'
component={SluicePieceContainer}
hideFooter />
<Route
path='editions/:editionId'
component={EditionContainer}
hideFooter />
<Route
path='coa_verify'
component={CoaVerifyContainer}
hideFooter />
<Route
path='*'
component={ErrorNotFoundPage}
hideFooter />
</Route>
),
portfolioreview: (
<Route path='/' component={PRApp}>
<IndexRoute component={ProxyHandler(AuthPrizeRoleRedirect({ to: '/collection', when: ['is_admin', 'is_judge', 'is_jury'] }))(PRLanding)} />
<IndexRoute
component={ProxyHandler(AuthPrizeRoleRedirect({ to: '/collection', when: ['is_admin', 'is_judge', 'is_jury'] }))(PRLanding)}
hideFooter />
<Route
path='register_piece'
component={ProxyHandler(AuthRedirect({to: '/login', when: 'loggedOut'}))(PRRegisterPiece)}/>
component={ProxyHandler(AuthRedirect({to: '/login', when: 'loggedOut'}))(PRRegisterPiece)}
hideFooter />
<Route
path='collection'
component={ProxyHandler(AuthRedirect({to: '/login', when: 'loggedOut'}))(SPPieceList)}
headerTitle='SUBMISSIONS'/>
headerTitle='SUBMISSIONS'
hideFooter />
<Route
path='login'
component={ProxyHandler(
AuthPrizeRoleRedirect({ to: '/collection', when: ['is_admin', 'is_judge', 'is_jury'] }),
AuthRedirect({to: '/register_piece', when: 'loggedIn'})
)(SPLoginContainer)} />
)(SPLoginContainer)}
hideFooter />
<Route
path='logout'
component={ProxyHandler(AuthRedirect({to: '/', when: 'loggedOut'}))(LogoutContainer)} />
component={ProxyHandler(AuthRedirect({to: '/', when: 'loggedOut'}))(LogoutContainer)}
hideFooter />
<Route
path='signup'
component={ProxyHandler(
AuthPrizeRoleRedirect({ to: '/collection', when: ['is_admin', 'is_judge', 'is_jury'] }),
AuthRedirect({to: '/register_piece', when: 'loggedIn'})
)(SPSignupContainer)} />
)(SPSignupContainer)}
hideFooter />
<Route
path='password_reset'
component={ProxyHandler(
AuthPrizeRoleRedirect({ to: '/collection', when: ['is_admin', 'is_judge', 'is_jury'] }),
AuthRedirect({to: '/register_piece', when: 'loggedIn'})
)(PasswordResetContainer)} />
)(PasswordResetContainer)}
hideFooter />
<Route
path='settings'
component={ProxyHandler(AuthRedirect({to: '/login', when: 'loggedOut'}))(SPSettingsContainer)}/>
<Route path='pieces/:pieceId' component={SPPieceContainer} />
<Route path='editions/:editionId' component={EditionContainer} />
<Route path='verify' component={CoaVerifyContainer} />
<Route path='*' component={ErrorNotFoundPage} />
component={ProxyHandler(AuthRedirect({to: '/login', when: 'loggedOut'}))(SPSettingsContainer)}
hideFooter />
<Route
path='pieces/:pieceId'
component={SPPieceContainer}
hideFooter />
<Route
path='editions/:editionId'
component={EditionContainer}
hideFooter />
<Route
path='coa_verify'
component={CoaVerifyContainer}
hideFooter />
<Route
path='*'
component={ErrorNotFoundPage}
hideFooter />
</Route>
)
};

View File

@ -10,8 +10,6 @@ import PieceListStore from '../../../../../../stores/piece_list_store';
import PrizeRatingActions from '../../actions/prize_rating_actions';
import UserStore from '../../../../../../stores/user_store';
import InputCheckbox from '../../../../../ascribe_forms/input_checkbox';
import AccordionListItemPiece from '../../../../../ascribe_accordion_list/accordion_list_item_piece';
@ -23,34 +21,30 @@ import AclProxy from '../../../../../acl_proxy';
import SubmitToPrizeButton from './../ascribe_buttons/submit_to_prize_button';
import { getLangText } from '../../../../../../utils/lang_utils';
import { mergeOptions } from '../../../../../../utils/general_utils';
let AccordionListItemPrize = React.createClass({
propTypes: {
className: React.PropTypes.string,
content: React.PropTypes.object,
content: React.PropTypes.object.isRequired,
currentUser: React.PropTypes.object.isRequired,
children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.element),
React.PropTypes.element
])
]),
className: React.PropTypes.string
},
getInitialState() {
return mergeOptions(
PieceListStore.getState(),
UserStore.getState()
);
return PieceListStore.getState();
},
componentDidMount() {
PieceListStore.listen(this.onChange);
UserStore.listen(this.onChange);
},
componentWillUnmount() {
PieceListStore.unlisten(this.onChange);
UserStore.unlisten(this.onChange);
},
onChange(state) {
@ -62,29 +56,30 @@ let AccordionListItemPrize = React.createClass({
PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
let notification = new GlobalNotificationModel(response.notification, 'success', 10000);
const notification = new GlobalNotificationModel(response.notification, 'success', 10000);
GlobalNotificationActions.appendGlobalNotification(notification);
},
getPrizeButtons() {
if (this.state.currentUser && this.state.currentUser.is_jury){
if ((this.props.content.ratings) &&
(this.props.content.ratings.rating || this.props.content.ratings.average)){
const { currentUser, content: { id, ratings } } = this.props;
if (currentUser && (currentUser.is_jury || currentUser.is_judge)) {
if (ratings && (ratings.rating || ratings.average)) {
// jury and rating available
let rating = null,
caption = null;
if (this.props.content.ratings.rating){
rating = parseInt(this.props.content.ratings.rating, 10);
let rating = null;
let caption = null;
if (ratings.rating) {
rating = parseInt(ratings.rating, 10);
caption = getLangText('Your rating');
}
else if (this.props.content.ratings.average){
rating = this.props.content.ratings.average;
caption = getLangText('Average of ' + this.props.content.ratings.num_ratings + ' rating(s)');
} else if (ratings.average) {
rating = ratings.average;
caption = getLangText('Average of ' + ratings.num_ratings + ' rating(s)');
}
return (
<div id="list-rating" className="pull-right">
<Link to={`/pieces/${this.props.content.id}`}>
<Link to={`/pieces/${id}`}>
<StarRating
ref='rating'
name="prize-rating"
@ -94,47 +89,46 @@ let AccordionListItemPrize = React.createClass({
rating={rating}
ratingAmount={5} />
</Link>
</div>);
}
else {
if (this.state.currentUser.is_judge){
</div>
);
} else {
if (currentUser.is_judge) {
return (
<div className="react-rating-caption pull-right">
{getLangText('Not rated')}
</div>
);
} else {
// jury and no rating yet
return (
<div className="react-rating-caption pull-right">
<Link to={`/pieces/${id}`}>
{getLangText('Submit your rating')}
</Link>
</div>
);
}
// jury and no rating yet
return (
<div className="react-rating-caption pull-right">
<Link to={`/pieces/${this.props.content.id}`}>
{getLangText('Submit your rating')}
</Link>
</div>
);
}
} else {
return this.getPrizeButtonsParticipant();
}
return this.getPrizeButtonsParticipant();
},
getPrizeButtonsParticipant() {
return (
<div>
<AclProxy
aclObject={this.props.content.acl}
aclName="acl_wallet_submit">
<SubmitToPrizeButton
className="pull-right"
piece={this.props.content}
handleSuccess={this.handleSubmitPrizeSuccess}/>
</AclProxy>
</div>
<AclProxy
aclObject={this.props.content.acl}
aclName="acl_wallet_submit">
<SubmitToPrizeButton
className="pull-right"
piece={this.props.content}
handleSuccess={this.handleSubmitPrizeSuccess} />
</AclProxy>
);
},
handleShortlistSuccess(message){
let notification = new GlobalNotificationModel(message, 'success', 2000);
handleShortlistSuccess(message) {
const notification = new GlobalNotificationModel(message, 'success', 2000);
GlobalNotificationActions.appendGlobalNotification(notification);
},
@ -144,56 +138,52 @@ let AccordionListItemPrize = React.createClass({
PieceListActions.fetchPieceList({ page, pageSize, search, orderBy, orderAsc, filterBy });
},
onSelectChange(){
onSelectChange() {
PrizeRatingActions.toggleShortlist(this.props.content.id)
.then(
(res) => {
this.refreshPieceData();
return res;
})
.then(
(res) => {
this.handleShortlistSuccess(res.notification);
}
);
.then((res) => {
this.refreshPieceData();
this.handleShortlistSuccess(res.notification);
});
},
getPrizeBadge(){
if (this.state.currentUser && this.state.currentUser.is_judge) {
getPrizeBadge() {
const { currentUser } = this.props;
if (currentUser && currentUser.is_judge) {
return (
<span className="pull-right ascribe-checkbox-wrapper ascribe-checkbox-badge">
<InputCheckbox
defaultChecked={this.props.content.selected}
onChange={this.onSelectChange}/>
onChange={this.onSelectChange} />
</span>
);
} else {
return null;
}
return null;
},
render() {
const { children, className, content } = this.props;
const { currentUser } = this.state;
const { children, className, content, currentUser } = this.props;
// Only show the artist name if you are the participant or if you are a judge and the piece is shortlisted
let artistName = ((currentUser.is_jury && !currentUser.is_judge) || (currentUser.is_judge && !content.selected )) ?
const artistName = ((currentUser.is_jury && !currentUser.is_judge) || (currentUser.is_judge && !content.selected )) ?
<span className="glyphicon glyphicon-eye-close" aria-hidden="true"/> : content.artist_name;
return (
<div>
<AccordionListItemPiece
className={className}
piece={content}
artistName={artistName}
subsubheading={
<div>
<span>{Moment(content.date_created, 'YYYY-MM-DD').year()}</span>
</div>}
buttons={this.getPrizeButtons()}
badge={this.getPrizeBadge()}>
{children}
</AccordionListItemPiece>
</div>
<AccordionListItemPiece
className={className}
piece={content}
artistName={artistName}
subsubheading={
<div>
<span>{Moment(content.date_created, 'YYYY-MM-DD').year()}</span>
</div>
}
buttons={this.getPrizeButtons()}
badge={this.getPrizeBadge()}>
{children}
</AccordionListItemPiece>
);
}
});

View File

@ -14,13 +14,10 @@ import PrizeStore from '../../stores/prize_store';
import PrizeRatingActions from '../../actions/prize_rating_actions';
import PrizeRatingStore from '../../stores/prize_rating_store';
import PieceActions from '../../../../../../actions/piece_actions';
import PieceStore from '../../../../../../stores/piece_store';
import PieceListStore from '../../../../../../stores/piece_list_store';
import PieceListActions from '../../../../../../actions/piece_list_actions';
import UserStore from '../../../../../../stores/user_store';
import UserActions from '../../../../../../actions/user_actions';
import PieceActions from '../../../../../../actions/piece_actions';
import PieceStore from '../../../../../../stores/piece_store';
import Piece from '../../../../../../components/ascribe_detail/piece';
import Note from '../../../../../../components/ascribe_detail/note';
@ -53,24 +50,26 @@ import { setDocumentTitle } from '../../../../../../utils/dom_utils';
*/
let PrizePieceContainer = React.createClass({
propTypes: {
params: React.PropTypes.object,
selectedPrizeActionButton: React.PropTypes.func
selectedPrizeActionButton: React.PropTypes.func,
// Provided from PrizeApp
currentUser: React.PropTypes.object.isRequired,
whitelabel: React.PropTypes.object,
// Provided from router
location: React.PropTypes.object,
params: React.PropTypes.object
},
mixins: [ReactError],
getInitialState() {
return mergeOptions(
PieceStore.getInitialState(),
UserStore.getState()
);
return PieceStore.getInitialState();
},
componentDidMount() {
PieceStore.listen(this.onChange);
UserStore.listen(this.onChange);
UserActions.fetchCurrentUser();
this.loadPiece();
},
@ -94,7 +93,6 @@ let PrizePieceContainer = React.createClass({
componentWillUnmount() {
PieceStore.unlisten(this.onChange);
UserStore.unlisten(this.onChange);
},
onChange(state) {
@ -102,7 +100,8 @@ let PrizePieceContainer = React.createClass({
},
getActions() {
const { currentUser, piece } = this.state;
const { currentUser } = this.props;
const { piece } = this.state;
if (piece.notifications && piece.notifications.length > 0) {
return (
@ -119,8 +118,8 @@ let PrizePieceContainer = React.createClass({
},
render() {
const { selectedPrizeActionButton } = this.props;
const { currentUser, piece } = this.state;
const { currentUser, selectedPrizeActionButton } = this.props;
const { piece } = this.state;
if (piece.id) {
/*
@ -187,8 +186,8 @@ let PrizePieceContainer = React.createClass({
let NavigationHeader = React.createClass({
propTypes: {
piece: React.PropTypes.object,
currentUser: React.PropTypes.object
currentUser: React.PropTypes.object.isRequired,
piece: React.PropTypes.object.isRequired
},
render() {
@ -224,9 +223,10 @@ let NavigationHeader = React.createClass({
let PrizePieceRatings = React.createClass({
propTypes: {
loadPiece: React.PropTypes.func,
piece: React.PropTypes.object,
currentUser: React.PropTypes.object,
currentUser: React.PropTypes.object.isRequired,
loadPiece: React.PropTypes.func.isRequired,
piece: React.PropTypes.object.isRequired,
selectedPrizeActionButton: React.PropTypes.func
},
@ -239,12 +239,18 @@ let PrizePieceRatings = React.createClass({
},
componentDidMount() {
PieceListStore.listen(this.onChange);
PrizeStore.listen(this.onChange);
PrizeRatingStore.listen(this.onChange);
PrizeStore.listen(this.onChange);
PieceListStore.listen(this.onChange);
PrizeActions.fetchPrize();
this.fetchPrizeRatings();
this.fetchRatingsIfAuthorized();
},
componentWillReceiveProps(nextProps) {
if (nextProps.currentUser.email !== this.props.currentUser.email) {
this.fetchRatingsIfAuthorized();
}
},
componentWillUnmount() {
@ -259,7 +265,7 @@ let PrizePieceRatings = React.createClass({
// with the problem.
onChange(state) {
if (state.prize && state.prize.active_round != this.state.prize.active_round) {
this.fetchPrizeRatings(state);
this.fetchRatingsIfAuthorized(state);
}
this.setState(state);
@ -274,9 +280,18 @@ let PrizePieceRatings = React.createClass({
}
},
fetchPrizeRatings(state = this.state) {
PrizeRatingActions.fetchOne(this.props.piece.id, state.prize.active_round);
PrizeRatingActions.fetchAverage(this.props.piece.id, state.prize.active_round);
fetchRatingsIfAuthorized(state = this.state) {
const { currentUser: {
is_admin: isAdmin,
is_judge: isJudge,
is_jury: isJury
},
piece: { id: pieceId } } = this.props;
if (state.prize && 'active_round' in state.prize && (isAdmin || isJudge || isJury)) {
PrizeRatingActions.fetchOne(pieceId, state.prize.active_round);
PrizeRatingActions.fetchAverage(pieceId, state.prize.active_round);
}
},
onRatingClick(event, args) {
@ -425,7 +440,7 @@ let PrizePieceRatings = React.createClass({
let PrizePieceDetails = React.createClass({
propTypes: {
piece: React.PropTypes.object
piece: React.PropTypes.object.isRequired
},
render() {

View File

@ -1,57 +1,47 @@
'use strict';
import React from 'react';
import { History } from 'react-router';
import PrizeActions from '../actions/prize_actions';
import PrizeStore from '../stores/prize_store';
import Button from 'react-bootstrap/lib/Button';
import ButtonGroup from 'react-bootstrap/lib/ButtonGroup';
import LinkContainer from 'react-router-bootstrap/lib/LinkContainer';
import UserStore from '../../../../../stores/user_store';
import UserActions from '../../../../../actions/user_actions';
import PrizeActions from '../actions/prize_actions';
import PrizeStore from '../stores/prize_store';
import { mergeOptions } from '../../../../../utils/general_utils';
import { getLangText } from '../../../../../utils/lang_utils';
let Landing = React.createClass({
mixins: [History],
let Landing = React.createClass({
propTypes: {
// Provided from PrizeApp
currentUser: React.PropTypes.object,
whitelabel: React.PropTypes.object,
// Provided from router
location: React.PropTypes.object
},
getInitialState() {
return mergeOptions(
PrizeStore.getState(),
UserStore.getState()
);
return PrizeStore.getState();
},
componentDidMount() {
UserStore.listen(this.onChange);
UserActions.fetchCurrentUser();
PrizeStore.listen(this.onChange);
PrizeActions.fetchPrize();
},
componentWillUnmount() {
UserStore.unlisten(this.onChange);
PrizeStore.unlisten(this.onChange);
},
onChange(state) {
this.setState(state);
// if user is already logged in, redirect him to piece list
if(this.state.currentUser && this.state.currentUser.email) {
// FIXME: hack to redirect out of the dispatch cycle
window.setTimeout(() => this.history.replace('/collection'), 0);
}
},
getButtons() {
if (this.state.prize && this.state.prize.active){
if (this.state.prize && this.state.prize.active) {
return (
<ButtonGroup className="enter" bsSize="large" vertical>
<LinkContainer to="/signup">
@ -70,39 +60,37 @@ let Landing = React.createClass({
</LinkContainer>
</ButtonGroup>
);
}
return (
<ButtonGroup className="enter" bsSize="large" vertical>
<a className="btn btn-default" href="https://www.ascribe.io/app/signup">
{getLangText('Sign up to ascribe')}
</a>
} else {
return (
<ButtonGroup className="enter" bsSize="large" vertical>
<a className="btn btn-default" href="https://www.ascribe.io/app/signup">
{getLangText('Sign up to ascribe')}
</a>
<p>
{getLangText('or, already an ascribe user?')}
</p>
<LinkContainer to="/login">
<Button>
{getLangText('Log in')}
</Button>
</LinkContainer>
</ButtonGroup>
);
<p>
{getLangText('or, already an ascribe user?')}
</p>
<LinkContainer to="/login">
<Button>
{getLangText('Log in')}
</Button>
</LinkContainer>
</ButtonGroup>
);
}
},
getTitle() {
if (this.state.prize && this.state.prize.active){
return (
<p>
{getLangText('This is the submission page for Sluice_screens ↄc Prize 2015.')}
</p>
);
}
const { prize } = this.state;
return (
<p>
{getLangText('Submissions for Sluice_screens ↄc Prize 2015 are now closed.')}
{getLangText(prize && prize.active ? 'This is the submission page for Sluice_screens ↄc Prize 2015.'
: 'Submissions for Sluice_screens ↄc Prize 2015 are now closed.')}
</p>
);
},
render() {
return (
<div className="container">

View File

@ -11,6 +11,11 @@ import { setDocumentTitle } from '../../../../../utils/dom_utils';
let LoginContainer = React.createClass({
propTypes: {
// Provided from PrizeApp
currentUser: React.PropTypes.object,
whitelabel: React.PropTypes.object,
// Provided from router
location: React.PropTypes.object
},
@ -21,12 +26,11 @@ let LoginContainer = React.createClass({
<div className="ascribe-login-wrapper">
<LoginForm
headerMessage={getLangText('Log in with ascribe')}
location={this.props.location}/>
<div
className="ascribe-login-text">
location={this.props.location} />
<div className="ascribe-login-text">
{getLangText('I\'m not a user') + ' '}
<Link to="/signup">{getLangText('Sign up...')}</Link>
<br/>
<br />
{getLangText('I forgot my password') + ' '}
<Link to="/password_reset">{getLangText('Rescue me...')}</Link>

View File

@ -1,19 +1,15 @@
'use strict';
import React from 'react';
import PieceList from '../../../../piece_list';
import UserActions from '../../../../../actions/user_actions';
import UserStore from '../../../../../stores/user_store';
import Button from 'react-bootstrap/lib/Button';
import LinkContainer from 'react-router-bootstrap/lib/LinkContainer';
import PrizeActions from '../actions/prize_actions';
import PrizeStore from '../stores/prize_store';
import Button from 'react-bootstrap/lib/Button';
import LinkContainer from 'react-router-bootstrap/lib/LinkContainer';
import AccordionListItemPrize from './ascribe_accordion_list/accordion_list_item_prize';
import PieceList from '../../../../piece_list';
import { mergeOptions } from '../../../../../utils/general_utils';
import { getLangText } from '../../../../../utils/lang_utils';
@ -21,25 +17,24 @@ import { setDocumentTitle } from '../../../../../utils/dom_utils';
let PrizePieceList = React.createClass({
propTypes: {
// Provided from PrizeApp
currentUser: React.PropTypes.object.isRequired,
whitelabel: React.PropTypes.object,
// Provided from router
location: React.PropTypes.object
},
getInitialState() {
return mergeOptions(
PrizeStore.getState(),
UserStore.getState()
);
return PrizeStore.getState();
},
componentDidMount() {
UserStore.listen(this.onChange);
UserActions.fetchCurrentUser();
PrizeStore.listen(this.onChange);
PrizeActions.fetchPrize();
},
componentWillUnmount() {
UserStore.unlisten(this.onChange);
PrizeStore.unlisten(this.onChange);
},
@ -48,7 +43,8 @@ let PrizePieceList = React.createClass({
},
getButtonSubmit() {
const { currentUser, prize } = this.state;
const { currentUser } = this.props;
const { prize } = this.state;
if (prize && prize.active && !currentUser.is_jury && !currentUser.is_admin && !currentUser.is_judge) {
return (
<LinkContainer to="/register_piece">
@ -57,32 +53,40 @@ let PrizePieceList = React.createClass({
</Button>
</LinkContainer>
);
} else {
return null;
}
return null;
},
shouldRedirect(pieceCount) {
const { currentUser } = this.props;
return !currentUser.is_admin && !currentUser.is_jury && !currentUser.is_judge && !pieceCount;
},
render() {
const { currentUser, location } = this.props;
setDocumentTitle(getLangText('Collection'));
let orderParams = ['artist_name', 'title'];
if (this.state.currentUser.is_jury) {
if (currentUser.is_jury) {
orderParams = ['rating', 'title'];
}
if (this.state.currentUser.is_judge) {
if (currentUser.is_judge) {
orderParams = ['rating', 'title', 'selected'];
}
return (
<div>
<PieceList
ref="list"
redirectTo="/register_piece"
accordionListItemType={AccordionListItemPrize}
orderParams={orderParams}
orderBy={this.state.currentUser.is_jury ? 'rating' : null}
filterParams={[]}
customSubmitButton={this.getButtonSubmit()}
location={this.props.location}/>
</div>
<PieceList
ref="list"
{...this.props}
accordionListItemType={AccordionListItemPrize}
customSubmitButton={this.getButtonSubmit()}
filterParams={[]}
orderParams={orderParams}
orderBy={currentUser.is_jury ? 'rating' : null}
shouldRedirect={this.shouldRedirect} />
);
}
});

View File

@ -16,6 +16,11 @@ import { setDocumentTitle } from '../../../../../utils/dom_utils';
let PrizeRegisterPiece = React.createClass({
propTypes: {
// Provided from PrizeApp
currentUser: React.PropTypes.object,
whitelabel: React.PropTypes.object,
// Provided from router
location: React.PropTypes.object
},
@ -37,63 +42,59 @@ let PrizeRegisterPiece = React.createClass({
},
render() {
const { location } = this.props;
const { prize } = this.state;
setDocumentTitle(getLangText('Submit to the prize'));
if(this.state.prize && this.state.prize.active){
if (prize && prize.active) {
return (
<div>
<RegisterPiece
enableLocalHashing={false}
headerMessage={''}
submitMessage={getLangText('Submit')}
location={location}>
<Property
name='artist_statement'
label={getLangText('Artist statement')}
editable={true}
overrideForm={true}>
<InputTextAreaToggable
rows={1}
placeholder={getLangText('Enter your statement')}
required />
</Property>
<Property
name='work_description'
label={getLangText('Work description')}
editable={true}
overrideForm={true}>
<InputTextAreaToggable
rows={1}
placeholder={getLangText('Enter the description for your work')}
required />
</Property>
<Property
name="terms"
className="ascribe-property-collapsible-toggle"
style={{paddingBottom: 0}}>
<InputCheckbox>
<span>
{' ' + getLangText('I agree to the Terms of Service the art price') + ' '}
(<a href="https://s3-us-west-2.amazonaws.com/ascribe0/whitelabel/sluice/terms.pdf" target="_blank" style={{fontSize: '0.9em', color: 'rgba(0,0,0,0.7)'}}>
{getLangText('read')}
</a>)
</span>
</InputCheckbox>
</Property>
</RegisterPiece>
</div>
<RegisterPiece
{...this.props}
enableLocalHashing={false}
headerMessage={''}
submitMessage={getLangText('Submit')}>
<Property
name='artist_statement'
label={getLangText('Artist statement')}
editable={true}
overrideForm={true}>
<InputTextAreaToggable
rows={1}
placeholder={getLangText('Enter your statement')}
required />
</Property>
<Property
name='work_description'
label={getLangText('Work description')}
editable={true}
overrideForm={true}>
<InputTextAreaToggable
rows={1}
placeholder={getLangText('Enter the description for your work')}
required />
</Property>
<Property
name="terms"
className="ascribe-property-collapsible-toggle">
<InputCheckbox>
<span>
{' ' + getLangText('I agree to the Terms of Service the art price') + ' '}
(<a href="https://s3-us-west-2.amazonaws.com/ascribe0/whitelabel/sluice/terms.pdf" target="_blank" style={{fontSize: '0.9em', color: 'rgba(0,0,0,0.7)'}}>
{getLangText('read')}
</a>)
</span>
</InputCheckbox>
</Property>
</RegisterPiece>
);
}
else {
} else {
return (
<div className='row'>
<div style={{textAlign: 'center'}}>
{getLangText('The prize is no longer active')}
</div>
</div>
);
);
}
}
});

View File

@ -2,8 +2,6 @@
import React from 'react';
import UserStore from '../../../../../stores/user_store';
import UserActions from '../../../../../actions/user_actions';
import PrizeActions from '../actions/prize_actions';
import PrizeStore from '../stores/prize_store';
import PrizeJuryActions from '../actions/prize_jury_actions';
@ -28,40 +26,27 @@ import { setDocumentTitle } from '../../../../../utils/dom_utils';
let Settings = React.createClass({
getInitialState() {
return UserStore.getState();
},
propTypes: {
// Provided from PrizeApp
currentUser: React.PropTypes.object.isRequired,
whitelabel: React.PropTypes.object,
componentDidMount() {
UserStore.listen(this.onChange);
UserActions.fetchCurrentUser();
},
componentWillUnmount() {
UserStore.unlisten(this.onChange);
},
onChange(state) {
this.setState(state);
// Provided from router
location: React.PropTypes.object
},
render() {
setDocumentTitle(getLangText('Account settings'));
let prizeSettings = null;
if (this.state.currentUser.is_admin){
prizeSettings = <PrizeSettings />;
}
return (
<SettingsContainer>
{prizeSettings}
<SettingsContainer {...this.props}>
{this.props.currentUser.is_admin ? <PrizeSettings /> : null}
</SettingsContainer>
);
}
});
let PrizeSettings = React.createClass({
getInitialState() {
return PrizeStore.getState();
},

View File

@ -8,6 +8,11 @@ import { setDocumentTitle } from '../../../../../utils/dom_utils';
let SignupContainer = React.createClass({
propTypes: {
// Provided from PrizeApp
currentUser: React.PropTypes.object,
whitelabel: React.PropTypes.object,
// Provided from router
location: React.PropTypes.object
},
@ -18,7 +23,7 @@ let SignupContainer = React.createClass({
};
},
handleSuccess(message){
handleSuccess(message) {
this.setState({
submitted: true,
message: message
@ -26,13 +31,15 @@ let SignupContainer = React.createClass({
},
render() {
const { location } = this.props;
const { message, submitted } = this.state;
setDocumentTitle(getLangText('Sign up'));
if (this.state.submitted){
if (submitted) {
return (
<div className="ascribe-login-wrapper">
<div className="ascribe-login-text ascribe-login-header">
{this.state.message}
{message}
</div>
</div>
);
@ -43,7 +50,7 @@ let SignupContainer = React.createClass({
headerMessage={getLangText('Create account for submission')}
submitMessage={getLangText('Sign up')}
handleSuccess={this.handleSuccess}
location={this.props.location}/>
location={location} />
</div>
);
}

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