Aggiunte tante cose

This commit is contained in:
2022-07-04 03:49:29 +02:00
parent 658a40c8bb
commit 8823418daa
20 changed files with 1354 additions and 313 deletions
+1
View File
@@ -0,0 +1 @@
export const Icon = ({ name }) => <span class="material-symbols-outlined">{name}</span>
+61
View File
@@ -0,0 +1,61 @@
import { useStore } from '../context.jsx'
import { changeCase } from '../util.jsx'
import { Icon } from './Icon.jsx'
import { AdminPanel } from '../pages/Admin.jsx'
import { ApiKeys } from '../pages/ApiKeys.jsx'
import { Login } from '../pages/Login.jsx'
import { Dashboard } from '../pages/Dashboard.jsx'
export const MainContent = () => {
const { setSidebarVisible, route, user } = useStore()
const Route =
{
index: Dashboard,
login: Login,
admin: AdminPanel,
apiKeys: ApiKeys,
}[route.id] || (() => <>Error</>)
return (
<div class={`main-content route-${changeCase('camel', 'dash', route.id)}`}>
<header>
<div class="group">
{user === 'admin' && (
<div
class="button icon flat"
onClick={() => setSidebarVisible(value => !value)}
>
<Icon name="menu" />
</div>
)}
<div class="label">
{route.id === 'bucket' ? (
<>
Bucket / <code>{route.params.bucket}</code>
</>
) : (
route.name
)}
</div>
</div>
{user === 'admin' ? (
<div class="label">{user}</div>
) : (
route.id !== 'login' && (
<div class="group">
<a class="button flat" href="/login">
Login
</a>
</div>
)
)}
</header>
<div class="content">
<Route />
</div>
</div>
)
}
+9 -4
View File
@@ -1,5 +1,5 @@
import { useEffect, useRef } from 'preact/hooks'
import { hashCode } from '../util.js'
import { hashCode } from '../util.jsx'
const CANVAS_SIZE = 350
@@ -15,8 +15,13 @@ export const PieChartWidget = ({ title, parts, labels, total }) => {
if (canvasRef.current) {
const $canvas = canvasRef.current
$canvas.style.width = `${CANVAS_SIZE}px`
$canvas.style.height = `${CANVAS_SIZE}px`
const size = Math.min($canvas.offsetWidth, $canvas.offsetHeight)
$canvas.width = size * 2
$canvas.height = size * 2
$canvas.style.width = `${size}px`
$canvas.style.height = `${size}px`
const width = $canvas.width / 2
const height = $canvas.height / 2
@@ -75,7 +80,7 @@ export const PieChartWidget = ({ title, parts, labels, total }) => {
<>
<div class="title">{title}</div>
<div class="content">
<canvas ref={canvasRef} width={CANVAS_SIZE * 2} height={CANVAS_SIZE * 2}></canvas>
<canvas ref={canvasRef}></canvas>
</div>
</>
)
+95
View File
@@ -0,0 +1,95 @@
import { useState } from 'preact/hooks'
import { Icon } from './Icon.jsx'
import { useStore } from '../context.jsx'
const SidebarDropdownItem = ({ icon, label, children }) => {
const [collapsed, setCollapsed] = useState(false)
return (
<div class="item dropdown">
<div class="label" onClick={() => setCollapsed(x => !x)}>
<div class="row">
<div class="row-group">
<span class="icon">
<Icon name={icon} />
</span>
<span>{label}</span>
</div>
<div class="row-group">
<span class="icon">
<Icon name={collapsed ? 'expand_more' : 'expand_less'} />
</span>
</div>
</div>
</div>
<div class={collapsed ? 'children collapsed' : 'children'}>{children}</div>
</div>
)
}
export const Sidebar = () => {
const { sidebarVisibile, buckets, user } = useStore()
return (
user === 'admin' && (
<div class={'sidebar' + (sidebarVisibile ? '' : ' collapsed')}>
<div class="logo">Storage</div>
<div class="items">
<div class="item single">
<a href="/" class="label">
<div class="row">
<div class="row-group">
<Icon name="dashboard" />
<div class="text">Dashboard</div>
</div>
</div>
</a>
</div>
<div class="item single">
<a href="/admin" class="label">
<div class="row">
<div class="row-group">
<Icon name="security" />
<div class="text">Admin Panel</div>
</div>
</div>
</a>
</div>
<div class="item single">
<a href="/api-keys" class="label">
<div class="row">
<div class="row-group">
<Icon name="key" />
<div class="text">API Keys</div>
</div>
</div>
</a>
</div>
<hr />
<div class="item single">
<a href="/buckets" class="label">
<div class="row">
<div class="row-group">
<Icon name="database" />
<div class="text">Buckets</div>
</div>
</div>
</a>
</div>
{buckets.map(bucket => (
<div class="item">
<a href={'/buckets/' + bucket} class="label">
<div class="row">
<div class="row-group">
<Icon name="view_list" />
<div>{bucket}</div>
</div>
</div>
</a>
</div>
))}
</div>
</div>
)
)
}
+35
View File
@@ -0,0 +1,35 @@
import { useStore } from '../context.jsx'
let globalToastId = 0
export const Toasts = () => {
const { toasts } = useStore()
return (
<div class="toasts">
{toasts.map(({ i, removed, message }) => (
<div key={i} class={removed ? 'toast removed' : 'toast'}>
{message}
</div>
))}
</div>
)
}
const cleanToasts = setToasts => {
setToasts(ts => ts.filter((t, i) => !t.removed))
}
export const showToast = (_toasts, setToasts) => message => {
const toast = { i: globalToastId++, removed: false, message }
setTimeout(() => {
setToasts(ts => ts.map(t => (t === toast ? { ...t, removed: true } : t)))
}, 3000)
setTimeout(() => {
cleanToasts(setToasts)
}, 4000)
setToasts(ts => [...ts.slice(-5), toast])
}
+17
View File
@@ -0,0 +1,17 @@
import { MessageWidget } from './MessageWidget.jsx'
import { PieChartWidget } from './PieChartWidget.jsx'
const WidgetTypes = {
pie: PieChartWidget,
message: MessageWidget,
}
export const Widget = ({ type, value }) => {
const CustomWidget = WidgetTypes[type]
return (
<div class={'widget ' + type}>
<CustomWidget {...value} />
</div>
)
}
+8
View File
@@ -0,0 +1,8 @@
import { createContext } from 'preact'
import { useContext } from 'preact/hooks'
export const Store = createContext(null)
export function useStore() {
return useContext(Store)
}
-53
View File
@@ -1,53 +0,0 @@
import { render } from 'preact'
import { useEffect, useState } from 'preact/hooks'
import { MessageWidget } from './components/MessageWidget.jsx'
import { PieChartWidget } from './components/PieChartWidget.jsx'
import { useUser } from './util.js'
const WidgetTypes = {
pie: PieChartWidget,
message: MessageWidget,
}
const Widget = ({ type, value }) => {
const CustomWidget = WidgetTypes[type]
return (
<div class={'widget ' + type}>
<CustomWidget {...value} />
</div>
)
}
const App = () => {
const user = useUser()
const [widgets, setWidgets] = useState([])
useEffect(() => {
fetch('/api/dashboard-state')
.then(res => res.json())
.then(state => setWidgets(state.widgets))
.catch(e => console.error(e))
}, [])
return (
<>
<header>
<div class="logo">Dashboard</div>
<div class="spacer">&bull;</div>
<div class="machine">space.phc.dm.unipi.it</div>
</header>
<p>
(Viewing page as <b>{user}</b>)
</p>
<div class="widgets">
{widgets.map(w => (
<Widget {...w} />
))}
</div>
</>
)
}
render(<App />, document.querySelector('main'))
+86
View File
@@ -0,0 +1,86 @@
import { render } from 'preact'
import { useEffect, useState } from 'preact/hooks'
import { AdminPanel } from './pages/Admin.jsx'
import { ApiKeys } from './pages/ApiKeys.jsx'
import { Icon } from './components/Icon.jsx'
import { Login } from './pages/Login.jsx'
import { Store, useStore } from './context.jsx'
import { changeCase, useRouter, useUser } from './util.jsx'
import { Dashboard } from './pages/Dashboard.jsx'
import { showToast, Toasts } from './components/Toasts.jsx'
import { Sidebar } from './components/Sidebar.jsx'
import { MainContent } from './components/MainContent.jsx'
const App = () => {
const [id, route, routeParams] = useRouter({
index: {
pattern: '/',
name: 'Dashboard',
},
login: {
pattern: '/login',
name: 'Login',
},
admin: {
pattern: '/admin',
name: 'Admin',
},
apiKeys: {
pattern: '/api-keys',
name: 'API Keys',
},
buckets: {
pattern: '/buckets',
name: 'Buckets',
},
bucket: {
pattern: '/buckets/:bucket',
name: 'Bucket',
},
})
const user = useUser(user => {
if (id !== 'login' && user !== 'admin') {
location.href = '/login'
}
})
const [toasts, setToasts] = useState([])
const [sidebarVisibile, setSidebarVisible] = useState(true)
const [buckets, setBuckets] = useState([])
useEffect(() => {
fetch('/api/buckets')
.then(res => res.json())
.then(value => setBuckets(value))
}, [])
const context = {
// Auth
user,
// Sidebar
sidebarVisibile,
setSidebarVisible,
buckets,
// Toasts
toasts,
setToasts,
showToast: showToast(toasts, setToasts),
// Routing
route: {
...route,
id,
params: routeParams,
},
}
return (
<Store.Provider value={context}>
<Sidebar />
<MainContent />
<Toasts />
</Store.Provider>
)
}
render(<App />, document.querySelector('main'))
+46
View File
@@ -0,0 +1,46 @@
import { useEffect, useState } from 'preact/hooks'
export const AdminPanel = () => {
const [text, setText] = useState('')
useEffect(() => {
fetch('/api/dashboard-state')
.then(res => res.json())
.then(state => setText(JSON.stringify(state, null, 2)))
}, [])
const onSubmit = async e => {
const formatted = JSON.stringify(JSON.parse(text), null, 2)
const res = await fetch('/api/dashboard-state', {
headers: { 'Content-Type': 'application/json' },
method: 'POST',
body: text,
})
if (!res.ok) {
alert('An error occurred while updating the state!')
}
setText(formatted)
}
return (
<form>
<div class="fill title">Dashboard State</div>
<textarea
class="fill mono"
name="state"
cols="80"
rows="20"
value={text}
onInput={e => setText(e.target.value)}
></textarea>
<div class="fill center">
<button type="button" onClick={onSubmit}>
Update
</button>
</div>
</form>
)
}
+91
View File
@@ -0,0 +1,91 @@
import { useEffect, useState } from 'preact/hooks'
import { Icon } from '../components/Icon.jsx'
import { useStore } from '../context.jsx'
export const ApiKeys = () => {
const { showToast } = useStore()
const [keys, setKeys] = useState([])
useEffect(() => {
fetch('/api/api-keys')
.then(res => res.json())
.then(value => setKeys(value))
.catch(e => console.error(e))
}, [])
const createKey = async () => {
const res = await fetch('/api/api-keys', { method: 'POST' })
if (!res.ok) {
showToast('Errore!')
}
const key = await res.json()
setKeys(keys => [...keys, key])
}
const removeKey = async key => {
const res = await fetch('/api/api-keys/' + key, { method: 'DELETE' })
if (res.ok) {
showToast('Chiave rimossa')
setKeys(keys => keys.filter(k => k !== key))
} else {
showToast('Errore!')
}
}
const copyKey = async key => {
await navigator.clipboard.writeText(key)
showToast(
<>
Copiata <code>{key}</code> negli appunti
</>
)
}
return (
<>
<div class="panel">
<div class="row">
<div class="row-group">
<div class="title">API Keys</div>
</div>
<div class="row-group">
<button class="icon" onClick={() => createKey()}>
<Icon name="add" />
</button>
</div>
</div>
<div class="table">
<div class="cells" style="grid-template-columns: 1fr auto;">
{/* Header */}
<div class="header">Chiave</div>
<div class="header">Opzioni</div>
{/* Rows */}
{keys.map(key => {
return (
<>
<div class="name">
<button class="flat" onClick={() => copyKey(key)}>
{key}
</button>
</div>
<div class="options">
<button
class="icon delete flat"
onClick={() => removeKey(key)}
>
<Icon name="delete" />
</button>
</div>
</>
)
})}
</div>
</div>
</div>
</>
)
}
+20
View File
@@ -0,0 +1,20 @@
import { useEffect, useState } from 'preact/hooks'
import { Widget } from '../components/Widget.jsx'
export const Dashboard = () => {
const [widgets, setWidgets] = useState([])
useEffect(() => {
fetch('/api/dashboard-state')
.then(res => res.json())
.then(state => setWidgets(state.widgets))
}, [])
return (
<div class="widgets">
{widgets.map(w => (
<Widget {...w} />
))}
</div>
)
}
+12
View File
@@ -0,0 +1,12 @@
export const Login = () => {
return (
<form action="/api/login" method="POST">
<div class="fill title">Login</div>
<label for="login-password">Password</label>
<input type="password" name="password" id="login-password" autoComplete="password" />
<div class="fill center">
<button type="submit">Accedi</button>
</div>
</form>
)
}
-30
View File
@@ -1,30 +0,0 @@
import { useEffect, useState } from 'preact/hooks'
export function hashCode(s) {
s = s.toString() + "seed iniziale dell'hash"
let hash = 0
if (s.length === 0) return hash
for (let i = 0; i < s.length; i++) {
const chr = s.charCodeAt(i)
hash = (hash << 5) - hash + chr
hash |= 0
}
return Math.abs(hash)
}
export function useUser() {
const [user, setUser] = useState(null)
useEffect(() => {
fetch('/api/current-user')
.then(res => res.json())
.then(value => setUser(value))
.catch(e => console.error(e))
}, [])
return user
}
+67
View File
@@ -0,0 +1,67 @@
import { toChildArray } from 'preact'
import { useCallback, useEffect, useState } from 'preact/hooks'
export function hashCode(s) {
s = s.toString() + "seed iniziale dell'hash"
let hash = 0
if (s.length === 0) return hash
for (let i = 0; i < s.length; i++) {
const chr = s.charCodeAt(i)
hash = (hash << 5) - hash + chr
hash |= 0
}
return Math.abs(hash)
}
export function useUser(onLoginStateChanged) {
const [user, setUser] = useState(null)
useEffect(() => {
fetch('/api/current-user')
.then(res => res.json())
.then(value => {
setUser(value)
onLoginStateChanged(value)
})
.catch(e => console.error(e))
}, [])
return user
}
function matchPattern(pattern, url) {
const r = `^${pattern.replace(/:([a-zA-Z0-9\_\-]+)/g, '(?<$1>.+?)')}$`
return new RegExp(r).exec(url)
}
export const useRouter = routes => {
for (const [id, route] of Object.entries(routes)) {
const m = matchPattern(route.pattern, location.pathname)
if (m) {
return [id, route, m.groups]
}
}
return ['unknown', { id: 'unknown' }, {}]
}
//
// Change Case Utility
//
const fromCaseMap = {
camel: s => s.split(/(?=[A-Z])/),
// ...
}
const toCaseMap = {
dash: parts => parts.map(p => p.toLowerCase()).join('-'),
// ...
}
export function changeCase(from, to, s) {
return toCaseMap[to](fromCaseMap[from](s))
}