Implement three divination modes, learn pages, and PM2 deploy on port 3130.

Add liuyao/bazi/combined flows with shared calc and AI infrastructure, 64-gua learn routes, and update Ubuntu PM2 deployment docs for port 3130.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-06-10 20:19:49 +08:00
parent d141623070
commit fff77dac3f
41 changed files with 2590 additions and 385 deletions
-256
View File
@@ -1,256 +0,0 @@
"use client";
import React, { useEffect, useRef, useState } from "react";
import Coin from "@/components/coin";
import Hexagram, { HexagramObj } from "@/components/hexagram";
import { bool } from "aimless.js";
import Result, { ResultObj } from "@/components/result";
import Question from "@/components/question";
import ResultAI from "@/components/result-ai";
import { animateChildren } from "@/lib/animate";
import guaIndexData from "@/lib/data/gua-index.json";
import guaListData from "@/lib/data/gua-list.json";
import { getAnswer } from "@/app/server";
import { readStreamableValue } from "ai/rsc";
import { Button } from "./ui/button";
import { BrainCircuit, ListRestart } from "lucide-react";
import { ERROR_PREFIX } from "@/lib/constant";
const AUTO_DELAY = 600;
function Divination() {
const [error, setError] = useState<string>("");
const [isLoading, setIsLoading] = useState(false);
const [completion, setCompletion] = useState<string>("");
async function onCompletion() {
setError("");
setCompletion("");
setIsLoading(true);
try {
const { data, error } = await getAnswer(
question,
resultObj!.guaMark,
resultObj!.guaTitle,
resultObj!.guaResult,
resultObj!.guaChange,
);
if (error) {
setError(error);
return;
}
if (data) {
let ret = "";
for await (const delta of readStreamableValue(data)) {
if (delta.startsWith(ERROR_PREFIX)) {
setError(delta.slice(ERROR_PREFIX.length));
return;
}
ret += delta;
setCompletion(ret);
}
}
} catch (err: any) {
setError(err.message ?? err);
} finally {
setIsLoading(false);
}
}
const [frontList, setFrontList] = useState([true, true, true]);
const [rotation, setRotation] = useState(false);
const [hexagramList, setHexagramList] = useState<HexagramObj[]>([]);
const [resultObj, setResultObj] = useState<ResultObj | null>(null);
const [question, setQuestion] = useState("");
const [resultAi, setResultAi] = useState(false);
const flexRef = useRef<HTMLDivElement>(null);
const [count, setCount] = useState(0);
// 自动卜筮
useEffect(() => {
if (rotation || resultObj || count >= 6 || !question) {
return;
}
setTimeout(startClick, AUTO_DELAY);
}, [question, rotation]);
useEffect(() => {
if (!flexRef.current) {
return;
}
const observer = animateChildren(flexRef.current);
return () => observer.disconnect();
}, []);
function onTransitionEnd() {
setRotation(false);
let frontCount = frontList.reduce((acc, val) => (val ? acc + 1 : acc), 0);
setHexagramList((list) => {
const newList = [
...list,
{
change: frontCount == 0 || frontCount == 3 || null,
yang: frontCount >= 2,
separate: list.length == 3,
},
];
setResult(newList);
return newList;
});
}
function startClick() {
if (rotation) {
return;
}
if (hexagramList.length >= 6) {
setHexagramList([]);
}
setFrontList([bool(), bool(), bool()]);
setRotation(true);
setCount(count + 1);
}
async function testClick() {
for (let i = 0; i < 6; i++) {
onTransitionEnd();
}
}
function restartClick() {
setResultObj(null);
setHexagramList([]);
setQuestion("");
setResultAi(false);
setCount(0);
stop();
}
function aiClick() {
setResultAi(true);
onCompletion();
}
function setResult(list: HexagramObj[]) {
if (list.length != 6) {
return;
}
const guaDict1 = ["坤", "震", "坎", "兑", "艮", "离", "巽", "乾"];
const guaDict2 = ["地", "雷", "水", "泽", "山", "火", "风", "天"];
const changeYang = ["初九", "九二", "九三", "九四", "九五", "上九"];
const changeYin = ["初六", "六二", "六三", "六四", "六五", "上六"];
const changeList: String[] = [];
list.forEach((value, index) => {
if (!value.change) {
return;
}
changeList.push(value.yang ? changeYang[index] : changeYin[index]);
});
// 卦的结果: 第X卦 X卦 XX卦 X上X下
// 计算卦的索引,111对应乾卦,000对应坤卦,索引转为10进制。
const upIndex =
(list[5].yang ? 4 : 0) + (list[4].yang ? 2 : 0) + (list[3].yang ? 1 : 0);
const downIndex =
(list[2].yang ? 4 : 0) + (list[1].yang ? 2 : 0) + (list[0].yang ? 1 : 0);
const guaIndex = guaIndexData[upIndex][downIndex] - 1;
const guaName1 = guaListData[guaIndex];
let guaName2;
if (upIndex === downIndex) {
// 上下卦相同,格式为X为X
guaName2 = guaDict1[upIndex] + "为" + guaDict2[upIndex];
} else {
guaName2 = guaDict2[upIndex] + guaDict2[downIndex] + guaName1;
}
const guaDesc = guaDict1[upIndex] + "上" + guaDict1[downIndex] + "下";
setResultObj({
// 例:26.山天大畜
guaMark: `${(guaIndex + 1).toString().padStart(2, "0")}.${guaName2}`,
guaTitle: `周易第${guaIndex + 1}`,
// 例:大畜卦(山天大畜)_艮上乾下
guaResult: `${guaName1}卦(${guaName2})_${guaDesc}`,
guaChange:
changeList.length === 0 ? "无变爻" : `变爻: ${changeList.toString()}`,
});
}
const showResult = resultObj !== null;
const inputQuestion = question === "";
return (
<main
ref={flexRef}
className="gap mx-auto flex h-0 w-[90%] flex-1 flex-col flex-nowrap items-center"
>
<Question question={question} setQuestion={setQuestion} />
{!resultAi && !inputQuestion && (
<Coin
onTransitionEnd={onTransitionEnd}
frontList={frontList}
rotation={rotation}
/>
)}
{!inputQuestion && !showResult && (
<div className="relative">
<span className="pl-2 text-lg font-medium">
🎲 {" "}
<span className="font-mono text-xl font-bold text-orange-500">
{count === 0 ? "-/-" : `${count}/6`}
</span>{" "}
</span>
</div>
)}
{!inputQuestion && hexagramList.length != 0 && (
<div className="flex max-w-md gap-2">
<Hexagram list={hexagramList} />
{showResult && (
<div className="flex flex-col justify-around">
<Result {...resultObj} />
<div className="flex flex-col gap-2 sm:px-6">
<Button
size="sm"
variant="destructive"
onClick={restartClick}
disabled={rotation}
>
<ListRestart size={18} className="mr-1" />
</Button>
{resultAi ? null : (
<Button size="sm" onClick={aiClick} disabled={rotation}>
<BrainCircuit size={16} className="mr-1" />
AI
</Button>
)}
</div>
</div>
)}
</div>
)}
{resultAi && (
<ResultAI
completion={completion}
isLoading={isLoading}
onCompletion={onCompletion}
error={error}
/>
)}
</main>
);
}
export default Divination;
+43 -5
View File
@@ -1,15 +1,53 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { ChatGPT } from "@/components/svg";
import { ModeToggle } from "@/components/mode-toggle";
const NAV_ITEMS = [
{ href: "/learn", label: "易经学习" },
{ href: "/liuyao", label: "六爻算卦" },
{ href: "/bazi", label: "生辰八字" },
{ href: "/combined", label: "综合测算" },
];
function NavLink({ href, label }: { href: string; label: string }) {
const pathname = usePathname();
const active =
href === "/"
? pathname === "/"
: pathname === href || pathname.startsWith(`${href}/`);
return (
<Link
href={href}
className={`whitespace-nowrap text-sm transition-colors ${
active
? "font-medium text-foreground"
: "text-muted-foreground hover:text-foreground"
}`}
>
{label}
</Link>
);
}
export default function Header() {
return (
<header className="h-14 bg-secondary py-2 shadow">
<div className="mx-auto flex h-full w-full items-center justify-center sm:max-w-md sm:justify-between md:max-w-2xl">
<div className="flex gap-2">
<header className="bg-secondary py-2 shadow">
<div className="mx-auto flex w-full max-w-4xl flex-col gap-2 px-4 sm:flex-row sm:items-center sm:justify-between">
<Link href="/" className="flex items-center justify-center gap-2 sm:justify-start">
<ChatGPT />
<span></span>
<span className="font-medium"></span>
</Link>
<nav className="flex flex-wrap items-center justify-center gap-x-4 gap-y-1">
{NAV_ITEMS.map((item) => (
<NavLink key={item.href} {...item} />
))}
</nav>
<div className="flex justify-center sm:justify-end">
<ModeToggle />
</div>
<ModeToggle />
</div>
</header>
);
+16
View File
@@ -0,0 +1,16 @@
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Sparkles } from "lucide-react";
export default function GuaFooter({ guaMark }: { guaMark: string }) {
return (
<div className="mt-8 flex flex-wrap gap-3 border-t pt-6">
<Button asChild size="sm">
<Link href={`/liuyao?gua=${encodeURIComponent(guaMark)}`}>
<Sparkles size={16} className="mr-1" />
</Link>
</Button>
</div>
);
}
+75
View File
@@ -0,0 +1,75 @@
import Link from "next/link";
import Markdown from "react-markdown";
import type { LearnVariant } from "@/lib/content/zhouyi";
function resolveLearnHref(
href: string | undefined,
variant: LearnVariant,
): string | undefined {
if (!href) {
return href;
}
if (href.startsWith("http://") || href.startsWith("https://")) {
return href;
}
const base = variant === "traditional" ? "/learn" : "/learn/other";
if (href === "index.md" || href === "./index.md") {
return base;
}
if (href === "other/index.md") {
return "/learn/other";
}
if (href.endsWith("/index.md")) {
const mark = href.replace(/\/index\.md$/, "").replace(/^\.\//, "");
if (mark.startsWith("other/")) {
return `/learn/other/${mark.slice("other/".length)}`;
}
return `${base}/${mark}`;
}
return href;
}
export default function MarkdownContent({
content,
variant = "traditional",
}: {
content: string;
variant?: LearnVariant;
}) {
return (
<Markdown
className="prose max-w-none dark:prose-invert prose-headings:scroll-mt-20 prose-a:text-primary"
components={{
a: ({ href, children, ...props }) => {
const resolved = resolveLearnHref(href, variant);
if (resolved?.startsWith("/")) {
return (
<Link href={resolved} {...props}>
{children}
</Link>
);
}
return (
<a href={resolved} {...props}>
{children}
</a>
);
},
img: ({ src, alt, ...props }) => {
if (typeof src === "string" && !src.startsWith("http")) {
return (
<span className="my-2 block rounded border border-dashed p-4 text-center text-sm text-muted-foreground">
[{alt || "卦象图片"}]
</span>
);
}
return <img src={src} alt={alt} {...props} />;
},
}}
>
{content}
</Markdown>
);
}
+72
View File
@@ -0,0 +1,72 @@
import type { BaziChart, PillarInfo } from "@/lib/calc/bazi";
function PillarRow({ label, pillar }: { label: string; pillar: PillarInfo }) {
return (
<tr className="border-t">
<td className="px-3 py-2 font-medium">{label}</td>
<td className="px-3 py-2 font-mono">{pillar.ganZhi}</td>
<td className="px-3 py-2">{pillar.shiShenGan}</td>
<td className="px-3 py-2 text-sm">
{pillar.shiShenZhi.join("、") || "—"}
</td>
<td className="px-3 py-2 text-sm">{pillar.naYin}</td>
</tr>
);
}
export default function BaziChartDisplay({ chart }: { chart: BaziChart }) {
return (
<div className="space-y-4 rounded-lg border bg-card p-4 text-sm">
<div className="grid gap-1 text-muted-foreground sm:grid-cols-2">
<span>{chart.birthTime}</span>
<span>{chart.trueSolarTime}</span>
<span className="sm:col-span-2">{chart.lunarDate}</span>
</div>
<div className="overflow-x-auto">
<table className="w-full">
<thead className="bg-muted/50 text-left">
<tr>
<th className="px-3 py-2"></th>
<th className="px-3 py-2"></th>
<th className="px-3 py-2"></th>
<th className="px-3 py-2"></th>
<th className="px-3 py-2"></th>
</tr>
</thead>
<tbody>
<PillarRow label="年柱" pillar={chart.pillars.year} />
<PillarRow label="月柱" pillar={chart.pillars.month} />
<PillarRow label="日柱" pillar={chart.pillars.day} />
<PillarRow label="时柱" pillar={chart.pillars.time} />
</tbody>
</table>
</div>
<div>
<div className="mb-1 font-medium"></div>
<p className="text-muted-foreground">
{chart.daYun.startYear} {chart.daYun.startMonth} {" "}
{chart.daYun.startDay} ·{" "}
{chart.daYun.items.map((d) => `${d.startAge}${d.ganZhi}`).join(" → ")}
</p>
</div>
<div>
<div className="mb-1 font-medium"></div>
<p className="text-muted-foreground">
{chart.liuNian.map((l) => `${l.year}(${l.ganZhi})`).join("、")}
</p>
</div>
<div>
<div className="mb-1 font-medium"></div>
<p className="text-muted-foreground">
{chart.shenSha.ji.join("、") || "无"}
<br />
{chart.shenSha.xiong.join("、") || "无"}
</p>
</div>
</div>
);
}
+188
View File
@@ -0,0 +1,188 @@
"use client";
import { useState } from "react";
import { readStreamableValue } from "ai/rsc";
import { BrainCircuit } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import ResultAI from "@/components/result-ai";
import BaziChartDisplay from "@/components/modes/bazi-chart";
import DateTimePicker, { nowDateString } from "@/components/shared/datetime-picker";
import RegionSelect, {
useRegionLocation,
} from "@/components/shared/region-select";
import { calculateBazi, type BaziChart } from "@/lib/calc/bazi";
import { getBaziAnswer } from "@/app/actions/bazi";
import { ERROR_PREFIX } from "@/lib/constant";
export default function BaziForm() {
const [date, setDate] = useState(nowDateString());
const [time, setTime] = useState("12:00");
const [unknownHour, setUnknownHour] = useState(false);
const [gender, setGender] = useState<"male" | "female">("male");
const [provinceCode, setProvinceCode] = useState("");
const [cityCode, setCityCode] = useState("");
const [question, setQuestion] = useState("");
const [chart, setChart] = useState<BaziChart | null>(null);
const [completion, setCompletion] = useState("");
const [error, setError] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [showAi, setShowAi] = useState(false);
const location = useRegionLocation(provinceCode, cityCode);
function buildInput() {
if (!location) {
return null;
}
return {
date,
time: unknownHour ? "12:00" : time,
gender,
longitude: location.longitude,
unknownHour,
};
}
function handleCalculate() {
const input = buildInput();
if (!input) {
setError("请选择出生地域");
return;
}
if (!question.trim()) {
setError("请输入问事");
return;
}
setError("");
setChart(calculateBazi(input));
setShowAi(false);
setCompletion("");
}
async function handleAnalyze() {
const input = buildInput();
if (!input || !chart) {
return;
}
setError("");
setCompletion("");
setIsLoading(true);
setShowAi(true);
try {
const { data, error: apiError } = await getBaziAnswer(
input,
question,
location!.name,
);
if (apiError) {
setError(apiError);
return;
}
if (data) {
let ret = "";
for await (const delta of readStreamableValue(data)) {
if (typeof delta === "string" && delta.startsWith(ERROR_PREFIX)) {
setError(delta.slice(ERROR_PREFIX.length));
return;
}
ret += delta ?? "";
setCompletion(ret);
}
}
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setIsLoading(false);
}
}
return (
<div className="flex flex-1 flex-col gap-4 px-4 py-6">
<div className="mx-auto w-full max-w-lg space-y-4">
<DateTimePicker
label="出生日期 / 时间"
date={date}
time={time}
timeDisabled={unknownHour}
onDateChange={setDate}
onTimeChange={setTime}
/>
<label className="flex items-center gap-2 text-xs text-muted-foreground">
<input
type="checkbox"
checked={unknownHour}
onChange={(e) => setUnknownHour(e.target.checked)}
/>
</label>
<div className="space-y-1">
<label className="text-sm font-medium"></label>
<div className="flex gap-4">
{(["male", "female"] as const).map((g) => (
<label key={g} className="flex items-center gap-2 text-sm">
<input
type="radio"
name="gender"
checked={gender === g}
onChange={() => setGender(g)}
/>
{g === "male" ? "男" : "女"}
</label>
))}
</div>
</div>
<RegionSelect
label="出生地域"
provinceCode={provinceCode}
cityCode={cityCode}
onProvinceChange={setProvinceCode}
onCityChange={setCityCode}
/>
<div className="space-y-1">
<label className="text-sm font-medium"></label>
<Textarea
placeholder="事业、婚姻、健康等..."
value={question}
onChange={(e) => setQuestion(e.target.value)}
rows={3}
/>
</div>
{error && !showAi && (
<p className="text-sm text-destructive">{error}</p>
)}
<Button onClick={handleCalculate} className="w-full">
</Button>
</div>
{chart && (
<div className="mx-auto w-full max-w-lg space-y-4">
<BaziChartDisplay chart={chart} />
{!showAi && (
<Button onClick={handleAnalyze} className="w-full">
<BrainCircuit size={16} className="mr-1" />
</Button>
)}
</div>
)}
{showAi && (
<div className="mx-auto h-96 w-full max-w-lg flex-1">
<ResultAI
completion={completion}
isLoading={isLoading}
onCompletion={handleAnalyze}
error={error}
/>
</div>
)}
</div>
);
}
+325
View File
@@ -0,0 +1,325 @@
"use client";
import { useState } from "react";
import { readStreamableValue } from "ai/rsc";
import { Compass } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import Result from "@/components/result";
import ResultAI from "@/components/result-ai";
import BaziChartDisplay from "@/components/modes/bazi-chart";
import DateTimePicker, {
nowDateString,
nowTimeString,
} from "@/components/shared/datetime-picker";
import HexagramInput from "@/components/shared/hexagram-input";
import RegionSelect, {
useRegionLocation,
} from "@/components/shared/region-select";
import { calculateBazi, type BaziChart } from "@/lib/calc/bazi";
import type { GuaResult } from "@/lib/calc/hexagram";
import { getCombinedAnswer } from "@/app/actions/combined";
import { ERROR_PREFIX } from "@/lib/constant";
export default function CombinedForm() {
const [birthDate, setBirthDate] = useState("1990-01-01");
const [birthTime, setBirthTime] = useState("12:00");
const [unknownHour, setUnknownHour] = useState(false);
const [gender, setGender] = useState<"male" | "female">("male");
const [birthProvince, setBirthProvince] = useState("");
const [birthCity, setBirthCity] = useState("");
const [currentProvince, setCurrentProvince] = useState("");
const [currentCity, setCurrentCity] = useState("");
const [calcDate, setCalcDate] = useState(nowDateString);
const [calcTime, setCalcTime] = useState(nowTimeString);
const [question, setQuestion] = useState("");
const [withHexagram, setWithHexagram] = useState(false);
const [castMode, setCastMode] = useState<"online" | "offline">("online");
const [guaData, setGuaData] = useState<GuaResult | null>(null);
const [chart, setChart] = useState<BaziChart | null>(null);
const [completion, setCompletion] = useState("");
const [error, setError] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [showAi, setShowAi] = useState(false);
const birthLocation = useRegionLocation(birthProvince, birthCity);
const currentLocation = useRegionLocation(currentProvince, currentCity);
const hexagramReady =
!withHexagram ||
(question.trim() !== "" && currentLocation !== null && guaData !== null);
function validate(): string | null {
if (!birthLocation) {
return "请选择出生地域";
}
if (!currentLocation) {
return "请选择当前所在地域";
}
if (!question.trim()) {
return "请输入问事内容";
}
if (withHexagram && !guaData) {
return "请完成六爻起卦,或取消附加六爻";
}
return null;
}
function handlePreview() {
const err = validate();
if (err) {
setError(err);
return;
}
setError("");
setChart(
calculateBazi({
date: birthDate,
time: unknownHour ? "12:00" : birthTime,
gender,
longitude: birthLocation!.longitude,
unknownHour,
}),
);
setShowAi(false);
setCompletion("");
}
async function handleAnalyze() {
const err = validate();
if (err) {
setError(err);
return;
}
if (!chart) {
setChart(
calculateBazi({
date: birthDate,
time: unknownHour ? "12:00" : birthTime,
gender,
longitude: birthLocation!.longitude,
unknownHour,
}),
);
}
setError("");
setCompletion("");
setIsLoading(true);
setShowAi(true);
try {
const { data, error: apiError } = await getCombinedAnswer({
birth: {
date: birthDate,
time: unknownHour ? "12:00" : birthTime,
gender,
longitude: birthLocation!.longitude,
unknownHour,
},
birthPlaceName: birthLocation!.name,
currentPlaceName: currentLocation!.name,
currentLongitude: currentLocation!.longitude,
calcDate,
calcTime,
question,
hexagram: withHexagram && guaData
? {
guaMark: guaData.result.guaMark,
guaTitle: guaData.result.guaTitle,
guaResult: guaData.result.guaResult,
guaChange: guaData.result.guaChange,
}
: undefined,
});
if (apiError) {
setError(apiError);
return;
}
if (data) {
let ret = "";
for await (const delta of readStreamableValue(data)) {
if (typeof delta === "string" && delta.startsWith(ERROR_PREFIX)) {
setError(delta.slice(ERROR_PREFIX.length));
return;
}
ret += delta ?? "";
setCompletion(ret);
}
}
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setIsLoading(false);
}
}
return (
<div className="flex flex-1 flex-col gap-4 px-4 py-6">
<div className="mx-auto w-full max-w-lg space-y-6">
<section className="space-y-3">
<h2 className="text-sm font-semibold text-primary"> · </h2>
<DateTimePicker
label="出生日期 / 时间"
date={birthDate}
time={birthTime}
timeDisabled={unknownHour}
onDateChange={setBirthDate}
onTimeChange={setBirthTime}
/>
<label className="flex items-center gap-2 text-xs text-muted-foreground">
<input
type="checkbox"
checked={unknownHour}
onChange={(e) => setUnknownHour(e.target.checked)}
/>
</label>
<div className="flex gap-4">
{(["male", "female"] as const).map((g) => (
<label key={g} className="flex items-center gap-2 text-sm">
<input
type="radio"
name="combined-gender"
checked={gender === g}
onChange={() => setGender(g)}
/>
{g === "male" ? "男" : "女"}
</label>
))}
</div>
<RegionSelect
label="出生地域"
provinceCode={birthProvince}
cityCode={birthCity}
onProvinceChange={setBirthProvince}
onCityChange={setBirthCity}
/>
</section>
<section className="space-y-3">
<h2 className="text-sm font-semibold text-primary"> · </h2>
<RegionSelect
label="所在地域"
provinceCode={currentProvince}
cityCode={currentCity}
onProvinceChange={setCurrentProvince}
onCityChange={setCurrentCity}
/>
</section>
<section className="space-y-3">
<h2 className="text-sm font-semibold text-primary"> · </h2>
<DateTimePicker
label="日期 / 时间"
date={calcDate}
time={calcTime}
onDateChange={setCalcDate}
onTimeChange={setCalcTime}
/>
</section>
<section className="space-y-3">
<h2 className="text-sm font-semibold text-primary"></h2>
<Textarea
placeholder="具体所求..."
value={question}
onChange={(e) => setQuestion(e.target.value)}
rows={3}
/>
</section>
<section className="space-y-3">
<label className="flex items-center gap-2 text-sm font-medium">
<input
type="checkbox"
checked={withHexagram}
onChange={(e) => {
setWithHexagram(e.target.checked);
setGuaData(null);
setShowAi(false);
}}
/>
</label>
{withHexagram && (
<div className="space-y-3 rounded-md border p-3">
<div className="flex gap-2">
<Button
type="button"
size="sm"
variant={castMode === "online" ? "default" : "outline"}
onClick={() => {
setCastMode("online");
setGuaData(null);
}}
>
线
</Button>
<Button
type="button"
size="sm"
variant={castMode === "offline" ? "default" : "outline"}
onClick={() => {
setCastMode("offline");
setGuaData(null);
}}
>
线
</Button>
</div>
<HexagramInput
key={castMode}
mode={castMode}
enabled={question.trim() !== "" && currentLocation !== null}
onResult={setGuaData}
onClear={() => setGuaData(null)}
/>
{guaData && (
<div className="rounded-md border bg-card p-3">
<Result {...guaData.result} />
</div>
)}
</div>
)}
</section>
{error && !showAi && (
<p className="text-sm text-destructive">{error}</p>
)}
<div className="flex gap-2">
<Button variant="outline" onClick={handlePreview} className="flex-1">
</Button>
<Button
onClick={handleAnalyze}
disabled={withHexagram && !hexagramReady}
className="flex-1"
>
<Compass size={16} className="mr-1" />
</Button>
</div>
</div>
{chart && (
<div className="mx-auto w-full max-w-lg">
<BaziChartDisplay chart={chart} />
</div>
)}
{showAi && (
<div className="mx-auto h-96 w-full max-w-lg flex-1">
<ResultAI
completion={completion}
isLoading={isLoading}
onCompletion={handleAnalyze}
error={error}
/>
</div>
)}
</div>
);
}
+237
View File
@@ -0,0 +1,237 @@
"use client";
import { useState } from "react";
import { readStreamableValue } from "ai/rsc";
import { Compass, ListRestart } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import Result from "@/components/result";
import ResultAI from "@/components/result-ai";
import DateTimePicker, {
nowDateString,
nowTimeString,
} from "@/components/shared/datetime-picker";
import HexagramInput from "@/components/shared/hexagram-input";
import RegionSelect, {
useRegionLocation,
} from "@/components/shared/region-select";
import { getLiuyaoAnswer } from "@/app/actions/liuyao";
import type { GuaResult } from "@/lib/calc/hexagram";
import { ERROR_PREFIX } from "@/lib/constant";
import todayJson from "@/lib/data/today.json";
const todayData: string[] = todayJson;
export default function LiuyaoForm() {
const [question, setQuestion] = useState("");
const [provinceCode, setProvinceCode] = useState("");
const [cityCode, setCityCode] = useState("");
const [calcDate, setCalcDate] = useState(nowDateString);
const [calcTime, setCalcTime] = useState(nowTimeString);
const [castMode, setCastMode] = useState<"online" | "offline">("online");
const [guaData, setGuaData] = useState<GuaResult | null>(null);
const [completion, setCompletion] = useState("");
const [error, setError] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [showAi, setShowAi] = useState(false);
const location = useRegionLocation(provinceCode, cityCode);
const formReady = question.trim() !== "" && location !== null;
function validate(): string | null {
if (!question.trim()) {
return "请输入问事";
}
if (!location) {
return "请选择起卦地域";
}
if (!guaData) {
return "请先完成起卦(线上摇卦或线下录入)";
}
return null;
}
async function handleAnalyze() {
const err = validate();
if (err) {
setError(err);
return;
}
setError("");
setCompletion("");
setIsLoading(true);
setShowAi(true);
try {
const { data, error: apiError } = await getLiuyaoAnswer({
question,
calcDate,
calcTime,
locationName: location!.name,
longitude: location!.longitude,
guaMark: guaData!.result.guaMark,
guaTitle: guaData!.result.guaTitle,
guaResult: guaData!.result.guaResult,
guaChange: guaData!.result.guaChange,
});
if (apiError) {
setError(apiError);
return;
}
if (data) {
let ret = "";
for await (const delta of readStreamableValue(data)) {
if (typeof delta === "string" && delta.startsWith(ERROR_PREFIX)) {
setError(delta.slice(ERROR_PREFIX.length));
return;
}
ret += delta ?? "";
setCompletion(ret);
}
}
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setIsLoading(false);
}
}
function handleReset() {
setQuestion("");
setProvinceCode("");
setCityCode("");
setCalcDate(nowDateString());
setCalcTime(nowTimeString());
setGuaData(null);
setCompletion("");
setError("");
setShowAi(false);
setIsLoading(false);
}
function handleGuaResult(data: GuaResult) {
setGuaData(data);
setShowAi(false);
setCompletion("");
}
return (
<div className="flex flex-1 flex-col gap-4 px-4 py-6">
<div className="mx-auto w-full max-w-lg space-y-5">
<section className="space-y-2">
<label className="text-sm font-medium"></label>
<Textarea
placeholder="您想算点什么?"
value={question}
onChange={(e) => setQuestion(e.target.value)}
rows={3}
/>
<div className="flex flex-wrap gap-2">
{todayData.map((item, index) => (
<button
key={index}
type="button"
onClick={() => setQuestion(item)}
className="rounded-md border bg-secondary px-2 py-1 text-xs text-muted-foreground transition hover:bg-accent"
>
{item}
</button>
))}
</div>
</section>
<RegionSelect
label="起卦地域"
provinceCode={provinceCode}
cityCode={cityCode}
onProvinceChange={setProvinceCode}
onCityChange={setCityCode}
/>
<DateTimePicker
label="起卦时辰"
date={calcDate}
time={calcTime}
onDateChange={setCalcDate}
onTimeChange={setCalcTime}
/>
<section className="space-y-2">
<label className="text-sm font-medium"></label>
<div className="flex gap-2">
<Button
type="button"
size="sm"
variant={castMode === "online" ? "default" : "outline"}
onClick={() => {
setCastMode("online");
setGuaData(null);
setShowAi(false);
}}
>
线
</Button>
<Button
type="button"
size="sm"
variant={castMode === "offline" ? "default" : "outline"}
onClick={() => {
setCastMode("offline");
setGuaData(null);
setShowAi(false);
}}
>
线
</Button>
</div>
</section>
<HexagramInput
key={castMode}
mode={castMode}
enabled={formReady}
onResult={handleGuaResult}
onClear={() => setGuaData(null)}
/>
{guaData && (
<div className="rounded-lg border bg-card p-4">
<Result {...guaData.result} />
</div>
)}
{error && !showAi && (
<p className="text-sm text-destructive">{error}</p>
)}
<div className="flex gap-2">
<Button variant="outline" onClick={handleReset} className="flex-1">
<ListRestart size={16} className="mr-1" />
</Button>
<Button
onClick={handleAnalyze}
disabled={!guaData || isLoading}
className="flex-1"
>
<Compass size={16} className="mr-1" />
</Button>
</div>
</div>
{showAi && (
<div className="mx-auto h-96 w-full max-w-lg flex-1">
<ResultAI
completion={completion}
isLoading={isLoading}
onCompletion={handleAnalyze}
error={error}
/>
</div>
)}
</div>
);
}
+20
View File
@@ -0,0 +1,20 @@
import Header from "@/components/header";
import Footer from "@/components/footer";
export default function PageShell({
children,
className = "",
}: {
children: React.ReactNode;
className?: string;
}) {
return (
<div className="flex min-h-screen flex-col">
<Header />
<div className={`mx-auto flex w-full flex-1 flex-col ${className}`}>
{children}
</div>
<Footer />
</div>
);
}
+49
View File
@@ -0,0 +1,49 @@
"use client";
interface DateTimePickerProps {
date: string;
time: string;
onDateChange: (date: string) => void;
onTimeChange: (time: string) => void;
label?: string;
timeDisabled?: boolean;
}
export function nowDateString() {
return new Date().toISOString().slice(0, 10);
}
export function nowTimeString() {
const d = new Date();
return `${d.getHours().toString().padStart(2, "0")}:${d.getMinutes().toString().padStart(2, "0")}`;
}
export default function DateTimePicker({
date,
time,
onDateChange,
onTimeChange,
label = "时间",
timeDisabled = false,
}: DateTimePickerProps) {
return (
<div className="space-y-2">
<label className="text-sm font-medium">{label}</label>
<div className="grid gap-2 sm:grid-cols-2">
<input
type="date"
className="rounded-md border bg-background px-3 py-2 text-sm disabled:opacity-50"
value={date}
onChange={(e) => onDateChange(e.target.value)}
/>
<input
type="time"
className="rounded-md border bg-background px-3 py-2 text-sm disabled:opacity-50"
value={time}
disabled={timeDisabled}
onChange={(e) => onTimeChange(e.target.value)}
/>
</div>
</div>
);
}
+202
View File
@@ -0,0 +1,202 @@
"use client";
import { useEffect, useState } from "react";
import { bool } from "aimless.js";
import Coin from "@/components/coin";
import Hexagram from "@/components/hexagram";
import { Button } from "@/components/ui/button";
import {
buildHexagramList,
COIN_OPTIONS,
computeGuaResult,
type GuaResult,
YAO_LABELS,
} from "@/lib/calc/hexagram";
const AUTO_DELAY = 600;
interface HexagramInputProps {
mode: "online" | "offline";
enabled: boolean;
onResult: (data: GuaResult) => void;
onClear: () => void;
}
export default function HexagramInput({
mode,
enabled,
onResult,
onClear,
}: HexagramInputProps) {
const [frontList, setFrontList] = useState([true, true, true]);
const [rotation, setRotation] = useState(false);
const [hexagramList, setHexagramList] = useState<
GuaResult["list"]
>([]);
const [count, setCount] = useState(0);
const [offlineCounts, setOfflineCounts] = useState<(number | null)[]>(
Array(6).fill(null),
);
useEffect(() => {
setHexagramList([]);
setCount(0);
setOfflineCounts(Array(6).fill(null));
setRotation(false);
}, [mode]);
useEffect(() => {
if (
mode !== "online" ||
!enabled ||
rotation ||
hexagramList.length >= 6 ||
count >= 6
) {
return;
}
const timer = setTimeout(startOnlineCast, AUTO_DELAY);
return () => clearTimeout(timer);
}, [mode, enabled, rotation, count, hexagramList.length]);
function finishList(list: GuaResult["list"]) {
const result = computeGuaResult(list);
if (result) {
onResult({ list, result });
}
}
function onTransitionEnd() {
setRotation(false);
const frontCount = frontList.reduce(
(acc, val) => (val ? acc + 1 : acc),
0,
);
setHexagramList((list) => {
const newList = [
...list,
{
change: frontCount === 0 || frontCount === 3,
yang: frontCount >= 2,
separate: list.length === 3,
},
];
if (newList.length === 6) {
finishList(newList);
}
return newList;
});
}
function startOnlineCast() {
if (rotation || !enabled || hexagramList.length >= 6) {
return;
}
setFrontList([bool(), bool(), bool()]);
setRotation(true);
setCount((c) => c + 1);
}
function handleOfflineSelect(index: number, frontCount: number) {
const next = [...offlineCounts];
next[index] = frontCount;
setOfflineCounts(next);
}
function confirmOffline() {
if (offlineCounts.some((v) => v === null)) {
return;
}
const list = buildHexagramList(offlineCounts as number[]);
finishList(list);
setHexagramList(list);
}
function handleReset() {
setHexagramList([]);
setCount(0);
setOfflineCounts(Array(6).fill(null));
setRotation(false);
onClear();
}
const complete = hexagramList.length === 6;
const offlineReady = offlineCounts.every((v) => v !== null);
if (!enabled) {
return (
<p className="text-center text-sm text-muted-foreground">
</p>
);
}
return (
<div className="flex w-full flex-col items-center gap-4">
{mode === "online" && !complete && (
<>
<Coin
onTransitionEnd={onTransitionEnd}
frontList={frontList}
rotation={rotation}
/>
<span className="text-lg font-medium">
🎲 {" "}
<span className="font-mono text-xl font-bold text-orange-500">
{count === 0 ? "-/-" : `${count}/6`}
</span>{" "}
</span>
</>
)}
{mode === "offline" && !complete && (
<div className="w-full max-w-md space-y-2">
<p className="text-center text-xs text-muted-foreground">
</p>
{YAO_LABELS.map((label, index) => (
<div
key={label}
className="flex flex-wrap items-center gap-2 rounded-md border p-2"
>
<span className="w-10 shrink-0 text-sm font-medium">{label}</span>
{COIN_OPTIONS.map((opt) => (
<button
key={opt.count}
type="button"
onClick={() => handleOfflineSelect(index, opt.count)}
className={`rounded border px-2 py-1 text-xs transition ${
offlineCounts[index] === opt.count
? "border-primary bg-primary/10 text-primary"
: "hover:bg-accent"
}`}
>
{opt.label}
</button>
))}
</div>
))}
<Button
className="w-full"
disabled={!offlineReady}
onClick={confirmOffline}
>
</Button>
</div>
)}
{hexagramList.length > 0 && (
<div className="flex flex-col items-center gap-3 sm:flex-row">
<Hexagram list={hexagramList} />
{complete && (
<Button size="sm" variant="outline" onClick={handleReset}>
</Button>
)}
</div>
)}
</div>
);
}
+64
View File
@@ -0,0 +1,64 @@
"use client";
import { getProvinces, getCities, getRegionLocation } from "@/lib/data/regions";
interface RegionSelectProps {
provinceCode: string;
cityCode: string;
onProvinceChange: (code: string) => void;
onCityChange: (code: string) => void;
label?: string;
}
export default function RegionSelect({
provinceCode,
cityCode,
onProvinceChange,
onCityChange,
label = "出生地域",
}: RegionSelectProps) {
const provinces = getProvinces();
const cities = provinceCode ? getCities(provinceCode) : [];
return (
<div className="space-y-2">
<label className="text-sm font-medium">{label}</label>
<div className="grid gap-2 sm:grid-cols-2">
<select
className="rounded-md border bg-background px-3 py-2 text-sm"
value={provinceCode}
onChange={(e) => {
onProvinceChange(e.target.value);
onCityChange("");
}}
>
<option value=""></option>
{provinces.map((p) => (
<option key={p.code} value={p.code}>
{p.name}
</option>
))}
</select>
<select
className="rounded-md border bg-background px-3 py-2 text-sm"
value={cityCode}
onChange={(e) => onCityChange(e.target.value)}
disabled={!provinceCode}
>
<option value="">/</option>
{cities.map((c) => (
<option key={c.code} value={c.code}>
{c.name}
</option>
))}
</select>
</div>
</div>
);
}
export function useRegionLocation(provinceCode: string, cityCode: string) {
return provinceCode
? getRegionLocation(provinceCode, cityCode)
: null;
}