CommentView.tsx 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { css } from '@emotion/css';
  2. import React, { FormEvent, useLayoutEffect, useRef, useState } from 'react';
  3. import { GrafanaTheme2 } from '@grafana/data';
  4. import { CustomScrollbar, TextArea, useStyles2 } from '@grafana/ui';
  5. import { Comment } from './Comment';
  6. import { Message } from './types';
  7. type Props = {
  8. comments: Message[];
  9. packetCounter: number;
  10. addComment: (comment: string) => Promise<boolean>;
  11. };
  12. export const CommentView = ({ comments, packetCounter, addComment }: Props) => {
  13. const styles = useStyles2(getStyles);
  14. const [comment, setComment] = useState('');
  15. const [scrollTop, setScrollTop] = useState(0);
  16. const commentViewContainer = useRef<HTMLDivElement>(null);
  17. useLayoutEffect(() => {
  18. if (commentViewContainer.current) {
  19. setScrollTop(commentViewContainer.current.offsetHeight);
  20. } else {
  21. setScrollTop(0);
  22. }
  23. }, [packetCounter]);
  24. const onUpdateComment = (event: FormEvent<HTMLTextAreaElement>) => {
  25. const element = event.target as HTMLInputElement;
  26. setComment(element.value);
  27. };
  28. const onKeyPress = async (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
  29. if (event?.key === 'Enter' && !event?.shiftKey) {
  30. event.preventDefault();
  31. if (comment.length > 0) {
  32. const result = await addComment(comment);
  33. if (result) {
  34. setComment('');
  35. }
  36. }
  37. }
  38. };
  39. return (
  40. <CustomScrollbar scrollTop={scrollTop}>
  41. <div ref={commentViewContainer} className={styles.commentViewContainer}>
  42. {comments.map((msg) => (
  43. <Comment key={msg.id} message={msg} />
  44. ))}
  45. <TextArea
  46. placeholder="Write a comment"
  47. value={comment}
  48. onChange={onUpdateComment}
  49. onKeyPress={onKeyPress}
  50. autoFocus={true}
  51. />
  52. </div>
  53. </CustomScrollbar>
  54. );
  55. };
  56. const getStyles = (theme: GrafanaTheme2) => ({
  57. commentViewContainer: css`
  58. margin: 5px;
  59. `,
  60. });