Skip to content

Instantly share code, notes, and snippets.

@yousefdergham
Last active December 31, 2022 12:55
Show Gist options
  • Save yousefdergham/6827f584de4d38101290ddac43d49d0e to your computer and use it in GitHub Desktop.
Save yousefdergham/6827f584de4d38101290ddac43d49d0e to your computer and use it in GitHub Desktop.
html widget
<link
rel="stylesheet"
href="https://almdrasa-gpt-public.vercel.app/assets/index-b0e69853.css"
/>
<style>
.app-cont-one {
width: 400px !important;
height: 600px !important;
}
.message_chat{
flex: 1;
color: #dcdcdc;
font-size: 20px;
max-width: 100%;
overflow-x: scroll;
/*
* white space refers to any spaces, tabs, or newline characters that are used to format the CSS code
* specifies how white space within an element should be handled. It is similar to the "pre" value, which tells the browser to treat all white space as significant and to preserve it exactly as it appears in the source code.
* The pre-wrap value allows the browser to wrap long lines of text onto multiple lines if necessary.
* The default value for the white-space property in CSS is "normal". This tells the browser to collapse multiple white space characters into a single space, and to wrap text onto multiple lines as needed to fit within its container.
*/
white-space: pre-wrap;
-ms-overflow-style: none;
scrollbar-width: none;
}
.message_chat::-webkit-scrollbar {
display: none;
}
</style>
<div id="app-cont-one">
<div id="website-content">
<div id="chat-display">
<div id="examples-column">
<h2>الامثلة</h2>
<ul>
<li>كيف اتعلم اللغة الانجليزية؟</li>
<li>هل لديك افكار لعمل عيد ميلاد لشخص عندى 10 سنين</li>
<li>كيف استطيع عمل لعبة باستخدام لغة بايثون</li>
</ul>
</div>
</div>
</div>
<div id="app">
<div id="chat_container"></div>
<form id="form_Almdrasa" onsubmit="handleSubmit(event)">
<textarea
name="prompt"
placeholder="Ask Almdrasa..."
id="Texta_Almdrasa"
></textarea>
<button type="submit" id="button-style">Send</button>
</form>
</div>
<script>
// import bot from 'https://i.imgur.com/79OsD69.png';
// import user from 'https://i.imgur.com/79OsD69.png';
const form = document.querySelector('#form_Almdrasa');
const chatContainer = document.querySelector('#chat_container');
const bot = 'https://i.imgur.com/79OsD69.png';
const user = 'https://i.imgur.com/79OsD69.png';
let loadInterval;
function loader(element) {
element.textContent = '';
loadInterval = setInterval(() => {
// Update the text content of the loading indicator
element.textContent += '.';
// If the loading indicator has reached three dots, reset it
if (element.textContent === '....') {
element.textContent = '';
}
}, 300);
}
function typeText(element, text) {
let index = 0;
let interval = setInterval(() => {
if (index < text.length) {
element.innerHTML += text.charAt(index);
index++;
} else {
clearInterval(interval);
}
}, 20);
}
// generate unique ID for each message div of bot
// necessary for typing text effect for that specific reply
// without unique ID, typing text will work on every element
function generateUniqueId() {
const timestamp = Date.now();
const randomNumber = Math.random();
const hexadecimalString = randomNumber.toString(16);
return `id-${timestamp}-${hexadecimalString}`;
}
function chatStripe(isAi, value, uniqueId) {
return `
<div class="wrapper ${isAi && 'ai'}">
<div class="chat">
<div class="profile">
<img
src=${isAi ? bot : user}
alt="${isAi ? 'bot' : 'user'}"
/>
</div>
<div class="message_chat" id=${uniqueId}>${value}</div>
</div>
</div>
`;
}
const handleSubmit = async (e) => {
e.preventDefault();
const data = new FormData(form);
console.log(data)
// user's chatstripe
chatContainer.innerHTML += chatStripe(false, data.get('prompt'));
// to clear the textarea input
form.reset();
// bot's chatstripe
const uniqueId = generateUniqueId();
chatContainer.innerHTML += chatStripe(true, ' ', uniqueId);
// to focus scroll to the bottom
chatContainer.scrollTop = chatContainer.scrollHeight;
// specific message div
const messageDiv = document.getElementById(uniqueId);
// messageDiv.innerHTML = "..."
loader(messageDiv);
const response = await fetch('https://almdrasa-ai.onrender.com', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
prompt: data.get('prompt'),
}),
});
clearInterval(loadInterval);
messageDiv.innerHTML = ' ';
if (response.ok) {
const data = await response.json();
const parsedData = data.bot.trim(); // trims any trailing spaces/'\n'
typeText(messageDiv, parsedData);
} else {
const err = await response.text();
messageDiv.innerHTML = 'Something went wrong';
alert(err);
}
};
form.addEventListener('submit', handleSubmit);
form.addEventListener('keyup', (e) => {
if (e.keyCode === 13) {
handleSubmit(e);
}
});
// Get the button element and the form element
const button = document.querySelector('#button-style');
const formstate = document.querySelector('#form_Almdrasa');
// Set up a function to handle the button click
const handleButtonClick = () => {
// Get the points value from the cookie
let points = getCookie('points');
// If the points value is not a number, set it to 3
if (isNaN(points)) {
points = 30;
} else {
// Otherwise, parse the points value as an integer
points = parseInt(points);
}
// Decrease the points value by 1
points -= 1;
// If the points value is less than 0, set it to 0
if (points < 0) {
points = 0;
}
// Store the updated points value in a cookie
setCookie('points', points, 1);
// If the points value is 0, remove the form from the page
if (points === 0) {
formstate.parentNode.removeChild(formstate);
}
const suggest = document.querySelector('#chat-display');
suggest.parentNode.removeChild(suggest);
document.getElementById('app').style.height = '100vh';
};
// Add event listeners for the button click and the enter key press
button.addEventListener('click', handleButtonClick);
window.addEventListener('keydown', (event) => {
if (event.keyCode === 13) {
handleButtonClick();
}
});
// Set up a function to check the points value every time the page is refreshed
window.onload = () => {
// Get the points value from the cookie
let points = getCookie('points');
// If the points value is not a number, set it to 3 and store it in a cookie
if (isNaN(points)) {
points = 30;
setCookie('points', points, 1);
}
};
// Set up a function to get the value of a cookie
function getCookie(name) {
const value = '; ' + document.cookie;
const parts = value.split('; ' + name + '=');
if (parts.length === 2) {
return parts.pop().split(';').shift();
}
}
// Set up a function to set the value of a cookie
function setCookie(name, value, days) {
const date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
const expires = 'expires=' + date.toUTCString();
document.cookie = name + '=' + value + ';' + expires + ';path=/';
}
const examplesColumn = document.getElementById('examples-column');
const chatTextarea = document.getElementById('Texta_Almdrasa');
examplesColumn.addEventListener('click', (event) => {
if (event.target.tagName === 'LI') {
chatTextarea.value = event.target.textContent;
chatTextarea.focus();
}
});
</script>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment