@mblaney/holster-browser 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,177 @@
1
+ import {useState} from "react"
2
+ import {grey} from "@mui/material/colors"
3
+ import Button from "@mui/material/Button"
4
+ import Card from "@mui/material/Card"
5
+ import CardContent from "@mui/material/CardContent"
6
+ import Container from "@mui/material/Container"
7
+ import FormControl from "@mui/material/FormControl"
8
+ import Grid from "@mui/material/Grid"
9
+ import IconButton from "@mui/material/IconButton"
10
+ import InputAdornment from "@mui/material/InputAdornment"
11
+ import InputLabel from "@mui/material/InputLabel"
12
+ import OutlinedInput from "@mui/material/OutlinedInput"
13
+ import Typography from "@mui/material/Typography"
14
+ import Visibility from "@mui/icons-material/Visibility"
15
+ import VisibilityOff from "@mui/icons-material/VisibilityOff"
16
+ import SearchAppBar from "./SearchAppBar.jsx"
17
+
18
+ const Settings = ({user, mode, setMode, appBar, buildDate, children}) => {
19
+ const [name] = useState(() => {
20
+ return sessionStorage.getItem("name") || localStorage.getItem("name") || ""
21
+ })
22
+ const [password, setPassword] = useState("")
23
+ const [showPassword, setShowPassword] = useState(false)
24
+ const [newPassword, setNewPassword] = useState("")
25
+ const [showNewPassword, setShowNewPassword] = useState(false)
26
+ const [message, setMessage] = useState("")
27
+ const [disabledButton, setDisabledButton] = useState(false)
28
+
29
+ const changePassword = () => {
30
+ if (!password) {
31
+ setMessage("Please provide your current password")
32
+ return
33
+ }
34
+
35
+ if (!newPassword) {
36
+ setMessage("Please provide a new password")
37
+ return
38
+ }
39
+
40
+ setDisabledButton(true)
41
+ setMessage("Updating password...")
42
+ user.change(user.is.username, password, newPassword, err => {
43
+ setDisabledButton(false)
44
+ if (err) {
45
+ setMessage(err)
46
+ } else {
47
+ setMessage("Password updated")
48
+ }
49
+ })
50
+ }
51
+
52
+ return (
53
+ <>
54
+ {user.is && (
55
+ <SearchAppBar mode={mode} setMode={setMode} {...appBar} />
56
+ )}
57
+ <Container maxWidth="sm">
58
+ <Grid container>
59
+ <Grid item xs={12}>
60
+ <Card sx={{mt: 2}}>
61
+ <CardContent>
62
+ <Typography sx={{m: 1}}>
63
+ {name
64
+ ? "Hello " + name
65
+ : "Account not found. Please try logging in again."}
66
+ </Typography>
67
+ </CardContent>
68
+ </Card>
69
+ {children}
70
+ <Card sx={{mt: 2}}>
71
+ <CardContent>
72
+ <Typography sx={{m: 1}}>
73
+ Use this form to change your password
74
+ </Typography>
75
+ <FormControl
76
+ variant="outlined"
77
+ fullWidth={true}
78
+ margin="normal"
79
+ value={password}
80
+ onChange={event => setPassword(event.target.value)}
81
+ >
82
+ <InputLabel htmlFor="settings-password">
83
+ Current Password
84
+ </InputLabel>
85
+ <OutlinedInput
86
+ id="settings-password"
87
+ autoComplete="password"
88
+ type={showPassword ? "text" : "password"}
89
+ endAdornment={
90
+ <InputAdornment position="end">
91
+ <IconButton
92
+ aria-label="toggle password visibility"
93
+ onClick={() => setShowPassword(show => !show)}
94
+ edge="end"
95
+ >
96
+ {showPassword ? <VisibilityOff /> : <Visibility />}
97
+ </IconButton>
98
+ </InputAdornment>
99
+ }
100
+ label="Current Password"
101
+ />
102
+ </FormControl>
103
+ <FormControl
104
+ variant="outlined"
105
+ fullWidth={true}
106
+ margin="normal"
107
+ value={newPassword}
108
+ onChange={event => setNewPassword(event.target.value)}
109
+ >
110
+ <InputLabel htmlFor="settings-new-password">
111
+ New Password
112
+ </InputLabel>
113
+ <OutlinedInput
114
+ id="settings-new-password"
115
+ autoComplete="new-password"
116
+ type={showNewPassword ? "text" : "password"}
117
+ endAdornment={
118
+ <InputAdornment position="end">
119
+ <IconButton
120
+ aria-label="toggle new password visibility"
121
+ onClick={() => setShowNewPassword(show => !show)}
122
+ edge="end"
123
+ >
124
+ {showNewPassword ? <VisibilityOff /> : <Visibility />}
125
+ </IconButton>
126
+ </InputAdornment>
127
+ }
128
+ label="New Password"
129
+ />
130
+ </FormControl>
131
+ <Button
132
+ sx={{mt: 1}}
133
+ variant="contained"
134
+ disabled={disabledButton}
135
+ onClick={changePassword}
136
+ >
137
+ Submit
138
+ </Button>
139
+ {message && (
140
+ <Typography sx={{m: 1}} variant="string">
141
+ {message}
142
+ </Typography>
143
+ )}
144
+ </CardContent>
145
+ </Card>
146
+ <Card sx={{mt: 2}}>
147
+ <CardContent>
148
+ <Typography sx={{m: 1}}>Log out of your account</Typography>
149
+ <Button
150
+ sx={{mt: 1}}
151
+ variant="contained"
152
+ onClick={() => {
153
+ user.leave()
154
+ sessionStorage.removeItem("name")
155
+ sessionStorage.removeItem("code")
156
+ localStorage.removeItem("name")
157
+ localStorage.removeItem("code")
158
+ window.location = "/login"
159
+ }}
160
+ >
161
+ Logout
162
+ </Button>
163
+ </CardContent>
164
+ </Card>
165
+ {buildDate && (
166
+ <Typography sx={{m: 1, color: grey[400]}}>
167
+ Build date: {buildDate}
168
+ </Typography>
169
+ )}
170
+ </Grid>
171
+ </Grid>
172
+ </Container>
173
+ </>
174
+ )
175
+ }
176
+
177
+ export default Settings
@@ -0,0 +1,177 @@
1
+ import {useState} from "react"
2
+ import Button from "@mui/material/Button"
3
+ import Card from "@mui/material/Card"
4
+ import CardContent from "@mui/material/CardContent"
5
+ import Container from "@mui/material/Container"
6
+ import FormControl from "@mui/material/FormControl"
7
+ import Grid from "@mui/material/Grid"
8
+ import IconButton from "@mui/material/IconButton"
9
+ import InputAdornment from "@mui/material/InputAdornment"
10
+ import InputLabel from "@mui/material/InputLabel"
11
+ import OutlinedInput from "@mui/material/OutlinedInput"
12
+ import TextField from "@mui/material/TextField"
13
+ import Typography from "@mui/material/Typography"
14
+ import Visibility from "@mui/icons-material/Visibility"
15
+ import VisibilityOff from "@mui/icons-material/VisibilityOff"
16
+ import SearchAppBar from "./SearchAppBar.jsx"
17
+
18
+ const UpdatePassword = ({
19
+ user,
20
+ loggedIn,
21
+ current,
22
+ code,
23
+ reset,
24
+ mode,
25
+ setMode,
26
+ appBar,
27
+ }) => {
28
+ const [name, setName] = useState(current ?? "")
29
+ const [password, setPassword] = useState("")
30
+ const [showPassword, setShowPassword] = useState(false)
31
+ const [message, setMessage] = useState(loggedIn ? "Already logged in" : "")
32
+ const [disabledButton, setDisabledButton] = useState(loggedIn)
33
+
34
+ const update = username => {
35
+ if (!username) {
36
+ setMessage("Please choose a username")
37
+ return
38
+ }
39
+
40
+ setDisabledButton(true)
41
+ setMessage("Updating password...")
42
+
43
+ user.create(username, password, err => {
44
+ if (err) {
45
+ if (err === "Username already exists") {
46
+ let match = username.match(/^(\w+)\.(\d)$/)
47
+ if (match) {
48
+ let increment = Number(match[2]) + 1
49
+ if (increment === 10) {
50
+ setDisabledButton(false)
51
+ setMessage("Too many password resets")
52
+ return
53
+ }
54
+ update(`${match[1]}.${increment}`)
55
+ return
56
+ }
57
+ update(`${username}.1`)
58
+ return
59
+ }
60
+ setDisabledButton(false)
61
+ setMessage(err)
62
+ return
63
+ }
64
+
65
+ user.auth(username, password, err => {
66
+ if (err) {
67
+ setDisabledButton(false)
68
+ setMessage(err)
69
+ return
70
+ }
71
+
72
+ fetch(`${window.location.origin}/update-password`, {
73
+ method: "POST",
74
+ headers: {"Content-Type": "application/json;charset=utf-8"},
75
+ body: JSON.stringify({
76
+ code: code ?? null,
77
+ reset: reset ?? null,
78
+ pub: user.is.pub,
79
+ epub: user.is.epub,
80
+ username: username,
81
+ name: name,
82
+ }),
83
+ })
84
+ .then(res => res.text().then(text => ({ok: res.ok, text: text})))
85
+ .then(res => {
86
+ if (!res.ok) {
87
+ setDisabledButton(false)
88
+ user.delete(username, password)
89
+ setMessage(res.text)
90
+ return
91
+ }
92
+
93
+ // The previous public key is returned to copy public user data.
94
+ user.get([res.text, "public"], data => {
95
+ user.get("public").put(data, err => {
96
+ if (err) console.error(err)
97
+ })
98
+ })
99
+
100
+ setMessage("Password updated")
101
+ setTimeout(() => {
102
+ setDisabledButton(false)
103
+ window.location = "/login"
104
+ }, 2000)
105
+ })
106
+ })
107
+ })
108
+ }
109
+
110
+ return (
111
+ <>
112
+ {loggedIn && (
113
+ <SearchAppBar mode={mode} setMode={setMode} {...appBar} />
114
+ )}
115
+ <Container maxWidth="sm">
116
+ <Grid container>
117
+ <Grid item xs={12}>
118
+ <Card sx={{mt: 2}}>
119
+ <CardContent>
120
+ <Typography variant="h5">Update Password</Typography>
121
+ <TextField
122
+ id="update-username"
123
+ label="Username"
124
+ variant="outlined"
125
+ fullWidth={true}
126
+ margin="normal"
127
+ value={name}
128
+ onChange={event => setName(event.target.value)}
129
+ />
130
+ <FormControl
131
+ variant="outlined"
132
+ fullWidth={true}
133
+ margin="normal"
134
+ value={password}
135
+ onChange={event => setPassword(event.target.value)}
136
+ >
137
+ <InputLabel htmlFor="update-password">Password</InputLabel>
138
+ <OutlinedInput
139
+ id="update-password"
140
+ type={showPassword ? "text" : "password"}
141
+ endAdornment={
142
+ <InputAdornment position="end">
143
+ <IconButton
144
+ aria-label="toggle password visibility"
145
+ onClick={() => setShowPassword(show => !show)}
146
+ edge="end"
147
+ >
148
+ {showPassword ? <VisibilityOff /> : <Visibility />}
149
+ </IconButton>
150
+ </InputAdornment>
151
+ }
152
+ label="Password"
153
+ />
154
+ </FormControl>
155
+ <Button
156
+ sx={{mt: 1}}
157
+ variant="contained"
158
+ disabled={disabledButton}
159
+ onClick={() => update(name)}
160
+ >
161
+ Submit
162
+ </Button>
163
+ {message && (
164
+ <Typography sx={{m: 1}} variant="string">
165
+ {message}
166
+ </Typography>
167
+ )}
168
+ </CardContent>
169
+ </Card>
170
+ </Grid>
171
+ </Grid>
172
+ </Container>
173
+ </>
174
+ )
175
+ }
176
+
177
+ export default UpdatePassword
@@ -0,0 +1,60 @@
1
+ import {useState} from "react"
2
+ import Button from "@mui/material/Button"
3
+ import Container from "@mui/material/Container"
4
+ import Grid from "@mui/material/Grid"
5
+ import Typography from "@mui/material/Typography"
6
+ import SearchAppBar from "./SearchAppBar.jsx"
7
+
8
+ const ValidateEmail = ({loggedIn, mode, setMode, appBar, code, validate}) => {
9
+ const [message, setMessage] = useState("Validate your email address:")
10
+ const [disabledButton, setDisabledButton] = useState(false)
11
+
12
+ const validateEmail = () => {
13
+ setMessage("Validating email...")
14
+ setDisabledButton(true)
15
+
16
+ fetch(`${window.location.origin}/validate-email`, {
17
+ method: "POST",
18
+ headers: {"Content-Type": "application/json;charset=utf-8"},
19
+ body: JSON.stringify({
20
+ code: code ?? null,
21
+ validate: validate ?? null,
22
+ }),
23
+ })
24
+ .then(res => res.text().then(text => ({ok: res.ok, text: text})))
25
+ .then(res => {
26
+ setDisabledButton(false)
27
+ setMessage(res.text)
28
+ if (res.ok) {
29
+ setTimeout(() => {
30
+ window.location = "/"
31
+ }, 1000)
32
+ }
33
+ })
34
+ }
35
+
36
+ return (
37
+ <>
38
+ {loggedIn && (
39
+ <SearchAppBar mode={mode} setMode={setMode} {...appBar} />
40
+ )}
41
+ <Container maxWidth="sm">
42
+ <Grid container>
43
+ <Grid item xs={12}>
44
+ <Typography sx={{m: 1}}>{message}</Typography>
45
+ <Button
46
+ sx={{mt: 1}}
47
+ variant="contained"
48
+ disabled={disabledButton}
49
+ onClick={validateEmail}
50
+ >
51
+ Validate
52
+ </Button>
53
+ </Grid>
54
+ </Grid>
55
+ </Container>
56
+ </>
57
+ )
58
+ }
59
+
60
+ export default ValidateEmail
@@ -0,0 +1,237 @@
1
+ import {describe, it, expect, beforeEach, vi} from "vitest"
2
+ import {render, screen, act} from "@testing-library/react"
3
+ import userEvent from "@testing-library/user-event"
4
+ import EditCache from "../EditCache.jsx"
5
+
6
+ const mockRemoveItem = vi.fn()
7
+ const mockClearCache = vi.fn()
8
+
9
+ const emptyCacheData = {
10
+ audio: {count: 0, size: 0, items: []},
11
+ video: {count: 0, size: 0, items: []},
12
+ }
13
+
14
+ const filledCacheData = {
15
+ audio: {
16
+ count: 2,
17
+ size: 5 * 1024 * 1024,
18
+ items: [
19
+ {url: "https://podcast.com/episodes/ep1.mp3", size: 3 * 1024 * 1024},
20
+ {url: "https://podcast.com/episodes/ep2.mp3", size: 2 * 1024 * 1024},
21
+ ],
22
+ },
23
+ video: {
24
+ count: 1,
25
+ size: 50 * 1024 * 1024,
26
+ items: [{url: "https://video.com/clips/clip1.mp4", size: 50 * 1024 * 1024}],
27
+ },
28
+ }
29
+
30
+ const manyAudioCacheData = {
31
+ audio: {
32
+ count: 15,
33
+ size: 15 * 1024 * 1024,
34
+ items: Array.from({length: 15}, (_, i) => ({
35
+ url: `https://podcast.com/ep${i + 1}.mp3`,
36
+ size: 1024 * 1024,
37
+ })),
38
+ },
39
+ video: {count: 0, size: 0, items: []},
40
+ }
41
+
42
+ describe("EditCache Component", () => {
43
+ beforeEach(() => {
44
+ vi.clearAllMocks()
45
+ })
46
+
47
+ it("renders nothing when cacheData is null", () => {
48
+ const {container} = render(
49
+ <EditCache
50
+ cacheData={null}
51
+ removeItem={mockRemoveItem}
52
+ clearCache={mockClearCache}
53
+ />,
54
+ )
55
+ expect(container.firstChild).toBeNull()
56
+ })
57
+
58
+ it("renders cache storage card when cacheData is provided", () => {
59
+ render(
60
+ <EditCache
61
+ cacheData={emptyCacheData}
62
+ removeItem={mockRemoveItem}
63
+ clearCache={mockClearCache}
64
+ />,
65
+ )
66
+ expect(screen.getByText("Cache storage")).toBeTruthy()
67
+ })
68
+
69
+ it("shows audio accordion with file count and size", () => {
70
+ render(
71
+ <EditCache
72
+ cacheData={filledCacheData}
73
+ removeItem={mockRemoveItem}
74
+ clearCache={mockClearCache}
75
+ />,
76
+ )
77
+ expect(
78
+ screen.getByRole("button", {name: /audio.*2 files.*5\.0 mb/i}),
79
+ ).toBeTruthy()
80
+ })
81
+
82
+ it("shows video accordion with singular file label", () => {
83
+ render(
84
+ <EditCache
85
+ cacheData={filledCacheData}
86
+ removeItem={mockRemoveItem}
87
+ clearCache={mockClearCache}
88
+ />,
89
+ )
90
+ expect(screen.getByRole("button", {name: /video.*1 file\b/i})).toBeTruthy()
91
+ })
92
+
93
+ it("shows no audio message when audio section is empty", async () => {
94
+ render(
95
+ <EditCache
96
+ cacheData={emptyCacheData}
97
+ removeItem={mockRemoveItem}
98
+ clearCache={mockClearCache}
99
+ />,
100
+ )
101
+ await act(async () => {
102
+ await userEvent.click(screen.getByRole("button", {name: /audio/i}))
103
+ })
104
+ expect(screen.getByText("No audio cached")).toBeTruthy()
105
+ })
106
+
107
+ it("shows no video message when video section is empty", async () => {
108
+ render(
109
+ <EditCache
110
+ cacheData={emptyCacheData}
111
+ removeItem={mockRemoveItem}
112
+ clearCache={mockClearCache}
113
+ />,
114
+ )
115
+ await act(async () => {
116
+ await userEvent.click(screen.getByRole("button", {name: /video/i}))
117
+ })
118
+ expect(screen.getByText("No video cached")).toBeTruthy()
119
+ })
120
+
121
+ it("shows filename and size for audio items when expanded", async () => {
122
+ render(
123
+ <EditCache
124
+ cacheData={filledCacheData}
125
+ removeItem={mockRemoveItem}
126
+ clearCache={mockClearCache}
127
+ />,
128
+ )
129
+ await act(async () => {
130
+ await userEvent.click(screen.getByRole("button", {name: /audio/i}))
131
+ })
132
+ expect(screen.getByText("podcast.com: ep1.mp3")).toBeTruthy()
133
+ expect(screen.getByText("3.0 MB")).toBeTruthy()
134
+ })
135
+
136
+ it("shows filename and size for video items when expanded", async () => {
137
+ render(
138
+ <EditCache
139
+ cacheData={filledCacheData}
140
+ removeItem={mockRemoveItem}
141
+ clearCache={mockClearCache}
142
+ />,
143
+ )
144
+ await act(async () => {
145
+ await userEvent.click(screen.getByRole("button", {name: /video/i}))
146
+ })
147
+ expect(screen.getByText("video.com: clip1.mp4")).toBeTruthy()
148
+ expect(screen.getByText("50.0 MB")).toBeTruthy()
149
+ })
150
+
151
+ it("calls removeItem with cache name and url when delete is clicked", async () => {
152
+ render(
153
+ <EditCache
154
+ cacheData={filledCacheData}
155
+ removeItem={mockRemoveItem}
156
+ clearCache={mockClearCache}
157
+ />,
158
+ )
159
+ await act(async () => {
160
+ await userEvent.click(screen.getByRole("button", {name: /audio/i}))
161
+ })
162
+ const removeButtons = screen.getAllByLabelText("remove")
163
+ await act(async () => {
164
+ await userEvent.click(removeButtons[0])
165
+ })
166
+ expect(mockRemoveItem).toHaveBeenCalledWith(
167
+ "audio",
168
+ "https://podcast.com/episodes/ep1.mp3",
169
+ )
170
+ })
171
+
172
+ it("calls clearCache with cache name when clear all is clicked", async () => {
173
+ render(
174
+ <EditCache
175
+ cacheData={filledCacheData}
176
+ removeItem={mockRemoveItem}
177
+ clearCache={mockClearCache}
178
+ />,
179
+ )
180
+ await act(async () => {
181
+ await userEvent.click(screen.getByRole("button", {name: /audio/i}))
182
+ })
183
+ await act(async () => {
184
+ await userEvent.click(
185
+ screen.getByRole("button", {name: /clear all audio/i}),
186
+ )
187
+ })
188
+ expect(mockClearCache).toHaveBeenCalledWith("audio")
189
+ })
190
+
191
+ it("shows only 10 items when there are more than 10", async () => {
192
+ render(
193
+ <EditCache
194
+ cacheData={manyAudioCacheData}
195
+ removeItem={mockRemoveItem}
196
+ clearCache={mockClearCache}
197
+ />,
198
+ )
199
+ await act(async () => {
200
+ await userEvent.click(screen.getByRole("button", {name: /audio/i}))
201
+ })
202
+ expect(screen.getAllByLabelText("remove")).toHaveLength(10)
203
+ })
204
+
205
+ it("shows show more button and count when items are truncated", async () => {
206
+ render(
207
+ <EditCache
208
+ cacheData={manyAudioCacheData}
209
+ removeItem={mockRemoveItem}
210
+ clearCache={mockClearCache}
211
+ />,
212
+ )
213
+ await act(async () => {
214
+ await userEvent.click(screen.getByRole("button", {name: /audio/i}))
215
+ })
216
+ expect(screen.getByText("Showing 10 of 15 files")).toBeTruthy()
217
+ expect(screen.getByRole("button", {name: /show more/i})).toBeTruthy()
218
+ })
219
+
220
+ it("shows all items after clicking show more", async () => {
221
+ render(
222
+ <EditCache
223
+ cacheData={manyAudioCacheData}
224
+ removeItem={mockRemoveItem}
225
+ clearCache={mockClearCache}
226
+ />,
227
+ )
228
+ await act(async () => {
229
+ await userEvent.click(screen.getByRole("button", {name: /audio/i}))
230
+ })
231
+ await act(async () => {
232
+ await userEvent.click(screen.getByRole("button", {name: /show more/i}))
233
+ })
234
+ expect(screen.getAllByLabelText("remove")).toHaveLength(15)
235
+ expect(screen.queryByRole("button", {name: /show more/i})).toBeNull()
236
+ })
237
+ })
package/src/index.js ADDED
@@ -0,0 +1,11 @@
1
+ export {default as EditCache} from "./components/EditCache.jsx"
2
+ export {default as RequestCode} from "./components/RequestCode.jsx"
3
+ export {default as LoginCodes} from "./components/LoginCodes.jsx"
4
+ export {default as Login} from "./components/Login.jsx"
5
+ export {default as Register} from "./components/Register.jsx"
6
+ export {default as ResetPassword} from "./components/ResetPassword.jsx"
7
+ export {default as SearchAppBar} from "./components/SearchAppBar.jsx"
8
+ export {default as Settings} from "./components/Settings.jsx"
9
+ export {default as UpdatePassword} from "./components/UpdatePassword.jsx"
10
+ export {default as ValidateEmail} from "./components/ValidateEmail.jsx"
11
+ export {register as registerServiceWorker} from "./utils/serviceWorkerRegistration.js"
@@ -0,0 +1,21 @@
1
+ import "@testing-library/jest-dom"
2
+ import {afterEach, vi} from "vitest"
3
+ import {cleanup} from "@testing-library/react"
4
+
5
+ afterEach(() => {
6
+ cleanup()
7
+ })
8
+
9
+ Object.defineProperty(window, "matchMedia", {
10
+ writable: true,
11
+ value: vi.fn().mockImplementation(query => ({
12
+ matches: false,
13
+ media: query,
14
+ onchange: null,
15
+ addListener: vi.fn(),
16
+ removeListener: vi.fn(),
17
+ addEventListener: vi.fn(),
18
+ removeEventListener: vi.fn(),
19
+ dispatchEvent: vi.fn(),
20
+ })),
21
+ })