better code
Massimo Melina committed
Mar 24, 2023 at 10:16 UTC
48dec42c34478def1f1a9c9560735709abc40214
8 files changed
+25
-30
admin/src/misc.ts
-4
@@ -127,10 +127,6 @@ export function err2msg(code: string) {
127
}[code] || code
128
}
129
130
-export function wantArray<T>(x?: void | T | T[]) {
131
- return x == null ? [] : Array.isArray(x) ? x : [x]
132
-}
133
-
130
export function reloadBtn(onClick: any, props?: any) {
131
return h(IconBtn, { icon: Refresh, title: "Reload", onClick, ...props })
132
}
frontend/src/BrowseFiles.ts
+3
-4
@@ -11,7 +11,7 @@ import {
11
useRef,
12
useState
13
} from 'react'
14
-import { domOn, formatBytes, hError, hIcon, isMobile } from './misc'
14
+import { domOn, formatBytes, ErrorMsg, hIcon, isMobile } from './misc'
15
import { Checkbox, CustomCode, Spinner } from './components'
16
import { Head } from './Head'
17
import { state, useSnapState } from './state'
@@ -32,13 +32,12 @@ export type DirList = DirEntry[]
32
33
export function BrowseFiles() {
34
useFetchList()
35
- const { error, list } = useSnapState()
35
+ const { error } = useSnapState()
36
return useAuthorized() && h(Fragment, {},
37
h(CustomCode, { name: 'beforeHeader' }),
38
h(Head),
39
h(CustomCode, { name: 'afterHeader' }),
40
- hError(error)
41
- || h(list ? FilesList : Spinner),
40
+ error ? h(ErrorMsg, { err: error }) : h(FilesList),
41
h(CustomCode, { name: 'afterList' }),
42
)
43
}
frontend/src/i18n.ts
+1
-1
@@ -2,7 +2,6 @@ import { findFirst, urlParams } from './misc'
2
import { createElement as h, Fragment, useEffect } from 'react'
3
import { useApi } from './api'
4
import { proxy, useSnapshot } from 'valtio'
5
-import _ from 'lodash'
5
6
const state = proxy<{ langs: string[], embedded: string }>({ embedded: '', langs: [] })
7
const warns = new Set() // avoid duplicates
@@ -55,6 +54,7 @@ export function t(keyOrTpl: string | string[] | TemplateStringsArray, params?: a
54
return Array.from(tokenizer(found)).map(([s,inside]) => {
55
if (!inside) return s
56
const [k,cmd,rest] = s.split(',')
57
+ if (!params) throw "missing params on " + keys[0]
58
const v = params[k]
59
if (cmd === 'plural')
60
return plural(v, rest)
frontend/src/menu.ts
+2
-7
@@ -3,7 +3,7 @@
3
import { state, useSnapState } from './state'
4
import { ComponentPropsWithoutRef, createElement as h, Fragment, useEffect, useMemo, useState } from 'react'
5
import { alertDialog, confirmDialog, ConfirmOptions, promptDialog } from './dialog'
6
-import { err2msg, hError, hIcon, onlyTruthy, prefix, useStateMounted } from './misc'
6
+import { err2msg, ErrorMsg, hIcon, onlyTruthy, prefix, useStateMounted } from './misc'
7
import { loginDialog } from './login'
8
import { showOptions } from './options'
9
import showUserPanel from './UserPanel'
@@ -213,12 +213,7 @@ async function deleteFiles(uris: string[], root: string) {
213
t('delete_completed', {n: n-e}, "Deletion: {n} completed"),
214
e > 0 && t('delete_failed', {n:e}, ", {n} failed"),
215
h('div', { style: { textAlign: 'left', marginTop: '1em', } },
216
- ...errors.map(e => {
217
- const msg = err2msg(e.err)
218
- return h(Fragment, {},
219
- hError(t(msg) + ': ' + e.uri),
220
- )
221
- })
216
+ ...errors.map(e => h(ErrorMsg, { err: t(err2msg(e.err)) + ': ' + e.uri }))
217
)
218
)).then()
219
}
\ No newline at end of file
frontend/src/misc.ts
+10
-5
@@ -23,11 +23,12 @@ export function err2msg(err: number | Error) {
23
}
24
25
export function hIcon(name: string, props?:any) {
26
- return h(Icon, { name, alt: name, ...props })
26
+ return h(Icon, { name, ...props })
27
}
28
29
-export function hError(err: Error | string | undefined) {
30
- return err && h('div', { className:'error-msg' }, typeof err === 'string' ? err : err.message)
29
+export function ErrorMsg({ err }: { err: Error | string | undefined }) {
30
+ return err ? h('div', { className:'error-msg' }, typeof err === 'string' ? err : err.message)
31
+ : null
32
}
33
34
export function isMobile() {
@@ -60,12 +61,16 @@ export function hfsEvent(name: string, params?:Dict) {
61
Object.assign((window as any).HFS ||= {}, {
62
onEvent(name: string, cb: (params:any, tools: any, output:any) => any) {
63
const tools = { h, React, state, t, _ }
63
- document.addEventListener('hfs.' + name, ev => {
64
+ const key = 'hfs.' + name
65
+ document.addEventListener(key, wrapper)
66
+ return () => document.removeEventListener(key, wrapper)
67
+
68
+ function wrapper(ev: Event) {
69
const { params, output } = (ev as CustomEvent).detail
70
const res = cb(params, tools, output)
71
if (res !== undefined && Array.isArray(output))
72
output.push(res)
68
- })
73
+ }
74
}
75
})
76
frontend/src/state.ts
-1
@@ -3,7 +3,6 @@
3
import _ from 'lodash'
4
import { proxy, useSnapshot } from 'valtio'
5
import { subscribeKey } from 'valtio/utils'
6
-import { apiCall } from './api'
6
import { DirList } from './BrowseFiles'
7
8
export const state = proxy<{
shared/index.ts
+4
@@ -135,3 +135,7 @@ export function readFile(f: File | Blob): Promise<string | undefined> {
135
export function formatPerc(p: number) {
136
return (p*100).toFixed(1) + '%'
137
}
138
+
139
+export function wantArray<T>(x?: void | T | T[]) {
140
+ return x == null ? [] : Array.isArray(x) ? x : [x]
141
+}
src/middlewares.ts
+5
-8
@@ -29,11 +29,12 @@ import { pipeline } from 'stream/promises'
29
import formidable from 'formidable'
30
import { uploadWriter } from './upload'
31
import { allowAdmin, favicon } from './adminApis'
32
+import { constants } from 'zlib'
33
34
export const gzipper = compress({
35
threshold: 2048,
35
- gzip: { flush: require('zlib').constants.Z_SYNC_FLUSH },
36
- deflate: { flush: require('zlib').constants.Z_SYNC_FLUSH },
36
+ gzip: { flush: constants.Z_SYNC_FLUSH },
37
+ deflate: { flush: constants.Z_SYNC_FLUSH },
38
br: false, // disable brotli
39
filter(type) {
40
return /text|javascript|style/i.test(type)
@@ -72,12 +73,8 @@ export const serveGuiAndSharedFiles: Koa.Middleware = async (ctx, next) => {
73
if (DEV && path.startsWith('/node_modules/')) {
74
let { referer } = ctx.headers
75
referer &&= new URL(referer).pathname
75
- if (referer) {
76
- if (referer.startsWith(ADMIN_URI))
77
- return serveAdminFiles(ctx, next)
78
- if (referer.startsWith(FRONTEND_URI))
79
- return serveFrontendFiles(ctx, next)
80
- }
76
+ return referer?.startsWith(ADMIN_URI) ? serveAdminFiles(ctx, next)
77
+ : serveFrontendFiles(ctx, next)
78
}
79
if (ctx.body)
80
return next()