@mitodl/smoot-design 0.0.0-preview215f7ae3fa

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 (190) hide show
  1. package/LICENSE +28 -0
  2. package/README.md +27 -0
  3. package/dist/bundles/aiChat.es.js +24812 -0
  4. package/dist/bundles/aiChat.umd.js +161 -0
  5. package/dist/cjs/ai.d.ts +2 -0
  6. package/dist/cjs/ai.js +5 -0
  7. package/dist/cjs/bundles/aiChat.d.ts +6 -0
  8. package/dist/cjs/bundles/aiChat.js +13 -0
  9. package/dist/cjs/components/AiChat/AiChat.d.ts +5 -0
  10. package/dist/cjs/components/AiChat/AiChat.js +150 -0
  11. package/dist/cjs/components/AiChat/AiChat.stories.d.ts +11 -0
  12. package/dist/cjs/components/AiChat/AiChat.stories.js +76 -0
  13. package/dist/cjs/components/AiChat/AiChat.test.d.ts +1 -0
  14. package/dist/cjs/components/AiChat/AiChat.test.js +130 -0
  15. package/dist/cjs/components/AiChat/story-utils.d.ts +3 -0
  16. package/dist/cjs/components/AiChat/story-utils.js +100 -0
  17. package/dist/cjs/components/AiChat/types.d.ts +45 -0
  18. package/dist/cjs/components/AiChat/types.js +3 -0
  19. package/dist/cjs/components/AiChat/utils.d.ts +9 -0
  20. package/dist/cjs/components/AiChat/utils.js +31 -0
  21. package/dist/cjs/components/Button/ActionButton.d.ts +30 -0
  22. package/dist/cjs/components/Button/ActionButton.js +73 -0
  23. package/dist/cjs/components/Button/ActionButton.stories.d.ts +15 -0
  24. package/dist/cjs/components/Button/ActionButton.stories.js +116 -0
  25. package/dist/cjs/components/Button/Button.d.ts +56 -0
  26. package/dist/cjs/components/Button/Button.js +273 -0
  27. package/dist/cjs/components/Button/Button.stories.d.ts +17 -0
  28. package/dist/cjs/components/Button/Button.stories.js +138 -0
  29. package/dist/cjs/components/Button/Button.test.d.ts +1 -0
  30. package/dist/cjs/components/Button/Button.test.js +46 -0
  31. package/dist/cjs/components/Input/Input.d.ts +115 -0
  32. package/dist/cjs/components/Input/Input.js +219 -0
  33. package/dist/cjs/components/Input/Input.stories.d.ts +19 -0
  34. package/dist/cjs/components/Input/Input.stories.js +134 -0
  35. package/dist/cjs/components/Input/Input.test.d.ts +1 -0
  36. package/dist/cjs/components/Input/Input.test.js +32 -0
  37. package/dist/cjs/components/LinkAdapter/LinkAdapter.d.ts +23 -0
  38. package/dist/cjs/components/LinkAdapter/LinkAdapter.js +34 -0
  39. package/dist/cjs/components/ScrollSnap/ScrollSnap.d.ts +19 -0
  40. package/dist/cjs/components/ScrollSnap/ScrollSnap.js +59 -0
  41. package/dist/cjs/components/ScrollSnap/ScrollSnap.stories.d.ts +6 -0
  42. package/dist/cjs/components/ScrollSnap/ScrollSnap.stories.js +43 -0
  43. package/dist/cjs/components/SrAnnouncer/SrAnnouncer.d.ts +25 -0
  44. package/dist/cjs/components/SrAnnouncer/SrAnnouncer.js +43 -0
  45. package/dist/cjs/components/SrAnnouncer/SrAnnouncer.stories.d.ts +6 -0
  46. package/dist/cjs/components/SrAnnouncer/SrAnnouncer.stories.js +44 -0
  47. package/dist/cjs/components/SrAnnouncer/SrAnnouncer.test.d.ts +1 -0
  48. package/dist/cjs/components/SrAnnouncer/SrAnnouncer.test.js +62 -0
  49. package/dist/cjs/components/TextField/TextField.d.ts +29 -0
  50. package/dist/cjs/components/TextField/TextField.js +33 -0
  51. package/dist/cjs/components/TextField/TextField.stories.d.ts +10 -0
  52. package/dist/cjs/components/TextField/TextField.stories.js +135 -0
  53. package/dist/cjs/components/TextField/TextField.test.d.ts +1 -0
  54. package/dist/cjs/components/TextField/TextField.test.js +77 -0
  55. package/dist/cjs/components/ThemeProvider/ThemeProvider.d.ts +23 -0
  56. package/dist/cjs/components/ThemeProvider/ThemeProvider.js +90 -0
  57. package/dist/cjs/components/ThemeProvider/ThemeProvider.stories.d.ts +58 -0
  58. package/dist/cjs/components/ThemeProvider/ThemeProvider.stories.js +97 -0
  59. package/dist/cjs/components/ThemeProvider/Typography.stories.d.ts +39 -0
  60. package/dist/cjs/components/ThemeProvider/Typography.stories.js +65 -0
  61. package/dist/cjs/components/ThemeProvider/breakpoints.d.ts +4 -0
  62. package/dist/cjs/components/ThemeProvider/breakpoints.js +20 -0
  63. package/dist/cjs/components/ThemeProvider/buttons.d.ts +7 -0
  64. package/dist/cjs/components/ThemeProvider/buttons.js +20 -0
  65. package/dist/cjs/components/ThemeProvider/chips.d.ts +3 -0
  66. package/dist/cjs/components/ThemeProvider/chips.js +154 -0
  67. package/dist/cjs/components/ThemeProvider/colors.d.ts +32 -0
  68. package/dist/cjs/components/ThemeProvider/colors.js +35 -0
  69. package/dist/cjs/components/ThemeProvider/typography.d.ts +18 -0
  70. package/dist/cjs/components/ThemeProvider/typography.js +174 -0
  71. package/dist/cjs/components/VisuallyHidden/VisuallyHidden.d.ts +24 -0
  72. package/dist/cjs/components/VisuallyHidden/VisuallyHidden.js +33 -0
  73. package/dist/cjs/components/VisuallyHidden/VisuallyHidden.stories.d.ts +6 -0
  74. package/dist/cjs/components/VisuallyHidden/VisuallyHidden.stories.js +13 -0
  75. package/dist/cjs/components/internal/FormHelpers/FormHelpers.d.ts +39 -0
  76. package/dist/cjs/components/internal/FormHelpers/FormHelpers.js +78 -0
  77. package/dist/cjs/components/internal/FormHelpers/FormHelpers.test.d.ts +1 -0
  78. package/dist/cjs/components/internal/FormHelpers/FormHelpers.test.js +93 -0
  79. package/dist/cjs/index.d.ts +16 -0
  80. package/dist/cjs/index.js +28 -0
  81. package/dist/cjs/jest-setup.d.ts +1 -0
  82. package/dist/cjs/jest-setup.js +18 -0
  83. package/dist/cjs/jsdom-extended.d.ts +6 -0
  84. package/dist/cjs/jsdom-extended.js +14 -0
  85. package/dist/cjs/story-utils/index.d.ts +6 -0
  86. package/dist/cjs/story-utils/index.js +17 -0
  87. package/dist/cjs/utils/composeRefs.d.ts +7 -0
  88. package/dist/cjs/utils/composeRefs.js +20 -0
  89. package/dist/cjs/utils/composeRefs.test.d.ts +1 -0
  90. package/dist/cjs/utils/composeRefs.test.js +19 -0
  91. package/dist/cjs/utils/useDevCheckStable.d.ts +8 -0
  92. package/dist/cjs/utils/useDevCheckStable.js +29 -0
  93. package/dist/cjs/utils/useInterval.d.ts +7 -0
  94. package/dist/cjs/utils/useInterval.js +25 -0
  95. package/dist/esm/ai.d.ts +2 -0
  96. package/dist/esm/ai.js +1 -0
  97. package/dist/esm/bundles/aiChat.d.ts +6 -0
  98. package/dist/esm/bundles/aiChat.js +10 -0
  99. package/dist/esm/components/AiChat/AiChat.d.ts +5 -0
  100. package/dist/esm/components/AiChat/AiChat.js +147 -0
  101. package/dist/esm/components/AiChat/AiChat.stories.d.ts +11 -0
  102. package/dist/esm/components/AiChat/AiChat.stories.js +73 -0
  103. package/dist/esm/components/AiChat/AiChat.test.d.ts +1 -0
  104. package/dist/esm/components/AiChat/AiChat.test.js +128 -0
  105. package/dist/esm/components/AiChat/story-utils.d.ts +3 -0
  106. package/dist/esm/components/AiChat/story-utils.js +96 -0
  107. package/dist/esm/components/AiChat/types.d.ts +45 -0
  108. package/dist/esm/components/AiChat/types.js +2 -0
  109. package/dist/esm/components/AiChat/utils.d.ts +9 -0
  110. package/dist/esm/components/AiChat/utils.js +28 -0
  111. package/dist/esm/components/Button/ActionButton.d.ts +30 -0
  112. package/dist/esm/components/Button/ActionButton.js +68 -0
  113. package/dist/esm/components/Button/ActionButton.stories.d.ts +15 -0
  114. package/dist/esm/components/Button/ActionButton.stories.js +113 -0
  115. package/dist/esm/components/Button/Button.d.ts +56 -0
  116. package/dist/esm/components/Button/Button.js +265 -0
  117. package/dist/esm/components/Button/Button.stories.d.ts +17 -0
  118. package/dist/esm/components/Button/Button.stories.js +135 -0
  119. package/dist/esm/components/Button/Button.test.d.ts +1 -0
  120. package/dist/esm/components/Button/Button.test.js +44 -0
  121. package/dist/esm/components/Input/Input.d.ts +115 -0
  122. package/dist/esm/components/Input/Input.js +214 -0
  123. package/dist/esm/components/Input/Input.stories.d.ts +19 -0
  124. package/dist/esm/components/Input/Input.stories.js +131 -0
  125. package/dist/esm/components/Input/Input.test.d.ts +1 -0
  126. package/dist/esm/components/Input/Input.test.js +30 -0
  127. package/dist/esm/components/LinkAdapter/LinkAdapter.d.ts +23 -0
  128. package/dist/esm/components/LinkAdapter/LinkAdapter.js +31 -0
  129. package/dist/esm/components/ScrollSnap/ScrollSnap.d.ts +19 -0
  130. package/dist/esm/components/ScrollSnap/ScrollSnap.js +56 -0
  131. package/dist/esm/components/ScrollSnap/ScrollSnap.stories.d.ts +6 -0
  132. package/dist/esm/components/ScrollSnap/ScrollSnap.stories.js +40 -0
  133. package/dist/esm/components/SrAnnouncer/SrAnnouncer.d.ts +25 -0
  134. package/dist/esm/components/SrAnnouncer/SrAnnouncer.js +40 -0
  135. package/dist/esm/components/SrAnnouncer/SrAnnouncer.stories.d.ts +6 -0
  136. package/dist/esm/components/SrAnnouncer/SrAnnouncer.stories.js +41 -0
  137. package/dist/esm/components/SrAnnouncer/SrAnnouncer.test.d.ts +1 -0
  138. package/dist/esm/components/SrAnnouncer/SrAnnouncer.test.js +60 -0
  139. package/dist/esm/components/TextField/TextField.d.ts +29 -0
  140. package/dist/esm/components/TextField/TextField.js +30 -0
  141. package/dist/esm/components/TextField/TextField.stories.d.ts +10 -0
  142. package/dist/esm/components/TextField/TextField.stories.js +132 -0
  143. package/dist/esm/components/TextField/TextField.test.d.ts +1 -0
  144. package/dist/esm/components/TextField/TextField.test.js +75 -0
  145. package/dist/esm/components/ThemeProvider/ThemeProvider.d.ts +23 -0
  146. package/dist/esm/components/ThemeProvider/ThemeProvider.js +86 -0
  147. package/dist/esm/components/ThemeProvider/ThemeProvider.stories.d.ts +58 -0
  148. package/dist/esm/components/ThemeProvider/ThemeProvider.stories.js +94 -0
  149. package/dist/esm/components/ThemeProvider/Typography.stories.d.ts +39 -0
  150. package/dist/esm/components/ThemeProvider/Typography.stories.js +62 -0
  151. package/dist/esm/components/ThemeProvider/breakpoints.d.ts +4 -0
  152. package/dist/esm/components/ThemeProvider/breakpoints.js +16 -0
  153. package/dist/esm/components/ThemeProvider/buttons.d.ts +7 -0
  154. package/dist/esm/components/ThemeProvider/buttons.js +17 -0
  155. package/dist/esm/components/ThemeProvider/chips.d.ts +3 -0
  156. package/dist/esm/components/ThemeProvider/chips.js +151 -0
  157. package/dist/esm/components/ThemeProvider/colors.d.ts +32 -0
  158. package/dist/esm/components/ThemeProvider/colors.js +32 -0
  159. package/dist/esm/components/ThemeProvider/typography.d.ts +18 -0
  160. package/dist/esm/components/ThemeProvider/typography.js +168 -0
  161. package/dist/esm/components/VisuallyHidden/VisuallyHidden.d.ts +24 -0
  162. package/dist/esm/components/VisuallyHidden/VisuallyHidden.js +30 -0
  163. package/dist/esm/components/VisuallyHidden/VisuallyHidden.stories.d.ts +6 -0
  164. package/dist/esm/components/VisuallyHidden/VisuallyHidden.stories.js +10 -0
  165. package/dist/esm/components/internal/FormHelpers/FormHelpers.d.ts +39 -0
  166. package/dist/esm/components/internal/FormHelpers/FormHelpers.js +73 -0
  167. package/dist/esm/components/internal/FormHelpers/FormHelpers.test.d.ts +1 -0
  168. package/dist/esm/components/internal/FormHelpers/FormHelpers.test.js +91 -0
  169. package/dist/esm/index.d.ts +16 -0
  170. package/dist/esm/index.js +11 -0
  171. package/dist/esm/jest-setup.d.ts +1 -0
  172. package/dist/esm/jest-setup.js +16 -0
  173. package/dist/esm/jsdom-extended.d.ts +6 -0
  174. package/dist/esm/jsdom-extended.js +12 -0
  175. package/dist/esm/story-utils/index.d.ts +6 -0
  176. package/dist/esm/story-utils/index.js +13 -0
  177. package/dist/esm/utils/composeRefs.d.ts +7 -0
  178. package/dist/esm/utils/composeRefs.js +17 -0
  179. package/dist/esm/utils/composeRefs.test.d.ts +1 -0
  180. package/dist/esm/utils/composeRefs.test.js +17 -0
  181. package/dist/esm/utils/useDevCheckStable.d.ts +8 -0
  182. package/dist/esm/utils/useDevCheckStable.js +26 -0
  183. package/dist/esm/utils/useInterval.d.ts +7 -0
  184. package/dist/esm/utils/useInterval.js +22 -0
  185. package/dist/tsconfig.tsbuildinfo +1 -0
  186. package/dist/type-augmentation/TypescriptDocs.mdx +17 -0
  187. package/dist/type-augmentation/index.d.ts +2 -0
  188. package/dist/type-augmentation/theme.d.ts +103 -0
  189. package/dist/type-augmentation/typography.d.ts +54 -0
  190. package/package.json +141 -0
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.gitLink = exports.enumValues = void 0;
4
+ /**
5
+ * A type helper just to make sure an array contains union values.
6
+ */
7
+ const enumValues = (obj) => {
8
+ return Object.keys(obj);
9
+ };
10
+ exports.enumValues = enumValues;
11
+ const gitLink = (filepath) => {
12
+ if (!filepath.startsWith("src/")) {
13
+ throw new Error(`Invalid filepath: ${filepath}\nShould start with "src/"`);
14
+ }
15
+ return `https://github.com/mitodl/smoot-design/blob/${process.env.STORYBOOK_GIT_SHA}/${filepath}`;
16
+ };
17
+ exports.gitLink = gitLink;
@@ -0,0 +1,7 @@
1
+ import type { MutableRefObject, ForwardedRef, RefCallback } from "react";
2
+ /**
3
+ * Compose 2+ refs. Useful when a reusable component needs a ref itself, but
4
+ * consumers may also need the ref.
5
+ */
6
+ declare const composeRefs: <T>(...refs: (ForwardedRef<T> | MutableRefObject<T | undefined> | RefCallback<T>)[]) => RefCallback<T>;
7
+ export { composeRefs };
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.composeRefs = void 0;
4
+ /**
5
+ * Compose 2+ refs. Useful when a reusable component needs a ref itself, but
6
+ * consumers may also need the ref.
7
+ */
8
+ const composeRefs = (...refs) => {
9
+ return (value) => {
10
+ refs.forEach((ref) => {
11
+ if (typeof ref === "function") {
12
+ ref(value);
13
+ }
14
+ else if (ref) {
15
+ ref.current = value;
16
+ }
17
+ });
18
+ };
19
+ };
20
+ exports.composeRefs = composeRefs;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const React = require("react");
4
+ const composeRefs_1 = require("./composeRefs");
5
+ const react_1 = require("@testing-library/react");
6
+ describe("composeRefs", () => {
7
+ test("Composing object + fn ref", () => {
8
+ const objRef1 = { current: null };
9
+ const objRef2 = { current: null };
10
+ const fnRef1 = jest.fn();
11
+ const fnRef2 = jest.fn();
12
+ (0, react_1.render)(React.createElement("div", { "data-testid": "my-div", ref: (0, composeRefs_1.composeRefs)(objRef1, objRef2, fnRef1, fnRef2) }));
13
+ const el = react_1.screen.getByTestId("my-div");
14
+ expect(objRef1.current).toBe(el);
15
+ expect(objRef2.current).toBe(el);
16
+ expect(fnRef1).toHaveBeenCalledWith(el);
17
+ expect(fnRef2).toHaveBeenCalledWith(el);
18
+ });
19
+ });
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Emits `console.error` if two subsequent values of `jsonSerializable` serialize
3
+ * to the same thing but are different references.
4
+ *
5
+ * This hook does NOT run in production.
6
+ */
7
+ declare const useDevCheckStable: (jsonSerializable: unknown, msg?: string) => void;
8
+ export { useDevCheckStable };
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useDevCheckStable = void 0;
4
+ const react_1 = require("react");
5
+ /**
6
+ * Emits `console.error` if two subsequent values of `jsonSerializable` serialize
7
+ * to the same thing but are different references.
8
+ *
9
+ * This hook does NOT run in production.
10
+ */
11
+ const useDevCheckStable = (jsonSerializable, msg = "The value has changed. This may cause unnecessary re-renders") => {
12
+ if (process.env.NODE_ENV !== "production") {
13
+ /**
14
+ * Calling hooks conditionally based on env vars is not really a problem.
15
+ * In a given environment, the hook will always run or always not run.
16
+ */
17
+ // eslint-disable-next-line react-hooks/rules-of-hooks
18
+ const valRef = (0, react_1.useRef)(jsonSerializable);
19
+ // eslint-disable-next-line react-hooks/rules-of-hooks
20
+ (0, react_1.useEffect)(() => {
21
+ const sameJson = JSON.stringify(valRef.current) === JSON.stringify(jsonSerializable);
22
+ const differentRefs = valRef.current !== jsonSerializable;
23
+ if (!sameJson || differentRefs) {
24
+ console.error(`useDevCheckStable: ${msg}`, valRef.current, jsonSerializable);
25
+ }
26
+ }, [jsonSerializable, msg]);
27
+ }
28
+ };
29
+ exports.useDevCheckStable = useDevCheckStable;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Calls a function at a specified interval.
3
+ *
4
+ * Based on https://overreacted.io/making-setinterval-declarative-with-react-hooks/
5
+ */
6
+ declare const useInterval: (callback: () => void, delay: number | null) => void;
7
+ export { useInterval };
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useInterval = void 0;
4
+ const react_1 = require("react");
5
+ /**
6
+ * Calls a function at a specified interval.
7
+ *
8
+ * Based on https://overreacted.io/making-setinterval-declarative-with-react-hooks/
9
+ */
10
+ const useInterval = (callback, delay) => {
11
+ const savedCallback = (0, react_1.useRef)();
12
+ (0, react_1.useEffect)(() => {
13
+ savedCallback.current = callback;
14
+ }, [callback]);
15
+ (0, react_1.useEffect)(() => {
16
+ if (delay !== null) {
17
+ const id = setInterval(() => { var _a; return (_a = savedCallback.current) === null || _a === void 0 ? void 0 : _a.call(savedCallback); }, delay);
18
+ return () => clearInterval(id);
19
+ }
20
+ else {
21
+ return () => { };
22
+ }
23
+ }, [delay]);
24
+ };
25
+ exports.useInterval = useInterval;
@@ -0,0 +1,2 @@
1
+ export { AiChat } from "./components/AiChat/AiChat";
2
+ export type { AiChatProps } from "./components/AiChat/AiChat";
package/dist/esm/ai.js ADDED
@@ -0,0 +1 @@
1
+ export { AiChat } from "./components/AiChat/AiChat";
@@ -0,0 +1,6 @@
1
+ import type { AiChatProps } from "../ai";
2
+ type CreateChatOptions = {
3
+ root: HTMLElement;
4
+ } & AiChatProps;
5
+ declare const aiChat: (opts: CreateChatOptions) => void;
6
+ export { aiChat };
@@ -0,0 +1,10 @@
1
+ import * as React from "react";
2
+ import { createRoot } from "react-dom/client";
3
+ import { AiChat } from "../ai";
4
+ import { ThemeProvider } from "../index";
5
+ const aiChat = (opts) => {
6
+ const root = opts.root;
7
+ createRoot(root).render(React.createElement(ThemeProvider, null,
8
+ React.createElement(AiChat, Object.assign({}, opts))));
9
+ };
10
+ export { aiChat };
@@ -0,0 +1,5 @@
1
+ import * as React from "react";
2
+ import type { AiChatProps } from "./types";
3
+ declare const AiChat: React.FC<AiChatProps>;
4
+ export { AiChat };
5
+ export type { AiChatProps };
@@ -0,0 +1,147 @@
1
+ import * as React from "react";
2
+ import styled from "@emotion/styled";
3
+ import Skeleton from "@mui/material/Skeleton";
4
+ import { Input } from "../Input/Input";
5
+ import { ActionButton } from "../Button/ActionButton";
6
+ import { RiSendPlaneFill } from "@remixicon/react";
7
+ import { useAiChat } from "./utils";
8
+ import Markdown from "react-markdown";
9
+ import { ScrollSnap } from "../ScrollSnap/ScrollSnap";
10
+ import classNames from "classnames";
11
+ import { SrAnnouncer } from "../SrAnnouncer/SrAnnouncer";
12
+ const ChatContainer = styled.div(({ theme }) => ({
13
+ width: "100%",
14
+ height: "100%",
15
+ border: `1px solid ${theme.custom.colors.silverGrayLight}`,
16
+ backgroundColor: theme.custom.colors.lightGray1,
17
+ display: "flex",
18
+ flexDirection: "column",
19
+ }));
20
+ const MessagesContainer = styled(ScrollSnap)({
21
+ display: "flex",
22
+ flexDirection: "column",
23
+ flex: 1,
24
+ padding: "24px",
25
+ paddingBottom: "0px",
26
+ overflow: "auto",
27
+ });
28
+ const MessageRow = styled.div(({ reverse }) => [
29
+ {
30
+ margin: "8px 0",
31
+ display: "flex",
32
+ width: "100%",
33
+ flexDirection: reverse ? "row-reverse" : "row",
34
+ },
35
+ ]);
36
+ const Avatar = styled.div({});
37
+ const Message = styled.div(({ theme }) => (Object.assign(Object.assign({ border: `1px solid ${theme.custom.colors.silverGrayLight}`, backgroundColor: theme.custom.colors.white, borderRadius: "24px", padding: "4px 16px" }, theme.typography.body2), { "p:first-of-type": {
38
+ marginTop: 0,
39
+ }, "p:last-of-type": {
40
+ marginBottom: 0,
41
+ }, a: {
42
+ color: theme.custom.colors.mitRed,
43
+ textDecoration: "none",
44
+ }, "a:hover": {
45
+ color: theme.custom.colors.red,
46
+ textDecoration: "underline",
47
+ } })));
48
+ const StarterContainer = styled.div({
49
+ alignSelf: "flex-end",
50
+ display: "flex",
51
+ flexDirection: "column",
52
+ gap: "4px",
53
+ });
54
+ const Starter = styled.button(({ theme }) => (Object.assign(Object.assign({ border: `1px solid ${theme.custom.colors.silverGrayLight}`, backgroundColor: theme.custom.colors.white, borderRadius: "24px", padding: "4px 16px" }, theme.typography.body2), { cursor: "pointer", "&:hover": {
55
+ backgroundColor: theme.custom.colors.lightGray1,
56
+ } })));
57
+ const Controls = styled.div(({ theme }) => ({
58
+ display: "flex",
59
+ justifyContent: "space-around",
60
+ padding: "12px 24px",
61
+ backgroundColor: theme.custom.colors.white,
62
+ }));
63
+ const Form = styled.form(() => ({
64
+ display: "flex",
65
+ width: "80%",
66
+ gap: "12px",
67
+ alignItems: "center",
68
+ }));
69
+ const DotsContainer = styled.span(({ theme }) => ({
70
+ display: "inline-flex",
71
+ gap: "4px",
72
+ ".MuiSkeleton-root": {
73
+ backgroundColor: theme.custom.colors.silverGray,
74
+ },
75
+ }));
76
+ const Dots = () => {
77
+ return (React.createElement(DotsContainer, null,
78
+ React.createElement(Skeleton, { variant: "circular", width: "8px", height: "8px" }),
79
+ React.createElement(Skeleton, { variant: "circular", width: "8px", height: "8px" }),
80
+ React.createElement(Skeleton, { variant: "circular", width: "8px", height: "8px" })));
81
+ };
82
+ const classes = {
83
+ root: "MitAiChat--root",
84
+ conversationStarter: "MitAiChat--conversationStarter",
85
+ messagesContainer: "MitAiChat--messagesContainer",
86
+ messageRow: "MitAiChat--messageRow",
87
+ message: "MitAiChat--message",
88
+ avatar: "MitAiChat--avatar",
89
+ input: "MitAiChat--input",
90
+ };
91
+ const AiChat = function AiChat({ className, conversationStarters, requestOpts, initialMessages: initMsgs, parseContent, srLoadingMessages, }) {
92
+ var _a;
93
+ const [showStarters, setShowStarters] = React.useState(true);
94
+ const messagesRef = React.useRef(null);
95
+ const initialMessages = React.useMemo(() => {
96
+ const prefix = Math.random().toString().slice(2);
97
+ return initMsgs.map((m, i) => (Object.assign(Object.assign({}, m), { id: `initial-${prefix}-${i}` })));
98
+ }, [initMsgs]);
99
+ const { messages: unparsed, input, handleInputChange, handleSubmit, append, isLoading, } = useAiChat(requestOpts, {
100
+ initialMessages: initialMessages,
101
+ });
102
+ const messages = React.useMemo(() => {
103
+ const initial = initialMessages.map((m) => m.id);
104
+ return unparsed.map((m) => {
105
+ if (m.role === "assistant" && !initial.includes(m.id)) {
106
+ const content = parseContent ? parseContent(m.content) : m.content;
107
+ return Object.assign(Object.assign({}, m), { content });
108
+ }
109
+ return m;
110
+ });
111
+ }, [parseContent, unparsed, initialMessages]);
112
+ const waiting = !showStarters && ((_a = messages[messages.length - 1]) === null || _a === void 0 ? void 0 : _a.role) === "user";
113
+ const scrollToBottom = () => {
114
+ var _a;
115
+ (_a = messagesRef.current) === null || _a === void 0 ? void 0 : _a.scrollBy({
116
+ behavior: "instant",
117
+ top: messagesRef.current.scrollHeight,
118
+ });
119
+ };
120
+ const lastMsg = messages[messages.length - 1];
121
+ return (React.createElement(ChatContainer, { className: classNames(className, classes.root) },
122
+ React.createElement(MessagesContainer, { className: classes.messagesContainer, ref: messagesRef },
123
+ messages.map((m) => (React.createElement(MessageRow, { key: m.id, reverse: m.role === "user", "data-chat-role": m.role, className: classes.messageRow },
124
+ React.createElement(Avatar, null),
125
+ React.createElement(Message, { className: classes.message },
126
+ React.createElement(Markdown, null, m.content))))),
127
+ showStarters ? (React.createElement(StarterContainer, null, conversationStarters === null || conversationStarters === void 0 ? void 0 : conversationStarters.map((m) => (React.createElement(Starter, { className: classes.conversationStarter, key: m.content, onClick: () => {
128
+ setShowStarters(false);
129
+ scrollToBottom();
130
+ append({ role: "user", content: m.content });
131
+ } }, m.content))))) : null,
132
+ waiting ? (React.createElement(MessageRow, { key: "loading" },
133
+ React.createElement(Avatar, { className: classes.avatar }),
134
+ React.createElement(Message, null,
135
+ React.createElement(Dots, null)))) : null),
136
+ React.createElement(Controls, null,
137
+ React.createElement(Form, { onSubmit: (e) => {
138
+ setShowStarters(false);
139
+ scrollToBottom();
140
+ handleSubmit(e);
141
+ } },
142
+ React.createElement(Input, { className: classes.input, placeholder: "Type a message...", name: "message", sx: { flex: 1 }, value: input, onChange: handleInputChange }),
143
+ React.createElement(ActionButton, { "aria-label": "Send", type: "submit", disabled: isLoading || !input },
144
+ React.createElement(RiSendPlaneFill, null)))),
145
+ React.createElement(SrAnnouncer, { isLoading: isLoading, loadingMessages: srLoadingMessages, message: lastMsg.role === "assistant" ? lastMsg.content : "" })));
146
+ };
147
+ export { AiChat };
@@ -0,0 +1,11 @@
1
+ import type { Meta, StoryObj } from "@storybook/react";
2
+ import { AiChat } from "./AiChat";
3
+ declare const meta: Meta<typeof AiChat>;
4
+ export default meta;
5
+ type Story = StoryObj<typeof AiChat>;
6
+ export declare const StreamingResponses: Story;
7
+ /**
8
+ * Here `AiChat` is used with a non-streaming JSON API. The JSON is converted
9
+ * to text via `parseContent`.
10
+ */
11
+ export declare const JsonResponses: Story;
@@ -0,0 +1,73 @@
1
+ import * as React from "react";
2
+ import { AiChat } from "./AiChat";
3
+ import { mockJson, mockStreaming } from "./story-utils";
4
+ import styled from "@emotion/styled";
5
+ const TEST_API_STREAMING = "http://localhost:4567/streaming";
6
+ const TEST_API_JSON = "http://localhost:4567/json";
7
+ const INITIAL_MESSAGES = [
8
+ {
9
+ content: "Hi! What are you interested in learning about?",
10
+ role: "assistant",
11
+ },
12
+ ];
13
+ const STARTERS = [
14
+ { content: "I'm interested in quantum computing" },
15
+ { content: "I want to understand global warming. " },
16
+ { content: "I am curious about AI applications for business" },
17
+ ];
18
+ const Container = styled.div({
19
+ width: "100%",
20
+ height: "350px",
21
+ });
22
+ const meta = {
23
+ title: "smoot-design/AiChat",
24
+ component: AiChat,
25
+ render: (args) => React.createElement(AiChat, Object.assign({}, args)),
26
+ decorators: (Story) => {
27
+ return (React.createElement(Container, null,
28
+ React.createElement(Story, null)));
29
+ },
30
+ args: {
31
+ initialMessages: INITIAL_MESSAGES,
32
+ requestOpts: { apiUrl: TEST_API_STREAMING },
33
+ conversationStarters: STARTERS,
34
+ },
35
+ argTypes: {
36
+ conversationStarters: {
37
+ control: { type: "object", disable: true },
38
+ },
39
+ initialMessages: {
40
+ control: { type: "object", disable: true },
41
+ },
42
+ requestOpts: {
43
+ control: { type: "object", disable: true },
44
+ table: { readonly: true }, // See above
45
+ },
46
+ },
47
+ beforeEach: () => {
48
+ const originalFetch = window.fetch;
49
+ window.fetch = (url, opts) => {
50
+ if (url === TEST_API_STREAMING) {
51
+ return mockStreaming();
52
+ }
53
+ else if (url === TEST_API_JSON) {
54
+ return mockJson();
55
+ }
56
+ return originalFetch(url, opts);
57
+ };
58
+ },
59
+ };
60
+ export default meta;
61
+ export const StreamingResponses = {};
62
+ /**
63
+ * Here `AiChat` is used with a non-streaming JSON API. The JSON is converted
64
+ * to text via `parseContent`.
65
+ */
66
+ export const JsonResponses = {
67
+ args: {
68
+ requestOpts: { apiUrl: TEST_API_JSON },
69
+ parseContent: (content) => {
70
+ return JSON.parse(content).message;
71
+ },
72
+ },
73
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,128 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ // This was giving false positives
11
+ /* eslint-disable testing-library/await-async-utils */
12
+ import { render, screen, waitFor } from "@testing-library/react";
13
+ import user from "@testing-library/user-event";
14
+ import { AiChat } from "./AiChat";
15
+ import { ThemeProvider } from "../ThemeProvider/ThemeProvider";
16
+ import * as React from "react";
17
+ import { faker } from "@faker-js/faker/locale/en";
18
+ const counter = jest.fn(); // use jest.fn as counter because it resets on each test
19
+ const mockFetch = jest.mocked(jest.fn(() => {
20
+ const count = counter.mock.calls.length;
21
+ counter();
22
+ return Promise.resolve(new Response(`AI Response ${count}`, {
23
+ headers: {
24
+ "Content-Type": "application/json",
25
+ },
26
+ }));
27
+ }));
28
+ window.fetch = mockFetch;
29
+ jest.mock("react-markdown", () => {
30
+ return {
31
+ __esModule: true,
32
+ default: ({ children }) => React.createElement("div", null, children),
33
+ };
34
+ });
35
+ const getMessages = () => {
36
+ return Array.from(document.querySelectorAll(".MitAiChat--message"));
37
+ };
38
+ const getConversationStarters = () => {
39
+ return Array.from(document.querySelectorAll("button.MitAiChat--conversationStarter"));
40
+ };
41
+ const whenCount = (cb, count) => __awaiter(void 0, void 0, void 0, function* () {
42
+ return yield waitFor(() => {
43
+ const result = cb();
44
+ expect(result).toHaveLength(count);
45
+ return result;
46
+ });
47
+ });
48
+ describe("AiChat", () => {
49
+ const setup = (props = {}) => {
50
+ const initialMessages = [
51
+ { role: "assistant", content: faker.lorem.sentence() },
52
+ ];
53
+ const conversationStarters = [
54
+ { content: faker.lorem.sentence() },
55
+ { content: faker.lorem.sentence() },
56
+ ];
57
+ render(React.createElement(AiChat, Object.assign({ initialMessages: initialMessages, conversationStarters: conversationStarters, requestOpts: { apiUrl: "http://localhost:4567/test" } }, props)), { wrapper: ThemeProvider });
58
+ return { initialMessages, conversationStarters };
59
+ };
60
+ test("Clicking conversation starters and sending chats", () => __awaiter(void 0, void 0, void 0, function* () {
61
+ const { initialMessages, conversationStarters } = setup();
62
+ const scrollBy = jest.spyOn(HTMLElement.prototype, "scrollBy");
63
+ const initialMessageEls = getMessages();
64
+ expect(initialMessageEls.length).toBe(1);
65
+ expect(initialMessageEls[0]).toHaveTextContent(initialMessages[0].content);
66
+ const starterEls = getConversationStarters();
67
+ expect(starterEls.length).toBe(2);
68
+ expect(starterEls[0]).toHaveTextContent(conversationStarters[0].content);
69
+ expect(starterEls[1]).toHaveTextContent(conversationStarters[1].content);
70
+ const chosen = faker.helpers.arrayElement([0, 1]);
71
+ yield user.click(starterEls[chosen]);
72
+ expect(scrollBy).toHaveBeenCalled();
73
+ scrollBy.mockReset();
74
+ const messageEls = yield whenCount(getMessages, 3);
75
+ expect(messageEls[0]).toHaveTextContent(initialMessages[0].content);
76
+ expect(messageEls[1]).toHaveTextContent(conversationStarters[chosen].content);
77
+ expect(messageEls[2]).toHaveTextContent("AI Response 0");
78
+ yield user.click(screen.getByPlaceholderText("Type a message..."));
79
+ yield user.paste("User message");
80
+ yield user.click(screen.getByRole("button", { name: "Send" }));
81
+ expect(scrollBy).toHaveBeenCalled();
82
+ const afterSending = yield whenCount(getMessages, 5);
83
+ expect(afterSending[3]).toHaveTextContent("User message");
84
+ expect(afterSending[4]).toHaveTextContent("AI Response 1");
85
+ }));
86
+ test("transformBody is called before sending requests", () => __awaiter(void 0, void 0, void 0, function* () {
87
+ const fakeBody = { message: faker.lorem.sentence() };
88
+ const apiUrl = faker.internet.url();
89
+ const transformBody = jest.fn(() => fakeBody);
90
+ const { initialMessages } = setup({
91
+ requestOpts: { apiUrl, transformBody },
92
+ });
93
+ yield user.click(screen.getByPlaceholderText("Type a message..."));
94
+ yield user.paste("User message");
95
+ yield user.click(screen.getByRole("button", { name: "Send" }));
96
+ expect(transformBody).toHaveBeenCalledWith([
97
+ expect.objectContaining(initialMessages[0]),
98
+ expect.objectContaining({ content: "User message", role: "user" }),
99
+ ]);
100
+ expect(mockFetch).toHaveBeenCalledTimes(1);
101
+ expect(mockFetch).toHaveBeenCalledWith(apiUrl, expect.objectContaining({
102
+ body: JSON.stringify(fakeBody),
103
+ }));
104
+ }));
105
+ test("parseContent is called on the API-received message content", () => __awaiter(void 0, void 0, void 0, function* () {
106
+ const fakeBody = { message: faker.lorem.sentence() };
107
+ const apiUrl = faker.internet.url();
108
+ const transformBody = jest.fn(() => fakeBody);
109
+ const { initialMessages, conversationStarters } = setup({
110
+ requestOpts: { apiUrl, transformBody },
111
+ parseContent: jest.fn((content) => `Parsed: ${content}`),
112
+ });
113
+ yield user.click(getConversationStarters()[0]);
114
+ yield whenCount(getMessages, initialMessages.length + 2);
115
+ yield user.click(screen.getByPlaceholderText("Type a message..."));
116
+ yield user.paste("User message");
117
+ yield user.click(screen.getByRole("button", { name: "Send" }));
118
+ yield whenCount(getMessages, initialMessages.length + 4);
119
+ const messagesTexts = getMessages().map((el) => el.textContent);
120
+ expect(messagesTexts).toEqual([
121
+ initialMessages[0].content,
122
+ conversationStarters[0].content,
123
+ "Parsed: AI Response 0",
124
+ "User message",
125
+ "Parsed: AI Response 1",
126
+ ]);
127
+ }));
128
+ });
@@ -0,0 +1,3 @@
1
+ declare const mockStreaming: () => Promise<Response>;
2
+ declare const mockJson: () => Promise<Response>;
3
+ export { mockStreaming, mockJson };
@@ -0,0 +1,96 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ const SAMPLE_RESPONSES = [
11
+ `For exploring AI applications in business, I recommend the following course from MIT:
12
+
13
+ 1. **[Machine Learning, Modeling, and Simulation Principles](https://xpro.mit.edu/courses/course-v1:xPRO+MLx1/)**: Offered by MIT xPRO, this course is part of the program "Machine Learning, Modeling, and Simulation: Engineering Problem-Solving in the Age of AI." It focuses on the principles of machine learning and how they can be applied to solve engineering problems, which is highly relevant for business applications of AI.
14
+
15
+ This course is not free, but it provides a certification upon completion, which can be valuable for professionals looking to apply AI in business contexts. It covers essential concepts that can help you understand how AI can be leveraged to improve business processes and decision-making.
16
+ `,
17
+ `
18
+ To understand global warming, I recommend the following resources from MIT:
19
+
20
+ 1. **[Global Warming Science](https://www.edx.org/learn/global-warming/massachusetts-institute-of-technology-global-warming-science)**: This course offered by MITx covers the physics, chemistry, biology, and geology of the earth’s climate system. It's a comprehensive introduction to the scientific principles underlying global warming.
21
+
22
+ 2. **[Global Warming Science](https://openlearninglibrary.mit.edu/courses/course-v1:MITx+12.340x+1T2020/about)**: Another offering of the same course by MITx, available through the Open Learning Library. It provides the same in-depth exploration of the earth's climate system.
23
+
24
+ These courses are free and provide a solid foundation in understanding the scientific aspects of global warming. They are suitable for anyone interested in the topic, regardless of prior knowledge.
25
+ `,
26
+ `
27
+ Here are some courses on linear algebra that you can explore:
28
+
29
+ 1. **[Linear Algebra (MIT OpenCourseWare)](https://openlearninglibrary.mit.edu/courses/course-v1:OCW+18.06SC+2T2019/about)**: This course covers matrix theory and linear algebra, emphasizing topics useful in various disciplines such as physics, economics, social sciences, natural sciences, and engineering. It parallels the combination of theory and applications in Professor Strang's textbook "Introduction to Linear Algebra." This course is free and available through MIT OpenCourseWare.
30
+
31
+ 2. **[Mathematical Methods for Quantitative Finance (MITx)](https://www.edx.org/learn/finance/massachusetts-institute-of-technology-mathematical-methods-for-quantitative-finance)**: This course covers the mathematical foundations essential for financial engineering and quantitative finance, including linear algebra, optimization, probability, stochastic processes, statistics, and applied computational techniques in R. It is free and offers certification upon completion.
32
+
33
+ 3. **[Quantum Information Science I, Part 1 (MITx)](https://openlearninglibrary.mit.edu/courses/course-v1:MITx+8.370.1x+1T2018/about)**: While primarily focused on quantum information science, this course requires some knowledge of linear algebra and is suitable for those interested in quantum mechanics. It is free and available through MITx.
34
+
35
+ These courses provide a comprehensive introduction to linear algebra and its applications across various fields.
36
+ `,
37
+ ];
38
+ const rand = (min, max) => {
39
+ // min and max included
40
+ return Math.floor(Math.random() * (max - min + 1) + min);
41
+ };
42
+ const mockStreaming = function mockApi() {
43
+ return __awaiter(this, void 0, void 0, function* () {
44
+ let timerId;
45
+ const response = SAMPLE_RESPONSES[rand(0, SAMPLE_RESPONSES.length - 1)];
46
+ const chunks = response.split(" ").reduce((acc, word) => {
47
+ const last = acc[acc.length - 1];
48
+ if (acc.length === 0) {
49
+ acc.push(word);
50
+ }
51
+ else if (Math.random() < 0.75) {
52
+ acc[acc.length - 1] = `${last} ${word}`;
53
+ }
54
+ else {
55
+ acc.push(` ${word}`);
56
+ }
57
+ return acc;
58
+ }, []);
59
+ const num = chunks.length;
60
+ let i = 0;
61
+ yield new Promise((resolve) => setTimeout(resolve, 1500));
62
+ const body = new ReadableStream({
63
+ start(controller) {
64
+ timerId = setInterval(() => {
65
+ const msg = new TextEncoder().encode(chunks[i]);
66
+ controller.enqueue(msg);
67
+ i++;
68
+ if (i === num) {
69
+ controller.close();
70
+ clearInterval(timerId);
71
+ }
72
+ }, 250);
73
+ },
74
+ cancel() {
75
+ if (timerId) {
76
+ clearInterval(timerId);
77
+ }
78
+ },
79
+ });
80
+ return Promise.resolve(new Response(body, {
81
+ headers: {
82
+ "Content-Type": "text/event-stream",
83
+ },
84
+ }));
85
+ });
86
+ };
87
+ const mockJson = () => __awaiter(void 0, void 0, void 0, function* () {
88
+ const message = SAMPLE_RESPONSES[rand(0, SAMPLE_RESPONSES.length - 1)];
89
+ yield new Promise((res) => setTimeout(res, 2000));
90
+ return Promise.resolve(new Response(JSON.stringify({ message }), {
91
+ headers: {
92
+ "Content-Type": "application/json",
93
+ },
94
+ }));
95
+ });
96
+ export { mockStreaming, mockJson };