File size: 5,211 Bytes
07acd33 3ec27e9 07acd33 3ec27e9 07acd33 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | const input = document.querySelector('#question');
const form = document.querySelector('#question-form');
const send = document.querySelector('#send');
const examples = document.querySelector('#examples');
const conversation = document.querySelector('#conversation');
const results = document.querySelector('#results');
const rankingEmpty = document.querySelector('#ranking-empty');
const status = document.querySelector('#status');
const databaseInfo = document.querySelector('#database-info');
const score = new Intl.NumberFormat('id-ID', { minimumFractionDigits: 4, maximumFractionDigits: 4 });
const threshold = 0.68;
const pending = new Map();
const worker = new Worker(new URL('./engine-worker.js', import.meta.url), { type: 'module' });
let nextId = 0;
let ready = false;
let busy = false;
let workerFailed = false;
function setStatus(message, isError = false) {
status.textContent = message;
status.classList.toggle('error', isError);
}
function updateControls() {
send.disabled = !ready || busy || workerFailed;
for (const button of examples.querySelectorAll('button')) {
button.disabled = send.disabled;
}
}
worker.addEventListener('message', ({ data: event }) => {
const job = pending.get(event.id);
if (!job) return;
if (event.type === 'progress') {
setStatus(event.message);
return;
}
pending.delete(event.id);
if (event.type === 'error') job.reject(new Error(event.message));
else job.resolve(event.data);
});
worker.addEventListener('error', () => {
workerFailed = true;
const error = new Error('Mesin pencarian gagal dibuka. Muat ulang halaman untuk mencoba lagi.');
for (const job of pending.values()) job.reject(error);
pending.clear();
updateControls();
setStatus(error.message, true);
});
function request(type, query) {
const id = ++nextId;
return new Promise((resolve, reject) => {
pending.set(id, { resolve, reject });
worker.postMessage({ id, type, query });
});
}
function element(tag, text, className) {
const node = document.createElement(tag);
if (text) node.textContent = text;
if (className) node.className = className;
return node;
}
function addTurn(query, top) {
conversation.querySelector('.empty')?.remove();
const turn = element('article', '', 'turn');
const question = element('div', '', 'message user-message');
question.append(element('strong', 'Kamu'), element('p', query));
const answer = element('div', '', 'message answer');
if (top && top.distance <= threshold) {
answer.append(
element('strong', top.title),
element('p', top.body),
element('p', `Sumber ${top.id} · Jarak ${score.format(top.distance)}`, 'source-id'),
);
} else {
answer.append(
element('strong', 'Belum menemukan catatan yang cukup dekat'),
element('p', 'Coba tanyakan tentang pgvector, Supabase, atau Hugging Face. Kamu tetap bisa memeriksa catatan yang jaraknya paling kecil.'),
);
}
turn.append(question, answer);
conversation.append(turn);
conversation.scrollTop = conversation.scrollHeight;
}
function renderRanking(rows) {
results.replaceChildren();
rankingEmpty.hidden = rows.length > 0;
for (const row of rows) {
const item = element('li');
const details = element('details');
const summary = element('summary', row.title);
const metadata = element('span', '', 'source-metadata');
metadata.append(
element('span', `${row.id} · ${row.topic}`),
element('span', `Jarak ${score.format(row.distance)}`, 'distance'),
);
summary.append(metadata);
details.append(summary, element('p', row.body, 'source-body'));
item.append(details);
results.append(item);
}
}
async function submit(question) {
const query = question.trim();
if (!ready || busy || workerFailed || !query || query.length > 600) return;
busy = true;
updateControls();
setStatus('Mencari catatan yang paling dekat…');
try {
const { rows, preset } = await request('search', query);
addTurn(query, rows[0]);
renderRanking(rows);
if (input.value.trim() === query) input.value = '';
setStatus(preset ? 'Pencarian selesai dengan embedding contoh.' : 'Pencarian selesai dengan embedding dari MiniLM.');
} catch (error) {
setStatus(error.message, true);
} finally {
busy = false;
updateControls();
}
}
form.addEventListener('submit', event => {
event.preventDefault();
void submit(input.value);
});
try {
const [{ extversion, count }, data] = await Promise.all([
request('init'),
fetch(new URL('./data.json', import.meta.url)).then(response => {
if (!response.ok) throw new Error('Catatan latihan gagal dimuat.');
return response.json();
}),
]);
for (const { label, query } of data.presets) {
const button = element('button', label, 'example');
button.type = 'button';
button.title = query;
button.addEventListener('click', () => void submit(query));
examples.append(button);
}
databaseInfo.textContent = `pgvector ${extversion} · ${count} catatan latihan fiktif.`;
ready = true;
updateControls();
setStatus('Siap mencari.');
} catch (error) {
setStatus(`${error.message} Muat ulang halaman jika perlu.`, true);
}
|