chore(release): 0.2.6
[risinglegends.git] / src / client / htmx.ts
1 import { io } from 'socket.io-client';
2 import { TimeManager } from '../shared/time';
3
4 function $<T>(selector: string, root: any = document): T {
5   return root.querySelector(selector) as T;
6 }
7
8 function $$<T>(selector: string, root: any = document): T[] {
9   return Array.from(root.querySelectorAll(selector)) as T[];
10 }
11
12 export function authToken(): string {
13   const token = localStorage.getItem('authToken');
14   return token || '';
15 }
16
17 function setTimeGradient() {
18   const gradientName = time.gradientName();
19   const $body = $<HTMLElement>('body');
20   $body.classList.value = gradientName; 
21
22   $body.classList.add(time.getTimePeriod());
23
24   let icon: string;
25   if(time.get24Hour() >= 5 && time.get24Hour() < 9) {
26     icon = 'morning';
27   }
28   else if(time.get24Hour() >= 9 && time.get24Hour() < 17) {
29     icon = 'afternoon';
30   }
31   else if(time.get24Hour() >= 17 && time.get24Hour() < 20) {
32     icon = 'evening'
33   }
34   else {
35     icon = 'night';
36   }
37   
38   $<HTMLElement>('#time-of-day').innerHTML = `<img src="/assets/img/icons/time-of-day/${icon}.png"> ${time.getHour()}${time.getAmPm()}`;
39 }
40
41 function renderChatMessage(msg: string) {
42   $<HTMLElement>('#chat-messages').innerHTML += msg;
43   $<HTMLElement>('#chat-messages').scrollTop = $<HTMLElement>('#chat-messages').scrollHeight;
44 }
45
46 const time = new TimeManager();
47 const socket = io({
48   extraHeaders: {
49     'x-authtoken': authToken()
50   }
51 });
52 setTimeGradient();
53 setInterval(setTimeGradient, 60 * 1000);
54
55 socket.on('connect', () => {
56   console.log(`Connected: ${socket.id}`);
57 });
58
59 socket.on('authToken', (authToken: string) => {
60   console.log(`recv auth token ${authToken}`);
61   localStorage.setItem('authToken', authToken);
62 });
63
64 socket.on('chat', renderChatMessage);
65 socket.on('ready', bootstrap);
66
67
68 $$<HTMLElement>('nav a').forEach(el => {
69   el.addEventListener('click', e => {
70     const el = e.target as HTMLElement;
71
72     $$<HTMLElement>('a', el.closest('nav')).forEach(el => {
73       el.classList.remove('active');
74     })
75
76     el.classList.add('active');
77
78     const targetEl = $<HTMLElement>(el.getAttribute('hx-target')!.toString());
79
80     Array.from(targetEl.parentElement!.children).forEach(el => {
81       el.classList.remove('active');
82     });
83     targetEl.classList.add('active');
84   });
85 });
86
87 $<HTMLElement>('body').addEventListener('click', e => {
88   const target = e.target as HTMLElement;
89
90   if(target!.parentElement!.classList.contains('filter')) {
91     // ok this is afunky filter object!
92     const children = Array.from(target!.parentElement!.children);
93     children.forEach(el => el.classList.remove('active'));
94     target.classList.add('active');
95
96     const dataFilter = target.getAttribute('data-filter');
97
98     const targetPane = $<HTMLElement>(`.filter-result[data-filter="${dataFilter}"]`, target.closest('.filter-container'));
99
100     if(targetPane) {
101       Array.from(targetPane!.parentElement!.children).forEach(el => {
102         if(el.getAttribute('data-filter') === dataFilter) {
103           el.classList.remove('hidden');
104           el.classList.add('active');
105         }
106         else {
107           el.classList.add('hidden');
108           el.classList.remove('active');
109         }
110       })
111     }
112   }
113
114   if(target.getAttribute('formmethod') === 'dialog' && target.getAttribute('value') === 'cancel') {
115     target.closest('dialog')?.close();
116   }
117 });
118
119 const modalMutations = new MutationObserver((list, observer) => {
120   const states = {
121     modal: false,
122     alert: false
123   };
124
125   list.forEach(mutation => {
126     switch(((mutation.target) as HTMLElement).id) {
127       case 'modal-wrapper':
128         states.modal = true;
129         break;
130       case 'alerts':
131         states.alert = true;
132         break;
133
134     }
135   });
136
137   if(states.modal) {
138     if($<HTMLElement>('#modal-wrapper').children.length) {
139       $$<HTMLDialogElement>('#modal-wrapper dialog').forEach(el => {
140         if(!el.open) {
141           el.showModal();
142         }
143       })
144     }
145   }
146
147   if(states.alert) {
148     if($<HTMLElement>('#alerts').children.length) {
149       $$<HTMLElement>('#alerts .alert').forEach(el => {
150         if(!el.getAttribute('data-dismiss-at')) {
151           const dismiss = Date.now() + 3000;
152           el.setAttribute('data-dismiss-at', dismiss.toString());
153           setTimeout(() => { el.remove(); }, 3000);
154         }
155       });
156     }
157   }
158
159 });
160
161 modalMutations.observe($<HTMLElement>('#modal-wrapper'), { childList: true });
162
163 modalMutations.observe($<HTMLElement>('#alerts'), { childList: true });
164
165
166 function bootstrap() {
167   console.log('Server connection verified');
168   $$<HTMLElement>('nav a')[0].click();
169 }
170 document.body.addEventListener('htmx:configRequest', function(evt) {
171   //@ts-ignore
172   evt.detail.headers['x-authtoken'] = authToken();
173 });
174 document.body.addEventListener('htmx:load', function(evt) {
175   $$<HTMLElement>('.disabled[data-block]').forEach(el => {
176     setTimeout(() => { el.removeAttribute('disabled'); }, 3000);
177   });
178 });
179 document.body.addEventListener('htmx:beforeSwap', function(e) {
180   const el = e.target as HTMLElement;
181   if(el.id === 'chat-form') {
182     $<HTMLInputElement>('#message').value = '';
183   }
184   //@ts-ignore
185   else if(e.detail.serverResponse === 'logout') {
186     localStorage.removeItem('authToken');
187     window.location.reload();
188   }
189 });
190