better code: less polluted global scope

Massimo Melina committed Feb 25, 2023 at 17:15 UTC f1d6710c62334aca7d78ea65a9f6017cc8f41195
5 files changed +19 -17
admin/index.html
+3 -1
@@ -5,7 +5,9 @@
5 <link rel="icon" type="image/svg+xml" href="/hfs-logo-icon.svg" />
6 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7 <script async src='https://unpkg.com/node-forge@1.3.1/dist/forge.min.js'></script>
8 - <script>SESSION = _HFS_SESSION_</script>
8 + <script>HFS = {
9 + session: _HFS_SESSION_
10 + }</script>
11 <title>HFS Admin</title>
12 </head>
13 <body>
admin/src/LoginRequired.ts
+1 -2
@@ -67,8 +67,7 @@ async function login(username: string, password: string) {
67 sessionRefresher(res)
68 }
69
70 -// @ts-ignore
71 -sessionRefresher(window.SESSION)
70 +sessionRefresher((window as any).HFS.session)
71
72 function sessionRefresher(response: any) {
73 if (!response) return
frontend/index.html
+3 -1
@@ -5,7 +5,9 @@
5 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=0" />
6 <link href="/fontello.css" rel="stylesheet" />
7 <link rel="icon"/>
8 - <script>SESSION = _HFS_SESSION_</script>
8 + <script>HFS = {
9 + session: _HFS_SESSION_
10 + }</script>
11 <title>_HFS_TITLE_</title>
12 </head>
13 <body>
frontend/src/login.ts
+1 -2
@@ -24,8 +24,7 @@ async function login(username:string, password:string) {
24 })
25 }
26
27 -// @ts-ignore
28 -sessionRefresher(window.SESSION)
27 +sessionRefresher((window as any).HFS.session)
28
29 function sessionRefresher(response: any) {
30 if (!response) return
frontend/src/misc.ts
+11 -11
@@ -56,14 +56,14 @@ export function hfsEvent(name: string, params?:Dict) {
56 return output
57 }
58
59 -const HFS: any = (window as any).HFS = {}
60 -
61 -HFS.onEvent = (name: string, cb: (params:any, tools: any, output:any) => any) => {
62 - const tools = { h, React, state, t }
63 - document.addEventListener('hfs.' + name, ev => {
64 - const { params, output } = (ev as CustomEvent).detail
65 - const res = cb(params, tools, output)
66 - if (res !== undefined && Array.isArray(output))
67 - output.push(res)
68 - })
69 -}
59 +Object.assign((window as any).HFS ||= {}, {
60 + onEvent(name: string, cb: (params:any, tools: any, output:any) => any) {
61 + const tools = { h, React, state, t }
62 + document.addEventListener('hfs.' + name, ev => {
63 + const { params, output } = (ev as CustomEvent).detail
64 + const res = cb(params, tools, output)
65 + if (res !== undefined && Array.isArray(output))
66 + output.push(res)
67 + })
68 + }
69 +})
\ No newline at end of file