-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
403 lines (363 loc) · 11.1 KB
/
app.js
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
/* global firebase */
const React = require('react')
const h = require('react-hyperscript')
const render = require('react-dom').render
const Router = require('react-router-dom').BrowserRouter
const Route = require('react-router-dom').Route
const Link = require('react-router-dom').Link
const Redirect = require('react-router-dom').Redirect
const qs = require('qs')
const SplitterLayout = require('react-splitter-layout').default
const cuid = require('cuid')
const debounce = require('debounce')
const gravatarURL = require('gravatar-url')
const View = require('./View')
const Entries = require('./Entries')
const Code = require('./Code')
const UI = require('./UI')
const {n_error, n_success} = require('./helpers')
firebase.initializeApp({
apiKey: 'AIzaSyBnsHuekLxCqbVSyb_np7j0Yn5jJK5QFpw',
authDomain: 'superform-xyz.firebaseapp.com',
databaseURL: 'https://superform-xyz.firebaseio.com',
projectId: 'superform-xyz',
storageBucket: 'superform-xyz.appspot.com',
messagingSenderId: '736573438203'
})
const db = firebase.firestore()
db.settings({
timestampsInSnapshots: true
})
class App extends React.Component {
constructor () {
super()
this.state = {
user: null,
userforms: []
}
this.formsRef = null
this.cancelFormsListener = () => {}
}
componentWillUnmount () {
this.cancelFormsListener()
}
componentDidMount () {
firebase.auth().onAuthStateChanged(user => {
this.cancelFormsListener()
this.setState({user})
if (user) {
this.cancelFormsListener = db.collection('forms').where('owner', '==', user.uid)
.onSnapshot(e => {
this.setState({
userforms: e.docs.map(d => Object.assign(d.data(), {id: d.id}))
})
})
}
})
firebase.auth().getRedirectResult()
}
render () {
return (
h(Router, [
h('div', [
h('.nav', [
h('.logo', [
h('div', [
h(Link, {to: '/'}, [ h('img', {src: '/icon.png'}) ])
]),
h('h1', [
h(Link, {to: '/'}, 'Superform')
])
]),
h(Route, {exact: true, path: '/:action/:form', render: ({match}) =>
h('.clone', [
h(Link, {to: `/new?from=${match.params.form}`}, 'Clone this')
])
}),
h('.user', this.state.user
? [
h(Link, {to: '/account'}, [
gravatar(this.state.user.email)
])
]
: [
['Google', new firebase.auth.GoogleAuthProvider()],
['Twitter', new firebase.auth.TwitterAuthProvider()]
].map(([name, provider]) =>
h('a', {
onClick: () => {
firebase.auth().signInWithPopup(provider)
}
}, 'Sign in with ' + name),
)
)
]),
h(Route, {path: '/new', render: ({location}) => {
let newid = cuid.slug()
let query = qs.parse(location.search.slice(1))
if (query.from) {
db.doc(`forms/${query.from}`).get()
.then(d => {
let data = d.data()
delete data.id
delete data.updated_at
data.owner = this.state.user && this.state.user.uid
data.created_at = firebase.firestore.Timestamp.now()
data.cloned_from = query.from
return db.doc(`forms/${newid}`).set(data)
})
.then(() => {
n_success('Cloned successfully.')
})
.catch(e => {
n_error('Failed to clone form. See console for more details.')
console.warn('failed to clone form:', e)
})
}
return h(Redirect, {to: `/edit/${newid}`})
}}),
h(Route, {exact: true, path: '/account', render: () =>
this.state.user
? (
h('#profile', [
h('div', [
gravatar(this.state.user.email),
h('h3', this.state.user.displayName),
h('h4', this.state.user.email),
h('h5', `<${this.state.user.uid}>`),
h('div', [
h(Link, {
to: '/',
onClick: () => {
firebase.auth().signOut()
}
}, 'Logout')
])
]),
h('div', [
h('h3', 'Forms'),
h('.forms', this.state.userforms.map(f =>
h('div', [
h(Link, {to: `/edit/${f.id}`}, [
h('h4', f.id)
]),
h('code', f.ui)
])
))
])
])
)
: null
}),
h(Route, {exact: true, path: '/', render: () => h('style', {
dangerouslySetInnerHTML: {
__html: `#landing { display: block !important; }`
}
})}),
h(Route, {exact: true, path: '/:action/:form', component: SingleForm})
])
])
)
}
}
class SingleForm extends React.Component {
constructor (props) {
super(props)
this.state = {
entries: [],
form: null
}
this.formRef = null
this.entriesRef = null
this.cancelFormListener = () => {}
this.cancelEntriesListener = () => {}
this.secondarySizes = JSON.parse(
localStorage.getItem('secondary-panel-sizes') ||
'[50, 0, 0]'
)
this.dpanelSizeChanged = debounce(this.panelSizeChanged, 700)
if (this.props.match.params.action === 'view') {
this.editing = false
} else if (this.props.match.params.action === 'edit') {
this.editing = true
}
}
componentWillUnmount () {
this.cancelFormListener()
this.cancelEntriesListener()
}
componentDidMount () {
this.formRef = db.doc(`forms/${this.props.match.params.form}`)
this.entriesRef = this.formRef.collection('entries')
this.cancelFormListener = this.formRef.onSnapshot(f => {
let form = f.exists
? f.data()
: {
owner: null,
created_at: firebase.firestore.Timestamp.now(),
code: `exports.reduce = function (state, entry) {
switch (entry.type) {
case 'normal_submission':
state.submissions.push(entry.content)
break
}
}
exports.init = function () {
return {
submissions: []
}
}`,
ui: `
div
h1 Hello, #{user.email || 'anonymous'}!
p These are the last submissions we have:
+list(state.submissions)
div
h3 Submit a new thing
form
+value('type', 'normal_submission')
+field('content', 'Content')
button 'Ok'
`
}
this.setState({form})
})
this.cancelEntriesListener = this.entriesRef.orderBy('created_at', 'asc')
.onSnapshot(e => {
this.setState({
entries: e.docs.map(d => {
let entry = d.data()
entry.created_at = entry.created_at.toDate()
entry.updated_at = entry.updated_at && entry.updated_at.toDate()
entry.id = d.id
return entry
})
})
})
firebase.auth().onAuthStateChanged(user => {
this.setState(st => {
st.user = user
if (user && !st.form.owner) st.form.owner = user.uid
return st
})
})
firebase.auth().getRedirectResult()
}
render () {
let secondarySizes = this.editing ? this.secondarySizes : [0, 0, 50]
return (
this.state.form && this.state.entries &&
h(SplitterLayout, {
percentage: true,
secondaryInitialSize: secondarySizes[0],
onSecondaryPaneSizeChange: s => this.dpanelSizeChanged(0, s)
}, [
h(SplitterLayout, {
vertical: true,
percentage: true,
secondaryInitialSize: secondarySizes[1],
onSecondaryPaneSizeChange: s => this.dpanelSizeChanged(1, s),
customClassName: 'view-splitter'
}, [
h(View, {
code: this.state.form.code,
ui: this.state.form.ui,
entries: this.state.entries,
user: this.state.user ? {
uid: this.state.user.uid,
email: this.state.user.email,
name: this.state.user.displayName
} : {},
addEntry: data => this.addEntry(data)
}),
h(Entries, {
entries: this.state.entries,
editEntry: (id, data) => this.editEntry(id, data),
deleteEntry: id => this.deleteEntry(id)
})
]),
h(SplitterLayout, {
vertical: true,
percentage: true,
secondaryInitialSize: secondarySizes[2],
onSecondaryPaneSizeChange: s => this.dpanelSizeChanged(2, s)
}, [
h(UI, {
code: this.state.form.ui,
save: ui => this.saveForm({ui})
}),
h(Code, {
code: this.state.form.code,
save: code => this.saveForm({code})
})
])
])
)
}
panelSizeChanged (index, size) {
if (this.state.editing) {
this.secondarySizes[index] = size
localStorage.setItem(
'secondary-panel-sizes',
JSON.stringify(this.secondarySizes)
)
}
}
saveForm (data) {
this.formRef.set(Object.assign(this.state.form, data))
.catch(e => {
n_error('Failed to save form. See console for more details.')
console.warn('failed to save form:', e)
})
}
addEntry (data) {
this.entriesRef.add({
submitter: this.state.user && this.state.user.uid,
email: this.state.user.email,
created_at: firebase.firestore.Timestamp.now(),
data
})
.then(() => {
n_success('Created entry successfully.')
})
.catch(e => {
n_error('Failed to create entry. See console for more details.')
console.warn('failed to create entry:', e)
})
}
editEntry (id, data) {
this.entriesRef.doc(id).set({
data,
updated_at: firebase.firestore.Timestamp.now()
}, {merge: true})
.then(() => {
n_success('Updated entry successfully.')
})
.catch(e => {
n_error('Failed to update entry. See console for more details.')
console.warn('failed to update entry:', e)
})
}
deleteEntry (id) {
this.entriesRef.doc(id).delete()
.then(() => {
n_success('Deleted entry successfully.')
})
.catch(e => {
n_error('Failed to delete entry. See console for more details.')
console.warn('failed to delete entry:', e)
})
}
}
function gravatar (email) {
return h('img.avatar', {
src: gravatarURL(email || '@', {
size: 270,
default: `https://robohash.org/${email}.png`
})
})
}
render(
h(App),
document.getElementById('app')
)