ملف العمل الأصلي
public/app.js
تحتفظ الشيفرة وصفحات الأمثلة القابلة للتشغيل بمعرّفاتها ونصوصها التجريبية الأصلية. يشرحها الدرس وإرشادات الملفات بلغتك.
const history = [],
form = document.querySelector("form"),
log = document.querySelector("#conversation"),
status = document.querySelector("[role=status]");
function show(role, text) {
const p = document.createElement("p");
p.textContent = role + ": " + text;
log.append(p);
}
form.addEventListener("submit", async (e) => {
e.preventDefault();
const text = form.elements.message.value.trim(),
button = form.querySelector("button");
if (!text) return;
if (history.length >= 8) {
status.textContent = "Practice limit reached. Reload to start another conversation.";
return;
}
button.disabled = true;
status.textContent = "Preparing a reply…";
const pending = [...history, { role: "user", text }];
try {
const r = await fetch("/.netlify/functions/mini-chat", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + form.elements.access.value,
},
body: JSON.stringify({ messages: pending }),
});
if (!r.ok) throw Error();
const value = await r.json();
if (typeof value.answer !== "string") throw Error();
history.push({ role: "user", text }, { role: "assistant", text: value.answer });
show("You", text);
show("Assistant", value.answer);
for (const source of value.sources || []) {
if (typeof source.title !== "string" || !/^sources\.html#[a-z]+$/.test(source.url))
continue;
const a = document.createElement("a");
a.href = source.url;
a.textContent = "Source: " + source.title;
a.target = "_blank";
a.rel = "noopener";
log.append(a);
}
form.elements.message.value = "";
status.textContent = "Reply received.";
} catch {
status.textContent =
"No reply received. Your message is still here; try again after checking the service.";
} finally {
button.disabled = false;
}
});
form.elements.message.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey && !e.isComposing) {
e.preventDefault();
if (!form.querySelector("button").disabled) form.requestSubmit();
}
});