SearchPage.tsx 19.9 KB
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 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
import { useState, useEffect, useMemo, useRef } from "react";
import {
  Search,
  FileText,
  Image,
  Video,
  Play,
  ChevronLeft,
  ChevronRight,
  Library,
} from "lucide-react";
import { KIOSK_EVENT, loadKnowledgeEntries, type KnowledgeEntry } from "../kioskStorage";
import { PAGE_CONTENT_INSET } from "../pageContentInset";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "../components/ui/dialog";
import { useI18n } from "../i18n";
import { resolveKioskMediaUrl } from "../api/kioskApi";

/** 搜索框下方固定展示的关键词(顺序与文案一致) */
const QUICK_KEYWORDS = [
  "天体物理",
  "教程",
  "日食",
  "星云",
  "暗物质",
  "望远镜",
  "深空摄影",
] as const;

/** 每页条数(大屏约 5 列×2 行,共 10 条) */
const PAGE_SIZE = 10;

function buildPageList(totalPages: number, currentPage: number): (number | "ellipsis")[] {
  if (totalPages <= 12) {
    return Array.from({ length: totalPages }, (_, i) => i + 1);
  }
  const set = new Set<number>([1, totalPages, currentPage]);
  for (let p = currentPage - 2; p <= currentPage + 2; p++) {
    if (p >= 1 && p <= totalPages) set.add(p);
  }
  const sorted = [...set].sort((a, b) => a - b);
  const out: (number | "ellipsis")[] = [];
  for (let i = 0; i < sorted.length; i++) {
    const p = sorted[i]!;
    if (i > 0 && p - sorted[i - 1]! > 1) {
      out.push("ellipsis");
    }
    out.push(p);
  }
  return out;
}

function matchesQuery(item: KnowledgeEntry, raw: string): boolean {
  const q = raw.trim();
  if (q === "") return true;
  const lower = q.toLowerCase();
  if (item.title.toLowerCase().includes(lower) || item.content.toLowerCase().includes(lower)) {
    return true;
  }
  return item.tags.some((t) => t.includes(q) || t.toLowerCase().includes(lower));
}

/** 有条目视频地址即可播放(类型误选为「文字」时也能在知识库观看) */
function hasKnowledgeVideoUrl(item: KnowledgeEntry): boolean {
  return typeof item.videoUrl === "string" && item.videoUrl.trim() !== "";
}

export function SearchPage() {
  const { t } = useI18n();
  const [dbRev, setDbRev] = useState(0);
  const [searchQuery, setSearchQuery] = useState("");
  const [page, setPage] = useState(1);
  const [activeItem, setActiveItem] = useState<KnowledgeEntry | null>(null);
  const searchInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    const h = () => setDbRev((r) => r + 1);
    window.addEventListener(KIOSK_EVENT, h);
    window.addEventListener("storage", h);
    return () => {
      window.removeEventListener(KIOSK_EVENT, h);
      window.removeEventListener("storage", h);
    };
  }, []);

  const searchResults = useMemo(() => loadKnowledgeEntries(), [dbRev]);

  const filteredResults = useMemo(
    () => searchResults.filter((item) => matchesQuery(item, searchQuery)),
    [searchResults, searchQuery]
  );

  const totalPages = Math.max(1, Math.ceil(filteredResults.length / PAGE_SIZE));

  useEffect(() => {
    setPage(1);
  }, [searchQuery, dbRev]);

  useEffect(() => {
    setPage((p) => Math.min(p, totalPages));
  }, [totalPages]);

  const currentPage = Math.min(page, totalPages);
  const pageItems = filteredResults.slice(
    (currentPage - 1) * PAGE_SIZE,
    currentPage * PAGE_SIZE
  );

  const toggleKeyword = (word: string) => {
    setSearchQuery((prev) => (prev.trim() === word ? "" : word));
  };

  const getTypeIcon = (type: string) => {
    switch (type) {
      case "文字":
        return FileText;
      case "图片":
        return Image;
      case "视频":
        return Video;
      default:
        return FileText;
    }
  };

  const goPage = (p: number) => {
    setPage(Math.max(1, Math.min(p, totalPages)));
  };

  return (
    <div
      className={`flex h-full min-h-0 w-full flex-1 flex-col overflow-hidden ${PAGE_CONTENT_INSET}`}
    >
      <div className="flex h-full min-h-0 w-full min-w-0 flex-col overflow-hidden">
        {/* 左:标题 · 右:搜索框,关键词仅在搜索框下方 */}
        <div className="shrink-0 pb-2">
          <div className="flex w-full min-w-0 flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
            <div className="flex min-w-0 shrink-0 items-center gap-2 text-xl font-bold text-white sm:text-2xl">
              <Library className="h-6 w-6 shrink-0 text-sky-400" aria-hidden />
              <span className="truncate">{t("search.title")}</span>
            </div>
            <div className="flex w-full min-w-0 flex-col gap-1.5 sm:ml-auto sm:min-w-0 sm:flex-1 sm:max-w-[min(38rem,calc(100vw-2rem))] md:max-w-[min(44rem,calc(100vw-2.5rem))]">
              <form
                className="flex w-full min-w-0 shrink-0 gap-2"
                onSubmit={(e) => {
                  e.preventDefault();
                  searchInputRef.current?.blur();
                }}
              >
                <div className="relative min-w-0 flex-1">
                  <input
                    ref={searchInputRef}
                    type="search"
                    name="q"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    placeholder={t("search.placeholder")}
                    autoComplete="off"
                    className="w-full rounded-lg border border-white/25 bg-transparent py-1.5 pl-8 pr-2.5 text-xs text-white placeholder-blue-300/80 transition-all focus:border-sky-400/80 focus:outline-none focus:ring-1 focus:ring-sky-400/30 sm:py-2 sm:pl-9 sm:text-sm"
                  />
                  <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-blue-300/90 sm:left-3 sm:h-4 sm:w-4" />
                </div>
                <button
                  type="submit"
                  className="shrink-0 rounded-lg bg-sky-500/90 px-3 py-1.5 text-xs font-medium text-white shadow-sm transition-colors hover:bg-sky-400/95 active:bg-sky-500 sm:px-4 sm:py-2 sm:text-sm"
                >
                  {t("search.button")}
                </button>
              </form>
              <div className="flex max-h-[2.125rem] flex-wrap gap-x-1 gap-y-0 overflow-hidden sm:max-h-[2.375rem] sm:gap-x-1.5">
                {QUICK_KEYWORDS.map((word) => {
                  const active = searchQuery.trim() === word;
                  return (
                    <button
                      key={word}
                      type="button"
                      onClick={() => toggleKeyword(word)}
                      className={`shrink-0 border-0 bg-transparent px-0 py-0 text-left !text-[11px] font-normal leading-snug transition-colors sm:!text-[12px] ${
                        active
                          ? "font-semibold text-sky-300 underline decoration-sky-400/80 underline-offset-2"
                          : "text-blue-100/90 hover:text-white"
                      }`}
                    >
                      {word}
                    </button>
                  );
                })}
              </div>
            </div>
          </div>
        </div>

        {/* 搜索结果 + 分页 */}
        <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
          <div className="mb-1.5 shrink-0">
            <h3 className="text-sm font-medium text-white sm:text-base">
              {t("search.foundPrefix")}{" "}
              <span className="text-sky-400">{filteredResults.length}</span>{" "}
              {t("search.foundSuffix")}
            </h3>
          </div>

          {filteredResults.length > 0 && (
            <>
              <div className="grid min-h-0 flex-1 auto-rows-max content-start grid-cols-2 gap-2 overflow-hidden sm:grid-cols-3 md:grid-cols-5 md:gap-2">
                {pageItems.map((result) => {
                  const Icon = getTypeIcon(result.type);
                  return (
                    <article
                      key={result.id}
                      role="button"
                      tabIndex={0}
                      onClick={() => setActiveItem(result)}
                      onKeyDown={(e) => {
                        if (e.key === "Enter" || e.key === " ") {
                          e.preventDefault();
                          setActiveItem(result);
                        }
                      }}
                      className="group flex min-h-0 min-w-0 cursor-pointer flex-col overflow-hidden rounded-lg border border-white/20 bg-white/10 transition-all hover:border-sky-400/45 hover:shadow-md hover:shadow-sky-400/10 focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300/70"
                    >
                      <div className="relative h-[8.75rem] w-full shrink-0 overflow-hidden bg-zinc-900/50 sm:h-[10rem] md:h-[11.5rem]">
                        {result.image ? (
                          <img
                            src={resolveKioskMediaUrl(result.image)}
                            alt=""
                            className="absolute inset-0 h-full w-full object-cover object-center transition-transform duration-300 group-hover:scale-105"
                          />
                        ) : (
                          <div className="flex h-full w-full items-center justify-center text-blue-300/50">
                            <Icon className="h-8 w-8 sm:h-9 sm:w-9" strokeWidth={1.25} />
                          </div>
                        )}
                        {result.type === "视频" || hasKnowledgeVideoUrl(result) ? (
                          <div
                            className="pointer-events-none absolute inset-0 z-[1] flex items-center justify-center bg-black/20 transition-colors group-hover:bg-black/30"
                            aria-hidden
                          >
                            <span className="flex h-9 w-9 items-center justify-center rounded-full bg-white/95 text-sky-600 shadow-md ring-2 ring-white/40 sm:h-10 sm:w-10">
                              <Play className="ml-0.5 h-4 w-4 fill-current sm:h-[1.15rem] sm:w-[1.15rem]" strokeWidth={0} />
                            </span>
                          </div>
                        ) : null}
                        <span className="absolute right-1 top-1 z-[2] rounded bg-black/50 px-1 py-px text-[9px] font-medium text-white backdrop-blur-sm sm:text-[10px]">
                          {result.type}
                        </span>
                      </div>
                      <div className="flex flex-col gap-1 px-1.5 py-1.5 sm:px-2 sm:py-2">
                        <h4 className="line-clamp-2 shrink-0 text-xs font-bold leading-snug text-white group-hover:text-sky-200 sm:text-sm">
                          {result.title}
                        </h4>
                        {result.content.trim() ? (
                          <p className="line-clamp-2 text-xs leading-relaxed text-blue-100/85 sm:text-[13px]">
                            {result.content.trim()}
                          </p>
                        ) : null}
                        <div className="mt-0.5 grid w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-2 border-t border-white/10 pt-1">
                          <div className="flex min-w-0 flex-wrap items-center gap-1 sm:gap-1.5">
                            {result.tags.length > 0 ? (
                              <>
                                {result.tags.slice(0, 3).map((tag) => (
                                  <span
                                    key={tag}
                                    className="max-w-full truncate rounded bg-sky-500/15 px-1 py-0.5 text-[10px] text-sky-200/95 ring-1 ring-sky-400/20 sm:text-xs"
                                  >
                                    {tag}
                                  </span>
                                ))}
                                {result.tags.length > 3 ? (
                                  <span className="text-[10px] text-blue-300/65 sm:text-xs">
                                    +{result.tags.length - 3}
                                  </span>
                                ) : null}
                              </>
                            ) : null}
                          </div>
                          <time
                            className="shrink-0 text-right text-[10px] tabular-nums text-blue-300/75 sm:text-xs"
                            dateTime={result.date}
                          >
                            {result.date}
                          </time>
                        </div>
                      </div>
                    </article>
                  );
                })}
              </div>

              <nav
                className="mt-1.5 w-full min-w-0 shrink-0 overflow-x-auto overflow-y-visible pb-0.5 [-ms-overflow-style:none] [scrollbar-width:none] sm:mt-2 [&::-webkit-scrollbar]:hidden"
                aria-label={t("pager.label")}
              >
                <div className="ml-auto flex w-max max-w-none flex-nowrap items-center gap-1.5 sm:gap-2">
                  <span className="shrink-0 text-[11px] tabular-nums text-blue-200 sm:text-xs">
                    {t("pager.page")} {currentPage} / {totalPages}
                  </span>
                  <button
                    type="button"
                    onClick={() => goPage(currentPage - 1)}
                    disabled={currentPage <= 1}
                    className="flex shrink-0 items-center gap-1 rounded-md border border-white/20 bg-white/5 px-2 py-1 text-[11px] text-white transition-colors hover:bg-white/10 disabled:pointer-events-none disabled:opacity-35 sm:px-2.5 sm:py-1.5 sm:text-xs"
                  >
                    <ChevronLeft className="h-3.5 w-3.5 shrink-0" aria-hidden />
                    {t("pager.prev")}
                  </button>
                  <div className="flex shrink-0 flex-nowrap items-center gap-1">
                    {buildPageList(totalPages, currentPage).map((item, idx) =>
                      item === "ellipsis" ? (
                        <span
                          key={`e-${idx}`}
                          className="shrink-0 px-0.5 text-[11px] text-blue-200/90 sm:text-xs"
                          aria-hidden
                        >

                        </span>
                      ) : (
                        <button
                          key={item}
                          type="button"
                          onClick={() => goPage(item)}
                          aria-current={item === currentPage ? "page" : undefined}
                          className={`min-w-[1.75rem] shrink-0 rounded-md border border-white/15 px-1.5 py-1 text-[11px] font-medium transition-colors sm:min-w-[2rem] sm:text-xs ${
                            item === currentPage
                              ? "border-sky-400/50 bg-sky-500/90 text-blue-950"
                              : "bg-white/10 text-white hover:border-white/25 hover:bg-white/15"
                          }`}
                        >
                          {item}
                        </button>
                      )
                    )}
                  </div>
                  <button
                    type="button"
                    onClick={() => goPage(currentPage + 1)}
                    disabled={currentPage >= totalPages}
                    className="flex shrink-0 items-center gap-1 rounded-md border border-white/20 bg-white/5 px-2 py-1 text-[11px] text-white transition-colors hover:bg-white/10 disabled:pointer-events-none disabled:opacity-35 sm:px-2.5 sm:py-1.5 sm:text-xs"
                  >
                    {t("pager.next")}
                    <ChevronRight className="h-3.5 w-3.5 shrink-0" aria-hidden />
                  </button>
                </div>
              </nav>
            </>
          )}

          {filteredResults.length === 0 && (
            <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-2 py-4 text-center">
              <Search className="h-10 w-10 text-blue-400 opacity-50 sm:h-12 sm:w-12" />
              <p className="text-sm text-blue-300 sm:text-base">{t("search.noneTitle")}</p>
              <p className="text-xs text-blue-400/90">{t("search.noneHint")}</p>
            </div>
          )}
        </div>
      </div>

      <Dialog open={activeItem != null} onOpenChange={(open) => (open ? null : setActiveItem(null))}>
        <DialogContent className="max-w-[min(56rem,calc(100%-2rem))] border-white/15 bg-blue-950/70 text-white backdrop-blur-xl">
          {activeItem ? (
            <div className="grid min-h-0 gap-4 md:grid-cols-[minmax(0,1.1fr)_minmax(0,1fr)]">
              <div className="min-h-0">
                <DialogHeader>
                  <DialogTitle className="text-white">{activeItem.title}</DialogTitle>
                  <DialogDescription className="text-blue-100/80">
                    {activeItem.type} · {activeItem.date}
                    {activeItem.tags.length ? ` · ${activeItem.tags.join(" / ")}` : ""}
                  </DialogDescription>
                </DialogHeader>

                <div className="mt-3 whitespace-pre-wrap text-sm leading-relaxed text-blue-50/90">
                  {activeItem.content?.trim() ? activeItem.content.trim() : "(无详细内容)"}
                </div>
              </div>

              <div className="min-h-0 space-y-2">
                {hasKnowledgeVideoUrl(activeItem) ? (
                  <div className="space-y-1.5">
                    <p className="text-xs text-blue-200/90">视频(点击播放器控件播放)</p>
                    <video
                      className="aspect-video w-full max-h-[min(70vh,28rem)] rounded-md border border-white/15 bg-black/70"
                      controls
                      playsInline
                      preload="metadata"
                      poster={
                        activeItem.image
                          ? resolveKioskMediaUrl(activeItem.image)
                          : undefined
                      }
                      src={resolveKioskMediaUrl(activeItem.videoUrl)}
                    >
                      您的浏览器不支持视频播放。
                    </video>
                  </div>
                ) : activeItem.type === "视频" ? (
                  activeItem.image ? (
                    <div className="space-y-1.5">
                      <p className="text-xs text-amber-200/90">本条为「视频」类型但未填写视频地址,暂显示封面图。</p>
                      <img
                        src={resolveKioskMediaUrl(activeItem.image)}
                        alt={activeItem.title}
                        className="w-full rounded-md border border-white/10 bg-black/30 object-contain"
                        loading="lazy"
                      />
                    </div>
                  ) : (
                    <div className="flex aspect-video w-full items-center justify-center rounded-md border border-white/10 bg-black/40 text-sm text-blue-100/80">
                      暂无视频地址
                    </div>
                  )
                ) : activeItem.image ? (
                  <img
                    src={resolveKioskMediaUrl(activeItem.image)}
                    alt={activeItem.title}
                    className="w-full rounded-md border border-white/10 bg-black/30 object-contain"
                    loading="lazy"
                  />
                ) : (
                  <div className="flex aspect-video w-full items-center justify-center rounded-md border border-white/10 bg-black/40 text-sm text-blue-100/80">
                    暂无封面与视频
                  </div>
                )}
                {hasKnowledgeVideoUrl(activeItem) && activeItem.image ? (
                  <p className="text-[11px] leading-snug text-blue-300/80">
                    上图为视频封面;播放请使用上方控件。
                  </p>
                ) : null}
              </div>
            </div>
          ) : (
            <div className="text-sm text-white"> </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}