@scuticode/shop-sdk
Version:
ScutiCode shop sdk
231 lines (224 loc) • 12.3 kB
JavaScript
;
var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
var _, done = false;
for (var i = decorators.length - 1; i >= 0; i--) {
var context = {};
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
if (kind === "accessor") {
if (result === void 0) continue;
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
if (_ = accept(result.get)) descriptor.get = _;
if (_ = accept(result.set)) descriptor.set = _;
if (_ = accept(result.init)) initializers.unshift(_);
}
else if (_ = accept(result)) {
if (kind === "field") initializers.unshift(_);
else descriptor[key] = _;
}
}
if (target) Object.defineProperty(target, contextIn.name, descriptor);
done = true;
};
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
var useValue = arguments.length > 2;
for (var i = 0; i < initializers.length; i++) {
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
}
return useValue ? value : void 0;
};
var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) {
if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MainChat = void 0;
const lit_1 = require("lit");
const decorators_js_1 = require("lit/decorators.js");
const main_chat_style_1 = require("./main-chat.style");
const ChatModel_1 = require("../models/ChatModel");
require("./svg-icon.component");
const utils_style_1 = require("../styles/utils.style");
let MainChat = (() => {
var _MainChat_userId_accessor_storage, _MainChat_chatBaseUrl_accessor_storage;
let _classDecorators = [(0, decorators_js_1.customElement)('main-chat')];
let _classDescriptor;
let _classExtraInitializers = [];
let _classThis;
let _classSuper = lit_1.LitElement;
let _instanceExtraInitializers = [];
let _userId_decorators;
let _userId_initializers = [];
let _chatBaseUrl_decorators;
let _chatBaseUrl_initializers = [];
var MainChat = _classThis = class extends _classSuper {
constructor() {
super(...arguments);
_MainChat_userId_accessor_storage.set(this, (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _userId_initializers, '1')));
_MainChat_chatBaseUrl_accessor_storage.set(this, __runInitializers(this, _chatBaseUrl_initializers, void 0));
this.chat = [];
this.typingIndicator = false;
}
get userId() { return __classPrivateFieldGet(this, _MainChat_userId_accessor_storage, "f"); }
set userId(value) { __classPrivateFieldSet(this, _MainChat_userId_accessor_storage, value, "f"); }
get chatBaseUrl() { return __classPrivateFieldGet(this, _MainChat_chatBaseUrl_accessor_storage, "f"); }
set chatBaseUrl(value) { __classPrivateFieldSet(this, _MainChat_chatBaseUrl_accessor_storage, value, "f"); }
get userInputEl() {
return this.shadowRoot.getElementById('chat-input');
}
get chatAreaEl() {
return this.shadowRoot.getElementById('chat-area');
}
render() {
return (0, lit_1.html) `
<div id="chatbot" class="main-card">
<span class="card-close-icon" @click="${this.toggle}">
<svg-icon type="close"></svg-icon>
</span >
<div class="main-title">
<svg-icon class="robot-icon" type="robot"></svg-icon>
<span>ScutiCode Shop</span>
</div>
<div id="chat-area" class="chat-area" id="message-box">
${this.chat.map((c) => (0, lit_1.html) `
${c.type == ChatModel_1.ChatMessageType.Text ? (0, lit_1.html) `<div class="message ${c.role}-message">${c.text}</div>` : lit_1.nothing}
${c.type == ChatModel_1.ChatMessageType.Items ? (0, lit_1.html) `
<div class="image-container">
${c.items.map((i) => (0, lit_1.html) `<img src="${this.chatBaseUrl}${i.pictures[0]?.url}" alt="Image 1">`)}
</div>
` : lit_1.nothing}
`)}
${this.typingIndicator ? (0, lit_1.html) `<div class="typing-indicator">Assistant is typing...</div>` : ``}
</div>
<div class="line"></div>
<div class="input-area">
<input id="chat-input" class="chat-input" type="text" @keyup=${this.handleKeyup} ?disabled=${this.typingIndicator} />
<button @click="${this.send}">
<svg-icon type="send-right"></svg-icon>
</button>
</div>
</div>
`;
}
async handleKeyup(event) {
if (event.key === 'Enter') {
await this.send();
}
}
toggle() {
this.dispatchEvent(new Event('close-event'));
}
async send() {
const userInput = this.userInputEl.value;
if (!userInput)
return;
this.userInputEl.value = '';
this.chat.push({ role: ChatModel_1.Constants.User, text: userInput, type: ChatModel_1.ChatMessageType.Text });
this.typingIndicator = true;
this.updateChat();
try {
const request = { userId: this.userId, userPrompt: userInput };
const response = await this._chat(request);
if (!response.isSuccess) {
console.error('Handle this err...');
}
if (response.searchInsights) {
const searchText = `${response.searchInsights.name} ${response.searchInsights.description}`;
this.chat.push({
role: ChatModel_1.Constants.Assistant,
text: `${searchText}`,
type: ChatModel_1.ChatMessageType.Text
});
this.updateChat();
const itemsResponse = await this._getCatalogItem({ text: response.searchInsights.translation });
this.chat.push({
role: ChatModel_1.Constants.Assistant,
type: ChatModel_1.ChatMessageType.Items,
items: itemsResponse.data
});
}
else {
this.chat.push({ role: ChatModel_1.Constants.Assistant, text: response.content, type: ChatModel_1.ChatMessageType.Text });
}
}
catch (e) {
console.error('Handle this err...', e);
}
finally {
this.typingIndicator = false;
this.updateChat();
}
}
updateChat() {
this.requestUpdate();
setTimeout(() => {
this.chatAreaEl.scrollTop = this.chatAreaEl.scrollHeight;
});
}
async _chat(req) {
const response = await window.fetch(`${this.chatBaseUrl}/chat`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(req)
});
if (!response.ok) {
throw new Error(response.status.toString());
}
return await response.json();
}
async _getCatalogItem(req) {
const response = await window.fetch(`${this.chatBaseUrl}/Catalog`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(req)
});
if (!response.ok) {
throw new Error(response.status.toString());
}
return await response.json();
}
};
_MainChat_userId_accessor_storage = new WeakMap();
_MainChat_chatBaseUrl_accessor_storage = new WeakMap();
__setFunctionName(_classThis, "MainChat");
(() => {
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
_userId_decorators = [(0, decorators_js_1.property)()];
_chatBaseUrl_decorators = [(0, decorators_js_1.property)()];
__esDecorate(_classThis, null, _userId_decorators, { kind: "accessor", name: "userId", static: false, private: false, access: { has: obj => "userId" in obj, get: obj => obj.userId, set: (obj, value) => { obj.userId = value; } }, metadata: _metadata }, _userId_initializers, _instanceExtraInitializers);
__esDecorate(_classThis, null, _chatBaseUrl_decorators, { kind: "accessor", name: "chatBaseUrl", static: false, private: false, access: { has: obj => "chatBaseUrl" in obj, get: obj => obj.chatBaseUrl, set: (obj, value) => { obj.chatBaseUrl = value; } }, metadata: _metadata }, _chatBaseUrl_initializers, _instanceExtraInitializers);
__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
MainChat = _classThis = _classDescriptor.value;
if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
})();
_classThis.styles = [main_chat_style_1.chat, utils_style_1.utils, (0, lit_1.css) `
`];
(() => {
__runInitializers(_classThis, _classExtraInitializers);
})();
return MainChat = _classThis;
})();
exports.MainChat = MainChat;