main
ts 56 lines 2.5 KB
Raw
1 import { createElement as h, useEffect, useMemo, useState } from 'react'
2 import { Box, Card, CardActions, CardContent } from '@mui/material'
3 import { Btn } from './mui'
4 import { state, useSnapState } from './state'
5 import { useApiList } from './api'
6 import { DAY, tryJson, wantArray } from './misc'
7 import _ from 'lodash'
8 import { renderName } from './InstalledPlugins'
9 import { installPluginFromResult } from './OnlinePlugins'
10 import { toast } from './dialog'
11
12 const cacheKey = 'onlinePluginsCache'
13
14 export function RandomPlugin() {
15 const { hideRandomPlugin } = useSnapState()
16 const serializedCache = localStorage.getItem(cacheKey)
17 const cached = useMemo(() => {
18 const obj = tryJson(serializedCache || '')
19 return obj?.ts && Date.now() - obj.ts < DAY && _.shuffle(obj.list)
20 }, [serializedCache])
21 const { list, initializing } = useApiList(!hideRandomPlugin && !cached && 'get_online_plugins')
22 const [idx, setIdx] = useState(-1)
23 const one = cached?.[idx]
24 useEffect(() => {
25 if (!cached && !initializing && list.length)
26 localStorage.setItem(cacheKey, JSON.stringify({ ts: Date.now(), list }))
27 setIdx(0)
28 }, [list, initializing])
29 useEffect(() => {
30 if (idx > 0 && !one)
31 toast("No more plugins!")
32 }, [idx])
33 if (hideRandomPlugin || !one) return
34 return h(Card, { sx: { display: { xs: 'none', md: 'block' }, float: 'right', width: 'min(50%, 30em)', ml: '1em' } },
35 h(CardContent, {},
36 h(Box, { sx: { fontWeight: 'bold', fontSize: '1.4em' } }, h(Box, { sx: { color: 'warning.main', mr: 1, display: 'inline' } }, '🎲'), "Random plugin:"),
37 h(Box, { sx: { fontWeight: 'bold', fontSize: '1.8em', my: 1 } }, renderName({ row: one })),
38 h(Box, {}, one.description),
39 one.preview && h('img', {
40 src: wantArray(one.preview)[0],
41 style: {
42 maxWidth: '100%',
43 maxHeight: '50vh',
44 marginTop: '1em',
45 border: '1px solid',
46 maskImage: 'radial-gradient(circle at center, black 50%, transparent 100%)'
47 }
48 }),
49 ),
50 h(CardActions, {},
51 h(Btn, { variant: 'outlined', onClick: () => installPluginFromResult(one) }, "Install"),
52 h(Btn, { variant: 'outlined', onClick: () => setIdx(x => x + 1) }, "Another"),
53 h(Btn, { variant: 'outlined', onClick() { state.hideRandomPlugin = true } }, "Hide this box"),
54 )
55 )
56 }