chatbot-test-william
Version:
A flexible and customizable React chat component that supports context-aware conversations and document processing
510 lines • 21.6 kB
JavaScript
// src/components/ChatWindow.tsx
function _array_like_to_array(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _array_with_holes(arr) {
if (Array.isArray(arr)) return arr;
}
function _array_without_holes(arr) {
if (Array.isArray(arr)) return _array_like_to_array(arr);
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _async_to_generator(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _iterable_to_array(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterable_to_array_limit(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally{
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally{
if (_d) throw _e;
}
}
return _arr;
}
function _non_iterable_rest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _non_iterable_spread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _sliced_to_array(arr, i) {
return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _to_consumable_array(arr) {
return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
function _unsupported_iterable_to_array(o, minLen) {
if (!o) return;
if (typeof o === "string") return _array_like_to_array(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
function _ts_generator(thisArg, body) {
var f, y, t, _ = {
label: 0,
sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
}, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
return this;
}), g;
function verb(n) {
return function(v) {
return step([
n,
v
]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while(g && (g = 0, op[0] && (_ = 0)), _)try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [
op[0] & 2,
t.value
];
switch(op[0]){
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return {
value: op[1],
done: false
};
case 5:
_.label++;
y = op[1];
op = [
0
];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [
6,
e
];
y = 0;
} finally{
f = t = 0;
}
if (op[0] & 5) throw op[1];
return {
value: op[0] ? op[1] : void 0,
done: true
};
}
}
import { useEffect, useRef, useState } from "react";
// src/components/ChatMessageBubble.tsx
import { AiFillRobot } from "react-icons/ai";
import { IoPerson } from "react-icons/io5";
import { jsx, jsxs } from "react/jsx-runtime";
function ChatMessageBubble(props) {
var isUserMessage = props.message.role === "user";
var bubbleClass = "message-bubble ".concat(isUserMessage ? "message-bubble-user" : "message-bubble-ai");
var _props_humanIcon, _props_aiIcon;
var prefix = isUserMessage ? (_props_humanIcon = props.humanIcon) !== null && _props_humanIcon !== void 0 ? _props_humanIcon : /* @__PURE__ */ jsx(IoPerson, {}) : (_props_aiIcon = props.aiIcon) !== null && _props_aiIcon !== void 0 ? _props_aiIcon : /* @__PURE__ */ jsx(AiFillRobot, {});
return /* @__PURE__ */ jsxs("div", {
className: bubbleClass,
children: [
/* @__PURE__ */ jsx("div", {
className: "message-prefix",
children: prefix
}),
/* @__PURE__ */ jsx("div", {
className: "message-content",
children: /* @__PURE__ */ jsx("span", {
children: props.message.content
})
})
]
});
}
// src/components/ChatWindow.tsx
import { FaRobot } from "react-icons/fa6";
// src/components/utils/chatbot_api.tsx
function fetchChatbotResponse(endpoint, message) {
return _async_to_generator(function() {
var response, data, error;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
_state.trys.push([
0,
3,
,
4
]);
return [
4,
fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
message: message
})
})
];
case 1:
response = _state.sent();
if (!response.ok) {
throw new Error("Failed to fetch response from backend");
}
return [
4,
response.json()
];
case 2:
data = _state.sent();
return [
2,
data.response
];
case 3:
error = _state.sent();
console.error("Error fetching chatbot response:", error);
return [
2,
"I'm having trouble responding right now. Please try again later."
];
case 4:
return [
2
];
}
});
})();
}
// src/components/ChatWindow.tsx
import { MdDarkMode, MdLightMode } from "react-icons/md";
import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
function ChatWindow(props) {
var messageContainerRef = useRef(null);
var _useState = _sliced_to_array(useState(false), 2), isChatOpen = _useState[0], setIsChatOpen = _useState[1];
var _useState1 = _sliced_to_array(useState("light"), 2), theme = _useState1[0], setTheme = _useState1[1];
var _useState2 = _sliced_to_array(useState([]), 2), messages = _useState2[0], setMessages = _useState2[1];
var _useState3 = _sliced_to_array(useState(""), 2), input = _useState3[0], setInput = _useState3[1];
var _useState4 = _sliced_to_array(useState(false), 2), chatEndpointIsLoading = _useState4[0], setChatEndpointIsLoading = _useState4[1];
useEffect(function() {
var mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
var themeChangeHandler = function(e) {
return setTheme(e.matches ? "dark" : "light");
};
mediaQuery.addEventListener("change", themeChangeHandler);
setTheme(mediaQuery.matches ? "dark" : "light");
return function() {
return mediaQuery.removeEventListener("change", themeChangeHandler);
};
}, []);
var toggleTheme = function() {
setTheme(function(currentTheme) {
return currentTheme === "light" ? "dark" : "light";
});
};
var isMobile = window.innerWidth <= 768;
var chatWindowStyles = {
flex: 1,
flexDirection: "column",
overflow: "hidden",
backgroundColor: theme === "dark" ? "#333333" : "white",
color: theme === "dark" ? "#fff" : "#000",
position: "fixed",
bottom: isMobile ? "160px" : "100px",
right: isMobile ? "60px" : "40px",
borderRadius: "10px",
width: isMobile ? "90%" : "400px"
};
var endpoint = props.endpoint, placeholder = props.placeholder, aiIcon = props.aiIcon, humanIcon = props.humanIcon, chatIcon = props.chatIcon, titleText = props.titleText, initialMessage = props.initialMessage;
var _useState5 = _sliced_to_array(useState({}), 2), sourcesForMessages = _useState5[0], setSourcesForMessages = _useState5[1];
useEffect(function() {
if (!messages.length) {
messages.push({
id: "initial",
content: initialMessage || "Hi, how may I help you?",
createdAt: new Date(Date.now()),
role: "assistant"
});
}
}, []);
function sendMessage(e) {
return _async_to_generator(function() {
var newMessage, response, aiMessage, error, errorMessage;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
e.preventDefault();
if (input.trim() === "") return [
2
];
newMessage = {
id: crypto.randomUUID(),
content: input,
createdAt: new Date(Date.now()),
role: "user"
};
setMessages(function(prev) {
return _to_consumable_array(prev).concat([
newMessage
]);
});
setInput("");
setChatEndpointIsLoading(true);
_state.label = 1;
case 1:
_state.trys.push([
1,
3,
4,
5
]);
return [
4,
fetchChatbotResponse(endpoint, newMessage.content)
];
case 2:
response = _state.sent();
if (response) {
aiMessage = {
id: "bot" + crypto.randomUUID(),
content: response,
createdAt: new Date(Date.now()),
role: "assistant"
};
setMessages(function(prev) {
return _to_consumable_array(prev).concat([
aiMessage
]);
});
}
return [
3,
5
];
case 3:
error = _state.sent();
console.error("Error fetching chatbot response:", error);
errorMessage = {
id: "bot-error" + crypto.randomUUID(),
content: "I'm having trouble responding right now. Please try again later.",
createdAt: new Date(Date.now()),
role: "assistant"
};
setMessages(function(prev) {
return _to_consumable_array(prev).concat([
errorMessage
]);
});
return [
3,
5
];
case 4:
setChatEndpointIsLoading(false);
return [
7
];
case 5:
return [
2
];
}
});
})();
}
;
return /* @__PURE__ */ jsxs2(Fragment, {
children: [
/* @__PURE__ */ jsx2("button", {
className: "chat-button",
onClick: function() {
return setIsChatOpen(!isChatOpen);
},
children: chatIcon !== null && chatIcon !== void 0 ? chatIcon : /* @__PURE__ */ jsx2(FaRobot, {})
}),
/* @__PURE__ */ jsxs2("div", {
style: chatWindowStyles,
children: [
isChatOpen && /* @__PURE__ */ jsxs2(Fragment, {
children: [
/* @__PURE__ */ jsxs2("div", {
className: "chat-header",
style: {
display: "flex",
justifyContent: "space-between",
alignItems: "center"
},
children: [
/* @__PURE__ */ jsx2("div", {
children: titleText
}),
/* @__PURE__ */ jsx2("div", {
style: {
display: "flex",
gap: "8px",
alignItems: "center"
},
children: /* @__PURE__ */ jsx2("button", {
onClick: toggleTheme,
className: "theme-toggle-button",
children: /* @__PURE__ */ jsx2("div", {
className: theme === "dark" ? "icon-wrapper" : "icon-wrapper dark-mode",
children: theme === "dark" ? /* @__PURE__ */ jsx2(MdLightMode, {}) : /* @__PURE__ */ jsx2(MdDarkMode, {})
})
})
})
]
}),
/* @__PURE__ */ jsx2("div", {
className: "chat-container",
children: /* @__PURE__ */ jsx2("div", {
ref: messageContainerRef,
children: messages.length > 0 ? _to_consumable_array(messages).map(function(m, i) {
return /* @__PURE__ */ jsx2(ChatMessageBubble, {
message: m,
aiIcon: aiIcon,
humanIcon: humanIcon
}, m.id);
}) : ""
})
})
]
}),
isChatOpen && /* @__PURE__ */ jsx2("form", {
onSubmit: sendMessage,
className: "form-container",
children: /* @__PURE__ */ jsxs2("div", {
className: "chat-input",
children: [
/* @__PURE__ */ jsx2("textarea", {
className: "input-field",
value: input,
placeholder: placeholder !== null && placeholder !== void 0 ? placeholder : "Type your message here...",
onChange: function(e) {
setInput(e.target.value);
var lineHeight = parseInt(window.getComputedStyle(e.target).lineHeight);
var contentHeight = e.target.scrollHeight;
if (contentHeight > lineHeight && contentHeight > 32) {
var newHeight = Math.min(contentHeight, 96);
e.target.style.height = "".concat(newHeight, "px");
} else {
e.target.style.height = "32px";
}
},
onKeyDown: function(e) {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
var form = e.currentTarget.form;
if (form) form.requestSubmit();
}
},
rows: 1,
style: {
height: "32px"
}
}),
/* @__PURE__ */ jsx2("button", {
type: "submit",
className: "submit-button",
children: chatEndpointIsLoading ? /* @__PURE__ */ jsx2("div", {
role: "status",
className: "flex justify-center",
children: /* @__PURE__ */ jsx2("span", {
children: "Loading..."
})
}) : "Send"
})
]
})
})
]
})
]
});
}
export { ChatWindow as default };
//# sourceMappingURL=index.mjs.map