@patternfly/chatbot 6.3.0-prerelease.22 → 6.3.0-prerelease.24

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.
Files changed (33) hide show
  1. package/dist/cjs/FileDropZone/FileDropZone.d.ts +15 -1
  2. package/dist/cjs/FileDropZone/FileDropZone.js +7 -2
  3. package/dist/cjs/FileDropZone/FileDropZone.test.js +55 -0
  4. package/dist/cjs/MessageBar/AttachButton.d.ts +18 -1
  5. package/dist/cjs/MessageBar/AttachButton.js +4 -6
  6. package/dist/cjs/MessageBar/AttachButton.test.js +54 -0
  7. package/dist/cjs/MessageBar/MessageBar.d.ts +23 -7
  8. package/dist/cjs/MessageBar/MessageBar.js +2 -2
  9. package/dist/cjs/ResponseActions/ResponseActions.js +27 -2
  10. package/dist/cjs/ResponseActions/ResponseActions.test.js +60 -0
  11. package/dist/esm/FileDropZone/FileDropZone.d.ts +15 -1
  12. package/dist/esm/FileDropZone/FileDropZone.js +7 -2
  13. package/dist/esm/FileDropZone/FileDropZone.test.js +55 -0
  14. package/dist/esm/MessageBar/AttachButton.d.ts +18 -1
  15. package/dist/esm/MessageBar/AttachButton.js +4 -6
  16. package/dist/esm/MessageBar/AttachButton.test.js +54 -0
  17. package/dist/esm/MessageBar/MessageBar.d.ts +23 -7
  18. package/dist/esm/MessageBar/MessageBar.js +2 -2
  19. package/dist/esm/ResponseActions/ResponseActions.js +27 -2
  20. package/dist/esm/ResponseActions/ResponseActions.test.js +60 -0
  21. package/package.json +1 -1
  22. package/patternfly-docs/content/extensions/chatbot/examples/Messages/MessageWithClickedResponseActions.tsx +25 -0
  23. package/patternfly-docs/content/extensions/chatbot/examples/Messages/MessageWithCustomResponseActions.tsx +1 -0
  24. package/patternfly-docs/content/extensions/chatbot/examples/Messages/Messages.md +17 -0
  25. package/patternfly-docs/content/extensions/chatbot/examples/demos/ChatbotAttachment.tsx +19 -1
  26. package/patternfly-docs/content/extensions/chatbot/examples/demos/ChatbotAttachmentMenu.tsx +1 -0
  27. package/src/FileDropZone/FileDropZone.test.tsx +83 -0
  28. package/src/FileDropZone/FileDropZone.tsx +32 -2
  29. package/src/MessageBar/AttachButton.test.tsx +75 -0
  30. package/src/MessageBar/AttachButton.tsx +35 -2
  31. package/src/MessageBar/MessageBar.tsx +47 -7
  32. package/src/ResponseActions/ResponseActions.test.tsx +98 -1
  33. package/src/ResponseActions/ResponseActions.tsx +31 -2
@@ -86,4 +86,58 @@ describe('Attach button', () => {
86
86
  yield userEvent.upload(input, file);
87
87
  expect(onAttachAccepted).not.toHaveBeenCalled();
88
88
  }));
89
+ it('should respect minSize restriction', () => __awaiter(void 0, void 0, void 0, function* () {
90
+ const onAttachRejected = jest.fn();
91
+ render(_jsx(AttachButton, { inputTestId: "input", minSize: 1000, onAttachRejected: onAttachRejected }));
92
+ const file = new File(['Test'], 'example.txt', { type: 'text/plain' });
93
+ const input = screen.getByTestId('input');
94
+ yield userEvent.upload(input, file);
95
+ expect(onAttachRejected).toHaveBeenCalled();
96
+ }));
97
+ it('should respect maxSize restriction', () => __awaiter(void 0, void 0, void 0, function* () {
98
+ const onAttachRejected = jest.fn();
99
+ render(_jsx(AttachButton, { inputTestId: "input", maxSize: 100, onAttachRejected: onAttachRejected }));
100
+ const largeContent = 'x'.repeat(200);
101
+ const file = new File([largeContent], 'example.txt', { type: 'text/plain' });
102
+ const input = screen.getByTestId('input');
103
+ yield userEvent.upload(input, file);
104
+ expect(onAttachRejected).toHaveBeenCalled();
105
+ }));
106
+ it('should respect maxFiles restriction', () => __awaiter(void 0, void 0, void 0, function* () {
107
+ const onAttachRejected = jest.fn();
108
+ render(_jsx(AttachButton, { inputTestId: "input", maxFiles: 1, onAttachRejected: onAttachRejected }));
109
+ const files = [
110
+ new File(['Test1'], 'example1.txt', { type: 'text/plain' }),
111
+ new File(['Test2'], 'example2.txt', { type: 'text/plain' })
112
+ ];
113
+ const input = screen.getByTestId('input');
114
+ yield userEvent.upload(input, files);
115
+ expect(onAttachRejected).toHaveBeenCalled();
116
+ }));
117
+ it('should be disabled when isAttachmentDisabled is true', () => __awaiter(void 0, void 0, void 0, function* () {
118
+ const onFileDrop = jest.fn();
119
+ render(_jsx(AttachButton, { inputTestId: "input", isAttachmentDisabled: true }));
120
+ const file = new File(['Test'], 'example.text', { type: 'text/plain' });
121
+ const input = screen.getByTestId('input');
122
+ yield userEvent.upload(input, file);
123
+ expect(onFileDrop).not.toHaveBeenCalled();
124
+ }));
125
+ it('should call onAttach when files are attached', () => __awaiter(void 0, void 0, void 0, function* () {
126
+ const onAttach = jest.fn();
127
+ render(_jsx(AttachButton, { inputTestId: "input", onAttach: onAttach }));
128
+ const file = new File(['Test'], 'example.txt', { type: 'text/plain' });
129
+ const input = screen.getByTestId('input');
130
+ yield userEvent.upload(input, file);
131
+ expect(onAttach).toHaveBeenCalled();
132
+ }));
133
+ it('should use custom validator when provided', () => __awaiter(void 0, void 0, void 0, function* () {
134
+ const validator = jest.fn().mockReturnValue({ message: 'Custom error' });
135
+ const onAttachRejected = jest.fn();
136
+ render(_jsx(AttachButton, { inputTestId: "input", validator: validator, onAttachRejected: onAttachRejected }));
137
+ const file = new File(['Test'], 'example.txt', { type: 'text/plain' });
138
+ const input = screen.getByTestId('input');
139
+ yield userEvent.upload(input, file);
140
+ expect(validator).toHaveBeenCalledWith(file);
141
+ expect(onAttachRejected).toHaveBeenCalled();
142
+ }));
89
143
  });
@@ -1,5 +1,5 @@
1
1
  import type { FunctionComponent } from 'react';
2
- import { Accept } from 'react-dropzone/.';
2
+ import { Accept, DropzoneOptions, FileError, FileRejection } from 'react-dropzone/.';
3
3
  import { ButtonProps, DropEvent, TextAreaProps, TooltipProps } from '@patternfly/react-core';
4
4
  import { ChatbotDisplayMode } from '../Chatbot';
5
5
  export interface MessageBarWithAttachMenuProps {
@@ -43,6 +43,28 @@ export interface MessageBarProps extends Omit<TextAreaProps, 'innerRef'> {
43
43
  handleStopButton?: (event: React.MouseEvent<HTMLButtonElement>) => void;
44
44
  /** Callback function for when attach button is used to upload a file */
45
45
  handleAttach?: (data: File[], event: DropEvent) => void;
46
+ /** Specifies the file types accepted by the attachment upload component.
47
+ * Files that don't match the accepted types will be disabled in the file picker.
48
+ * For example,
49
+ * allowedFileTypes: { 'application/json': ['.json'], 'text/plain': ['.txt'] }
50
+ **/
51
+ allowedFileTypes?: Accept;
52
+ /** Minimum file size allowed */
53
+ minSize?: number;
54
+ /** Max file size allowed */
55
+ maxSize?: number;
56
+ /** Max number of files allowed */
57
+ maxFiles?: number;
58
+ /** Whether attachments are disabled */
59
+ isAttachmentDisabled?: boolean;
60
+ /** Callback when file(s) are attached */
61
+ onAttach?: <T extends File>(acceptedFiles: T[], fileRejections: FileRejection[], event: DropEvent) => void;
62
+ /** Callback function for AttachButton when an attachment fails */
63
+ onAttachRejected?: (fileRejections: FileRejection[], event: DropEvent) => void;
64
+ /** Validator for files; see https://react-dropzone.js.org/#!/Custom%20validation for more information */
65
+ validator?: <T extends File>(file: T) => FileError | readonly FileError[] | null;
66
+ /** Additional props passed to react-dropzone */
67
+ dropzoneProps?: DropzoneOptions;
46
68
  /** Props to enable a menu that opens when the Attach button is clicked, instead of the attachment window */
47
69
  attachMenuProps?: MessageBarWithAttachMenuProps;
48
70
  /** Flag to provide manual control over whether send button is disabled */
@@ -81,12 +103,6 @@ export interface MessageBarProps extends Omit<TextAreaProps, 'innerRef'> {
81
103
  displayMode?: ChatbotDisplayMode;
82
104
  /** Whether message bar is compact */
83
105
  isCompact?: boolean;
84
- /** Specifies the file types accepted by the attachment upload component.
85
- * Files that don't match the accepted types will be disabled in the file picker.
86
- * For example,
87
- * allowedFileTypes: { 'application/json': ['.json'], 'text/plain': ['.txt'] }
88
- **/
89
- allowedFileTypes?: Accept;
90
106
  /** Ref applied to message bar textarea, for use with focus or other custom behaviors */
91
107
  innerRef?: React.Ref<HTMLTextAreaElement>;
92
108
  }
@@ -20,7 +20,7 @@ import AttachMenu from '../AttachMenu';
20
20
  import StopButton from './StopButton';
21
21
  export const MessageBarBase = (_a) => {
22
22
  var _b;
23
- var { onSendMessage, className, alwayShowSendButton, placeholder = 'Send a message...', hasAttachButton = true, hasMicrophoneButton, listeningText = 'Listening', handleAttach, attachMenuProps, isSendButtonDisabled, handleStopButton, hasStopButton, buttonProps, onChange, displayMode, value, isCompact = false, allowedFileTypes, innerRef } = _a, props = __rest(_a, ["onSendMessage", "className", "alwayShowSendButton", "placeholder", "hasAttachButton", "hasMicrophoneButton", "listeningText", "handleAttach", "attachMenuProps", "isSendButtonDisabled", "handleStopButton", "hasStopButton", "buttonProps", "onChange", "displayMode", "value", "isCompact", "allowedFileTypes", "innerRef"]);
23
+ var { onSendMessage, className, alwayShowSendButton, placeholder = 'Send a message...', hasAttachButton = true, hasMicrophoneButton, listeningText = 'Listening', handleAttach, attachMenuProps, isSendButtonDisabled, handleStopButton, hasStopButton, buttonProps, onChange, displayMode, value, isCompact = false, allowedFileTypes, minSize, maxSize, maxFiles, isAttachmentDisabled, onAttach, onAttachRejected, validator, dropzoneProps, innerRef } = _a, props = __rest(_a, ["onSendMessage", "className", "alwayShowSendButton", "placeholder", "hasAttachButton", "hasMicrophoneButton", "listeningText", "handleAttach", "attachMenuProps", "isSendButtonDisabled", "handleStopButton", "hasStopButton", "buttonProps", "onChange", "displayMode", "value", "isCompact", "allowedFileTypes", "minSize", "maxSize", "maxFiles", "isAttachmentDisabled", "onAttach", "onAttachRejected", "validator", "dropzoneProps", "innerRef"]);
24
24
  // Text Input
25
25
  // --------------------------------------------------------------------------
26
26
  const [message, setMessage] = useState(value !== null && value !== void 0 ? value : '');
@@ -176,7 +176,7 @@ export const MessageBarBase = (_a) => {
176
176
  if (hasStopButton && handleStopButton) {
177
177
  return (_jsx(StopButton, Object.assign({ onClick: handleStopButton, tooltipContent: (_a = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.stop) === null || _a === void 0 ? void 0 : _a.tooltipContent, isCompact: isCompact, tooltipProps: (_b = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.stop) === null || _b === void 0 ? void 0 : _b.tooltipProps }, (_c = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.stop) === null || _c === void 0 ? void 0 : _c.props)));
178
178
  }
179
- return (_jsxs(_Fragment, { children: [attachMenuProps && (_jsx(AttachButton, Object.assign({ ref: attachButtonRef, onClick: handleAttachMenuToggle, isDisabled: isListeningMessage, tooltipContent: (_d = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _d === void 0 ? void 0 : _d.tooltipContent, isCompact: isCompact, tooltipProps: (_e = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _e === void 0 ? void 0 : _e.tooltipProps, allowedFileTypes: allowedFileTypes }, (_f = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _f === void 0 ? void 0 : _f.props))), !attachMenuProps && hasAttachButton && (_jsx(AttachButton, Object.assign({ onAttachAccepted: handleAttach, isDisabled: isListeningMessage, tooltipContent: (_g = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _g === void 0 ? void 0 : _g.tooltipContent, inputTestId: (_h = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _h === void 0 ? void 0 : _h.inputTestId, isCompact: isCompact, tooltipProps: (_j = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _j === void 0 ? void 0 : _j.tooltipProps, allowedFileTypes: allowedFileTypes }, (_k = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _k === void 0 ? void 0 : _k.props))), hasMicrophoneButton && (_jsx(MicrophoneButton, Object.assign({ isListening: isListeningMessage, onIsListeningChange: setIsListeningMessage, onSpeechRecognition: handleSpeechRecognition, tooltipContent: (_l = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.microphone) === null || _l === void 0 ? void 0 : _l.tooltipContent, language: (_m = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.microphone) === null || _m === void 0 ? void 0 : _m.language, isCompact: isCompact, tooltipProps: (_o = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.microphone) === null || _o === void 0 ? void 0 : _o.tooltipProps }, (_p = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.microphone) === null || _p === void 0 ? void 0 : _p.props))), (alwayShowSendButton || message) && (_jsx(SendButton, Object.assign({ value: message, onClick: () => handleSend(message), isDisabled: isSendButtonDisabled, tooltipContent: (_q = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.send) === null || _q === void 0 ? void 0 : _q.tooltipContent, isCompact: isCompact, tooltipProps: (_r = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.send) === null || _r === void 0 ? void 0 : _r.tooltipProps }, (_s = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.send) === null || _s === void 0 ? void 0 : _s.props)))] }));
179
+ return (_jsxs(_Fragment, { children: [attachMenuProps && (_jsx(AttachButton, Object.assign({ ref: attachButtonRef, onClick: handleAttachMenuToggle, isDisabled: isListeningMessage, tooltipContent: (_d = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _d === void 0 ? void 0 : _d.tooltipContent, isCompact: isCompact, tooltipProps: (_e = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _e === void 0 ? void 0 : _e.tooltipProps, allowedFileTypes: allowedFileTypes, minSize: minSize, maxSize: maxSize, maxFiles: maxFiles, isAttachmentDisabled: isAttachmentDisabled, onAttach: onAttach, onAttachRejected: onAttachRejected, validator: validator, dropzoneProps: dropzoneProps }, (_f = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _f === void 0 ? void 0 : _f.props))), !attachMenuProps && hasAttachButton && (_jsx(AttachButton, Object.assign({ onAttachAccepted: handleAttach, isDisabled: isListeningMessage, tooltipContent: (_g = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _g === void 0 ? void 0 : _g.tooltipContent, inputTestId: (_h = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _h === void 0 ? void 0 : _h.inputTestId, isCompact: isCompact, tooltipProps: (_j = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _j === void 0 ? void 0 : _j.tooltipProps, allowedFileTypes: allowedFileTypes, minSize: minSize, maxSize: maxSize, maxFiles: maxFiles, isAttachmentDisabled: isAttachmentDisabled, onAttach: onAttach, onAttachRejected: onAttachRejected, validator: validator, dropzoneProps: dropzoneProps }, (_k = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.attach) === null || _k === void 0 ? void 0 : _k.props))), hasMicrophoneButton && (_jsx(MicrophoneButton, Object.assign({ isListening: isListeningMessage, onIsListeningChange: setIsListeningMessage, onSpeechRecognition: handleSpeechRecognition, tooltipContent: (_l = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.microphone) === null || _l === void 0 ? void 0 : _l.tooltipContent, language: (_m = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.microphone) === null || _m === void 0 ? void 0 : _m.language, isCompact: isCompact, tooltipProps: (_o = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.microphone) === null || _o === void 0 ? void 0 : _o.tooltipProps }, (_p = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.microphone) === null || _p === void 0 ? void 0 : _p.props))), (alwayShowSendButton || message) && (_jsx(SendButton, Object.assign({ value: message, onClick: () => handleSend(message), isDisabled: isSendButtonDisabled, tooltipContent: (_q = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.send) === null || _q === void 0 ? void 0 : _q.tooltipContent, isCompact: isCompact, tooltipProps: (_r = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.send) === null || _r === void 0 ? void 0 : _r.tooltipProps }, (_s = buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.send) === null || _s === void 0 ? void 0 : _s.props)))] }));
180
180
  };
181
181
  const messageBarContents = (_jsxs(_Fragment, { children: [_jsx("div", { className: `pf-chatbot__message-bar-input ${isCompact ? 'pf-m-compact' : ''}`, children: _jsx(TextArea, Object.assign({ className: "pf-chatbot__message-textarea", value: message, onChange: handleChange, "aria-label": isListeningMessage ? listeningText : placeholder, placeholder: isListeningMessage ? listeningText : placeholder, ref: textareaRef, onKeyDown: handleKeyDown }, props)) }), _jsx("div", { className: "pf-chatbot__message-bar-actions", children: renderButtons() })] }));
182
182
  if (attachMenuProps) {
@@ -17,11 +17,35 @@ import ResponseActionButton from './ResponseActionButton';
17
17
  export const ResponseActions = ({ actions }) => {
18
18
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z;
19
19
  const [activeButton, setActiveButton] = useState();
20
+ const [clickStatePersisted, setClickStatePersisted] = useState(false);
21
+ useEffect(() => {
22
+ // Define the order of precedence for checking initial `isClicked`
23
+ const actionPrecedence = ['positive', 'negative', 'copy', 'share', 'download', 'listen'];
24
+ let initialActive;
25
+ // Check predefined actions first based on precedence
26
+ for (const actionName of actionPrecedence) {
27
+ const actionProp = actions[actionName];
28
+ if (actionProp === null || actionProp === void 0 ? void 0 : actionProp.isClicked) {
29
+ initialActive = actionName;
30
+ break;
31
+ }
32
+ }
33
+ // If no predefined action was initially clicked, check additionalActions
34
+ if (!initialActive) {
35
+ const clickedActionName = Object.keys(additionalActions).find((actionName) => { var _a; return !actionPrecedence.includes(actionName) && ((_a = additionalActions[actionName]) === null || _a === void 0 ? void 0 : _a.isClicked); });
36
+ initialActive = clickedActionName;
37
+ }
38
+ if (initialActive) {
39
+ // Click state is explicitly controlled by consumer.
40
+ setClickStatePersisted(true);
41
+ }
42
+ setActiveButton(initialActive);
43
+ }, [actions]);
20
44
  const { positive, negative, copy, share, download, listen } = actions, additionalActions = __rest(actions, ["positive", "negative", "copy", "share", "download", "listen"]);
21
45
  const responseActions = useRef(null);
22
46
  useEffect(() => {
23
47
  const handleClickOutside = (e) => {
24
- if (responseActions.current && !responseActions.current.contains(e.target)) {
48
+ if (responseActions.current && !responseActions.current.contains(e.target) && !clickStatePersisted) {
25
49
  setActiveButton(undefined);
26
50
  }
27
51
  };
@@ -29,8 +53,9 @@ export const ResponseActions = ({ actions }) => {
29
53
  return () => {
30
54
  window.removeEventListener('click', handleClickOutside);
31
55
  };
32
- }, []);
56
+ }, [clickStatePersisted]);
33
57
  const handleClick = (e, id, onClick) => {
58
+ setClickStatePersisted(false);
34
59
  setActiveButton(id);
35
60
  onClick && onClick(e);
36
61
  };
@@ -111,6 +111,66 @@ describe('ResponseActions', () => {
111
111
  expect(goodBtn).not.toHaveClass('pf-chatbot__button--response-action-clicked');
112
112
  expect(badBtn).not.toHaveClass('pf-chatbot__button--response-action-clicked');
113
113
  }));
114
+ it('should handle isClicked prop within group of buttons correctly', () => __awaiter(void 0, void 0, void 0, function* () {
115
+ render(_jsx(ResponseActions, { actions: {
116
+ positive: { 'data-testid': 'positive-btn', onClick: jest.fn(), isClicked: true },
117
+ negative: { 'data-testid': 'negative-btn', onClick: jest.fn() }
118
+ } }));
119
+ expect(screen.getByTestId('positive-btn')).toHaveClass('pf-chatbot__button--response-action-clicked');
120
+ expect(screen.getByTestId('negative-btn')).not.toHaveClass('pf-chatbot__button--response-action-clicked');
121
+ }));
122
+ it('should set "listen" button as active if its `isClicked` is true', () => __awaiter(void 0, void 0, void 0, function* () {
123
+ render(_jsx(ResponseActions, { actions: {
124
+ positive: { 'data-testid': 'positive-btn', onClick: jest.fn(), isClicked: false },
125
+ negative: { 'data-testid': 'negative-btn', onClick: jest.fn(), isClicked: false },
126
+ listen: { 'data-testid': 'listen-btn', onClick: jest.fn(), isClicked: true }
127
+ } }));
128
+ expect(screen.getByTestId('listen-btn')).toHaveClass('pf-chatbot__button--response-action-clicked');
129
+ expect(screen.getByTestId('positive-btn')).not.toHaveClass('pf-chatbot__button--response-action-clicked');
130
+ expect(screen.getByTestId('negative-btn')).not.toHaveClass('pf-chatbot__button--response-action-clicked');
131
+ }));
132
+ it('should prioritize "positive" when both "positive" and "negative" are set to clicked', () => __awaiter(void 0, void 0, void 0, function* () {
133
+ render(_jsx(ResponseActions, { actions: {
134
+ positive: { 'data-testid': 'positive-btn', onClick: jest.fn(), isClicked: true },
135
+ negative: { 'data-testid': 'negative-btn', onClick: jest.fn(), isClicked: true }
136
+ } }));
137
+ // Positive button should take precendence
138
+ expect(screen.getByTestId('positive-btn')).toHaveClass('pf-chatbot__button--response-action-clicked');
139
+ expect(screen.getByTestId('negative-btn')).not.toHaveClass('pf-chatbot__button--response-action-clicked');
140
+ }));
141
+ it('should set an additional action button as active if it is initially clicked and no predefined are clicked', () => __awaiter(void 0, void 0, void 0, function* () {
142
+ const [additionalActions] = CUSTOM_ACTIONS;
143
+ const customActions = Object.assign({ positive: { 'data-testid': 'positive', onClick: jest.fn(), isClicked: false }, negative: { 'data-testid': 'negative', onClick: jest.fn(), isClicked: false } }, Object.keys(additionalActions).reduce((acc, actionKey) => {
144
+ acc[actionKey] = Object.assign(Object.assign({}, additionalActions[actionKey]), { 'data-testid': actionKey, isClicked: actionKey === 'regenerate' });
145
+ return acc;
146
+ }, {}));
147
+ render(_jsx(ResponseActions, { actions: customActions }));
148
+ Object.keys(customActions).forEach((actionKey) => {
149
+ if (actionKey === 'regenerate') {
150
+ expect(screen.getByTestId(actionKey)).toHaveClass('pf-chatbot__button--response-action-clicked');
151
+ }
152
+ else {
153
+ // Other actions should not have clicked class
154
+ expect(screen.getByTestId(actionKey)).not.toHaveClass('pf-chatbot__button--response-action-clicked');
155
+ }
156
+ });
157
+ }));
158
+ it('should activate the clicked button and deactivate any previously active button', () => __awaiter(void 0, void 0, void 0, function* () {
159
+ const actions = {
160
+ positive: { 'data-testid': 'positive', onClick: jest.fn(), isClicked: false },
161
+ negative: { 'data-testid': 'negative', onClick: jest.fn(), isClicked: true }
162
+ };
163
+ render(_jsx(ResponseActions, { actions: actions }));
164
+ const negativeBtn = screen.getByTestId('negative');
165
+ const positiveBtn = screen.getByTestId('positive');
166
+ // negative button is initially clicked
167
+ expect(negativeBtn).toHaveClass('pf-chatbot__button--response-action-clicked');
168
+ expect(positiveBtn).not.toHaveClass('pf-chatbot__button--response-action-clicked');
169
+ yield userEvent.click(positiveBtn);
170
+ // positive button should now have the clicked class
171
+ expect(positiveBtn).toHaveClass('pf-chatbot__button--response-action-clicked');
172
+ expect(negativeBtn).not.toHaveClass('pf-chatbot__button--response-action-clicked');
173
+ }));
114
174
  it('should render buttons correctly', () => {
115
175
  ALL_ACTIONS.forEach(({ type, label }) => {
116
176
  render(_jsx(ResponseActions, { actions: { [type]: { onClick: jest.fn() } } }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@patternfly/chatbot",
3
- "version": "6.3.0-prerelease.22",
3
+ "version": "6.3.0-prerelease.24",
4
4
  "description": "This library provides React components based on PatternFly 6 that can be used to build chatbots.",
5
5
  "main": "dist/cjs/index.js",
6
6
  "module": "dist/esm/index.js",
@@ -0,0 +1,25 @@
1
+ import { FunctionComponent } from 'react';
2
+
3
+ import Message from '@patternfly/chatbot/dist/dynamic/Message';
4
+ import patternflyAvatar from './patternfly_avatar.jpg';
5
+
6
+ export const ResponseActionClickedExample: FunctionComponent = () => (
7
+ <Message
8
+ name="Bot"
9
+ role="bot"
10
+ avatar={patternflyAvatar}
11
+ content="I updated your account with those settings. You're ready to set up your first dashboard!"
12
+ actions={{
13
+ // eslint-disable-next-line no-console
14
+ positive: { onClick: () => console.log('Good response'), isClicked: true },
15
+ // eslint-disable-next-line no-console
16
+ negative: { onClick: () => console.log('Bad response') },
17
+ // eslint-disable-next-line no-console
18
+ copy: { onClick: () => console.log('Copy') },
19
+ // eslint-disable-next-line no-console
20
+ download: { onClick: () => console.log('Download') },
21
+ // eslint-disable-next-line no-console
22
+ listen: { onClick: () => console.log('Listen') }
23
+ }}
24
+ />
25
+ );
@@ -15,6 +15,7 @@ export const CustomActionExample: FunctionComponent = () => (
15
15
  regenerate: {
16
16
  ariaLabel: 'Regenerate',
17
17
  clickedAriaLabel: 'Regenerated',
18
+ isClicked: true,
18
19
  // eslint-disable-next-line no-console
19
20
  onClick: () => console.log('Clicked regenerate'),
20
21
  tooltipContent: 'Regenerate',
@@ -79,6 +79,22 @@ You can add actions to a message, to allow users to interact with the message co
79
79
 
80
80
  ```
81
81
 
82
+ ### Message actions clicked state
83
+
84
+ You can apply a clicked state to message actions, to convey that the action has previously been selected.
85
+
86
+ To define which message response action should show a clicked state when the `<ResponseActions>` component first renders, use the `isClicked` boolean property within each action's configuration object.
87
+
88
+ To make an action button appear active by default, set `isClicked: true`. Only 1 action can be visually active at any given time.
89
+
90
+ If you unintentionally set `isClicked: true` for multiple buttons, the component will apply a predefined internal precedence order to resolve the conflict. The button encountered first in this order will be displayed as clicked, while other buttons will sustain their default appearance. The default precedence of button actions is: "positive", "negative", "copy", "share", "listen", followed by any other custom actions (in object key order).
91
+
92
+ Once the component has rendered, user interactions will take precedence over the initial `isClicked` prop. Clicking a button will activate it and deactivate any other active button. The `isDisabled` prop for each action button specifies if a button is interactive or not.
93
+
94
+ ```js file="./MessageWithClickedResponseActions.tsx"
95
+
96
+ ```
97
+
82
98
  ### Custom message actions
83
99
 
84
100
  Beyond the standard message actions (good response, bad response, copy, share, or listen), you can add custom actions to a bot message by passing an `actions` object to the `<Message>` component. This object can contain the following customizations:
@@ -86,6 +102,7 @@ Beyond the standard message actions (good response, bad response, copy, share, o
86
102
  - `ariaLabel`
87
103
  - `onClick`
88
104
  - `className`
105
+ - `isClicked`
89
106
  - `isDisabled`
90
107
  - `tooltipContent`
91
108
  - `tooltipContent`
@@ -138,10 +138,17 @@ export const BasicDemo: FunctionComponent = () => {
138
138
  }, 1000);
139
139
  })
140
140
  .catch((error: DOMException) => {
141
+ setShowAlert(true);
141
142
  setError(`Failed to read file: ${error.message}`);
142
143
  });
143
144
  };
144
145
 
146
+ const handleAttachRejected = () => {
147
+ setFile(undefined);
148
+ setShowAlert(true);
149
+ setError('This demo only supports file extensions .txt, .json, .yaml, and .yaml. Please try a different file.');
150
+ };
151
+
145
152
  const handleFileDrop = (event: DropEvent, data: File[]) => {
146
153
  handleFile(data);
147
154
  };
@@ -227,6 +234,7 @@ export const BasicDemo: FunctionComponent = () => {
227
234
  'application/json': ['.json'],
228
235
  'application/yaml': ['.yaml', '.yml']
229
236
  }}
237
+ onAttachRejected={handleAttachRejected}
230
238
  >
231
239
  <ChatbotContent>
232
240
  <MessageBox>
@@ -254,7 +262,17 @@ export const BasicDemo: FunctionComponent = () => {
254
262
  <FileDetailsLabel fileName={file.name} isLoading={isLoadingFile} onClose={onClose} />
255
263
  </div>
256
264
  )}
257
- <MessageBar onSendMessage={handleSend} hasAttachButton handleAttach={handleAttach} />
265
+ <MessageBar
266
+ onSendMessage={handleSend}
267
+ hasAttachButton
268
+ handleAttach={handleAttach}
269
+ allowedFileTypes={{
270
+ 'text/plain': ['.txt'],
271
+ 'application/json': ['.json'],
272
+ 'application/yaml': ['.yaml', '.yml']
273
+ }}
274
+ onAttachRejected={handleAttachRejected}
275
+ />
258
276
  <ChatbotFootnote label="ChatBot uses AI. Check for mistakes." />
259
277
  </ChatbotFooter>
260
278
  </FileDropZone>
@@ -127,6 +127,7 @@ export const AttachmentMenuDemo: FunctionComponent = () => {
127
127
  // Attachments
128
128
  // --------------------------------------------------------------------------
129
129
  const handleFileDrop = (event: DropEvent, data: File[]) => {
130
+ setIsOpen(false);
130
131
  setFile(data[0]);
131
132
  setIsLoadingFile(true);
132
133
  setTimeout(() => {
@@ -40,4 +40,87 @@ describe('FileDropZone', () => {
40
40
 
41
41
  expect(onFileDrop).not.toHaveBeenCalled();
42
42
  });
43
+
44
+ it('should respect minSize restriction', async () => {
45
+ const onAttachRejected = jest.fn();
46
+ const { container } = render(
47
+ <FileDropZone onFileDrop={jest.fn()} minSize={1000} onAttachRejected={onAttachRejected} />
48
+ );
49
+
50
+ const file = new File(['Test'], 'example.txt', { type: 'text/plain' });
51
+ const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
52
+
53
+ await userEvent.upload(fileInput, file);
54
+
55
+ expect(onAttachRejected).toHaveBeenCalled();
56
+ });
57
+ it('should respect maxSize restriction', async () => {
58
+ const onAttachRejected = jest.fn();
59
+ const { container } = render(
60
+ <FileDropZone onFileDrop={jest.fn()} maxSize={100} onAttachRejected={onAttachRejected} />
61
+ );
62
+
63
+ const largeContent = 'x'.repeat(200);
64
+ const file = new File([largeContent], 'example.txt', { type: 'text/plain' });
65
+ const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
66
+
67
+ await userEvent.upload(fileInput, file);
68
+
69
+ expect(onAttachRejected).toHaveBeenCalled();
70
+ });
71
+
72
+ it('should respect maxFiles restriction', async () => {
73
+ const onAttachRejected = jest.fn();
74
+ const { container } = render(
75
+ <FileDropZone onFileDrop={jest.fn()} maxFiles={1} onAttachRejected={onAttachRejected} />
76
+ );
77
+
78
+ const files = [
79
+ new File(['Test1'], 'example1.txt', { type: 'text/plain' }),
80
+ new File(['Test2'], 'example2.txt', { type: 'text/plain' })
81
+ ];
82
+ const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
83
+
84
+ await userEvent.upload(fileInput, files);
85
+
86
+ expect(onAttachRejected).toHaveBeenCalled();
87
+ });
88
+
89
+ it('should be disabled when isAttachmentDisabled is true', async () => {
90
+ const onFileDrop = jest.fn();
91
+ const { container } = render(<FileDropZone onFileDrop={onFileDrop} isAttachmentDisabled={true} />);
92
+
93
+ const file = new File(['Test'], 'example.text', { type: 'text/plain' });
94
+ const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
95
+ await userEvent.upload(fileInput, file);
96
+
97
+ expect(onFileDrop).not.toHaveBeenCalled();
98
+ });
99
+
100
+ it('should call onAttach when files are attached', async () => {
101
+ const onAttach = jest.fn();
102
+ const { container } = render(<FileDropZone onFileDrop={jest.fn()} onAttach={onAttach} />);
103
+
104
+ const file = new File(['Test'], 'example.txt', { type: 'text/plain' });
105
+ const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
106
+
107
+ await userEvent.upload(fileInput, file);
108
+
109
+ expect(onAttach).toHaveBeenCalled();
110
+ });
111
+ it('should use custom validator when provided', async () => {
112
+ const validator = jest.fn().mockReturnValue({ message: 'Custom error' });
113
+ const onAttachRejected = jest.fn();
114
+ const onFileDrop = jest.fn();
115
+ const { container } = render(
116
+ <FileDropZone onFileDrop={onFileDrop} validator={validator} onAttachRejected={onAttachRejected} />
117
+ );
118
+
119
+ const file = new File(['Test'], 'example.txt', { type: 'text/plain' });
120
+ const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
121
+ await userEvent.upload(fileInput, file);
122
+
123
+ expect(validator).toHaveBeenCalledWith(file);
124
+ expect(onAttachRejected).toHaveBeenCalled();
125
+ });
43
126
  });
@@ -3,7 +3,7 @@ import type { FunctionComponent } from 'react';
3
3
  import { useState } from 'react';
4
4
  import { ChatbotDisplayMode } from '../Chatbot';
5
5
  import { UploadIcon } from '@patternfly/react-icons';
6
- import { Accept } from 'react-dropzone/.';
6
+ import { Accept, FileError, FileRejection } from 'react-dropzone/.';
7
7
 
8
8
  export interface FileDropZoneProps {
9
9
  /** Content displayed when the drop zone is not currently in use */
@@ -22,6 +22,20 @@ export interface FileDropZoneProps {
22
22
  allowedFileTypes?: Accept;
23
23
  /** Display mode for the Chatbot parent; this influences the styles applied */
24
24
  displayMode?: ChatbotDisplayMode;
25
+ /** Minimum file size allowed */
26
+ minSize?: number;
27
+ /** Max file size allowed */
28
+ maxSize?: number;
29
+ /** Max number of files allowed */
30
+ maxFiles?: number;
31
+ /** Whether attachments are disabled */
32
+ isAttachmentDisabled?: boolean;
33
+ /** Callback when file(s) are attached */
34
+ onAttach?: <T extends File>(acceptedFiles: T[], fileRejections: FileRejection[], event: DropEvent) => void;
35
+ /** Callback function for AttachButton when an attachment fails */
36
+ onAttachRejected?: (fileRejections: FileRejection[], event: DropEvent) => void;
37
+ /** Validator for files; see https://react-dropzone.js.org/#!/Custom%20validation for more information */
38
+ validator?: <T extends File>(file: T) => FileError | readonly FileError[] | null;
25
39
  }
26
40
 
27
41
  const FileDropZone: FunctionComponent<FileDropZoneProps> = ({
@@ -30,6 +44,13 @@ const FileDropZone: FunctionComponent<FileDropZoneProps> = ({
30
44
  infoText = 'Maximum file size is 25 MB',
31
45
  onFileDrop,
32
46
  allowedFileTypes,
47
+ minSize,
48
+ maxSize,
49
+ maxFiles,
50
+ isAttachmentDisabled,
51
+ onAttach,
52
+ onAttachRejected,
53
+ validator,
33
54
  displayMode = ChatbotDisplayMode.default,
34
55
  ...props
35
56
  }: FileDropZoneProps) => {
@@ -50,7 +71,16 @@ const FileDropZone: FunctionComponent<FileDropZoneProps> = ({
50
71
  <MultipleFileUpload
51
72
  dropzoneProps={{
52
73
  accept: allowedFileTypes,
53
- onDrop: () => setShowDropZone(false),
74
+ onDrop: (acceptedFiles, fileRejections: FileRejection[], event: DropEvent) => {
75
+ setShowDropZone(false);
76
+ onAttach && onAttach(acceptedFiles, fileRejections, event);
77
+ },
78
+ minSize,
79
+ maxSize,
80
+ maxFiles,
81
+ disabled: isAttachmentDisabled,
82
+ onDropRejected: onAttachRejected,
83
+ validator,
54
84
  ...props
55
85
  }}
56
86
  onDragEnter={() => setShowDropZone(true)}
@@ -98,4 +98,79 @@ describe('Attach button', () => {
98
98
 
99
99
  expect(onAttachAccepted).not.toHaveBeenCalled();
100
100
  });
101
+
102
+ it('should respect minSize restriction', async () => {
103
+ const onAttachRejected = jest.fn();
104
+ render(<AttachButton inputTestId="input" minSize={1000} onAttachRejected={onAttachRejected} />);
105
+
106
+ const file = new File(['Test'], 'example.txt', { type: 'text/plain' });
107
+ const input = screen.getByTestId('input');
108
+
109
+ await userEvent.upload(input, file);
110
+
111
+ expect(onAttachRejected).toHaveBeenCalled();
112
+ });
113
+
114
+ it('should respect maxSize restriction', async () => {
115
+ const onAttachRejected = jest.fn();
116
+ render(<AttachButton inputTestId="input" maxSize={100} onAttachRejected={onAttachRejected} />);
117
+
118
+ const largeContent = 'x'.repeat(200);
119
+ const file = new File([largeContent], 'example.txt', { type: 'text/plain' });
120
+ const input = screen.getByTestId('input');
121
+
122
+ await userEvent.upload(input, file);
123
+
124
+ expect(onAttachRejected).toHaveBeenCalled();
125
+ });
126
+
127
+ it('should respect maxFiles restriction', async () => {
128
+ const onAttachRejected = jest.fn();
129
+ render(<AttachButton inputTestId="input" maxFiles={1} onAttachRejected={onAttachRejected} />);
130
+
131
+ const files = [
132
+ new File(['Test1'], 'example1.txt', { type: 'text/plain' }),
133
+ new File(['Test2'], 'example2.txt', { type: 'text/plain' })
134
+ ];
135
+
136
+ const input = screen.getByTestId('input');
137
+ await userEvent.upload(input, files);
138
+
139
+ expect(onAttachRejected).toHaveBeenCalled();
140
+ });
141
+
142
+ it('should be disabled when isAttachmentDisabled is true', async () => {
143
+ const onFileDrop = jest.fn();
144
+ render(<AttachButton inputTestId="input" isAttachmentDisabled={true} />);
145
+
146
+ const file = new File(['Test'], 'example.text', { type: 'text/plain' });
147
+ const input = screen.getByTestId('input');
148
+ await userEvent.upload(input, file);
149
+
150
+ expect(onFileDrop).not.toHaveBeenCalled();
151
+ });
152
+
153
+ it('should call onAttach when files are attached', async () => {
154
+ const onAttach = jest.fn();
155
+ render(<AttachButton inputTestId="input" onAttach={onAttach} />);
156
+
157
+ const file = new File(['Test'], 'example.txt', { type: 'text/plain' });
158
+ const input = screen.getByTestId('input');
159
+
160
+ await userEvent.upload(input, file);
161
+
162
+ expect(onAttach).toHaveBeenCalled();
163
+ });
164
+ it('should use custom validator when provided', async () => {
165
+ const validator = jest.fn().mockReturnValue({ message: 'Custom error' });
166
+ const onAttachRejected = jest.fn();
167
+ render(<AttachButton inputTestId="input" validator={validator} onAttachRejected={onAttachRejected} />);
168
+
169
+ const file = new File(['Test'], 'example.txt', { type: 'text/plain' });
170
+ const input = screen.getByTestId('input');
171
+ await userEvent.upload(input, file);
172
+
173
+ expect(validator).toHaveBeenCalledWith(file);
174
+ expect(onAttachRejected).toHaveBeenCalled();
175
+ });
101
176
  });