forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpfulness.js
90 lines (79 loc) · 2.35 KB
/
helpfulness.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
import { sendEvent } from './events'
export default function helpfulness () {
const forms = Array.from(document.querySelectorAll('.js-helpfulness'))
const texts = Array.from(document.querySelectorAll('.js-helpfulness input, .js-helpfulness textarea'))
const votes = Array.from(document.querySelectorAll('.js-helpfulness [type=radio]'))
if (!forms.length || !texts.length || !votes.length) return
forms.forEach(form => {
form.addEventListener('submit', async evt => {
evt.preventDefault()
await submitForm(evt.target)
updateDisplay(form, 'end')
})
})
votes.forEach(voteEl => {
voteEl.addEventListener('change', async evt => {
const state = evt.target.value.toLowerCase()
const form = voteEl.closest('form')
await submitForm(form)
updateDisplay(form, state)
})
})
// Prevent the site search from overtaking your input
texts.forEach(text => {
text.addEventListener('keydown', evt => {
if (evt.code === 'Slash') evt.stopPropagation()
})
})
function showElement (el) {
el.removeAttribute('hidden')
}
function hideElement (el) {
el.setAttribute('hidden', true)
}
function isRequired (el) {
el.setAttribute('required', true)
}
function notRequired (el) {
el.removeAttribute('required')
}
function updateDisplay (form, state) {
Array.from(
form.querySelectorAll(
['start', 'yes', 'no', 'end']
.map(xstate => '[data-help-' + xstate + ']')
.join(',')
)
)
.forEach(hideElement)
Array.from(form.querySelectorAll('[data-help-' + state + ']'))
.forEach(showElement)
if (state === 'no') {
isRequired(form.querySelector('select'))
} else {
notRequired(form.querySelector('select'))
}
}
async function submitForm (form) {
const formData = new FormData(form)
const data = Object.fromEntries(
Array.from(formData.entries())
.map(
([key, value]) => [
key.replace('helpfulness-', ''),
value || undefined // Convert empty strings to undefined
]
)
)
return trackEvent(data)
}
async function trackEvent ({ token, vote, email, comment }) {
return sendEvent({
type: 'survey',
token, // Honeypot
survey_vote: vote === 'Yes',
survey_comment: comment,
survey_email: email
})
}
}