fix search

This commit is contained in:
2024-12-19 09:43:19 +08:00
parent 3cd6bc5bc2
commit 9c2c314ce9

View File

@@ -2,6 +2,7 @@ import { IDBPDatabase } from "idb";
import { StateUpdater, useRef, useState, Dispatch } from "preact/hooks"; import { StateUpdater, useRef, useState, Dispatch } from "preact/hooks";
import { ChatStore } from "@/types/chatstore"; import { ChatStore } from "@/types/chatstore";
import { MessageDetail } from "./chatgpt";
interface ChatStoreSearchResult { interface ChatStoreSearchResult {
key: IDBValidKey; key: IDBValidKey;
@@ -83,15 +84,34 @@ export default function Search(props: {
if (now !== searchingNow) setSearchingNow(now); if (now !== searchingNow) setSearchingNow(now);
const value: ChatStore = await db.get("chatgpt-api-web", key); const value: ChatStore = await db.get("chatgpt-api-web", key);
const content = value.contents_for_index
.join(" ") let preview: string = "";
.toLowerCase(); for (const msg of value.history) {
if (content.includes(query)) { const contentType = typeof msg.content;
const beginIndex: number = content.indexOf(query); if (contentType === "string") {
const preview = content.slice( if (!msg.content.includes(query)) continue;
const beginIndex = msg.content.indexOf(query);
preview = msg.content.slice(
Math.max(0, beginIndex - 100), Math.max(0, beginIndex - 100),
Math.min(content.length, beginIndex + 239), Math.min(msg.content.length, beginIndex + 239),
); ) as string;
break;
} else if (contentType === "object") {
const details = msg.content as MessageDetail[];
for (const detail of details) {
if (detail.type !== "text") continue;
if (!detail.text?.includes(query)) continue;
const beginIndex = detail.text.indexOf(query);
preview = detail.text.slice(
Math.max(0, beginIndex - 100),
Math.min(detail.text.length, beginIndex + 239),
) as string;
break;
}
}
}
if (preview === "") continue;
result.push({ result.push({
key, key,
cs: value, cs: value,
@@ -99,7 +119,6 @@ export default function Search(props: {
preview: preview, preview: preview,
}); });
} }
}
// sort by key desc // sort by key desc
result.sort((a, b) => { result.sort((a, b) => {