forked from zooniverse/Panoptes-Front-End
-
Notifications
You must be signed in to change notification settings - Fork 0
/
classify.jsx
417 lines (354 loc) · 13.2 KB
/
classify.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import apiClient from 'panoptes-client/lib/api-client';
import React from 'react';
import PropTypes from 'prop-types';
import { Helmet } from 'react-helmet';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import counterpart from 'counterpart';
import ClassificationQueue from '../../lib/classification-queue';
import * as classifierActions from '../../redux/ducks/classify';
import * as translationActions from '../../redux/ducks/translations';
import Classifier from '../../classifier';
import FinishedBanner from './finished-banner';
import WorkflowAssignmentDialog from '../../components/workflow-assignment-dialog';
import ProjectThemeButton from './components/ProjectThemeButton';
import WorkflowSelection from './workflow-selection';
import ClassroomWorkflowSelection from './workflow-selection-classroom';
import { zooTheme } from '../../theme';
import { getCrowdHandler } from '../../crowd_handler';
import PreviewModeOverlay from './preview-mode-overlay';
// Disable beforeunload to prevent warning popup (via https://stackoverflow.com/a/61927625) - for
// some reason, this tends to fire in crowd platform iFrames.
window.addEventListener('beforeunload', e => {
window.onbeforeunload = null;
e.stopImmediatePropagation();
});
function isPresent(val) {
return val !== undefined && val !== null;
}
// Store this externally to persist during the session.
let sessionDemoMode = false;
export class ProjectClassifyPage extends React.Component {
constructor(props) {
super(props);
this.project = null;
this.workflow = null;
this.crowdHandler = getCrowdHandler()
console.info(this.crowdHandler)
this.classificationQueue = new ClassificationQueue(apiClient, this.onClassificationSaved.bind(this));
window.classificationQueue = this.classificationQueue;
this.state = {
projectIsComplete: false,
demoMode: sessionDemoMode,
promptWorkflowAssignmentDialog: false,
rejected: null,
savingClassification: {},
validUserGroup: false
};
}
onClassificationSaved(actualClassification) {
this.crowdHandler.addClassificationId(actualClassification.id);
console.info(actualClassification)
// set saving for that subject to off
this.setState((state) => {
const subjectId = actualClassification.links.subjects[0]
return { savingClassification: {
...state.savingClassification,
[subjectId]: false
} }
})
}
componentDidMount() {
const { workflow } = this.props;
if (workflow) {
this.loadAppropriateClassification();
}
this.validateUserGroup(this.props, this.context);
}
componentWillReceiveProps(nextProps, nextContext) {
const currentGroup = this.props.location.query && this.props.location.query.group;
const nextGroup = nextProps.location.query && nextProps.location.query.group;
if (nextGroup !== currentGroup || nextProps.user !== this.props.user) {
this.validateUserGroup(nextProps);
}
if (nextProps.user === null && nextContext.initialLoadComplete) {
this.clearUserGroupForClassification(nextProps, nextContext);
}
}
componentWillUpdate(nextProps) {
const nextWorkflowID = (isPresent(nextProps) && isPresent(nextProps.workflow)) ? nextProps.workflow : null;
this.context.geordi.remember({ workflowID: nextWorkflowID });
}
componentDidUpdate(prevProps) {
const { classification, upcomingSubjects, user, workflow } = this.props;
const { promptWorkflowAssignmentDialog } = this.state;
if (!promptWorkflowAssignmentDialog && user !== null) {
this.shouldWorkflowAssignmentPrompt();
}
if (workflow !== prevProps.workflow) {
this.loadAppropriateClassification();
}
// if no subject, and saving state contains keys and none are false, run crowd callback
if (
!upcomingSubjects.length &&
Object.values(this.state.savingClassification).length &&
Object.values(this.state.savingClassification).every(item => item === false)
) {
this.crowdHandler.triggerCallback()
}
if (workflow &&
classification !== prevProps.classification
) {
if (classification) {
// we've just started a new classification.
if (this.state.validUserGroup) {
classification.update({ 'metadata.selected_user_group_id': this.props.location.query.group });
}
}
}
}
componentWillUnmount() {
if (isPresent(this.context.geordi)) {
this.context.geordi.forget(['workflowID']);
}
}
refillSubjectQueue() {
const { actions, project, workflow } = this.props;
this.maybePromptWorkflowAssignmentDialog(this.props);
if (workflow) {
actions.classifier.fetchSubjects(workflow)
.then(() => actions.classifier.createClassification(project))
.catch((error) => {
this.setState({ rejected: { classification: error }});
});
}
}
loadAppropriateClassification() {
// We don't want to resume classifications, since we want to treat classification sessions as
// idempotent. So we don't want to
this.refillSubjectQueue();
}
shouldWorkflowAssignmentPrompt() {
// Only for Gravity Spy which is assigning workflows to logged in users
const { preferences, project, workflow } = this.props;
if (project.experimental_tools.indexOf('workflow assignment') > -1) {
const assignedWorkflowID = preferences &&
preferences.settings &&
preferences.settings.workflow_id;
const currentWorkflowID = workflow && workflow.id;
if (assignedWorkflowID && currentWorkflowID && assignedWorkflowID !== currentWorkflowID) {
const isActiveWorkflow = project.links.active_workflows &&
project.links.active_workflows.indexOf(assignedWorkflowID) > -1;
if (isActiveWorkflow) {
if (this.state.promptWorkflowAssignmentDialog === false) {
this.setState({ promptWorkflowAssignmentDialog: true });
}
} else {
preferences.update({ 'settings.workflow_id': undefined }).save();
}
}
}
}
handleDemoModeChange(newDemoMode) {
sessionDemoMode = newDemoMode;
this.setState({ demoMode: sessionDemoMode });
}
saveClassification() {
if (this.context.geordi) {
this.context.geordi.logEvent({ type: 'classify' });
}
const { classification } = this.props;
// Set flag to show that we're mid-save
this.setState((state) => {
const subjectId = classification.links.subjects[0]
return {
savingClassification: {
...state.savingClassification,
[subjectId]: true
}
}
})
console.info('Completed classification', classification);
if (!this.state.demoMode) {
this.classificationQueue.add(classification);
}
return Promise.resolve(classification);
}
loadAnotherSubject() {
const { actions, project, workflow } = this.props;
if (workflow) {
actions.classifier.nextSubject(project);
}
}
maybePromptWorkflowAssignmentDialog(props) {
const { actions, preferences, project, splits, translations } = props;
if (this.state.promptWorkflowAssignmentDialog) {
WorkflowAssignmentDialog.start({ splits, project }).then(() =>
this.setState({ promptWorkflowAssignmentDialog: false })
).then(() => {
if (preferences.preferences.selected_workflow !== preferences.settings.workflow_id) {
actions.classifier.loadWorkflow(preferences.settings.workflow_id, translations.locale, preferences);
}
});
}
}
validateUserGroup(props, context) {
if (props.location.query && props.location.query.group && props.user) {
apiClient.type('user_groups').get(props.location.query.group).then((group) => {
const isUserMemberOfGroup = group.links && group.links.users && group.links.users.includes(props.user.id);
this.setState({ validUserGroup: group && isUserMemberOfGroup });
if (!isUserMemberOfGroup || !group) {
this.clearUserGroupForClassification(props, context);
}
}).catch((error) => {
if (error.status === 404) {
this.clearUserGroupForClassification(props, context);
}
});
}
}
clearUserGroupForClassification(props, context) {
if (props.location.query && props.location.query.group) {
const query = props.location.query;
this.setState({ validUserGroup: false });
Object.keys(query).forEach((key) => {
if (key === 'group') { delete query[key]; }
});
const newLocation = Object.assign({}, props.location, { query });
newLocation.search = '';
context.router.push(newLocation);
}
}
renderClassifier() {
const { classification, upcomingSubjects, workflow } = this.props;
const { demoMode } = this.state;
const subject = upcomingSubjects[0];
if (!subject) {
return (<span>Loading, please wait...</span>)
}
if (classification && classification.links.workflow === workflow.id) {
return (
<Classifier
key={classification.links.workflow}
{...this.props}
classification={classification}
crowdHandler={this.crowdHandler}
subject={subject}
demoMode={demoMode}
onChangeDemoMode={this.handleDemoModeChange.bind(this)}
onComplete={this.saveClassification.bind(this)}
onClickNext={this.loadAnotherSubject.bind(this)}
requestUserProjectPreferences={this.props.requestUserProjectPreferences}
splits={this.props.splits}
/>
);
} else if (this.state.rejected && this.state.rejected.classification) {
return (
<code>Please try again. Something went wrong: {this.state.rejected.classification.toString()}</code>
);
} else {
return (
<span>Loading classification</span>
);
}
}
render() {
return (
<div
className={`${(this.props.theme === zooTheme.mode.light) ? 'classify-page' : 'classify-page classify-page--dark-theme'}`}
>
<Helmet title={`${this.props.project.display_name} » ${counterpart('project.classifyPage.title')}`} />
{this.crowdHandler.previewMode &&
<PreviewModeOverlay />}
{this.props.projectIsComplete &&
<FinishedBanner project={this.props.project} />}
{this.state.validUserGroup &&
<p className="anouncement-banner--group">You are classifying as a student of your classroom.</p>}
{this.props.workflow ? this.renderClassifier() : <p>Loading workflow</p>}
<ProjectThemeButton />
</div>
);
}
}
ProjectClassifyPage.contextTypes = {
geordi: PropTypes.object,
initialLoadComplete: PropTypes.bool,
router: PropTypes.object
};
ProjectClassifyPage.propTypes = {
actions: PropTypes.shape({
classifier: PropTypes.shape({
createClassification: PropTypes.func,
emptySubjectQueue: PropTypes.func,
fetchSubjects: PropTypes.func,
nextSubject: PropTypes.func,
refillSubjectQueue: PropTypes.func
}),
translations: PropTypes.shape({
load: PropTypes.func
})
}),
classification: PropTypes.shape({}),
location: PropTypes.shape({
query: PropTypes.shape({
group: PropTypes.string
})
}),
preferences: PropTypes.shape({
preferences: PropTypes.shape({
selected_workflow: PropTypes.string
})
}),
project: PropTypes.object,
storage: PropTypes.object,
translations: PropTypes.shape({
locale: PropTypes.string
}),
upcomingSubjects: PropTypes.arrayOf(PropTypes.object),
user: PropTypes.object,
workflow: PropTypes.object
};
ProjectClassifyPage.defaultProps = {
classification: null,
location: {
query: {}
},
upcomingSubjects: []
};
const mapStateToProps = state => ({
classification: state.classify.classification,
translations: state.translations,
upcomingSubjects: state.classify.upcomingSubjects,
theme: state.userInterface.theme,
workflow: state.classify.workflow
});
const mapDispatchToProps = dispatch => ({
actions: {
classifier: bindActionCreators(classifierActions, dispatch),
translations: bindActionCreators(translationActions, dispatch)
}
});
const ConnectedClassifyPage = connect(mapStateToProps, mapDispatchToProps)(ProjectClassifyPage);
function ConnectedClassifyPageWithWorkflow(props) {
const workflowKey = props.workflow ? props.workflow.id : 'no-workflow';
//Check for WildCam Lab classrooms (see https://github.com/zooniverse/edu-api-front-end)
const workflowFromUrl = props.location.query && props.location.query.workflow;
const isProjectForClassrooms = (props.project && props.project.experimental_tools && props.project.experimental_tools.indexOf('wildcam classroom') > -1);
const isUrlForClassrooms = props.location.query && props.location.query.classroom;
const isClassroom = isProjectForClassrooms && isUrlForClassrooms && workflowFromUrl;
const WorkflowStrategy = isClassroom ? ClassroomWorkflowSelection : WorkflowSelection;
return (
<WorkflowStrategy
key={workflowKey}
actions={props.actions}
location={props.location}
preferences={props.preferences}
project={props.project}
projectRoles={props.projectRoles}
user={props.user}
>
<ConnectedClassifyPage {...props} />
</WorkflowStrategy>
);
}
export default ConnectedClassifyPageWithWorkflow;