forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsurvey.ts
More file actions
69 lines (59 loc) · 2.15 KB
/
survey.ts
File metadata and controls
69 lines (59 loc) · 2.15 KB
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
import { sendEvent, EventType } from './events'
function showElement(el: HTMLElement) {
el.removeAttribute('hidden')
}
function hideElement(el: HTMLElement) {
el.setAttribute('hidden', 'hidden')
}
function updateDisplay(form: HTMLFormElement, state: string) {
const allSelector = ['start', 'yes', 'no', 'end']
.map((xstate) => '[data-help-' + xstate + ']')
.join(',')
const stateSelector = '[data-help-' + state + ']'
const allEls = Array.from(form.querySelectorAll(allSelector)) as Array<HTMLElement>
allEls.forEach(hideElement)
const stateEls = Array.from(form.querySelectorAll(stateSelector)) as Array<HTMLElement>
stateEls.forEach(showElement)
}
function submitForm(form: HTMLFormElement) {
const formData = new FormData(form)
return trackEvent(formData)
}
function trackEvent(formData: FormData) {
return sendEvent({
type: EventType.survey,
survey_token: (formData.get('survey-token') as string) || undefined, // Honeypot
survey_vote: formData.get('survey-vote') === 'Yes',
survey_comment: (formData.get('survey-comment') as string) || undefined,
survey_email: (formData.get('survey-email') as string) || undefined,
})
}
export default function survey() {
// @ts-ignore
if (window.IS_NEXTJS_PAGE) return
const form = document.querySelector('.js-survey') as HTMLFormElement | null
const texts = Array.from(
document.querySelectorAll('.js-survey input, .js-survey textarea')
) as Array<HTMLElement>
const votes = Array.from(document.querySelectorAll('.js-survey [type=radio]'))
if (!form || !texts.length || !votes.length) return
form.addEventListener('submit', (evt) => {
evt.preventDefault()
submitForm(form)
updateDisplay(form, 'end')
})
votes.forEach((voteEl) => {
voteEl.addEventListener('change', (evt) => {
const radio = evt.target as HTMLInputElement
const state = radio.value.toLowerCase()
submitForm(form)
updateDisplay(form, state)
})
})
// Prevent the site search from overtaking your input
texts.forEach((text) => {
text.addEventListener('keydown', (evt: KeyboardEvent) => {
if (evt.code === 'Slash') evt.stopPropagation()
})
})
}