1+ 'use strict' ;
2+
3+ ( function ( ) {
4+ const $ = document . querySelector . bind ( document )
5+ let chart
6+ let $options
7+ let $title
8+
9+ function onInit ( ) {
10+ $options = $ ( '#options' )
11+ $title = $ ( '[data-field="title"]' )
12+ chart = new google . visualization . PieChart ( $ ( '#chart' ) )
13+ const pollId = new URL ( location . href ) . searchParams . get ( 'poll' )
14+ const url = `http://localhost:8080/${ pollId } ?key=abc123`
15+
16+ $ ( '#delete' ) . addEventListener ( 'click' , ( ) => {
17+ if ( confirm ( 'Sure?' ) ) {
18+ fetch ( url , { method : 'DELETE' } ) . then ( ( ) => location . href = '/' ) . catch ( err => console . log ( err ) )
19+ }
20+ } )
21+ update ( url )
22+ }
23+
24+ function getItemListDomElements ( ) {
25+ const $li = document . createElement ( 'li' )
26+ const $small = document . createElement ( 'small' )
27+ const $span = document . createElement ( 'span' )
28+ $small . classList . add ( 'label' , 'label-default' )
29+ return { $small, $span, $li }
30+ }
31+
32+ function renderResultItems ( $options , key , value ) {
33+ const { $small, $span, $li } = getItemListDomElements ( )
34+ $small . textContent = value
35+ $span . textContent = key
36+ $li . appendChild ( $small )
37+ $li . appendChild ( $span )
38+ $options . appendChild ( $li )
39+ }
40+
41+ function update ( url ) {
42+ const $options = $ ( '#options' )
43+ const $title = $ ( '[data-field="title"]' )
44+ fetch ( url ) . then ( response => response . json ( ) ) . then ( polls => {
45+ const poll = polls [ 0 ]
46+ $options . textContent = poll . title
47+ $title . innerHTML = ''
48+ poll . options . forEach ( option => {
49+ const value = poll . results && poll . results [ option ] || 0
50+ renderResultItems ( $options , option , value )
51+ if ( poll . results ) {
52+ const data = new google . visualization . DataTable ( )
53+ data . addColumn ( 'string' , 'Option' )
54+ data . addColumn ( 'number' , 'Votes' )
55+ for ( const row of Object . entries ( poll . results ) ) {
56+ data . addRow ( row )
57+ }
58+ chart . draw ( data , { is3D : true } )
59+ }
60+ } )
61+ } )
62+ window . setTimeout ( update . bind ( null , url ) , 1000 )
63+ }
64+
65+ google . load ( 'visualization' , '1.0' , { 'packages' : [ 'corechart' ] } )
66+ google . setOnLoadCallback ( function ( ) { onInit ( ) } )
67+ } ) ( )
0 commit comments