Skip to content

Commit 624d040

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 2affea1 commit 624d040

7 files changed

Lines changed: 392 additions & 16 deletions

File tree

‎ui/package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@
3333
"remove-markdown": "^0.8.0",
3434
"tss-react": "^4.9.19",
3535
"vite": "^8.0.8",
36-
"vitest": "^5.0.0"
36+
"vitest": "^5.0.0",
37+
"zod": "^4.6.7"
3738
},
3839
"scripts": {
3940
"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;
@@ -212,6 +213,7 @@ const Message = ({
212213
{expanded ? 'Read Less' : 'Read More'}
213214
</Button>
214215
)}
216+
<MessageActions extras={extras} />
215217
</Container>
216218
</div>
217219
);

‎ui/src/message/MessageActions.tsx‎

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

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

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
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('reports requests fetch cannot send', () => {
65+
const result = parse(
66+
button({method: 'get', body: 'a'}),
67+
button({method: 'trace'}),
68+
button({method: 'post', body: 'a'})
69+
);
70+
expect(result.buttons.map((b) => b.http.method)).toEqual(['POST']);
71+
expect(result.error).toContain(
72+
'GET and HEAD requests cannot have a body\n → at ["client::action"].buttons[0].http.body'
73+
);
74+
expect(result.error).toContain(
75+
'Unsupported method\n → at ["client::action"].buttons[1].http.method'
76+
);
77+
});
78+
79+
it.each([
80+
['null', null],
81+
['a string', 'string'],
82+
['an empty label', {label: '', http: {method: 'POST', url: 'https://x.y/'}}],
83+
['a blank label', {label: ' ', http: {method: 'POST', url: 'https://x.y/'}}],
84+
['a missing http', {label: 'no http'}],
85+
['a missing url', button({url: undefined})],
86+
['a missing method', button({method: undefined})],
87+
['an invalid url', button({url: 'not a url'})],
88+
['a javascript url', button({url: 'javascript:alert(1)'})],
89+
['a data url', button({url: 'data:text/plain,hi'})],
90+
['a non-string header', button({headers: {A: 'b', C: 1}})],
91+
['a non-string body', button({body: {a: 1}})],
92+
['a GET body', button({method: 'get', body: 'a'})],
93+
['a HEAD body', button({method: 'HEAD', body: ''})],
94+
['the CONNECT method', button({method: 'connect'})],
95+
['the TRACE method', button({method: 'TRACE'})],
96+
['the TRACK method', button({method: 'track'})],
97+
])('rejects a button with %s', (_, invalid) => {
98+
const result = parse(invalid);
99+
expect(result.buttons).toEqual([]);
100+
expect(result.error).toContain('→ at ["client::action"].buttons[0]');
101+
});
102+
});

‎ui/src/message/extras.ts‎

Lines changed: 51 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,65 @@
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+
// fetch rejects these methods and a body on GET/HEAD requests without sending anything.
19+
const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'];
20+
const bodylessMethods = ['GET', 'HEAD'];
21+
22+
const httpAction = z
23+
.object({
24+
method: z.string().check(
25+
z.toUpperCase(),
26+
z.refine((method) => !forbiddenMethods.includes(method), 'Unsupported method')
27+
),
28+
url: z.url({protocol: /^https?$/}),
29+
headers: z._default(z.record(z.string(), z.string()), {}),
30+
body: z.optional(z.string()),
31+
})
32+
.check(
33+
z.refine(({method, body}) => body === undefined || !bodylessMethods.includes(method), {
34+
message: 'GET and HEAD requests cannot have a body',
35+
path: ['body'],
36+
})
37+
);
38+
39+
const actionButton = z.object({
40+
label: z.string().check(z.trim(), z.minLength(1)),
41+
http: httpAction,
42+
});
43+
44+
export type IActionButton = z.infer<typeof actionButton>;
1945

20-
if (!extras[key]) {
21-
return null;
22-
}
46+
const actionExtras = z.optional(
47+
z.object({
48+
'client::action': z.nullish(z.object({buttons: z.array(actionButton)})),
49+
})
50+
);
2351

24-
if (!extras[key][path]) {
25-
return null;
26-
}
52+
const validButtons = (rawButtons: unknown): IActionButton[] =>
53+
Array.isArray(rawButtons)
54+
? rawButtons.flatMap((rawButton) => actionButton.safeParse(rawButton).data ?? [])
55+
: [];
2756

28-
return extras[key][path];
57+
export const actionButtons = (
58+
extras?: IMessageExtras
59+
): {buttons: IActionButton[]; error?: string} => {
60+
const {error} = actionExtras.safeParse(extras);
61+
return {
62+
buttons: validButtons(extras?.['client::action']?.buttons),
63+
error: error && z.prettifyError(error),
64+
};
2965
};

0 commit comments

Comments
 (0)