forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpfulness.js
106 lines (93 loc) · 2.81 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import getCsrf from './get-csrf'
export default function helpfulness () {
const EVENT_TYPE = '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
let id = '' // So that we only create one event per pageview
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, category }) {
const response = await fetch(id ? '/events/' + id : '/events', {
method: id ? 'PUT' : 'POST',
headers: {
'Content-Type': 'application/json',
'CSRF-Token': getCsrf()
},
body: JSON.stringify({
type: EVENT_TYPE,
token, // Honeypot
url: window.location.origin + window.location.pathname,
vote,
email,
comment,
category
})
})
const data = response.ok ? await response.json() : {}
if (data.id) id = data.id
return id
}
}