Skip to content

Commit 741ea98

Browse files
EinfacheSachejmattheis
authored andcommitted
feat(ui): render message action buttons (client::action)
Render the HTTP action buttons defined in extras["client::action"].buttons as proposed in #494. Clicking a button sends the configured request via fetch (method, url, headers, body). Only http(s) URLs are accepted, invalid buttons are skipped and reported in a warning. Cookies are not sent (credentials: omit) and the result is reported via a snackbar.
1 parent 01086b9 commit 741ea98

7 files changed

Lines changed: 354 additions & 16 deletions

File tree

‎ui/package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@
3434
"remove-markdown": "^0.6.2",
3535
"tss-react": "^4.9.19",
3636
"vite": "^8.0.8",
37-
"vitest": "^5.0.0"
37+
"vitest": "^5.0.0",
38+
"zod": "^4.6.7"
3839
},
3940
"scripts": {
4041
"start": "vite",

‎ui/src/message/Message.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {Markdown} from '../common/Markdown';
1111
import * as config from '../config';
1212
import {IMessageExtras} from '../types';
1313
import {contentType, RenderMode} from './extras';
14+
import {MessageActions} from './MessageActions';
1415
import {TimeAgoFormatter} from '../common/TimeAgoFormatter';
1516

1617
const PREVIEW_LENGTH = 500;
@@ -199,6 +200,7 @@ const Message = ({
199200
}`}>
200201
{renderContent()}
201202
</Typography>
203+
<MessageActions extras={extras} />
202204
</div>
203205
{isOverflowing && (
204206
<Button

‎ui/src/message/MessageActions.tsx‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
import Alert from '@mui/material/Alert';
2+
import Button from '@mui/material/Button';
3+
import CircularProgress from '@mui/material/CircularProgress';
4+
import Tooltip from '@mui/material/Tooltip';
5+
import React from 'react';
6+
import {makeStyles} from 'tss-react/mui';
7+
import {useStores} from '../stores';
8+
import {IMessageExtras} from '../types';
9+
import {actionButtons, IActionButton} from './extras';
10+
11+
const useStyles = makeStyles()((theme) => ({
12+
actions: {
13+
display: 'flex',
14+
flexWrap: 'wrap',
15+
gap: theme.spacing(1),
16+
marginTop: theme.spacing(1.5),
17+
},
18+
error: {
19+
marginTop: theme.spacing(1.5),
20+
},
21+
errorDetails: {
22+
whiteSpace: 'pre-wrap',
23+
margin: 0,
24+
marginTop: theme.spacing(1),
25+
},
26+
}));
27+
28+
const executeAction = ({http}: IActionButton): Promise<Response> =>
29+
fetch(http.url, {
30+
method: http.method,
31+
headers: http.headers,
32+
body: http.body,
33+
credentials: 'omit',
34+
referrerPolicy: 'no-referrer',
35+
});
36+
37+
const describeTarget = ({http}: IActionButton) => {
38+
const url = new URL(http.url);
39+
return `${http.method} ${url.host}${url.pathname}`;
40+
};
41+
42+
const ActionButton = ({button}: {button: IActionButton}) => {
43+
const {snackManager} = useStores();
44+
const [running, setRunning] = React.useState(false);
45+
46+
const onClick = async () => {
47+
setRunning(true);
48+
try {
49+
const response = await executeAction(button);
50+
if (response.ok) {
51+
snackManager.snack(`Action '${button.label}' succeeded.`);
52+
} else {
53+
snackManager.snack(
54+
`Action '${button.label}' failed: ${response.status} ${response.statusText}`.trim()
55+
);
56+
}
57+
} catch {
58+
snackManager.snack(
59+
`Action '${button.label}': no readable response (network error or CORS). The request may still have been processed.`
60+
);
61+
} finally {
62+
setRunning(false);
63+
}
64+
};
65+
66+
return (
67+
<Tooltip title={describeTarget(button)}>
68+
<span>
69+
<Button
70+
className="action"
71+
variant="outlined"
72+
size="small"
73+
disabled={running}
74+
onClick={onClick}
75+
startIcon={running ? <CircularProgress size={16} /> : undefined}>
76+
{button.label}
77+
</Button>
78+
</span>
79+
</Tooltip>
80+
);
81+
};
82+
83+
const ActionError = ({error}: {error: string}) => {
84+
const {classes} = useStyles();
85+
const [showDetails, setShowDetails] = React.useState(false);
86+
return (
87+
<Alert
88+
className={`${classes.error} action-error`}
89+
severity="warning"
90+
action={
91+
<Button
92+
className="action-error-toggle"
93+
color="inherit"
94+
size="small"
95+
onClick={() => setShowDetails((show) => !show)}>
96+
{showDetails ? 'Hide details' : 'Details'}
97+
</Button>
98+
}>
99+
This message contains invalid action buttons.
100+
{showDetails && (
101+
<pre className={`${classes.errorDetails} action-error-details`}>{error}</pre>
102+
)}
103+
</Alert>
104+
);
105+
};
106+
107+
export const MessageActions = ({extras}: {extras?: IMessageExtras}) => {
108+
const {classes} = useStyles();
109+
const {buttons, error} = React.useMemo(() => actionButtons(extras), [extras]);
110+
return (
111+
<>
112+
{buttons.length > 0 && (
113+
<div className={`${classes.actions} actions`}>
114+
{buttons.map((button, index) => (
115+
<ActionButton key={index} button={button} />
116+
))}
117+
</div>
118+
)}
119+
{error && <ActionError error={error} />}
120+
</>
121+
);
122+
};

‎ui/src/message/extras.test.ts‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import {describe, expect, it} from 'vitest';
2+
import {actionButtons} from './extras';
3+
4+
const button = (http: object) => ({
5+
label: 'test',
6+
http: {method: 'POST', url: 'https://x.y/', ...http},
7+
});
8+
const parse = (...buttons: unknown[]) => actionButtons({'client::action': {buttons}});
9+
10+
describe('actionButtons', () => {
11+
it('returns nothing without client::action', () => {
12+
expect(actionButtons(undefined)).toEqual({buttons: []});
13+
expect(actionButtons({})).toEqual({buttons: []});
14+
expect(actionButtons({'client::action': null})).toEqual({buttons: []});
15+
});
16+
17+
it.each([{}, {buttons: 'nope'}])('reports a malformed client::action %j', (action) => {
18+
const result = actionButtons({'client::action': action});
19+
expect(result.buttons).toEqual([]);
20+
expect(result.error).toContain('→ at ["client::action"].buttons');
21+
});
22+
23+
it('parses the format from gotify/server#494', () => {
24+
const result = parse(
25+
{
26+
label: 'Power off',
27+
http: {
28+
method: 'post',
29+
url: 'https://example.com/power_off?id=5',
30+
headers: {Authorization: 'bearer token'},
31+
},
32+
},
33+
{label: 'Dismiss', http: {method: 'get', url: 'http://example.com/dismiss'}}
34+
);
35+
expect(result).toEqual({
36+
buttons: [
37+
{
38+
label: 'Power off',
39+
http: {
40+
method: 'POST',
41+
url: 'https://example.com/power_off?id=5',
42+
headers: {Authorization: 'bearer token'},
43+
},
44+
},
45+
{
46+
label: 'Dismiss',
47+
http: {method: 'GET', url: 'http://example.com/dismiss', headers: {}},
48+
},
49+
],
50+
});
51+
});
52+
53+
it('reports every invalid button and keeps the valid ones', () => {
54+
const result = parse(
55+
button({url: 'ftp://x.y/'}),
56+
{label: 'ok', http: {method: 'POST', url: 'https://x.y/'}},
57+
button({method: 1})
58+
);
59+
expect(result.buttons.map((b) => b.label)).toEqual(['ok']);
60+
expect(result.error).toContain('→ at ["client::action"].buttons[0].http.url');
61+
expect(result.error).toContain('→ at ["client::action"].buttons[2].http.method');
62+
});
63+
64+
it.each([
65+
['null', null],
66+
['a string', 'string'],
67+
['an empty label', {label: '', http: {method: 'POST', url: 'https://x.y/'}}],
68+
['a blank label', {label: ' ', http: {method: 'POST', url: 'https://x.y/'}}],
69+
['a missing http', {label: 'no http'}],
70+
['a missing url', button({url: undefined})],
71+
['a missing method', button({method: undefined})],
72+
['an invalid url', button({url: 'not a url'})],
73+
['a javascript url', button({url: 'javascript:alert(1)'})],
74+
['a data url', button({url: 'data:text/plain,hi'})],
75+
['a non-string header', button({headers: {A: 'b', C: 1}})],
76+
['a non-string body', button({body: {a: 1}})],
77+
])('rejects a button with %s', (_, invalid) => {
78+
const result = parse(invalid);
79+
expect(result.buttons).toEqual([]);
80+
expect(result.error).toContain('→ at ["client::action"].buttons[0]');
81+
});
82+
});

‎ui/src/message/extras.ts‎

Lines changed: 35 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,49 @@
1+
import {z} from 'zod/mini';
12
import {IMessageExtras} from '../types';
23

34
export enum RenderMode {
45
Markdown = 'text/markdown',
56
Plain = 'text/plain',
67
}
78

9+
const displayExtras = z.object({
10+
'client::display': z.object({contentType: z.enum(RenderMode)}),
11+
});
12+
813
export const contentType = (extras?: IMessageExtras): RenderMode => {
9-
const type = extract(extras, 'client::display', 'contentType');
10-
const valid = Object.values(RenderMode).includes(type);
11-
return valid ? type : RenderMode.Plain;
14+
const result = displayExtras.safeParse(extras);
15+
return result.success ? result.data['client::display'].contentType : RenderMode.Plain;
1216
};
1317

14-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
15-
const extract = (extras: IMessageExtras | undefined, key: string, path: string): any => {
16-
if (!extras) {
17-
return null;
18-
}
18+
const actionButton = z.object({
19+
label: z.string().check(z.trim(), z.minLength(1)),
20+
http: z.object({
21+
method: z.string().check(z.toUpperCase()),
22+
url: z.url({protocol: /^https?$/}),
23+
headers: z._default(z.record(z.string(), z.string()), {}),
24+
body: z.optional(z.string()),
25+
}),
26+
});
27+
28+
export type IActionButton = z.infer<typeof actionButton>;
1929

20-
if (!extras[key]) {
21-
return null;
22-
}
30+
const actionExtras = z.optional(
31+
z.object({
32+
'client::action': z.nullish(z.object({buttons: z.array(actionButton)})),
33+
})
34+
);
2335

24-
if (!extras[key][path]) {
25-
return null;
26-
}
36+
const validButtons = (rawButtons: unknown): IActionButton[] =>
37+
Array.isArray(rawButtons)
38+
? rawButtons.flatMap((rawButton) => actionButton.safeParse(rawButton).data ?? [])
39+
: [];
2740

28-
return extras[key][path];
41+
export const actionButtons = (
42+
extras?: IMessageExtras
43+
): {buttons: IActionButton[]; error?: string} => {
44+
const {error} = actionExtras.safeParse(extras);
45+
return {
46+
buttons: validButtons(extras?.['client::action']?.buttons),
47+
error: error && z.prettifyError(error),
48+
};
2949
};

0 commit comments

Comments
 (0)