fix: 移除误推送的文件(.DS_Store、web/、server/web/)
Publish Mini Program Dev Version / publish (push) Waiting to run

This commit is contained in:
gouki
2026-08-06 22:29:35 +00:00
parent 90baf8441c
commit c754ae6be1
93 changed files with 1 additions and 13444 deletions
Vendored
BIN
View File
Binary file not shown.
+1
View File
@@ -57,6 +57,7 @@ server/vendor/
# 前端构建(如果 server 包含前端) # 前端构建(如果 server 包含前端)
server/public/build/ server/public/build/
server/public/hot server/public/hot
server/web/
# 数据库 # 数据库
*.db *.db
-38
View File
@@ -1,38 +0,0 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ .title }} - 祈福小助手管理后台</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://unpkg.com/@inertiajs/vue3@1.0.0/dist/index.umd.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="bg-gray-100">
<div id="app" data-page='{"component":"{{ .page }}","props":{},"url":"{{ .url }}","version":""}'></div>
<script>
const { createApp, h } = Vue;
const { createInertiaApp } = Inertia;
createInertiaApp({
resolve: name => {
const pages = {
dashboard: () => import('/static/js/pages/Dashboard.js'),
users: () => import('/static/js/pages/Users.js'),
orders: () => import('/static/js/pages/Orders.js'),
wishes: () => import('/static/js/pages/Wishes.js'),
settings: () => import('/static/js/pages/Settings.js'),
};
return pages[name] ? pages[name]() : pages.dashboard();
},
setup({ el, App, props, plugin }) {
createApp({ render: () => h(App, props) })
.use(plugin)
.mount(el);
},
});
</script>
</body>
</html>
-135
View File
@@ -1,135 +0,0 @@
// Dashboard 页面组件
export default {
template: `
<div class="min-h-screen bg-gray-100">
<nav class="bg-white shadow-sm">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex">
<div class="flex-shrink-0 flex items-center">
<h1 class="text-xl font-bold text-red-600">祈福小助手</h1>
</div>
<div class="hidden sm:ml-6 sm:flex sm:space-x-8">
<a href="/admin" class="border-red-500 text-gray-900 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
仪表盘
</a>
<a href="/admin/users" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
用户管理
</a>
<a href="/admin/orders" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
订单管理
</a>
<a href="/admin/wishes" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
许愿管理
</a>
<a href="/admin/settings" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
系统设置
</a>
</div>
</div>
</div>
</div>
</nav>
<main class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
<div class="px-4 py-6 sm:px-0">
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<div class="bg-white overflow-hidden shadow rounded-lg">
<div class="p-5">
<div class="flex items-center">
<div class="flex-shrink-0">
<i class="fas fa-users text-2xl text-blue-500"></i>
</div>
<div class="ml-5 w-0 flex-1">
<dl>
<dt class="text-sm font-medium text-gray-500 truncate">总用户数</dt>
<dd class="text-lg font-medium text-gray-900">1,234</dd>
</dl>
</div>
</div>
</div>
</div>
<div class="bg-white overflow-hidden shadow rounded-lg">
<div class="p-5">
<div class="flex items-center">
<div class="flex-shrink-0">
<i class="fas fa-shopping-cart text-2xl text-green-500"></i>
</div>
<div class="ml-5 w-0 flex-1">
<dl>
<dt class="text-sm font-medium text-gray-500 truncate">总订单数</dt>
<dd class="text-lg font-medium text-gray-900">567</dd>
</dl>
</div>
</div>
</div>
</div>
<div class="bg-white overflow-hidden shadow rounded-lg">
<div class="p-5">
<div class="flex items-center">
<div class="flex-shrink-0">
<i class="fas fa-star text-2xl text-yellow-500"></i>
</div>
<div class="ml-5 w-0 flex-1">
<dl>
<dt class="text-sm font-medium text-gray-500 truncate">总许愿数</dt>
<dd class="text-lg font-medium text-gray-900">890</dd>
</dl>
</div>
</div>
</div>
</div>
<div class="bg-white overflow-hidden shadow rounded-lg">
<div class="p-5">
<div class="flex items-center">
<div class="flex-shrink-0">
<i class="fas fa-money-bill-wave text-2xl text-red-500"></i>
</div>
<div class="ml-5 w-0 flex-1">
<dl>
<dt class="text-sm font-medium text-gray-500 truncate">总收入</dt>
<dd class="text-lg font-medium text-gray-900">¥12,345</dd>
</dl>
</div>
</div>
</div>
</div>
</div>
<div class="mt-8">
<div class="bg-white shadow rounded-lg p-6">
<h2 class="text-lg font-medium text-gray-900 mb-4">最近订单</h2>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">订单号</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">金额</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">时间</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
<tr>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">L20240101001</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">用户A</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">¥10.00</td>
<td class="px-6 py-4 whitespace-nowrap">
<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">已支付</span>
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">2024-01-01 12:00</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</main>
</div>
`
}
-71
View File
@@ -1,71 +0,0 @@
// Orders 页面组件
export default {
template: `
<div class="min-h-screen bg-gray-100">
<nav class="bg-white shadow-sm">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex">
<div class="flex-shrink-0 flex items-center">
<h1 class="text-xl font-bold text-red-600">祈福小助手</h1>
</div>
<div class="hidden sm:ml-6 sm:flex sm:space-x-8">
<a href="/admin" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
仪表盘
</a>
<a href="/admin/users" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
用户管理
</a>
<a href="/admin/orders" class="border-red-500 text-gray-900 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
订单管理
</a>
<a href="/admin/wishes" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
许愿管理
</a>
<a href="/admin/settings" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
系统设置
</a>
</div>
</div>
</div>
</div>
</nav>
<main class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
<div class="px-4 py-6 sm:px-0">
<div class="bg-white shadow rounded-lg">
<div class="px-4 py-5 sm:p-6">
<h2 class="text-lg font-medium text-gray-900 mb-4">订单列表</h2>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">订单号</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">商品</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">金额</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
<tr>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">L20240101001</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">许愿</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">普通许愿条</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">¥1.00</td>
<td class="px-6 py-4 whitespace-nowrap">
<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">已支付</span>
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">2024-01-01 12:00</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</main>
</div>
`
}
-68
View File
@@ -1,68 +0,0 @@
// Settings 页面组件
export default {
template: `
<div class="min-h-screen bg-gray-100">
<nav class="bg-white shadow-sm">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex">
<div class="flex-shrink-0 flex items-center">
<h1 class="text-xl font-bold text-red-600">祈福小助手</h1>
</div>
<div class="hidden sm:ml-6 sm:flex sm:space-x-8">
<a href="/admin" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
仪表盘
</a>
<a href="/admin/users" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
用户管理
</a>
<a href="/admin/orders" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
订单管理
</a>
<a href="/admin/wishes" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
许愿管理
</a>
<a href="/admin/settings" class="border-red-500 text-gray-900 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
系统设置
</a>
</div>
</div>
</div>
</div>
</nav>
<main class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
<div class="px-4 py-6 sm:px-0">
<div class="bg-white shadow rounded-lg">
<div class="px-4 py-5 sm:p-6">
<h2 class="text-lg font-medium text-gray-900 mb-4">系统设置</h2>
<form class="space-y-6">
<div>
<label class="block text-sm font-medium text-gray-700">许愿树最大许愿数</label>
<input type="number" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-red-500 focus:border-red-500 sm:text-sm" value="100">
</div>
<div>
<label class="block text-sm font-medium text-gray-700">免费许愿最大字数</label>
<input type="number" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-red-500 focus:border-red-500 sm:text-sm" value="20">
</div>
<div>
<label class="block text-sm font-medium text-gray-700">付费许愿最大字数</label>
<input type="number" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-red-500 focus:border-red-500 sm:text-sm" value="100">
</div>
<div>
<label class="block text-sm font-medium text-gray-700">机器人许愿间隔(小时)</label>
<input type="number" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-red-500 focus:border-red-500 sm:text-sm" value="2">
</div>
<div>
<button type="submit" class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">
保存设置
</button>
</div>
</form>
</div>
</div>
</div>
</main>
</div>
`
}
-69
View File
@@ -1,69 +0,0 @@
// Users 页面组件
export default {
template: `
<div class="min-h-screen bg-gray-100">
<nav class="bg-white shadow-sm">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex">
<div class="flex-shrink-0 flex items-center">
<h1 class="text-xl font-bold text-red-600">祈福小助手</h1>
</div>
<div class="hidden sm:ml-6 sm:flex sm:space-x-8">
<a href="/admin" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
仪表盘
</a>
<a href="/admin/users" class="border-red-500 text-gray-900 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
用户管理
</a>
<a href="/admin/orders" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
订单管理
</a>
<a href="/admin/wishes" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
许愿管理
</a>
<a href="/admin/settings" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
系统设置
</a>
</div>
</div>
</div>
</div>
</nav>
<main class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
<div class="px-4 py-6 sm:px-0">
<div class="bg-white shadow rounded-lg">
<div class="px-4 py-5 sm:p-6">
<h2 class="text-lg font-medium text-gray-900 mb-4">用户列表</h2>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">昵称</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">OpenID</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">注册时间</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
<tr>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">1</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">微信用户</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">mock_openid_xxx</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">2024-01-01</td>
<td class="px-6 py-4 whitespace-nowrap">
<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">正常</span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</main>
</div>
`
}
-69
View File
@@ -1,69 +0,0 @@
// Wishes 页面组件
export default {
template: `
<div class="min-h-screen bg-gray-100">
<nav class="bg-white shadow-sm">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex">
<div class="flex-shrink-0 flex items-center">
<h1 class="text-xl font-bold text-red-600">祈福小助手</h1>
</div>
<div class="hidden sm:ml-6 sm:flex sm:space-x-8">
<a href="/admin" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
仪表盘
</a>
<a href="/admin/users" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
用户管理
</a>
<a href="/admin/orders" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
订单管理
</a>
<a href="/admin/wishes" class="border-red-500 text-gray-900 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
许愿管理
</a>
<a href="/admin/settings" class="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium">
系统设置
</a>
</div>
</div>
</div>
</div>
</nav>
<main class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
<div class="px-4 py-6 sm:px-0">
<div class="bg-white shadow rounded-lg">
<div class="px-4 py-5 sm:p-6">
<h2 class="text-lg font-medium text-gray-900 mb-4">许愿列表</h2>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">内容</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
<tr>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">1</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">愿世界和平</td>
<td class="px-6 py-4 whitespace-nowrap">
<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-yellow-800">付费</span>
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">用户A</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">2024-01-01 12:00</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</main>
</div>
`
}
-9
View File
@@ -1,9 +0,0 @@
node_modules
dist
.vite
*.tsbuildinfo
*.local
.DS_Store
*.log
coverage
.swc
-72
View File
@@ -1,72 +0,0 @@
# Lunar Calendar App (万年历)
Chinese almanac/perpetual calendar app with Bazi calculation, daily fortune, divination tools, and beautiful UI.
## Documentation
Detailed docs live in `docs/` — read them before starting any task:
- **docs/ARCHITECTURE.md** — tech stack, layered design, API surface, routes, stores
- **docs/REQUIREMENTS.md** — full feature inventory with completion status
- **docs/PROGRESS.md** — milestones, current state, prioritized backlog
- **docs/BUGS.md** — known bugs, algorithmic approximations, dead code
- **docs/CHANGELOG.md** — version history
## Tech Stack
- **Monorepo**: pnpm workspaces
- **Core**: TypeScript + tyme4ts (calendar engine)
- **Web**: React 19 + Vite + TailwindCSS v4 + Framer Motion + Zustand + React Router v7
- **PWA**: vite-plugin-pwa (configured and built — autoUpdate + Workbox)
## Project Structure
```
lunar/
├── docs/ # Architecture / Requirements / Progress / Bugs / Changelog
├── packages/
│ ├── core/ # @lunar/core — Pure TS, no UI deps
│ │ └── src/
│ │ ├── types/ # calendar.ts, bazi.ts, almanac.ts, fortune.ts
│ │ ├── transformers/ # tyme4ts → plain objects (day.ts, bazi.ts, almanac.ts)
│ │ └── calculators/ # dailyMatch.ts, relationship.ts, elementStrength.ts, plumBlossom.ts, boneWeight.ts
│ └── web/ # @lunar/web — React app
│ └── src/
│ ├── stores/ # Zustand: calendar, user, settings, ui, bookmarks
│ ├── hooks/ # useCalendar, useDayDetail, useBazi, useDailyFortune
│ ├── components/ # calendar/, layout/, ui/
│ └── pages/ # Home, Calendar, DayDetail, Bazi, DailyFortune, Settings, Divination, SolarTerms
```
## Key Architecture Principles
1. **tyme4ts objects never enter React** — all transformed to plain JS objects in @lunar/core
2. **@lunar/core has zero UI deps** — works in any JS runtime (web, Node, RN, mini-program)
3. **Mobile-first responsive** — phone first, desktop sidebar layout
4. **Dark mode via CSS custom properties** — theme toggle with system preference detection
## Commands
- `pnpm dev` — Start Vite dev server (port 4258)
- `pnpm build` — Build core (ESM+CJS) + web
- `pnpm --filter @lunar/core build` — Build core only (tsup)
- `pnpm --filter @lunar/web dev` — Start web dev server
- `pnpm preview` — Preview production build
- `pnpm test` — Run core unit tests (vitest)
- `pnpm lint` — Run ESLint on all packages
## Core API (from @lunar/core)
- `getDayInfo(year, month, day)` → DayInfo
- `getTodayInfo()` → DayInfo
- `getMonthCalendar(year, month, weekStart?)` → DayInfo[][]
- `getAlmanacInfo(year, month, day)` → AlmanacInfo
- `birthInfoToBazi(params)` → BaziFullResult
- `calculateDailyFortune(userBazi, date)` → DailyFortuneResult
- `analyzeElementBalance(bazi)` → ElementProfile
- `calculatePlumBlossom(y, m, d, hour?)` → PlumBlossomResult
- `calculateBoneWeight(...)` → BoneWeightResult
- `getBranchRelationship(a, b)` / `getTenStarRelationship(s, o)` / `checkStemCombine` / `checkStemOpposite`
- `getBuddhistFestival(lunarMonth, lunarDay)` → string | null
- `analyzeShensha(bazi)` → ShenshaInfo[]22 个常见神煞)
- `analyzeFortuneGanzhi(ganzhi, dayStem, dayBranch)` → FortuneLuck(大运/流年 vs 日主生克冲合)
- `getYearMonths(year)` → YearMonthInfo[](按节气月)
## Known Issues
See **docs/BUGS.md** for the current list. Resolved: core CJS export, week-start setting, PWA manifest metadata, tests (50), lint, 称骨 data tables, 八字流派 switching, shensha, 大运流年 explorer. Remaining: simplified 互卦 algorithm, dead code cleanup.
-72
View File
@@ -1,72 +0,0 @@
# Lunar Calendar App (万年历)
Chinese almanac/perpetual calendar app with Bazi calculation, daily fortune, divination tools, and beautiful UI.
## Documentation
Detailed docs live in `docs/` — read them before starting any task:
- **docs/ARCHITECTURE.md** — tech stack, layered design, API surface, routes, stores
- **docs/REQUIREMENTS.md** — full feature inventory with completion status
- **docs/PROGRESS.md** — milestones, current state, prioritized backlog
- **docs/BUGS.md** — known bugs, algorithmic approximations, dead code
- **docs/CHANGELOG.md** — version history
## Tech Stack
- **Monorepo**: pnpm workspaces
- **Core**: TypeScript + tyme4ts (calendar engine)
- **Web**: React 19 + Vite + TailwindCSS v4 + Framer Motion + Zustand + React Router v7
- **PWA**: vite-plugin-pwa (configured and built — autoUpdate + Workbox)
## Project Structure
```
lunar/
├── docs/ # Architecture / Requirements / Progress / Bugs / Changelog
├── packages/
│ ├── core/ # @lunar/core — Pure TS, no UI deps
│ │ └── src/
│ │ ├── types/ # calendar.ts, bazi.ts, almanac.ts, fortune.ts
│ │ ├── transformers/ # tyme4ts → plain objects (day.ts, bazi.ts, almanac.ts)
│ │ └── calculators/ # dailyMatch.ts, relationship.ts, elementStrength.ts, plumBlossom.ts, boneWeight.ts
│ └── web/ # @lunar/web — React app
│ └── src/
│ ├── stores/ # Zustand: calendar, user, settings, ui, bookmarks
│ ├── hooks/ # useCalendar, useDayDetail, useBazi, useDailyFortune
│ ├── components/ # calendar/, layout/, ui/
│ └── pages/ # Home, Calendar, DayDetail, Bazi, DailyFortune, Settings, Divination, SolarTerms
```
## Key Architecture Principles
1. **tyme4ts objects never enter React** — all transformed to plain JS objects in @lunar/core
2. **@lunar/core has zero UI deps** — works in any JS runtime (web, Node, RN, mini-program)
3. **Mobile-first responsive** — phone first, desktop sidebar layout
4. **Dark mode via CSS custom properties** — theme toggle with system preference detection
## Commands
- `pnpm dev` — Start Vite dev server (port 4258)
- `pnpm build` — Build core (ESM+CJS) + web
- `pnpm --filter @lunar/core build` — Build core only (tsup)
- `pnpm --filter @lunar/web dev` — Start web dev server
- `pnpm preview` — Preview production build
- `pnpm test` — Run core unit tests (vitest)
- `pnpm lint` — Run ESLint on all packages
## Core API (from @lunar/core)
- `getDayInfo(year, month, day)` → DayInfo
- `getTodayInfo()` → DayInfo
- `getMonthCalendar(year, month, weekStart?)` → DayInfo[][]
- `getAlmanacInfo(year, month, day)` → AlmanacInfo
- `birthInfoToBazi(params)` → BaziFullResult
- `calculateDailyFortune(userBazi, date)` → DailyFortuneResult
- `analyzeElementBalance(bazi)` → ElementProfile
- `calculatePlumBlossom(y, m, d, hour?)` → PlumBlossomResult
- `calculateBoneWeight(...)` → BoneWeightResult
- `getBranchRelationship(a, b)` / `getTenStarRelationship(s, o)` / `checkStemCombine` / `checkStemOpposite`
- `getBuddhistFestival(lunarMonth, lunarDay)` → string | null
- `analyzeShensha(bazi)` → ShenshaInfo[]22 个常见神煞)
- `analyzeFortuneGanzhi(ganzhi, dayStem, dayBranch)` → FortuneLuck(大运/流年 vs 日主生克冲合)
- `getYearMonths(year)` → YearMonthInfo[](按节气月)
## Known Issues
See **docs/BUGS.md** for the current list. Resolved: core CJS export, week-start setting, PWA manifest metadata, tests (50), lint, 称骨 data tables, 八字流派 switching, shensha, 大运流年 explorer. Remaining: simplified 互卦 algorithm, dead code cleanup.
-56
View File
@@ -1,56 +0,0 @@
# 万年历(Lunar Calendar App
中国农历 / 黄历应用:农历转换、黄历宜忌、八字排盘(大运流年流月流日)、每日运势、神煞、梅花易数、称骨算命、节气、佛教节日。移动端优先,支持 PWA 离线安装。
## 技术栈
- **Monorepo**pnpm workspaces
- **@lunar/core**TypeScript + [tyme4ts](https://github.com/6tail/tyme4ts)(历法引擎),零 UI 依赖,ESM+CJS 双产物
- **@lunar/web**React 19 + Vite 6 + TailwindCSS v4 + Zustand 5 + React Router v7 + Framer Motion + vite-plugin-pwa
## 快速开始
```bash
pnpm install
pnpm dev # http://localhost:4258
pnpm test # core 单元测试(vitest50 例)
pnpm lint # ESLint
pnpm build # 构建 core + web(含 PWA
pnpm preview # 预览构建产物
```
> 需要 Node ≥ 18、pnpm ≥ 9。
## 文档
详细文档见 `docs/`
- [ARCHITECTURE.md](docs/ARCHITECTURE.md) — 架构、API、路由、状态管理
- [REQUIREMENTS.md](docs/REQUIREMENTS.md) — 功能点清单与完成状态
- [PROGRESS.md](docs/PROGRESS.md) — 里程碑与待办
- [BUGS.md](docs/BUGS.md) — 已知 BUG、技术债、死代码
- [CHANGELOG.md](docs/CHANGELOG.md) — 变更日志
- [RETROSPECT.md](docs/RETROSPECT.md) — 会话回顾(做了什么/没做什么/疑问)
## 目录结构
```
lunar/
├── docs/ # 项目文档
├── packages/
│ ├── core/ # @lunar/core —— 纯 TS 计算引擎
│ └── web/ # @lunar/web —— React 应用
├── AGENTS.md / CLAUDE.md # 开发代理指引
└── eslint.config.js # ESLint flat config
```
## 核心能力
| 模块 | 说明 |
|---|---|
| 历法 | 公历/农历/干支/节气/季节/儒略日/佛历/伊斯兰历/月相 |
| 黄历 | 宜忌、值神(日/时)、二十八宿、彭祖百忌、胎神、冲煞 |
| 八字 | 四柱、十神、藏干、十二长生、大运、流年、神煞、流派切换 |
| 运势 | 每日运势、流年/流月/流日 vs 日主生克冲合 |
| 占卜 | 梅花易数(64 卦)、袁天罡称骨 |
| 其他 | 佛教节日、节气列表、收藏、PWA |
-162
View File
@@ -1,162 +0,0 @@
# 架构文档(Architecture
> 最后更新:2026-08-03
## 1. 项目概述
万年历(Lunar Calendar App):中国农历/黄历应用,提供农历转换、黄历宜忌、八字排盘、每日运势、梅花易数、称骨算命、节气等命理功能,移动端优先,支持 PWA 离线安装。
## 2. 技术栈
| 层 | 技术 |
|---|---|
| Monorepo | pnpm workspaces`packages/*` |
| 核心引擎 | TypeScript + [tyme4ts](https://github.com/6tail/tyme4ts) ^1.5.1(历法/干支计算) |
| 构建 | tsupcore)、Vite 6 + tscweb |
| UI | React 19、React Router v7、Zustand 5、TailwindCSS v4CSS-first)、Framer Motion、lucide-react |
| PWA | vite-plugin-pwa 0.21Workbox,已启用) |
## 3. 目录结构
```
lunar/
├── docs/ # 项目文档(本目录,含 RETROSPECT 会话回顾)
├── AGENTS.md # 开发代理指引
├── package.json # workspace 聚合脚本
├── pnpm-workspace.yaml # 工作区定义
├── tsconfig.base.json # 共享 TS 配置
└── packages/
├── core/ # @lunar/core —— 纯 TS 计算引擎,零 UI 依赖
│ ├── tsup.config.ts
│ └── src/
│ ├── index.ts # 公共 API 出口(barrel
│ ├── types/ # calendar.ts / bazi.ts / almanac.ts / fortune.ts
│ ├── transformers/ # day.ts / bazi.ts / almanac.ts / yearMonths.tstyme4ts → 纯对象)
│ └── calculators/ # dailyMatch / relationship / elementStrength / plumBlossom / boneWeight / buddhistDates / shensha / fortuneLuck
└── web/ # @lunar/web —— React 应用
├── vite.config.ts # Vite + Tailwind v4 + PWA
├── index.html
└── src/
├── App.tsx # 路由 + 懒加载 + 页面过渡 + ErrorBoundary
├── main.tsx
├── styles/globals.css # 设计令牌(亮/暗主题)
├── lib/utils.ts # cn、日期格式化等工具
├── stores/ # calendar / user / settings / ui / bookmarksZustand
├── hooks/ # useCalendar / useDayDetail / useBazi / useDailyFortune
├── components/
│ ├── calendar/ # CalendarGrid / CalendarCell / MonthYearPicker / WeekDayBar
│ ├── layout/ # AppShell / Header / BottomNav
│ ├── ui/ # Badge / Button / Card / AnimatedPanel / ErrorBoundary / Skeleton
│ ├── day-detail/ bazi/ daily-fortune/(页面内联实现,目录内暂无独立组件)
└── pages/ # 8 个页面(见路由表)
```
## 4. 分层设计
```
┌───────────────────────────────┐
│ @lunar/web (React 页面层) │
│ pages → hooks → stores │
├───────────────────────────────┤
│ @lunar/core (纯计算引擎) │
│ index.ts │
│ ├─ transformers tyme4ts → │
│ │ 纯 JS 对象 │
│ ├─ calculators 业务算法 │
│ └─ types 类型定义 │
├───────────────────────────────┤
│ tyme4ts (历法计算源) │
└───────────────────────────────┘
```
### 4.1 核心原则
1. **tyme4ts 对象永不进入 React**:所有历法对象在 `@lunar/core` 内转换为普通 JS 对象(`DayInfo``AlmanacInfo``BaziFullResult` 等),React 层只消费纯数据。
2. **@lunar/core 零 UI 依赖**:仅依赖 tyme4ts,可在任意 JS 运行时运行(web / Node / RN / 小程序)。
3. **移动端优先**:手机优先布局,桌面端自适应。
4. **暗色模式**CSS 自定义属性 + `.dark` class,跟随系统偏好 + 手动切换。
### 4.2 数据流示例
```
SolarDay (tyme4ts)
→ solarDayToDayInfo() # DayInfo
→ solarDayToAlmanacInfo() # AlmanacInfo(含 12 时辰)
→ birthInfoToBazi() # BaziFullResult(四柱/十神/大运…)
→ calculateDailyFortune() # DailyFortuneResult(每日运势)
```
## 5. @lunar/core API 一览
### 类型
`DayInfo``AlmanacInfo``HourAlmanac``PillarInfo``HideStemInfo``EightCharInfo``DecadeFortuneInfo``FortuneInfo``ChildLimitInfo``BaziFullResult``PillarRelationship``DailyFortuneResult``BirthParams``BranchRelationship``ElementProfile``TrigramInfo``HexagramInfo``PlumBlossomResult``BoneWeightResult`
### 函数
| 函数 | 说明 |
|---|---|
| `solarDayToDayInfo(solarDay)` | SolarDay → DayInfo(含季节/节气进度/儒略日/佛历/伊斯兰历/佛教节日) |
| `getDayInfo(y, m, d)` / `getTodayInfo()` | 获取某日/今日信息 |
| `getMonthCalendar(y, m, weekStart?)` | 月历二维数组(周 × 天),可指定周起始 |
| `solarDayToAlmanacInfo(solarDay)` | SolarDay → AlmanacInfo |
| `getAlmanacInfo(y, m, d)` | 获取黄历信息(宜忌/值神/冲煞/时辰) |
| `birthInfoToBazi(params)` | 出生信息 → 完整八字排盘(`ziSect` 流派参数:晚子时换日) |
| `getYearMonths(year)` | 按节气月返回某年 12 个流月 |
| `getBranchRelationship(a, b)` | 地支六合/三合/六冲/六害/相刑 |
| `getTenStarRelationship(s, o)` / `checkStemCombine` / `checkStemOpposite` | 干支关系判断 |
| `calculateDailyFortune(userBazi, date)` | 用户八字 × 日期 → 每日运势评分 |
| `analyzeElementBalance(bazi)` | 五行力量分析 |
| `calculatePlumBlossom(y, m, d, h?)` | 梅花易数起卦 |
| `calculateBoneWeight(...)` | 袁天罡称骨算命 |
| `getBuddhistFestival(lunarMonth, lunarDay)` | 农历佛教节日 |
| `analyzeShensha(bazi)` | 22 个常见神煞 |
| `analyzeFortuneGanzhi(ganzhi, dayStem, dayBranch)` | 大运/流年/流月/流日 vs 日主生克冲合 |
## 6. 前端状态管理(Zustand
| Store | 持久化 Key | 职责 | 备注 |
|---|---|---|---|
| `calendar` | — | 视图日期 / 选中日期 / 周起始 | `weekStart``clearSelection` 当前未被使用 |
| `user` | `lunar-user-profiles` | 出生档案(最多 3 个)、active 档案、八字结果 | |
| `settings` | `lunar-settings` | 主题、周起始、显示开关、八字来源 | `showLunar` 等 4 个字段未被消费 |
| `ui` | — | 侧栏 / 移动端 / 底部面板 | 多数 action 未被消费 |
| `bookmarks` | `lunar-bookmarks` | 日期收藏(标记在日历格上) | `getByDate`/`getByLunarDate` 未使用 |
## 7. 路由(React Router v7,全部懒加载)
| 路径 | 页面 | 底部导航 |
|---|---|---|
| `/` | HomePage(今日概览) | ✔ |
| `/calendar` | CalendarPage(月/周视图) | ✔ |
| `/calendar/:date` | DayDetailPage(日详情) | — |
| `/bazi` | BaziPage(八字排盘) | ✔ |
| `/daily-fortune` | DailyFortunePage(每日运势) | ✔ |
| `/settings` | SettingsPage(设置) | ✔ |
| `/divination` | DivinationPage(梅花易数 + 称骨) | 首页快捷入口 |
| `/solar-terms` | SolarTermsPage(节气) | 首页快捷入口 |
| `*` | 重定向 `/` | — |
## 8. PWA(已启用)
- `vite-plugin-pwa`autoUpdate 模式 + Workbox 预缓存 + google-fonts 运行时缓存
- 构建产物:`manifest.webmanifest``sw.js``registerSW.js`
- manifest 已与 index.html 对齐(`lang: zh-CN``theme_color: #FFFBF5`
## 9. 构建与命令
| 命令 | 说明 |
|---|---|
| `pnpm dev` | 启动 web dev(端口 4258 |
| `pnpm build` | 构建 core → web |
| `pnpm --filter @lunar/core build` | 仅构建 coretsupESM+CJS |
| `pnpm --filter @lunar/web build` | 仅构建 webtsc -b && vite build |
| `pnpm preview` | 预览构建产物 |
| `pnpm test` | core 单元测试(vitest50 例) |
| `pnpm lint` | ESLintflat config + typescript-eslint |
| `pnpm clean` | 清理 dist |
## 10. 已知架构问题(详见 BUGS.md)
- 梅花易数互卦为简化实现(上下卦互换,非真·互卦 2-4/3-5 爻法)
- 每日运势当日八字固定取午时;称骨极端总重仍取"最近值"
- 若干死代码(未使用的 hooks / 组件 / store action,见 BUGS.md 清单)
-64
View File
@@ -1,64 +0,0 @@
# BUG 记录(Known Issues
> 最后更新:2026-08-02
> 严重度:🔴 高(影响功能/构建) · 🟠 中 · 🟡 低
> 状态:⬜ 待修复 · 🔧 修复中 · ✅ 已修复
## 0. 已修复汇总(2026-08-02
- BUG-01 core CJS 导出 · BUG-02 周起始设置 · BUG-05 lint · BUG-07 版本号 · BUG-08 死分支
- BUG-03 PWA manifest 与 index.html 对齐(lang=zh-CN、theme_color 统一)
- BUG-09 日历页"回到今天"按钮永不显示(条件恒为 false)
- BUG-10 日详情页时辰列表重复 React key(早子/晚子均为"子",改用 ganzhi 作 key
- TECH-03 更正:梅花卦库实测 **64/64 完整**(原 review 报告"缺 8 卦"不属实),已添加测试锁定
- TECH-06 以 `solarAdjusted` 类型安全字段替代 `(as any)._solarAdjusted`
- TECH-04 称骨数据表整体修正(年表主流版本 + 日表初五 + 歌诀 21~72 补全)
- TECH-05 占卜页称骨年索引改用出生年干支
- 新增单元测试 50 个(vitest)与 ESLint 配置
- 功能深化:八字流派/出生地全国化/海外时区/太阳时开关、神煞、大运流年流月流日交互、历法信息、佛教节日(见 CHANGELOG)
## 1. 已知 BUG
| ID | 严重度 | 状态 | 位置 | 描述 |
|---|---|---|---|---|
| BUG-01 | 🟠 | ✅ | `packages/core` | ~~exports.require 指向不存在的 dist/index.cjs~~ → tsup 改为 `format: ['esm','cjs']``dist/index.cjs` 已生成并通过 `require()` 验证 |
| BUG-02 | 🟠 | ✅ | `useCalendar` / `CalendarGrid` / `WeekDayBar` / `CalendarPage` | ~~周一开始设置无效~~`settings.weekStartDay` 已贯通至 `getMonthCalendar(weekStart)` 与表头渲染 |
| BUG-03 | 🟡 | ✅ | `vite.config.ts` / `index.html` | ~~PWA manifest lang=en、theme_color 不一致~~ → manifest 增加 `lang: zh-CN``theme_color` 统一为 `#FFFBF5`,与 index.html 一致 |
| BUG-04 | 🟡 | ⬜ | `HomePage`InfoCard | `highlight` prop 传为布尔值,但渲染时当作 `border-primary/30` 样式类处理,语义不符(需确认意图) |
| BUG-05 | 🟡 | ✅ | 根 `package.json` | ~~pnpm lint 失败~~ → 已配置 ESLint 9 flat config + typescript-eslint,两个包均通过 |
| BUG-06 | 🟡 | ⬜ | `pnpm-workspace.yaml` | `allowBuilds` 不是 pnpm 标准字段(应为 `onlyBuiltDependencies`),疑似无效配置 |
| BUG-07 | 🟡 | ✅ | `SettingsPage` 关于区 | ~~版本号 v0.2~~ → 与 package.json 统一为 v0.1.0 |
| BUG-08 | 🟡 | ✅ | `transformers/day.ts` | ~~getMonthCalendar 死分支~~ → 已移除 if/else 相同调用 |
| BUG-09 | 🟡 | ✅ | `CalendarPage.tsx` | ~~"回到今天"按钮永不显示~~ → 条件误用 `todaySummary.di.isToday`(恒为 true),改为基于 `viewDate` 判断是否正在查看今天;已在浏览器实测 |
| BUG-10 | 🟡 | ✅ | `DayDetailPage.tsx` | ~~时辰列表重复 React key~~`getHours()` 返回 13 个时辰(早子 00:00 / 晚子 23:00 均为地支"子"),原用 `h.branch` 作 key 冲突,改为唯一的 `h.ganzhi`;已在浏览器实测无警告 |
## 2. 算法近似 / 技术债
> 非紧急,但应在后续迭代中改善。
| ID | 位置 | 说明 |
|---|---|---|
| TECH-01 | `calculators/dailyMatch.ts` | 当日八字固定取午时(`getHours()[6]`),无法体现时辰差异 |
| TECH-02 | `calculators/plumBlossom.ts` | 互卦为简化实现(上下卦互换),非真·互卦(2-4/3-5 爻法) |
| TECH-03 | `calculators/plumBlossom.ts` | ✅ 已核实:数据集 64/64 完整,`plumBlossom.test.ts` 含完整性校验用例 |
| TECH-04 | `calculators/boneWeight.ts` | ✅ 已修复:歌诀补全 2两1钱~7两2钱(原缺 5两8钱/5两9钱/6两1钱/6两3钱/6两5钱/6两7钱/6两9钱/7两1钱,此前这些总重会错误地取"最近值");年表已按主流版本整体修正(原混用两套网络变体错约 40 处),日表修正初五重量 |
| TECH-05 | `DivinationPage` | ✅ 已修复:称骨年索引改用出生年干支(`ec.yearPillar.ganzhi`),不再用日干支近似 |
| TECH-06 | `types/bazi.ts` | ✅ 已修复:`BaziFullResult` 新增 `solarAdjusted?: boolean`,替代 `(as any)` 补丁 |
| TECH-07 | `calculators/elementStrength.ts` | 五行推断按天干名字映射而非复用 tyme4ts 元素定义(可接受但存在重复逻辑) |
| TECH-08 | `lib/utils.ts` | `getChineseDayName` / `getChineseMonthName` 未使用 |
## 3. 死代码清单
| 位置 | 内容 | 建议 |
|---|---|---|
| `hooks/useDayDetail.ts` | 从未被 import | 删除或接入 DayDetailPage |
| `hooks/useBazi.ts` | 从未被 import(本轮仅修复了其 lint 错误) | 删除或接入 BaziPage |
| `components/ui/AnimatedPanel.tsx` | 从未使用 | 删除或接入日详情弹层 |
| `components/ui/Card.tsx` `CardHeader` | 未使用 | 删除导出 |
| `components/ui/Skeleton.tsx` `CalendarSkeleton`/`BaziSkeleton` | 未使用 | 删除 |
| `stores/ui.ts` | `toggleSideNav`/`closeSideNav`/`setActiveTab`/`openDayDetail`/`closeDayDetail``activeTab`/`showDayDetail` 未被消费 | 精简或接入 |
| `stores/settings.ts` | `showLunar`/`showSolarTerm`/`showHoliday`/`eightCharProvider` 及对应 toggle 未被读取 | 接入设置页或删除 |
| `stores/calendar.ts` | `weekStart`/`setWeekStart`/`clearSelection` 未使用(周起始现直接读 settings store | 删除 |
| `stores/bookmarks.ts` | `getByDate`/`getByLunarDate` 未使用 | 配合农历收藏规划 |
| `lib/utils.ts` | `getChineseDayName`/`getChineseMonthName` | 删除 |
| web 依赖 | `tailwind-variants` 从未 import | 移除依赖 |
-80
View File
@@ -1,80 +0,0 @@
# 变更日志(Changelog
> 格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/)。版本号遵循 SemVer。
## [Unreleased]
### 文档
- 新增 `docs/` 文档体系:架构(ARCHITECTURE)、需求(REQUIREMENTS)、进度(PROGRESS)、BUGBUGS)、变更日志(CHANGELOG
- 更新 `AGENTS.md` / `CLAUDE.md`:补全新页面/Store/API、修正 PWA 状态、指向文档目录
### 功能
- **八字流派切换**`birthInfoToBazi` 新增 `ziSect` 参数,设置页新增"八字流派"选项(晚子时算次日 23点换日 / 晚子时算当日 0点换日),BaziPage 排盘实时生效;浏览器实测两种流派排出不同日柱/时柱
- **出生时间选择器**:BaziPage 出生时间改为 时/分 下拉选择器(替代不对称的 −/+ 步进),时辰格可点击快速设置时辰
- **出生地全国化 + 海外时区**:出生地列出全国 34 个省级城市(含省会经度真太阳时校正),新增"海外"模式按时区(UTC-12~+14,含半小时时区)将当地出生时间换算为北京时间(UTC+8)排盘;换算与真太阳时校正均按日期运算处理,支持跨日回退(浏览器实测:UTC-5 23:30 → 次日北京 12:30;乌鲁木齐 00:30 真太阳 → 前日 22:20
- **真太阳时校正开关**:设置页新增"真太阳时校正"开关(默认开启);关闭后中国出生按北京时间直接排盘,海外时区换算不受影响(浏览器实测:关闭时乌鲁木齐 00:30 排日柱己酉,开启时排戊申)
- **宜忌完整显示**:引擎本就返回完整黄历宜忌(如 8/3 共 22 条宜),此前首页 `slice(0,6)` 截断导致显得比别的黄历站少;已放开并标注总数
- **历法信息增强**:DayInfo 新增季节、所处节气/第几天/距下节气天数、儒略日、佛历年(公历+543)、伊斯兰历日期(tyme4ts 原生支持 Hijri),日详情页新增"历法信息"卡片
- **佛教节日**:tyme4ts 无佛教日期支持,新增 `getBuddhistFestival`(农历 21 个重大佛教节日表),日详情页显示 🪷 徽章
- **八字神煞**:新增 `analyzeShensha`(22 个常见神煞:天乙/天厨/文昌贵人、禄神、羊刃、金舆、天德/月德贵人、桃花、驿马、华盖、劫煞、亡神、将星、红鸾、天喜、孤辰、寡宿、天罗、地网、魁罡、阴差阳错),八字页新增"神煞"卡片;查法采用主流排盘工具版本(神煞版本差异已在文档注明)
- **大运/流年生克冲合**:新增 `analyzeFortuneGanzhi`(任意干支 vs 日主:十神、五行生克 生我/我生/克我/我克/比和、天干合冲、地支六合三合冲害刑、吉凶分级);八字页"起运·大运"改为全量 10 个大运并附生克冲合,新增"流年(小运)"10 条卡片
- **今日流年·流月·流日**:八字页新增卡片,用今日年/月/日干支 vs 日主展示生克冲合
- **大运·流年·流月·流日交互下钻**:core 新增 `getYearMonths(year)`(按节气月返回 12 个流月);八字页改为交互浏览器——点选大运 → 流年(按年度切换)→ 流月 12 chips → 该月每日流日列表(带吉凶点与十神),点击日期跳转日详情页;默认定位到当前年份/月份
### 修复
- **称骨算命数据表整体修正**:年份表改为主流通行版本(原混用两套网络变体错约 40 处);日表修正初五(1两6钱);歌诀补全 2两1钱~7两2钱全部 52 条(原缺 5两8钱~7两1钱共 8 条,此前这些总重错误取"最近值")
- **占卜页称骨年索引**:改用出生年干支(`ec.yearPillar.ganzhi`),不再用日干支近似
- **BUG-01**core 包改为同时输出 ESM + CJS`exports.require` 指向的 `dist/index.cjs` 现在真实存在并通过 `require()` 验证
- **BUG-02**:周起始设置生效 —— `settings.weekStartDay` 贯通 `useCalendar``getMonthCalendar(weekStart)``WeekDayBar` 表头渲染
- **BUG-03**PWA manifest 对齐 —— `lang: zh-CN``theme_color` 统一为 `#FFFBF5`(与 index.html 一致)
- **BUG-05**:配置 ESLint 9 flat config + typescript-eslint`pnpm lint` 通过(修复 24 处代码问题)
- **BUG-07**:设置页版本号统一为 0.1.0
- **BUG-08**:移除 `getMonthCalendar` 中的死分支
- **BUG-09**:日历页"回到今天"浮动按钮恢复正常 —— 原条件 `todaySummary.di.isToday` 恒为 true 导致按钮永不显示,改为基于 `viewDate` 判断(浏览器实测:非本月可见、点击返回本月)
- **BUG-10**:日详情页时辰列表重复 key 修复 —— 早子/晚子地支均为"子",key 改用唯一的干支(`h.ganzhi`
- **TECH-06**`BaziFullResult` 新增 `solarAdjusted?: boolean` 字段,替代 `(as any)._solarAdjusted` 非类型安全补丁
### 工程
-@lunar/core 引入 vitest 单元测试(7 个测试文件 / 29 个用例),覆盖历法转换、八字排盘、每日运势、梅花易数(含 64 卦完整性校验)、称骨、干支关系、五行分析
- 根与子包新增 `test` / `lint` 脚本;根 package.json 标记 `"type": "module"`
- 核实梅花卦库为 64/64 完整(此前 review 报告"缺 8 卦"不属实),并以测试固化
### 已知问题(见 docs/BUGS.md
- 梅花易数互卦仍为简化实现(上下卦互换)
- 每日运势当日八字固定取午时;称骨年索引用日干支近似
- PWA manifest `lang`/`theme_color` 不一致;死代码待清理
## [0.1.0] - 2026-06-07
首个可用版本(monorepo 初始化于 2026-06-06)。
### 新增 — @lunar/core
- 历法转换:`getDayInfo` / `getTodayInfo` / `getMonthCalendar` / `solarDayToDayInfo`
- 黄历:`getAlmanacInfo` / `solarDayToAlmanacInfo`(含 12 时辰逐时黄历)
- 八字:`birthInfoToBazi`(四柱、十神、藏干、十二长生、胎元胎息、命宫身宫、空亡、起运、10 大运、10 流年)
- 干支关系:`getBranchRelationship` / `getTenStarRelationship` / `checkStemCombine` / `checkStemOpposite`
- 五行分析:`analyzeElementBalance`
- 每日运势:`calculateDailyFortune`(四柱打分、宜忌、幸运色/数/方位、分项得分)
- 占卜:`calculatePlumBlossom`(梅花易数,56/64 卦)、`calculateBoneWeight`(袁天罡称骨)
### 新增 — @lunar/web
- 路由与骨架:8 页面懒加载、页面过渡动画、ErrorBoundary、Suspense 骨架屏
- 首页:今日概览、宜忌、运势预览、快捷入口
- 日历:月/周视图、年/月切换、收藏星标、运势点、滑动切月、日详情页(四柱/黄历/12 时辰/收藏)
- 八字排盘页:档案管理(最多 3 个,localStorage 持久化)、排盘全览、称骨
- 每日运势页:日期导航、评分与建议
- 占卜页:梅花易数今日卦象、称骨
- 节气页:全年 24 节气
- 设置页:主题切换(亮/暗/跟随系统)、周起始、阴阳历转换、今日干支
- 状态管理:Zustand 5 个 storecalendar / user / settings / ui / bookmarks
- PWAvite-plugin-pwa 集成(autoUpdate + Workbox 预缓存)
- 设计系统:Tailwind v4 设计令牌(亮/暗主题)、Badge / Button / Card / Skeleton
### 已知问题(见 docs/BUGS.md
- core 包 require 导出指向不存在的 `dist/index.cjs`
- 周起始设置未生效
- 梅花易数互卦简化、卦库缺 8 卦;称骨年索引用日干支近似
- 无自动化测试、无 lint
-49
View File
@@ -1,49 +0,0 @@
# 开发进度(Progress
> 最后更新:2026-08-03
## 1. 里程碑
| 里程碑 | 时间 | 内容 | 状态 |
|---|---|---|---|
| M0 项目初始化 | 2026-06-06 | monorepo 脚手架、tsconfig、workspace、核心类型定义 | ✅ |
| M1 核心引擎 | 2026-06-06 ~ 06-07 | transformersday/almanac/bazi)、calculatorsrelationship/elementStrength | ✅ |
| M2 高级算法 | 2026-06-07 | dailyMatch(每日运势)、plumBlossom(梅花)、boneWeight(称骨) | ✅ |
| M3 前端页面 | 2026-06-07 | 8 个页面、5 个 store、路由、布局、组件库 | ✅ |
| M4 构建与 PWA | 2026-06-07 | Vite 构建、tsup、PWA 集成(Workbox 缓存) | ✅ |
| M5 文档化 | 2026-08-02 | 架构/需求/进度/BUG/CHANGELOG 文档建立 | ✅ |
| M6 质量加固 | 2026-08-02 | 单元测试(vitest)、ESLint、CJS 导出修复、周起始修复、版本号 | ✅ |
| M7 功能深化 | 2026-08-02 ~ 08-03 | 称骨数据修正、八字流派/出生地/太阳时开关、神煞、大运流年流月流日交互、历法信息、佛教节日 | ✅ |
| M8 收尾 | 2026-08-03 | README、文档整理、源码打包(node_modules 清理) | ✅ |
> 注:主体功能于 2026-06-06 ~ 06-07 完成;2026-08-02 ~ 08-03 进行质量加固与功能深化。
## 2. 当前状态
- **可运行**`pnpm dev` 可启动,`pnpm build` 可产出 coreESM+CJS+ web 产物(含 PWA)。
- **质量**:50 个单元测试通过(vitest)、`pnpm lint` 通过(ESLint flat config + typescript-eslint)。
- 剩余 BUG 与技术债见 BUGS.md。
## 3. 待办清单(Backlog
按优先级排序:
| 优先级 | 事项 | 类型 | 关联 | 状态 |
|---|---|---|---|---|
| P0 | 修复 core 包 `require` 导出指向不存在的 `dist/index.cjs` | BUG | BUG-01 | ✅ |
| P1 | 周起始设置生效 | 功能 | BUG-02 | ✅ |
| P1 | 为 core 算法补充单元测试 | 工程 | N5 | ✅ 50 例 |
| P2 | 六十四卦数据补全 | 算法 | C10 | ✅ 已核实 64/64 完整,测试锁定 |
| P2 | 互卦算法实现真·互卦(2-4/3-5 爻) | 算法 | C10 | ⬜ |
| P2 | 清理死代码(useDayDetail/useBazi、AnimatedPanel、CardHeader、未用 store action 等) | 工程 | — | ⬜ |
| P3 | PWA manifest 修复 | BUG | BUG-03 | ✅ |
| P3 | 农历周期收藏 UI | 功能 | M2 | ⬜ |
| P3 | 收藏列表页 | 功能 | M3 | ⬜ |
| P4 | 配置 lint 并修复 `pnpm lint` | 工程 | N6 | ✅ |
| P4 | 显示开关字段真正消费(showLunar 等) | 功能 | T6 | ⬜ |
| P4 | 版本号统一(0.1.0 | BUG | BUG-07 | ✅ |
| P4 | 称骨数据表整体修正(年表/日表/歌诀) | 算法 | C11 | ✅ |
| P4 | 占卜页称骨年索引用出生年干支 | 算法 | TECH-05 | ✅ |
| P5 | 每日运势当日八字取午时 → 改为可选时辰 | 算法 | C9 | ⬜ |
| P5 | 称骨极端总重仍取"最近值" → 提示超出范围 | 算法 | TECH-04 | ⬜ |
| P5 | README 编写 | 工程 | M8 | ✅ |
-142
View File
@@ -1,142 +0,0 @@
# 需求文档(Requirements & 功能清单)
> 最后更新:2026-08-02
> 状态说明:✅ 已完成 · 🟡 部分完成 / 有已知问题 · ⬜ 规划中
## 1. 需求总览
| 模块 | 状态 | 说明 |
|---|---|---|
| 历法核心引擎(@lunar/core) | ✅ | 农历/干支/黄历/八字/运势算法 |
| 万年历(首页 + 日历 + 日详情) | ✅ | 功能齐全(周起始设置已修复) |
| 八字排盘 | 🟡 | 功能齐全,含一个非类型安全补丁 |
| 每日运势 | ✅ | 依赖用户档案 |
| 占卜工具(梅花易数 / 称骨) | 🟡 | 算法为简化实现(见备注) |
| 节气 | ✅ | 24 节气列表 |
| 用户档案 + 设置 | 🟡 | 部分设置字段未生效 |
| 收藏 | 🟡 | 仅支持公历单日收藏 |
| PWA | ✅ | 已构建,manifest 有瑕疵 |
## 2. 功能点清单
### 2.1 历法核心(@lunar/core
| # | 功能点 | 描述 | 状态 |
|---|---|---|---|
| C1 | 日期转换 | tyme4ts → DayInfo(公历/农历/干支/星座/生肖/节日/假日/月相) | ✅ |
| C2 | 月历生成 | `getMonthCalendar` 周×天网格,含相邻月补位 | ✅ |
| C3 | 黄历信息 | 宜忌、值神(日/时)、十二/廿八/九/六曜星、彭祖百忌、胎神、冲煞、纳音、三合/六合 | ✅ |
| C4 | 时辰黄历 | 12 时辰逐时黄历(buildHourlyAlmanac | ✅ |
| C5 | 八字排盘 | 四柱、十神、藏干、十二长生、胎元/胎息、命宫/身宫、空亡、起运 | ✅ |
| C6 | 大运/流年 | 10 大运 + 10 流年 | ✅ |
| C7 | 干支关系 | 六合/三合/六冲/六害/相刑/三合局/天干合冲 | ✅ |
| C8 | 五行分析 | 五行力量统计(藏干 0.5 权重)、旺衰、平衡度 | ✅ |
| C9 | 每日运势 | 四柱逐柱 vs 当日干支打分(日 40%/月 25%/年 20%/时 15%),输出评分、宜忌、幸运色/数/方位、分项(感情/事业/财运/健康) | 🟡 当日八字固定取午时 |
| C10 | 梅花易数 | 时间起卦、变卦、互卦(简化)、体用关系、64 卦辞 | 🟡 互卦简化为上下互换(卦库 64/64 完整,已有测试) |
| C11 | 称骨算命 | 年/月/日/时称骨表 + 52 首解诗(2两1钱~7两2钱完整) | ✅ 数据表已按主流版本修正,歌诀补全(极端值仍取最近) |
| C12 | 历法信息 | 季节、所处节气/第几天/距下节气、儒略日、佛历年、伊斯兰历(Hijri) | ✅ |
| C13 | 佛教节日 | 农历 21 个重大佛教节日(`getBuddhistFestival`) | ✅ 日详情页 🪷 徽章展示 |
| C14 | 八字神煞 | 22 个常见神煞(`analyzeShensha` | ✅ 八字页"神煞"卡片 |
| C15 | 大运/流年 vs 日主生克冲合 | 十神、五行生克、天干合冲、地支关系、吉凶(`analyzeFortuneGanzhi` | ✅ |
| C16 | 流年·流月·流日分析 | 任意日期年/月/日干支 vs 日主(`getYearMonths` 按节气月) | ✅ 八字页交互浏览器 |
### 2.2 首页 HomePage`/`
| # | 功能点 | 状态 |
|---|---|---|
| H1 | 今日概览:日期、农历、干支、宜忌摘要 | ✅ |
| H2 | 运势预览(需档案) | ✅ |
| H3 | 快捷导航(占卜、节气) | ✅ |
| H4 | 值神/彭祖/胎神展示 | ✅ |
### 2.3 日历 CalendarPage`/calendar`
| # | 功能点 | 状态 |
|---|---|---|
| K1 | 月视图/周视图切换 | ✅ |
| K2 | 年/月切换(MonthYearPicker | ✅ |
| K3 | 格子显示:节日/节气缩写、农历、周末/今日高亮、收藏星标、运势点 | ✅ |
| K4 | 点击日期 → 日详情页 | ✅ |
| K5 | 手势滑动切换月份 | ✅ |
| K6 | 周起始(周一/周日)设置生效 | ✅ 已修复(BUG-02) |
| K7 | 非本月时显示"回到今天"浮动按钮,点击返回当月 | ✅ 已修复(BUG-09) |
### 2.4 日详情 DayDetailPage`/calendar/:date`
| # | 功能点 | 状态 |
|---|---|---|
| D1 | 四柱、纳音、值星展示 | ✅ |
| D2 | 冲合害煞、宜忌列表 | ✅ |
| D3 | 值神、彭祖百忌、胎神 | ✅ |
| D4 | 12 时辰逐时黄历 | ✅ |
| D5 | 收藏按钮 | ✅ 仅公历收藏 |
### 2.5 八字 BaziPage`/bazi`
| # | 功能点 | 状态 |
|---|---|---|
| B1 | 出生档案管理(最多 3 个,持久化) | ✅ |
| B2 | 排盘:四柱 + 十神 + 藏干 | ✅ |
| B3 | 五行力量 / 十二长生展示 | ✅ |
| B4 | 起运 / 大运 / 流年 | ✅ |
| B5 | 称骨集成 | ✅ 使用出生年干支(占卜页已同步修正) |
| B6 | 日柱类型安全 | ✅ `solarAdjusted` 字段替代 `(as any)` 补丁 |
| B7 | 八字流派切换(晚子时换日 23点 / 0点换日) | ✅ 设置页可切换,排盘实时生效 |
| B8 | 出生地:全国 34 省级城市真太阳时校正 | ✅ 含跨日处理,受"真太阳时校正"开关控制 |
| B9 | 出生地:海外时区 → 北京时间(UTC+8)换算排盘 | ✅ 含跨日处理 |
| B10 | 神煞展示(22 个常见神煞,吉/凶/中性分组) | ✅ |
| B11 | 大运全量 10 条 + 流年(小运)10 条,均附生克冲合 | ✅ |
| B12 | 大运→流年→流月→流日交互下钻(按年度切换) | ✅ 点选日期跳转日详情 |
### 2.6 每日运势 DailyFortunePage`/daily-fortune`
| # | 功能点 | 状态 |
|---|---|---|
| F1 | 日期导航查看任意日运势 | ✅ |
| F2 | 无档案时引导创建 | ✅ |
| F3 | 评分等级、宜忌、幸运信息、分项得分 | ✅ |
### 2.7 占卜 DivinationPage`/divination`
| # | 功能点 | 状态 |
|---|---|---|
| P1 | 今日梅花易数卦象 + 体用分析 | 🟡 算法简化 |
| P2 | 称骨算命输入与结果 | 🟡 年索引用日干支近似 |
### 2.8 节气 SolarTermsPage`/solar-terms`
| # | 功能点 | 状态 |
|---|---|---|
| S1 | 全年 24 节气列表 | ✅ |
### 2.9 设置 SettingsPage`/settings`
| # | 功能点 | 状态 |
|---|---|---|
| T1 | 档案管理入口 | ✅ |
| T2 | 农历日期查询(阴阳历转换) | ✅ |
| T3 | 今日天干地支/纳音 | ✅ |
| T4 | 主题切换(亮/暗/跟随系统) | ✅ |
| T5 | 周起始设置 | ✅ 已修复(BUG-02) |
| T6 | 显示开关(农历/节气/假日)、八字来源 | 🟡 字段已持久化但未消费 |
| T7 | 关于:版本号 | ✅ 已统一为 0.1.0BUG-07 |
| T8 | 真太阳时校正开关(默认开启) | ✅ 关闭后按北京时间排盘 |
### 2.10 收藏 Bookmarks
| # | 功能点 | 状态 |
|---|---|---|
| M1 | 收藏/取消收藏日期,日历格星标 | ✅ |
| M2 | 农历周期收藏(每年/月循环) | ⬜ 字段已预留,UI 未提供 |
| M3 | 收藏列表页 | ⬜ 规划中 |
### 2.11 非功能需求
| # | 需求 | 状态 |
|---|---|---|
| N1 | PWA 可安装、离线可用 | ✅ 已构建 |
| N2 | 移动端优先响应式 | ✅ |
| N3 | 暗色模式(跟随系统) | ✅ |
| N4 | 页面懒加载 + 骨架屏 + 错误边界 | ✅ |
| N5 | 自动化测试 | ✅ 2026-08-02 引入 vitest29 个用例(历法/八字/运势/梅花/称骨/干支) |
| N6 | Lint / 代码规范 | ✅ 2026-08-02 配置 ESLint 9 flat config + typescript-eslint`pnpm lint` 通过 |
-74
View File
@@ -1,74 +0,0 @@
# 开发回顾记录(Retrospect
> 会话日期:2026-08-02 ~ 2026-08-03
> 用途:记录本次会话"做了什么 / 没做什么 / 有疑问的事项",便于事后回顾与决策。
## 一、本次完成的工作
### 1. 文档体系(docs/
- 新建 `docs/`ARCHITECTURE / REQUIREMENTS / PROGRESS / BUGS / CHANGELOG,另加根 README.md
- 修正 AGENTS.md / CLAUDE.md 的过时信息(PWA 状态、页面/Store/API 补全),并持续同步
### 2. BUG 修复(BUGS.md 均已标记 ✅)
| ID | 内容 |
|---|---|
| BUG-01 | core 包 CJS 导出:tsup 增加 cjs 产物,`require()` 实测可用 |
| BUG-02 | 周起始设置生效:settings → useCalendar → getMonthCalendar(weekStart) → WeekDayBar |
| BUG-03 | PWA manifest 对齐(lang=zh-CN、theme_color=#FFFBF5 |
| BUG-05 | 配置 ESLint 9 flat config + typescript-eslint`pnpm lint` 通过(修复 24 处) |
| BUG-07 | 版本号统一 v0.1.0 |
| BUG-08 | getMonthCalendar 死分支移除 |
| BUG-09 | "回到今天"按钮条件恒 false,改为基于 viewDate 判断 |
| BUG-10 | 日详情时辰列表重复 React key(早子/晚子均"子"),改用 ganzhi 作 key |
| TECH-06 | `(as any)._solarAdjusted``BaziFullResult.solarAdjusted` 类型化 |
### 3. 功能深化
- **八字流派切换**`birthInfoToBazi` 新增 `ziSect`(晚子时算次日/当日),设置页开关
- **出生时间选择器**:时/分下拉 + 时辰格可点
- **出生地全国化 + 海外时区**:34 省级城市(真太阳时校正)+ 海外 UTC-12~+14 换算北京时间,均支持跨日
- **真太阳时校正开关**(设置页,默认开启)
- **宜忌完整显示**:根因是首页 `slice(0,6)`,引擎本有 22 条宜
- **历法信息增强**:DayInfo 新增 季节/所处节气/第几天/距下节气/儒略日/佛历年/伊斯兰历(tyme4ts 原生 Hijri
- **佛教节日**:新增 `getBuddhistFestival`(农历 21 个节日),日详情 🪷 徽章
- **八字神煞**:新增 `analyzeShensha`(22 个常见神煞),八字页"神煞"卡
- **大运/流年生克冲合**:新增 `analyzeFortuneGanzhi`(十神/五行生克/合冲害刑/吉凶)
- **大运→流年→流月→流日交互下钻**:新增 `getYearMonths`(节气月);八字页交互浏览器,流日可跳日详情
### 4. 质量
- 单元测试 29 → **50 个**(vitest),覆盖历法/八字/运势/梅花/称骨/干支/五行/神煞/流月/流年
- 浏览器 E2E 验证(headless Chrome + CDP 脚本,无新增依赖):周起始、回到今天、流派、出生地、太阳时开关、宜忌、历法信息、神煞、大运流年交互 全部实测通过
### 5. 工程清理
- 整理全部文档;删除 node_modules / dist / tsbuildinfo;源码 241M → 764K;打包 164K/tmp/lunar-source-20260803.tar.gz
## 二、未完成 / 待办(详见 PROGRESS.md Backlog
| 事项 | 说明 |
|---|---|
| 互卦真算法 | 梅花易数互卦仍为上下卦互换简化(2-4/3-5 爻法未实现) |
| 死代码清理 | useDayDetail/useBazi hooks、AnimatedPanel、CardHeader、CalendarSkeleton/BaziSkeleton、ui store 未用 action、settings 显示开关字段、calendar store weekStart、bookmarks getByDate、utils 未用函数、tailwind-variants 依赖 |
| 显示开关字段 | settings.showLunar/showSolarTerm/showHoliday/eightCharProvider 已持久化但未消费(其中 eightCharProvider 已被 ziHourSect 替换) |
| 农历周期收藏 | bookmarks 的 isLunar 字段已预留,UI 未提供;收藏列表页未做 |
| 午时假设 | calculateDailyFortune 当日八字固定取午时(TECH-01) |
| 称骨极端值 | 超出 2两1钱~7两2钱范围的总重仍取"最近值"TECH-04 残余) |
| 紫微斗数 | 未做(大工程,用户同意先做神煞) |
| web 端自动化测试 | 仅 core 有单测;web 无测试框架 |
| git | 项目未初始化 git 仓库,无版本管理与回滚能力 |
## 三、有疑问 / 待确认事项
1. **称骨年表存在两套网络变体**:本实现采用主流版本(算准网/网易/sunfinelife 三家一致:丙子16钱、戊子15钱等),但另一套变体(丙子19钱、戊子12钱等)也在流通。若用户希望换另一套,改 `boneWeight.ts``YEAR_WEIGHTS` 即可。
2. **天厨贵人查法有版本差异**:本实现采用主流版(甲巳、乙午、丙巳、丁午、戊申、己酉、庚亥、辛子、壬寅、癸卯);传统版(丙寅、丁酉、戊申、己未、庚亥、辛戌、壬卯、癸子)也有出处。代码注释已注明。
3. **tyme4ts 十神方向语义**:实测 `A.getTenStar(B)` 返回"B 以 A 为日主"的十神。`dailyMatch.ts` 中的用法方向(userPillar vs dayPillar 同位置比较)语义上存疑,但**未改动**(避免影响每日运势结果);新写的 `fortuneLuck` 已按正确方向实现。需确认 dailyMatch 是否也要调整。
4. **佛历年**:按公历 + 543(泰国惯例);bmcx 示例 2570 对应的是其他年份。
5. **佛教节日表**:21 个为通行版本,个别日期(如腊月廿九华严菩萨圣诞)在不同资料有出入。
6. **默认出生地变化**:默认从"120°E 不校正"改为"北京 116.4°E-14 分钟真太阳校正)",临界时辰的结果会变。太阳时校正开关默认开启——用户接受度未知,如需要可默认关闭。
7. **BUG-04HomePage InfoCard highlight**`highlight` 传布尔但被当作样式类 `border-primary/30` 处理,语义不清,需确认意图(是要"高亮边框"还是别的)。
8. **起运前年份 UX**:大运流年浏览器中,出生当年(起运前)不在任何大运区间,自动落到第一柱大运(如 2026 年出生 → 从 2028 起显示)。是否要显示"起运前"年份待定。
9. **pnpm-workspace.yaml `allowBuilds`**:非 pnpm 标准字段(应为 onlyBuiltDependencies),疑似无效但无害,未改。
10. **打包清理**:已删除 node_modules/dist,开发前需 `pnpm install`
## 四、验证方式备忘
- E2E 通过 headless ChromePlaywright 缓存目录的 chromium headless shell+ CDP 协议 Node 脚本驱动,未引入 Playwright npm 依赖;脚本存于 `/tmp/lunar-*.mjs`(会话临时文件,未入库)。
- 所有功能均以"单测 + 浏览器实测"双重验证;仅 UI 纯样式类改动(如时间选择器)以 tsc 构建验证为主。
-11
View File
@@ -1,11 +0,0 @@
import tseslint from 'typescript-eslint';
export default tseslint.config(
{ ignores: ['**/dist/**', '**/node_modules/**', '**/*.tsbuildinfo'] },
tseslint.configs.recommended,
{
rules: {
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }],
},
},
);
-24
View File
@@ -1,24 +0,0 @@
{
"name": "lunar-calendar",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "万年历 - Chinese Almanac Calendar App",
"scripts": {
"dev": "pnpm --filter @lunar/web dev",
"build": "pnpm --filter @lunar/core build && pnpm --filter @lunar/web build",
"preview": "pnpm --filter @lunar/web preview",
"test": "pnpm -r test",
"lint": "pnpm -r lint",
"clean": "pnpm -r clean"
},
"engines": {
"node": ">=18",
"pnpm": ">=9"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"eslint": "^10.8.0",
"typescript-eslint": "^8.65.0"
}
}
-34
View File
@@ -1,34 +0,0 @@
{
"name": "@lunar/core",
"version": "0.1.0",
"private": true,
"description": "Core calculation engine for lunar calendar app",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"require": "./dist/index.cjs"
}
},
"files": [
"dist"
],
"scripts": {
"dev": "tsup --watch",
"build": "tsup",
"test": "vitest run",
"lint": "eslint .",
"clean": "rm -rf dist"
},
"dependencies": {
"tyme4ts": "^1.5.1"
},
"devDependencies": {
"tsup": "^8.4.0",
"typescript": "^5.7.0",
"vitest": "^4.1.10"
}
}
@@ -1,51 +0,0 @@
import { describe, it, expect } from 'vitest';
import { birthInfoToBazi } from '../index';
const GANZHI = /^[甲乙丙丁戊己庚辛壬癸][子丑寅卯辰巳午未申酉戌亥]$/;
describe('bazi transformer', () => {
const bazi = birthInfoToBazi({ year: 1990, month: 5, day: 15, hour: 12, minute: 0, gender: 'male' });
it('produces four pillars with valid ganzhi', () => {
expect(bazi.eightChar.yearPillar.ganzhi).toMatch(GANZHI);
expect(bazi.eightChar.monthPillar.ganzhi).toMatch(GANZHI);
expect(bazi.eightChar.dayPillar.ganzhi).toMatch(GANZHI);
expect(bazi.eightChar.hourPillar.ganzhi).toMatch(GANZHI);
});
it('exposes day master info', () => {
expect(bazi.eightChar.dayMasterStem).toMatch(/^[甲乙丙丁戊己庚辛壬癸]$/);
expect(['木', '火', '土', '金', '水']).toContain(bazi.eightChar.dayMasterElement);
});
it('returns 10 decade fortunes and 10 annual fortunes', () => {
expect(bazi.decadeFortunes).toHaveLength(10);
expect(bazi.annualFortunes).toHaveLength(10);
expect(bazi.decadeFortunes[0].ganzhi).toMatch(GANZHI);
});
it('returns child limit with non-negative start age', () => {
expect(bazi.childLimit.startAge).toBeGreaterThanOrEqual(0);
expect(bazi.childLimit.forward).toBeTypeOf('boolean');
});
it('includes hidden stems with ten stars', () => {
const yearHs = bazi.eightChar.yearPillar.hideStems;
expect(yearHs.length).toBeGreaterThan(0);
expect(yearHs[0].stem).toMatch(/^[甲乙丙丁戊己庚辛壬癸]$/);
});
it('default sect: late zi (23:30) rolls to next day', () => {
const late = birthInfoToBazi({ year: 2026, month: 8, day: 3, hour: 23, minute: 30, gender: 'male' });
expect(late.eightChar.dayPillar.ganzhi).toBe('庚戌');
expect(late.eightChar.hourPillar.ganzhi).toBe('丙子');
});
it('earlyZiSameDay sect: late zi (23:30) keeps the current day', () => {
const early = birthInfoToBazi({
year: 2026, month: 8, day: 3, hour: 23, minute: 30, gender: 'male', ziSect: 'earlyZiSameDay',
});
expect(early.eightChar.dayPillar.ganzhi).toBe('己酉');
expect(early.eightChar.hourPillar.ganzhi).toBe('甲子');
});
});
@@ -1,68 +0,0 @@
import { describe, it, expect } from 'vitest';
import { calculateBoneWeight } from '../index';
describe('bone weight', () => {
it('sums weights correctly for 甲子年正月初一子时', () => {
const r = calculateBoneWeight(0, 1, 1, 0);
expect(r.yearWeight).toBe(12);
expect(r.monthWeight).toBe(6);
expect(r.dayWeight).toBe(5);
expect(r.hourWeight).toBe(16);
expect(r.totalWeight).toBe(39);
expect(r.totalLiang).toBe(3);
expect(r.totalQian).toBe(9);
});
it('returns a non-empty interpretation with a valid fortune grade', () => {
const r = calculateBoneWeight(12, 6, 15, 6);
expect(r.interpretation.length).toBeGreaterThan(0);
expect(['上上', '上', '中上', '中', '中下', '下']).toContain(r.fortune);
});
it('falls back to the nearest interpretation for unknown totals', () => {
// 4 + 9 + 9 + 9 = 31 → exact match exists; use an out-of-range input
const r = calculateBoneWeight(0, 1, 1, 11); // 12 + 6 + 5 + 6 = 29
expect(r.totalWeight).toBe(29);
expect(r.interpretation.length).toBeGreaterThan(0);
});
it('year table matches the mainstream 称骨年表', () => {
const cases: [number, number][] = [
[0, 12], // 甲子
[7, 8], // 辛未
[16, 12], // 庚辰
[17, 6], // 辛巳
[18, 8], // 壬午
[21, 15], // 乙酉
[51, 8], // 乙卯
[54, 19], // 戊午
];
for (const [idx, wt] of cases) {
const r = calculateBoneWeight(idx, 1, 1, 0);
expect(r.yearWeight, `year index ${idx}`).toBe(wt);
}
});
it('day table: 初五 is 1两6钱', () => {
const r = calculateBoneWeight(0, 1, 5, 0);
expect(r.dayWeight).toBe(16);
});
it('previously missing poems (5两8钱~7两1钱) resolve exactly, not by nearest match', () => {
const cases: [number, number, number, number, number, string][] = [
[18, 6, 26, 5, 58, '雁塔题名'],
[15, 6, 8, 7, 59, '甲第之中'],
[24, 3, 18, 6, 61, '金榜客'],
[42, 6, 26, 5, 63, '定中高科'],
[54, 9, 18, 6, 65, '安邦'],
[54, 6, 8, 5, 67, '田园家业'],
[54, 6, 18, 5, 69, '前禄星'],
[54, 3, 26, 5, 71, '公侯卿相'],
];
for (const [y, m, d, h, total, phrase] of cases) {
const r = calculateBoneWeight(y, m, d, h);
expect(r.totalWeight, `expected total ${total}`).toBe(total);
expect(r.interpretation, `poem for ${total}`).toContain(phrase);
}
});
});
@@ -1,62 +0,0 @@
import { describe, it, expect } from 'vitest';
import { getDayInfo, getMonthCalendar, getTodayInfo } from '../index';
describe('day transformers', () => {
it('returns correct lunar info for 2024-02-10 (春节正月初一)', () => {
const di = getDayInfo(2024, 2, 10);
expect(di.solarDate).toBe('2024-02-10');
expect(di.lunarMonth).toBe(1);
expect(di.lunarDay).toBe(1);
expect(di.lunarDayName).toBe('初一');
expect(di.lunarYearGanzhi).toMatch(/^[甲乙丙丁戊己庚辛壬癸][子丑寅卯辰巳午未申酉戌亥]$/);
expect(di.weekDayIndex).toBe(6);
expect(di.isWeekend).toBe(true);
});
it('getTodayInfo returns today', () => {
const now = new Date();
const di = getTodayInfo();
expect(di.solarYear).toBe(now.getFullYear());
expect(di.solarMonth).toBe(now.getMonth() + 1);
expect(di.solarDay).toBe(now.getDate());
expect(di.isToday).toBe(true);
});
it('getMonthCalendar respects weekStart', () => {
// 2024-02-01 is a Thursday
const sunFirst = getMonthCalendar(2024, 2, 0);
const monFirst = getMonthCalendar(2024, 2, 1);
for (const row of sunFirst) expect(row).toHaveLength(7);
for (const row of monFirst) expect(row).toHaveLength(7);
expect(sunFirst[0][0].weekDayIndex).toBe(0); // Sunday first
expect(monFirst[0][0].weekDayIndex).toBe(1); // Monday first
// Both grids must contain the 1st of the month
const flatSun = sunFirst.flat();
const flatMon = monFirst.flat();
expect(flatSun.some(d => d.solarDate === '2024-02-01')).toBe(true);
expect(flatMon.some(d => d.solarDate === '2024-02-01')).toBe(true);
});
it('provides season, term progress, julian, buddhist era and hijri date', () => {
const di = getDayInfo(2026, 8, 3); // 大暑期间,农历六月廿一
expect(di.season).toBe('夏季');
expect(di.termDayIndex).toBeGreaterThan(0);
expect(di.nextSolarTerm).toBe('立秋');
expect(di.daysToNextTerm).toBe(4);
expect(di.julianDay).toBeGreaterThan(2450000);
expect(di.buddhistYear).toBe(2026 + 543);
expect(di.hijriDate).toMatch(/^\d{4}年\d{2}月\d{2}日$/);
});
it('marks Buddhist festivals by lunar date', () => {
// 2024-05-15 is 佛诞(浴佛节)农历四月初八
const di = getDayInfo(2024, 5, 15);
expect(di.lunarMonth).toBe(4);
expect(di.lunarDay).toBe(8);
expect(di.buddhistFestival).toBe('释迦牟尼佛圣诞(浴佛节)');
});
});
@@ -1,22 +0,0 @@
import { describe, it, expect } from 'vitest';
import { analyzeElementBalance, birthInfoToBazi } from '../index';
describe('element balance', () => {
const eightChar = birthInfoToBazi({
year: 1990, month: 5, day: 15, hour: 12, minute: 0, gender: 'male',
}).eightChar;
const profile = analyzeElementBalance(eightChar);
it('has positive total that matches sum of parts', () => {
expect(profile.total).toBeGreaterThan(0);
expect(profile.wood + profile.fire + profile.earth + profile.metal + profile.water)
.toBeCloseTo(profile.total);
});
it('identifies dominant and weakest elements', () => {
expect(['木', '火', '土', '金', '水']).toContain(profile.dominant);
expect(['木', '火', '土', '金', '水']).toContain(profile.weakest);
expect(profile.isBalanced).toBeTypeOf('boolean');
});
});
@@ -1,34 +0,0 @@
import { describe, it, expect } from 'vitest';
import { calculateDailyFortune, birthInfoToBazi } from '../index';
const SCORE_LEVELS = ['great', 'good', 'fair', 'poor', 'bad'] as const;
describe('daily fortune', () => {
const eightChar = birthInfoToBazi({
year: 1990, month: 5, day: 15, hour: 12, minute: 0, gender: 'female',
}).eightChar;
const fortune = calculateDailyFortune(eightChar, new Date(2026, 7, 2));
it('returns bounded score and valid level', () => {
expect(fortune.overallScore).toBeGreaterThanOrEqual(-100);
expect(fortune.overallScore).toBeLessThanOrEqual(100);
expect(SCORE_LEVELS).toContain(fortune.scoreLevel);
});
it('evaluates all four pillars', () => {
expect(fortune.pillarRelationships).toHaveLength(4);
expect(fortune.pillarRelationships.map(r => r.pillar)).toEqual(['year', 'month', 'day', 'hour']);
});
it('returns the requested date', () => {
expect(fortune.date).toBe('2026-08-02');
});
it('produces suggestions and category scores', () => {
expect(fortune.suggestions.length).toBeGreaterThan(0);
expect(fortune.luckyAspects.length).toBeGreaterThan(0);
const { love, career, wealth, health } = fortune.categoryScores;
expect([love, career, wealth, health].every(v => v >= -100 && v <= 100)).toBe(true);
});
});
@@ -1,40 +0,0 @@
import { describe, it, expect } from 'vitest';
import { analyzeFortuneGanzhi, birthInfoToBazi } from '../index';
describe('fortune luck (大运/流年 vs 日主)', () => {
// 2026-08-03 12:00: 日干己、日支酉
const bazi = birthInfoToBazi({ year: 2026, month: 8, day: 3, hour: 12, minute: 0, gender: 'male' });
const dayStem = bazi.eightChar.dayPillar.heavenStem;
const dayBranch = bazi.eightChar.dayPillar.earthBranch;
it('甲子 vs 己酉: 正官 + 天干合 + 克我 → 吉', () => {
const r = analyzeFortuneGanzhi('甲子', dayStem, dayBranch);
expect(r.tenStar).toBe('正官');
expect(r.stemCombine).toBe(true);
expect(r.elementRelation).toBe('克我');
expect(r.level).toBe('吉');
});
it('乙酉 vs 己酉: 七杀 + 自刑 → 凶', () => {
const r = analyzeFortuneGanzhi('乙酉', dayStem, dayBranch);
expect(r.tenStar).toBe('七杀');
expect(r.branchPunish).toBe(true); // 酉酉自刑
expect(r.level).toBe('凶');
});
it('丙子 vs 己未: 正印 + 子未六害', () => {
const r = analyzeFortuneGanzhi('丙子', '己', '未');
expect(r.tenStar).toBe('正印');
expect(r.branchHarm).toBe(true);
});
it('all decade fortunes produce valid luck info', () => {
for (const df of bazi.decadeFortunes) {
const r = analyzeFortuneGanzhi(df.ganzhi, dayStem, dayBranch);
expect(['比和', '生我', '我生', '克我', '我克']).toContain(r.elementRelation);
expect(['吉', '凶', '平']).toContain(r.level);
expect(r.score).toBeGreaterThanOrEqual(-10);
expect(r.score).toBeLessThanOrEqual(10);
}
});
});
@@ -1,47 +0,0 @@
import { describe, it, expect } from 'vitest';
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import { calculatePlumBlossom } from '../index';
describe('plum blossom', () => {
it('produces expected hexagram for known input (2026-08-02 12:00)', () => {
const r = calculatePlumBlossom(2026, 8, 2, 12);
expect(r.upperTrigram.name).toBe('巽');
expect(r.lowerTrigram.name).toBe('兑');
expect(r.originalHexagram.name).toBe('风泽中孚');
expect(r.originalHexagram.changingLine).toBe(4);
expect(r.relationship).toBeTruthy();
});
it('is deterministic', () => {
const a = calculatePlumBlossom(2024, 3, 5, 8);
const b = calculatePlumBlossom(2024, 3, 5, 8);
expect(a).toEqual(b);
});
it('dataset covers all 64 hexagram combinations', () => {
const srcFile = fileURLToPath(new URL('../calculators/plumBlossom.ts', import.meta.url));
const src = fs.readFileSync(srcFile, 'utf8');
const keys = [...src.matchAll(/'(\d,\d)':/g)].map(m => m[1]);
expect(keys).toHaveLength(64);
expect(new Set(keys).size).toBe(64);
for (let upper = 1; upper <= 8; upper++) {
for (let lower = 1; lower <= 8; lower++) {
expect(keys).toContain(`${upper},${lower}`);
}
}
});
it('never falls back to a placeholder across a broad date grid', () => {
for (let y = 2000; y <= 2030; y++) {
for (let m = 1; m <= 12; m++) {
for (let d = 1; d <= 28; d += 7) {
const r = calculatePlumBlossom(y, m, d, 12);
// Real hexagram names are 3+ chars; fallback names are 2-char concatenations
expect(r.originalHexagram.name.length).toBeGreaterThan(2);
}
}
}
});
});
@@ -1,45 +0,0 @@
import { describe, it, expect } from 'vitest';
import {
getBranchRelationship,
getTenStarRelationship,
checkStemCombine,
checkStemOpposite,
} from '../index';
describe('relationship calculator', () => {
it('detects 六合 (子丑合)', () => {
expect(getBranchRelationship('子', '丑').combine).toBe(true);
expect(getBranchRelationship('子', '午').combine).toBe(false);
});
it('detects 六冲 (子午冲)', () => {
expect(getBranchRelationship('子', '午').opposite).toBe(true);
});
it('detects 三合 (申子辰水局)', () => {
const rel = getBranchRelationship('申', '辰');
expect(rel.threeCombine).toBe(true);
expect(rel.formation).toBe('水局');
});
it('detects 六害 (子未害)', () => {
expect(getBranchRelationship('子', '未').harm).toBe(true);
});
it('detects 相刑 (寅巳无恩之刑)', () => {
expect(getBranchRelationship('寅', '巳').punish).toBe(true);
});
it('detects 天干合 (甲己合)', () => {
expect(checkStemCombine('甲', '己')).toBe(true);
expect(checkStemCombine('甲', '乙')).toBe(false);
});
it('detects 天干冲 (甲庚冲)', () => {
expect(checkStemOpposite('甲', '庚')).toBe(true);
});
it('computes ten star for a day master (甲日主见戊土 → 偏财)', () => {
expect(getTenStarRelationship('甲', '戊')).toContain('财');
});
});
@@ -1,55 +0,0 @@
import { describe, it, expect } from 'vitest';
import { analyzeShensha, birthInfoToBazi } from '../index';
describe('shensha', () => {
// 2026-08-03 12:00: 年柱丙午、月柱乙未、日柱己酉、时柱庚午
const bazi = birthInfoToBazi({ year: 2026, month: 8, day: 3, hour: 12, minute: 0, gender: 'male' });
it('finds 天乙贵人 by year stem 丙 → 亥酉, hit 日支酉', () => {
const s = analyzeShensha(bazi.eightChar);
const t = s.find(x => x.name === '天乙贵人');
expect(t).toBeDefined();
expect(t!.foundIn).toContain('日支');
expect(t!.anchors.some(a => a.includes('年干'))).toBe(true);
});
it('finds 文昌贵人 by day stem 己 → 酉, hit 日支酉', () => {
const s = analyzeShensha(bazi.eightChar);
const t = s.find(x => x.name === '文昌贵人');
expect(t).toBeDefined();
expect(t!.anchors.some(a => a.includes('日干'))).toBe(true);
});
it('finds 禄神 and 羊刃 by day/year stem 己/丙 → 午', () => {
const s = analyzeShensha(bazi.eightChar);
const lu = s.find(x => x.name === '禄神');
const yang = s.find(x => x.name === '羊刃');
expect(lu).toBeDefined();
expect(lu!.foundIn).toEqual(expect.arrayContaining(['年支', '时支']));
expect(yang).toBeDefined();
});
it('finds 桃花 by day branch 酉 (巳酉丑) → 午', () => {
const s = analyzeShensha(bazi.eightChar);
const t = s.find(x => x.name.startsWith('桃花'));
expect(t).toBeDefined();
expect(t!.foundIn).toContain('年支');
});
it('finds 将星 and 红鸾', () => {
const s = analyzeShensha(bazi.eightChar);
expect(s.find(x => x.name === '将星')).toBeDefined(); // 年支午(寅午戌) → 午
expect(s.find(x => x.name === '红鸾')).toBeDefined(); // 年支午 → 酉,日支酉
});
it('does not flag 魁罡/阴差阳错 for day 己酉', () => {
const s = analyzeShensha(bazi.eightChar);
expect(s.find(x => x.name === '魁罡')).toBeUndefined();
expect(s.find(x => x.name === '阴差阳错')).toBeUndefined();
});
it('all stem rules cover all 10 stems and branch rules cover 12 branches', () => {
const s = analyzeShensha(bazi.eightChar);
expect(s.length).toBeGreaterThan(0);
});
});
@@ -1,26 +0,0 @@
import { describe, it, expect } from 'vitest';
import { getYearMonths } from '../index';
describe('getYearMonths (流月)', () => {
it('returns 12 months starting from 立春', () => {
const months = getYearMonths(2026);
expect(months).toHaveLength(12);
expect(months[0].name).toBe('正月');
expect(months[0].startDate).toBe('2026-02-04'); // 立春 2026
expect(months[0].ganzhi).toBe('庚寅'); // 丙午年 五虎遁 → 寅月庚寅
expect(months[11].name).toBe('腊月');
expect(months[11].startDate).toMatch(/^2027-01-/); // 小寒 2027
});
it('endDate is the day before the next 节', () => {
const months = getYearMonths(2026);
expect(months[0].endDate).toBe('2026-03-04'); // 惊蛰 2026-03-05 前一天
expect(months[1].ganzhi).toBe('辛卯'); // 惊蛰起卯月
});
it('all month ganzhi match the 五虎遁 sequence', () => {
const months = getYearMonths(2026);
const seq = ['庚寅', '辛卯', '壬辰', '癸巳', '甲午', '乙未', '丙申', '丁酉', '戊戌', '己亥', '庚子', '辛丑'];
expect(months.map(m => m.ganzhi)).toEqual(seq);
});
});
@@ -1,161 +0,0 @@
/**
* 袁天罡称骨算命法 (Bone Weight Fortune Telling)
* Based on year/month/day/hour pillars to calculate total "bone weight"
* Each unit = 钱 (1两 = 10钱)
*/
export interface BoneWeightResult {
yearWeight: number; // in 钱
monthWeight: number;
dayWeight: number;
hourWeight: number;
totalWeight: number; // in 钱
totalLiang: number; // 两
totalQian: number; // 钱
interpretation: string; // The fate poem/interpretation
fortune: '上上' | '上' | '中上' | '中' | '中下' | '下';
}
// Year bone weight table (by 干支 year stem-branch)
// 主流称骨年表(百度百科/网易/算准网等通行版本):year % 60 → weight in 钱
const YEAR_WEIGHTS: Record<number, number> = {
0: 12, 1: 9, 2: 6, 3: 7, 4: 12, 5: 5, 6: 9, 7: 8, 8: 7, 9: 8,
10: 15, 11: 9, 12: 16, 13: 8, 14: 8, 15: 19, 16: 12, 17: 6, 18: 8, 19: 7,
20: 5, 21: 15, 22: 6, 23: 16, 24: 15, 25: 7, 26: 9, 27: 12, 28: 10, 29: 7,
30: 15, 31: 6, 32: 5, 33: 14, 34: 14, 35: 9, 36: 7, 37: 7, 38: 9, 39: 12,
40: 8, 41: 7, 42: 13, 43: 5, 44: 14, 45: 5, 46: 9, 47: 17, 48: 5, 49: 7,
50: 12, 51: 8, 52: 8, 53: 6, 54: 19, 55: 6, 56: 8, 57: 16, 58: 10, 59: 6,
};
// Month bone weight (lunar month 1-12)
const MONTH_WEIGHTS: Record<number, number> = {
1: 6, 2: 7, 3: 18, 4: 9, 5: 5, 6: 16,
7: 9, 8: 15, 9: 18, 10: 8, 11: 9, 12: 5,
};
// Day bone weight (lunar day 1-30)
const DAY_WEIGHTS: Record<number, number> = {
1: 5, 2: 10, 3: 8, 4: 15, 5: 16, 6: 15, 7: 8, 8: 16, 9: 8, 10: 16,
11: 9, 12: 17, 13: 8, 14: 17, 15: 10, 16: 8, 17: 9, 18: 18, 19: 5, 20: 15,
21: 10, 22: 9, 23: 8, 24: 9, 25: 15, 26: 18, 27: 7, 28: 8, 29: 16, 30: 6,
};
// Hour bone weight (时辰, 地支 index 0-11)
const HOUR_WEIGHTS: Record<number, number> = {
0: 16, // 子时 23-01
1: 6, // 丑时 01-03
2: 7, // 寅时 03-05
3: 10, // 卯时 05-07
4: 9, // 辰时 07-09
5: 16, // 巳时 09-11
6: 10, // 午时 11-13
7: 8, // 未时 13-15
8: 8, // 申时 15-17
9: 9, // 酉时 17-19
10: 6, // 戌时 19-21
11: 6, // 亥时 21-23
};
// Interpretation for each total weight (in 钱)
const INTERPRETATIONS: Record<number, { text: string; fortune: string }> = {
21: { text: '短命非业谓大凶,平生灾难事重重,凶祸频临陷逆境,终世困苦事不成。', fortune: '下' },
22: { text: '身寒骨冷苦伶仃,此命推来行乞人,劳劳碌碌无度日,终年打拱过平生。', fortune: '下' },
23: { text: '此命推来骨格轻,求谋作事事难成,妻儿兄弟应难许,别处他乡作散人。', fortune: '下' },
24: { text: '此命推来福禄无,门庭困苦总难荣,六亲骨肉皆无靠,流浪他乡作老翁。', fortune: '下' },
25: { text: '此命推来祖业微,门庭营度似稀奇,六亲骨肉如冰炭,一世勤劳自把持。', fortune: '中下' },
26: { text: '平生衣禄苦中求,独自营谋事不休,离祖出门宜早计,晚来衣禄自无休。', fortune: '中下' },
27: { text: '一生作事少商量,难靠祖宗怎主张,独马单枪空做去,早年晚岁总无长。', fortune: '中下' },
28: { text: '一生行事似飘蓬,祖宗产业在梦中,若不过房改名姓,也当移徒二三通。', fortune: '中下' },
29: { text: '初年运限未曾亨,纵有功名在后成,须过四旬才可立,移居改姓始为良。', fortune: '中' },
30: { text: '劳劳碌碌苦中求,东奔西走何日休,若使终身勤与俭,老来稍可免忧愁。', fortune: '中' },
31: { text: '忙忙碌碌苦中求,何日云开见日头,难得祖基家可立,中年衣食渐无忧。', fortune: '中' },
32: { text: '初年运蹇事难谋,渐有财源如水流,到得中年衣食旺,那时名利一齐收。', fortune: '中上' },
33: { text: '早年做事事难成,百年勤劳枉费心,半世自如流水去,后来运到始得金。', fortune: '中上' },
34: { text: '此命福气果如何,僧道门中衣禄多,离祖出家方为妙,朝晚拜佛念弥陀。', fortune: '中上' },
35: { text: '生平福量不周全,祖业根基觉少传,营事生涯宜守旧,时来衣食胜从前。', fortune: '中' },
36: { text: '不须劳碌过平生,独自成家福不轻,早有福星常照命,任君行去百般成。', fortune: '上' },
37: { text: '此命般般事不成,弟兄少力自孤行,虽然祖业须微有,来得明时去不明。', fortune: '中下' },
38: { text: '一身骨肉最清高,早入簧门姓氏标,待到年将三十六,蓝衫脱去换红袍。', fortune: '上' },
39: { text: '此命终身运不通,劳劳作事尽皆空,苦心竭力成家计,到得那时在梦中。', fortune: '中下' },
40: { text: '平生衣禄是绵长,件件心中自主张,前面风霜多受过,后来必定享安康。', fortune: '上' },
41: { text: '此命推来自不同,为人能干异凡庸,中年还有逍遥福,不比前时运未通。', fortune: '上' },
42: { text: '得宽怀处且宽怀,何用双眉皱不开,若使中年命运济,那时名利一齐来。', fortune: '上' },
43: { text: '为人心性最聪明,作事轩昂近贵人,衣禄一生天注定,不须劳碌是丰亨。', fortune: '上上' },
44: { text: '万事由天莫苦求,须知福碌赖人修,当年财帛难如意,晚景欣然便不忧。', fortune: '中上' },
45: { text: '名利推求竟若何,前番辛苦后奔波,命中难养男和女,骨肉扶持也不多。', fortune: '中' },
46: { text: '东西南北尽皆通,出姓移居更觉隆,衣禄无穷无数定,中年晚景一般同。', fortune: '上' },
47: { text: '此命推求旺末年,妻荣子贵自怡然,平生原有滔滔福,可卜财源若水泉。', fortune: '上' },
48: { text: '初年运道未曾通,几许蹉跎命亦穷,兄弟六亲无依靠,一生事业晚来整。', fortune: '中' },
49: { text: '此命推来福不轻,自成自立显门庭,从来富贵人钦敬,使婢差奴过一生。', fortune: '上' },
50: { text: '为利为名终日劳,中年福禄也多遭,老来自有财星照,不比前番目下高。', fortune: '上' },
51: { text: '一世荣华事事通,不须劳碌自亨通,兄弟叔侄皆如意,家业成时福禄宏。', fortune: '上' },
52: { text: '一世亨通事事能,不须劳苦自然宁,宗族有光欣喜甚,家产丰盈自称心。', fortune: '上' },
53: { text: '此格推来福泽宏,兴家立业在其中,一生衣食安排定,却是人间一福翁。', fortune: '上' },
54: { text: '此命推来厚且清,诗书满腹看功成,丰衣足食自然稳,正是人间有福人。', fortune: '上上' },
55: { text: '走马扬鞭争利名,少年作事费筹论,一朝福禄源源至,富贵荣华显六亲。', fortune: '上' },
56: { text: '此格推来礼义通,一身福禄用无穷,甜酸苦辣皆尝过,滚滚财源稳且丰。', fortune: '上' },
57: { text: '福禄丰盈万事全,一身荣耀乐天年,名扬威震人争羡,此世逍遥宛似仙。', fortune: '上上' },
58: { text: '平生福禄自然来,名利双全福禄偕,雁塔题名为贵客,紫袍玉带走金阶。', fortune: '上' },
59: { text: '细推此格妙且清,必定财高礼义通,甲第之中应有分,扬鞭走马显威荣。', fortune: '上' },
60: { text: '一朝金榜快题名,显祖荣宗大器成,衣禄定然无欠缺,田园财帛更丰盈。', fortune: '上上' },
61: { text: '不作朝中金榜客,定为世上一财翁,聪明天赋经书熟,名显高科自是荣。', fortune: '上上' },
62: { text: '此命生来福不穷,读书必定显亲宗,紫衣玉带为卿相,富贵荣华孰与同。', fortune: '上上' },
63: { text: '命主为官福禄长,得来富贵定非常,名题雁塔传金榜,定中高科天下扬。', fortune: '上上' },
64: { text: '此命生成福不轻,读书必定有功名,果然富贵前生定,一世荣华事事成。', fortune: '上上' },
65: { text: '细推此命福不轻,安国安邦极品人,文纷雕梁徽富贵,威声照耀四方闻。', fortune: '上上' },
66: { text: '此命推来福且宏,荣华富贵自然通,命中注定衣禄足,一世亨通稳且丰。', fortune: '上上' },
67: { text: '此命生来福自宏,田园家业最高隆,平生衣禄丰盈足,一世荣华万事通。', fortune: '上上' },
68: { text: '富贵荣华莫强求,强求不出反成羞,有福之人还自至,无福之人反成忧。', fortune: '中' },
69: { text: '君是人间前禄星,一生富贵众人钦,纵然福禄由天定,安享荣华过一生。', fortune: '上上' },
70: { text: '此命推来福禄宏,不须劳碌过平生,妻儿和顺皆如意,家道兴隆福自成。', fortune: '上' },
71: { text: '此命生来大不同,公侯卿相在其中,一生自有逍遥福,富贵荣华极品隆。', fortune: '上上' },
72: { text: '此命生来福泽长,兴家立业有祯祥,一生自有逍遥福,富贵荣华极品良。', fortune: '上上' },
};
/** Calculate Bone Weight Fortune from lunar calendar data */
export function calculateBoneWeight(
lunarYearGanzhiIndex: number, // 0-59 六十甲子 index
lunarMonth: number, // 1-12
lunarDay: number, // 1-30
earthBranchHourIndex: number, // 0-11 地支时辰 index
): BoneWeightResult {
const yearWt = YEAR_WEIGHTS[lunarYearGanzhiIndex] || 9;
const monthWt = MONTH_WEIGHTS[lunarMonth] || 9;
const dayWt = DAY_WEIGHTS[lunarDay] || 9;
const hourWt = HOUR_WEIGHTS[earthBranchHourIndex] || 9;
const totalWeight = yearWt + monthWt + dayWt + hourWt;
const totalLiang = Math.floor(totalWeight / 10);
const totalQian = totalWeight % 10;
// Find closest interpretation
const interpretation = findInterpretation(totalWeight);
return {
yearWeight: yearWt,
monthWeight: monthWt,
dayWeight: dayWt,
hourWeight: hourWt,
totalWeight,
totalLiang,
totalQian,
interpretation: interpretation.text,
fortune: interpretation.fortune as BoneWeightResult['fortune'],
};
}
function findInterpretation(totalQian: number): { text: string; fortune: string } {
// Direct match
if (INTERPRETATIONS[totalQian]) return INTERPRETATIONS[totalQian];
// Find closest
const keys = Object.keys(INTERPRETATIONS).map(Number).sort((a, b) => a - b);
let closest = keys[0];
let minDiff = Math.abs(totalQian - closest);
for (const k of keys) {
const diff = Math.abs(totalQian - k);
if (diff < minDiff) { minDiff = diff; closest = k; }
}
return INTERPRETATIONS[closest] || { text: '命格推来,自有天定', fortune: '中' };
}
@@ -1,32 +0,0 @@
/**
* 佛教节日(农历)— tyme4ts 不提供,这里维护常用重大佛教日期表
*/
const BUDDHIST_FESTIVALS: Record<string, string> = {
'1-1': '弥勒菩萨圣诞',
'2-8': '释迦牟尼佛出家日',
'2-15': '释迦牟尼佛涅槃日',
'2-19': '观音菩萨圣诞',
'2-21': '普贤菩萨圣诞',
'3-16': '准提菩萨圣诞',
'4-4': '文殊菩萨圣诞',
'4-8': '释迦牟尼佛圣诞(浴佛节)',
'5-3': '伽蓝菩萨圣诞',
'6-3': '韦驮菩萨圣诞',
'6-19': '观音菩萨成道日',
'7-13': '大势至菩萨圣诞',
'7-15': '盂兰盆节(佛欢喜日)',
'7-30': '地藏菩萨圣诞',
'8-22': '燃灯佛圣诞',
'9-19': '观音菩萨出家日',
'9-30': '药师佛圣诞',
'10-5': '达摩祖师诞辰',
'11-17': '阿弥陀佛圣诞',
'12-8': '释迦牟尼佛成道日(腊八)',
'12-29': '华严菩萨圣诞',
};
/** Get Buddhist festival name by lunar month/day (闰月不重复过节) */
export function getBuddhistFestival(lunarMonth: number, lunarDay: number): string | null {
return BUDDHIST_FESTIVALS[`${lunarMonth}-${lunarDay}`] || null;
}
@@ -1,275 +0,0 @@
import { SolarDay } from 'tyme4ts';
import type { EightCharInfo, PillarInfo } from '../types/bazi';
import type { DailyFortuneResult, PillarRelationship } from '../types/fortune';
import {
getBranchRelationship,
getTenStarRelationship,
checkStemCombine,
checkStemOpposite,
} from './relationship';
const PILLAR_LABELS: Record<string, string> = {
year: '年柱', month: '月柱', day: '日柱', hour: '时柱',
};
const PILLAR_KEYS = ['year', 'month', 'day', 'hour'] as const;
export function calculateDailyFortune(userBazi: EightCharInfo, date: Date): DailyFortuneResult {
const solarDay = SolarDay.fromYmd(date.getFullYear(), date.getMonth() + 1, date.getDate());
const lunarDay = solarDay.getLunarDay();
const lunarHour = lunarDay.getHours()[6];
const dayEightChar = lunarHour.getEightChar();
const dayPillars: Record<string, { ganzhi: string; stem: string; branch: string }> = {
year: { ganzhi: dayEightChar.getYear().getName(), stem: dayEightChar.getYear().getHeavenStem().getName(), branch: dayEightChar.getYear().getEarthBranch().getName() },
month: { ganzhi: dayEightChar.getMonth().getName(), stem: dayEightChar.getMonth().getHeavenStem().getName(), branch: dayEightChar.getMonth().getEarthBranch().getName() },
day: { ganzhi: dayEightChar.getDay().getName(), stem: dayEightChar.getDay().getHeavenStem().getName(), branch: dayEightChar.getDay().getEarthBranch().getName() },
hour: { ganzhi: dayEightChar.getHour().getName(), stem: dayEightChar.getHour().getHeavenStem().getName(), branch: dayEightChar.getHour().getEarthBranch().getName() },
};
const userPillars: Record<string, PillarInfo> = {
year: userBazi.yearPillar, month: userBazi.monthPillar, day: userBazi.dayPillar, hour: userBazi.hourPillar,
};
const relationships: PillarRelationship[] = [];
for (const key of PILLAR_KEYS) {
const userPillar = userPillars[key]; const dayP = dayPillars[key];
const stemTenStar = getTenStarRelationship(userPillar.heavenStem, dayP.stem);
const stemCombine = checkStemCombine(userPillar.heavenStem, dayP.stem);
const stemOpposite = checkStemOpposite(userPillar.heavenStem, dayP.stem);
const branchRel = getBranchRelationship(userPillar.earthBranch, dayP.branch);
let score = 0;
if (stemTenStar) {
const good = ['正印','偏印','食神','正财','偏财','正官'];
const bad = ['七杀','劫财','伤官'];
if (good.includes(stemTenStar)) score += 4;
else if (bad.includes(stemTenStar)) score -= 3;
else score += 1;
}
if (stemCombine) score += 5;
if (stemOpposite) score -= 6;
if (branchRel.combine) score += 4;
if (branchRel.threeCombine) score += 3;
if (branchRel.opposite) score -= 5;
if (branchRel.harm) score -= 4;
if (branchRel.punish) score -= 3;
score = Math.max(-10, Math.min(10, score));
relationships.push({
pillar: key, pillarLabel: PILLAR_LABELS[key],
userGanzhi: userPillar.ganzhi, dayGanzhi: dayP.ganzhi,
stemTenStar, stemCombine, stemOpposite,
branchCombine: branchRel.combine, branchThreeCombine: branchRel.threeCombine,
branchOpposite: branchRel.opposite, branchHarm: branchRel.harm,
branchPunish: branchRel.punish, branchFormation: branchRel.formation,
score,
});
}
const weightedScore =
relationships[0].score * 0.20 + relationships[1].score * 0.25 +
relationships[2].score * 0.40 + relationships[3].score * 0.15;
const overallScore = Math.max(-100, Math.min(100, Math.round(weightedScore * 10)));
const scoreLevel: DailyFortuneResult['scoreLevel'] =
overallScore >= 50 ? 'great' : overallScore >= 20 ? 'good' :
overallScore >= -20 ? 'fair' : overallScore >= -50 ? 'poor' : 'bad';
const luckyAspects = generateLuckyAspects(relationships);
const unluckyAspects = generateUnluckyAspects(relationships);
const suggestions = generateSuggestions(relationships, userBazi, overallScore);
const affectedAreas = determineAffectedAreas(relationships);
const luckyMeta = computeLuckyMeta(userBazi, dayPillars.day.ganzhi, overallScore);
const categoryScores = computeCategoryScores(relationships);
const lunarDateStr = `${lunarDay.getLunarMonth().getLunarYear().getYear()}${lunarDay.getLunarMonth().getName()}${lunarDay.getName()}`;
return {
date: `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`,
lunarDate: lunarDateStr, dayGanzhi: dayPillars.day.ganzhi,
overallScore, scoreLevel, pillarRelationships: relationships,
luckyAspects, unluckyAspects, suggestions, affectedAreas, luckyMeta, categoryScores,
};
}
function generateLuckyAspects(relationships: PillarRelationship[]): string[] {
const seen = new Set<string>(); const aspects: string[] = [];
const tenStarPlain: Record<string, string> = {
'正官':'事业运不错,工作上容易得到认可和赏识',
'七杀':'进取心强,适合挑战难题和竞争性事务',
'正印':'学习运佳,适合读书充电或向长辈请教',
'偏印':'灵感丰富,适合研究和创意工作',
'食神':'心情舒畅,适合休闲放松和享受生活',
'伤官':'表达欲强,适合沟通交流和展示自我',
'正财':'财运平稳,适合处理日常财务和长期投资',
'偏财':'偏财运佳,可能有意外之财或投资收益',
'比肩':'人际关系和睦,容易得到朋友和同事的帮助',
'劫财':'社交活跃,适合参加聚会和团队活动',
};
const hasStemCombine = relationships.some(r => r.stemCombine);
const hasBranchCombine = relationships.some(r => r.branchCombine || r.branchThreeCombine);
for (const rel of relationships) {
if (rel.stemTenStar && tenStarPlain[rel.stemTenStar] && !seen.has(rel.stemTenStar)) {
aspects.push(tenStarPlain[rel.stemTenStar]); seen.add(rel.stemTenStar);
}
}
if (hasStemCombine && !seen.has('combine')) { aspects.push('天时地利人和,容易遇到贵人相助和好机会'); seen.add('combine'); }
if (hasBranchCombine && !seen.has('branch')) { aspects.push('身边关系和谐,适合与人合作或开展团队项目'); seen.add('branch'); }
if (aspects.length === 0) aspects.push('今天整体运势平稳,适合按部就班处理日常事务');
return aspects.slice(0, 4);
}
function generateUnluckyAspects(relationships: PillarRelationship[]): string[] {
const aspects: string[] = [];
const hasOpposite = relationships.some(r => r.branchOpposite);
const hasHarm = relationships.some(r => r.branchHarm);
const hasPunish = relationships.some(r => r.branchPunish);
const hasStemOpposite = relationships.some(r => r.stemOpposite);
const hasQiSha = relationships.some(r => r.stemTenStar === '七杀');
const hasJieCai = relationships.some(r => r.stemTenStar === '劫财');
const hasShangGuan = relationships.some(r => r.stemTenStar === '伤官');
if (hasStemOpposite) aspects.push('今天可能遇到突发变化或计划被打乱,保持冷静和弹性很重要');
if (hasOpposite) aspects.push('与他人意见不合的可能性较高,尽量避免争执和正面冲突');
if (hasHarm) aspects.push('留意身边的小人和是非,不要轻易透露自己的计划和秘密');
if (hasPunish) aspects.push('容易说错话或做出不恰当的举动,多听少说更安全');
if (hasQiSha) aspects.push('压力较大的一天,注意调节情绪,重要决策可暂缓');
if (hasJieCai) aspects.push('财务方面要谨慎,不宜大额消费或借钱给别人');
if (hasShangGuan) aspects.push('表达时注意方式方法,容易词不达意引起误会');
if (aspects.length === 0) aspects.push('今天没有什么特别需要注意的,保持平常心即可');
return aspects.slice(0, 3);
}
function generateSuggestions(
relationships: PillarRelationship[],
userBazi: EightCharInfo,
overallScore: number,
): string[] {
const s: string[] = [];
const de = userBazi.dayMasterElement;
const colors: Record<string,string> = { '木':'绿色/青色','火':'红色/紫色','土':'黄色/棕色','金':'白色/浅色','水':'蓝色/黑色' };
const dirs: Record<string,string> = { '木':'东方','火':'南方','土':'中央','金':'西方','水':'北方' };
const hasConflict = relationships.some(r => r.branchOpposite || r.stemOpposite);
const hasCombine = relationships.some(r => r.branchCombine || r.stemCombine);
const hasHarm = relationships.some(r => r.branchHarm);
const hasPunish = relationships.some(r => r.branchPunish);
const goodPool = [
de ? `👔 幸运色${colors[de]||'浅色'},穿对颜色运气更好` : `👔 今天穿浅色衣服心情更好`,
`✅ 适合推进重要事项,果断决策会有好结果`,
`📝 把计划写下来按部就班执行,效率翻倍`,
`🎯 专注一件事比多线作战更有效果`,
`🤝 适合约重要的人见面,贵人运在线`,
`🌅 早起一点早晨的效率最高`,
`📊 适合总结和复盘能发现新机会`,
`🏃 运动或户外活动对运势有加成`,
];
const fairPool = [
`💡 运势平稳该做什么就做什么`,
`☕ 适合处理日常事务不宜做重大改变`,
`📖 适合学习充电多读多听少说`,
`🧹 整理收纳会让心情变好`,
`🍵 节奏放慢一点稳扎稳打`,
`📞 适合和老朋友聊聊天`,
];
const poorPool = [
`🧘 适合保守行事多观察多思考`,
`☕ 适合独处和复盘少社交`,
`🛡️ 以守成为主避免冲动`,
`📿 冥想或听音乐能化解负面情绪`,
`🙏 遇到不顺心的事深呼吸三秒`,
`📝 把想法写下来明天再行动`,
];
const badPool = [
`🛡️ 宜静不宜动重要决策能缓则缓`,
`🚫 避免签合同或做出重大承诺`,
`🧘 适合冥想休息养精蓄锐`,
`📿 去清净处走走转换气场`,
`💤 早点休息好睡眠是最好的转运`,
`🙏 好事多磨心态会好很多`,
];
let pool = fairPool;
if (overallScore >= 30) pool = goodPool;
else if (overallScore >= 0) pool = fairPool;
else if (overallScore >= -30) pool = poorPool;
else pool = badPool;
const seed = new Date().getDate() + new Date().getMonth() * 31;
s.push(pool[seed % pool.length]);
s.push(pool[(seed + 5) % pool.length]);
if (overallScore >= 10 && de && dirs[de]) s.push(`🧭 向${dirs[de]}行事有意外好运`);
if (hasCombine && !hasConflict) s.push('🤝 人际关系活跃适合合作洽谈');
else if (hasConflict && hasHarm) s.push('⚠️ 人际关系有暗礁保持微笑少说话');
else if (hasConflict) s.push('🙏 意见不合时先认同再引导');
else if (hasPunish) s.push('💬 说话前过遍脑子今天容易说错话');
const seen = new Set<string>();
const unique = s.filter(t => { if (seen.has(t)) return false; seen.add(t); return true; });
return unique.slice(0, 4);
}
function computeLuckyMeta(userBazi: EightCharInfo, dayGanzhi: string, score: number) {
const de = userBazi.dayMasterElement;
const colorMap: Record<string, string[]> = { '木': ['绿色','青色','翠绿'], '火': ['红色','紫色','粉色'], '土': ['黄色','棕色','米色'], '金': ['白色','银色','浅灰'], '水': ['蓝色','黑色','深灰'] };
const dirMap: Record<string, string> = { '木': '东方', '火': '南方', '土': '中央', '金': '西方', '水': '北方' };
const actMap: Record<string, string[]> = {
'木': ['户外散步','园艺','阅读','写作'], '火': ['社交','演讲','创意','运动'], '土': ['整理收纳','理财','烹饪','冥想'],
'金': ['商务洽谈','签约','购物','美容'], '水': ['学习进修','旅行','游泳','听音乐'],
};
const colors = colorMap[de] || ['红色','白色'];
const direction = dirMap[de] || '东方';
const seed = parseInt(dayGanzhi.charCodeAt(0).toString()) + new Date().getDate();
const n1 = (seed % 9) + 1;
const n2 = ((seed * 3 + 7) % 9) + 1;
const activities = actMap[de] || ['运动','阅读'];
const activity = activities[seed % activities.length];
return {
colors: [colors[0], colors[1]],
numbers: [n1, n2],
direction,
element: de,
activity: score >= 0 ? activity : activities[(seed + 3) % activities.length],
};
}
function computeCategoryScores(relationships: PillarRelationship[]) {
const tenStarLove: Record<string,number> = { '正官':8,'七杀':-2,'正印':3,'偏印':2,'食神':6,'伤官':5,'正财':4,'偏财':3 };
const tenStarCareer: Record<string,number> = { '正官':10,'七杀':8,'正印':5,'偏印':4,'食神':3,'伤官':2,'正财':2 };
const tenStarWealth: Record<string,number> = { '正财':10,'偏财':8,'食神':6,'伤官':4,'正官':2,'七杀':-2 };
const tenStarHealth: Record<string,number> = { '正印':8,'偏印':6,'比肩':5,'食神':4,'七杀':-4,'伤官':-2 };
let love=0, career=0, wealth=0, health=0;
for (const rel of relationships) {
const ts = rel.stemTenStar;
if (!ts) continue;
const w = rel.pillar === 'day' ? 3 : rel.pillar === 'month' ? 2 : 1;
love += (tenStarLove[ts]||0) * w + (rel.branchHarm?-5:0) * w + (rel.branchCombine?4:0) * w;
career += (tenStarCareer[ts]||0) * w + (rel.branchOpposite?-4:0) * w + (rel.branchThreeCombine?5:0) * w;
wealth += (tenStarWealth[ts]||0) * w + (rel.stemCombine?5:0) * w;
health += (tenStarHealth[ts]||0) * w + (rel.branchOpposite?-3:0) * w;
}
// Normalize to -100..100
const clamp = (v:number) => Math.max(-100, Math.min(100, Math.round(v * 2.5)));
return { love: clamp(love), career: clamp(career), wealth: clamp(wealth), health: clamp(health) };
}
function determineAffectedAreas(relationships: PillarRelationship[]): string[] {
const areas = new Set<string>();
const areaMapping: Record<string, string> = {
'正财':'财运','偏财':'偏财/投资','正官':'事业','七杀':'事业/压力',
'正印':'学业','偏印':'学业/智慧','食神':'创作/享乐','伤官':'口才/表达',
'比肩':'人际关系','劫财':'竞争/人际',
};
for (const rel of relationships) {
if (rel.stemTenStar && areaMapping[rel.stemTenStar]) areas.add(areaMapping[rel.stemTenStar]);
if (rel.branchOpposite && rel.pillar === 'year') areas.add('长辈/根基');
if (rel.branchOpposite && rel.pillar === 'month') areas.add('事业/家庭');
if (rel.branchOpposite && rel.pillar === 'day') areas.add('婚姻/健康');
if (rel.branchOpposite && rel.pillar === 'hour') areas.add('子女/晚年');
}
return areas.size > 0 ? [...areas] : ['综合运势'];
}
@@ -1,99 +0,0 @@
import type { EightCharInfo } from '../types/bazi';
/** Five Element profile */
export interface ElementProfile {
wood: number;
fire: number;
earth: number;
metal: number;
water: number;
total: number;
dominant: string;
weakest: string;
isBalanced: boolean;
}
/** Analyze the five element balance in a Bazi chart */
export function analyzeElementBalance(bazi: EightCharInfo): ElementProfile {
const pillars = [bazi.yearPillar, bazi.monthPillar, bazi.dayPillar, bazi.hourPillar];
const counts: Record<string, number> = {
'木': 0,
'火': 0,
'土': 0,
'金': 0,
'水': 0,
};
for (const pillar of pillars) {
// Count stem element
if (pillar.elementStem && counts[pillar.elementStem] !== undefined) {
counts[pillar.elementStem] += 1;
}
// Count branch element
if (pillar.elementBranch && counts[pillar.elementBranch] !== undefined) {
counts[pillar.elementBranch] += 1;
}
// Count hidden stem elements (half weight)
for (const hs of pillar.hideStems) {
// Infer element from stem name
const element = inferElementFromStem(hs.stem);
if (element && counts[element] !== undefined) {
counts[element] += 0.5;
}
}
}
const total = counts['木'] + counts['火'] + counts['土'] + counts['金'] + counts['水'];
// Find dominant and weakest
let dominant = '木';
let weakest = '木';
let maxCount = 0;
let minCount = Infinity;
for (const [element, count] of Object.entries(counts)) {
if (count > maxCount) {
maxCount = count;
dominant = element;
}
if (count < minCount) {
minCount = count;
weakest = element;
}
}
// Balance check: each element should be within 30% of ideal (20% each)
const ideal = total / 5;
let isBalanced = true;
for (const count of Object.values(counts)) {
if (Math.abs(count - ideal) > ideal * 0.4) {
isBalanced = false;
break;
}
}
return {
wood: counts['木'] || 0,
fire: counts['火'] || 0,
earth: counts['土'] || 0,
metal: counts['金'] || 0,
water: counts['水'] || 0,
total,
dominant,
weakest,
isBalanced,
};
}
/** Infer five element from heavenly stem name */
function inferElementFromStem(stem: string): string | null {
const stemElements: Record<string, string> = {
'甲': '木', '乙': '木',
'丙': '火', '丁': '火',
'戊': '土', '己': '土',
'庚': '金', '辛': '金',
'壬': '水', '癸': '水',
};
return stemElements[stem] || null;
}
@@ -1,88 +0,0 @@
/**
* 大运/流年/流月/流日 与日主的生克冲合分析
* 将任意干支与日主(日干/日支)比较,输出十神、五行生克、天干合冲、地支关系与简化吉凶。
*/
import { getTenStarRelationship, checkStemCombine, checkStemOpposite, getBranchRelationship } from './relationship';
export interface FortuneLuck {
ganzhi: string;
tenStar: string | null;
/** 该柱五行 vs 日主五行:比和/生我/我生/克我/我克 */
elementRelation: string;
stemCombine: boolean;
stemOpposite: boolean;
branchCombine: boolean;
branchThreeCombine: boolean;
branchOpposite: boolean;
branchHarm: boolean;
branchPunish: boolean;
score: number;
level: '吉' | '凶' | '平';
}
const STEM_ELEMENT: Record<string, string> = {
'甲': '木', '乙': '木', '丙': '火', '丁': '火', '戊': '土',
'己': '土', '庚': '金', '辛': '金', '壬': '水', '癸': '水',
};
const GENERATES: Record<string, string> = { '木': '火', '火': '土', '土': '金', '金': '水', '水': '木' };
const KILLS: Record<string, string> = { '木': '土', '土': '水', '水': '火', '火': '金', '金': '木' };
const GOOD_TEN_STARS = ['正印', '偏印', '食神', '正财', '偏财', '正官'];
const BAD_TEN_STARS = ['七杀', '劫财', '伤官'];
/** Analyze an external ganzhi (大运/流年/流月/流日) against the day master pillar */
export function analyzeFortuneGanzhi(
ganzhi: string,
dayStem: string,
dayBranch: string,
): FortuneLuck {
const stem = ganzhi[0];
const branch = ganzhi[1];
const tenStar = getTenStarRelationship(dayStem, stem);
const el = STEM_ELEMENT[stem];
const de = STEM_ELEMENT[dayStem];
let elementRelation: string;
if (!el || !de || el === de) elementRelation = '比和';
else if (GENERATES[el] === de) elementRelation = '生我';
else if (GENERATES[de] === el) elementRelation = '我生';
else if (KILLS[el] === de) elementRelation = '克我';
else elementRelation = '我克';
const stemCombine = checkStemCombine(stem, dayStem);
const stemOpposite = checkStemOpposite(stem, dayStem);
const br = getBranchRelationship(branch, dayBranch);
let score = 0;
if (tenStar) {
if (GOOD_TEN_STARS.includes(tenStar)) score += 4;
else if (BAD_TEN_STARS.includes(tenStar)) score -= 3;
else score += 1;
}
if (stemCombine) score += 5;
if (stemOpposite) score -= 6;
if (br.combine) score += 4;
if (br.threeCombine) score += 3;
if (br.opposite) score -= 5;
if (br.harm) score -= 4;
if (br.punish) score -= 3;
score = Math.max(-10, Math.min(10, score));
const level: FortuneLuck['level'] = score >= 3 ? '吉' : score <= -3 ? '凶' : '平';
return {
ganzhi,
tenStar,
elementRelation,
stemCombine,
stemOpposite,
branchCombine: br.combine,
branchThreeCombine: br.threeCombine,
branchOpposite: br.opposite,
branchHarm: br.harm,
branchPunish: br.punish,
score,
level,
};
}
@@ -1,258 +0,0 @@
/**
* 梅花易数 (Plum Blossom I-Ching Divination)
* Based on time (year, month, day, hour) to derive hexagrams
*/
export interface TrigramInfo {
index: number; // 1-8 (乾兑离震巽坎艮坤)
name: string; // Chinese name
symbol: string; // Unicode trigram symbol
element: string; // Five element
direction: string; // Direction
nature: string; // Natural phenomenon
trait: string; // Personality trait
body: string; // Body part
}
export interface HexagramInfo {
number: number; // 1-64
name: string; // Chinese name e.g. "乾为天"
upperTrigram: TrigramInfo;
lowerTrigram: TrigramInfo;
changingLine: number; // 1-6, which line changes
interpretation: string; // Overall interpretation
judgment: string; // 彖辞
image: string; // 象辞
lines: string[]; // 6 line interpretations
}
export interface PlumBlossomResult {
originalHexagram: HexagramInfo;
transformedHexagram: HexagramInfo | null;
mutualHexagram: HexagramInfo | null;
upperTrigram: TrigramInfo;
lowerTrigram: TrigramInfo;
changingLine: number;
constitution: string; // 体卦
function: string; // 用卦
relationship: string; // 体用关系
}
// 8 Trigrams (八卦)
const TRIGRAMS: Record<number, TrigramInfo> = {
1: { index: 1, name: '乾', symbol: '☰', element: '金', direction: '西北', nature: '天', trait: '健', body: '首' },
2: { index: 2, name: '兑', symbol: '☱', element: '金', direction: '西', nature: '泽', trait: '悦', body: '口' },
3: { index: 3, name: '离', symbol: '☲', element: '火', direction: '南', nature: '火', trait: '丽', body: '目' },
4: { index: 4, name: '震', symbol: '☳', element: '木', direction: '东', nature: '雷', trait: '动', body: '足' },
5: { index: 5, name: '巽', symbol: '☴', element: '木', direction: '东南', nature: '风', trait: '入', body: '股' },
6: { index: 6, name: '坎', symbol: '☵', element: '水', direction: '北', nature: '水', trait: '陷', body: '耳' },
7: { index: 7, name: '艮', symbol: '☶', element: '土', direction: '东北', nature: '山', trait: '止', body: '手' },
8: { index: 8, name: '坤', symbol: '☷', element: '土', direction: '西南', nature: '地', trait: '顺', body: '腹' },
};
// All 64 Hexagrams (complete I-Ching)
const H: Record<string, { name: string; judgment: string; image: string; lines: string[] }> = {
// 乾宫八卦 (1-8)
'1,1':{name:'乾为天',judgment:'大哉乾元,万物资始,乃统天。云行雨施,品物流形',image:'天行健,君子以自强不息',lines:['潜龙勿用','见龙在田,利见大人','君子终日乾乾,夕惕若厉','或跃在渊,无咎','飞龙在天,利见大人','亢龙有悔']},
'1,5':{name:'天风姤',judgment:'姤,遇也,柔遇刚也。天地相遇,品物咸章',image:'天下有风,姤。后以施命诰四方',lines:['系于金柅,贞吉','包有鱼,无咎','臀无肤,其行次且','包无鱼,起凶','以杞包瓜,含章','姤其角,吝']},
'1,7':{name:'天山遁',judgment:'遁亨,遁而亨也。刚当位而应,与时行也',image:'天下有山,遁。君子以远小人,不恶而严',lines:['遁尾厉,勿用有攸往','执之用黄牛之革','系遁,有疾厉','好遁,君子吉','嘉遁,贞吉','肥遁,无不利']},
'1,8':{name:'天地否',judgment:'否之匪人,不利君子贞。大往小来',image:'天地不交,否。君子以俭德辟难',lines:['拔茅茹,以其汇,贞吉','包承,小人吉,大人否','包羞','有命无咎,畴离祉','休否,大人吉','倾否,先否后喜']},
'5,8':{name:'风地观',judgment:'观,盥而不荐,有孚颙若。观天之神道而四时不忒',image:'风行地上,观。先王以省方观民设教',lines:['童观,小人无咎','窥观,利女贞','观我生进退','观国之光,利用宾于王','观我生,君子无咎','观其生,君子无咎']},
'7,8':{name:'山地剥',judgment:'剥,剥也,柔变刚也。不利有攸往',image:'山附于地,剥。上以厚下安宅',lines:['剥床以足,蔑贞凶','剥床以辨,蔑贞凶','剥之无咎','剥床以肤,凶','贯鱼以宫人宠,无不利','硕果不食,君子得舆']},
'3,8':{name:'火地晋',judgment:'晋,进也。明出地上,顺而丽乎大明',image:'明出地上,晋。君子以自昭明德',lines:['晋如摧如,贞吉','晋如愁如,贞吉','众允,悔亡','晋如鼫鼠,贞厉','悔亡,失得勿恤','晋其角,维用伐邑']},
'3,1':{name:'火天大有',judgment:'大有,柔得尊位,大中而上下应之',image:'火在天上,大有。君子以遏恶扬善,顺天休命',lines:['无交害,匪咎','大车以载,有攸往','公用亨于天子','匪其彭,无咎','厥孚交如,威如','自天佑之,吉无不利']},
// 坎宫八卦 (9-16)
'6,6':{name:'坎为水',judgment:'习坎,重险也。水流而不盈,行险而不失其信',image:'水洊至,习坎。君子以常德行习教事',lines:['习坎,入于坎窞','坎有险,求小得','来之坎坎,险且枕','樽酒簋贰,用缶','坎不盈,祗既平','系用徽纆,寘于丛棘']},
'6,2':{name:'水泽节',judgment:'节亨,苦节不可贞',image:'泽上有水,节。君子以制数度议德行',lines:['不出户庭,无咎','不出门庭,凶','不节若,则嗟若','安节,亨','甘节,吉','苦节,贞凶']},
'6,4':{name:'水雷屯',judgment:'屯,刚柔始交而难生。动乎险中,大亨贞',image:'云雷屯,君子以经纶',lines:['磐桓,利居贞','屯如邅如,乘马班如','即鹿无虞,惟入于林中','乘马班如,求婚媾','屯其膏,小贞吉','乘马班如,泣血涟如']},
'6,3':{name:'水火既济',judgment:'既济亨,小者亨也。利贞,初吉终乱',image:'水在火上,既济。君子以思患而豫防之',lines:['曳其轮,濡其尾','妇丧其茀,勿逐','高宗伐鬼方,三年克之','繻有衣袽,终日戒','东邻杀牛,不如西邻','濡其首,厉']},
'2,3':{name:'泽火革',judgment:'革,水火相息。天地革而四时成',image:'泽中有火,革。君子以治历明时',lines:['巩用黄牛之革','巳日乃革之,征吉','征凶,贞厉','悔亡,有孚改命','大人虎变,未占有孚','君子豹变,小人革面']},
'4,3':{name:'雷火丰',judgment:'丰,大也。明以动,故丰',image:'雷电皆至,丰。君子以折狱致刑',lines:['遇其配主,虽旬无咎','丰其蔀,日中见斗','丰其沛,日中见沬','丰其蔀,日中见斗','来章,有庆誉','丰其屋,蔀其家']},
'8,3':{name:'地火明夷',judgment:'明夷,利艰贞。明入地中,明夷',image:'明入地中,明夷。君子以莅众用晦而明',lines:['明夷于飞,垂其翼','明夷,夷于左股','明夷于南狩,得其大首','入于左腹,获明夷之心','箕子之明夷,利贞','不明晦,初登于天']},
'8,6':{name:'地水师',judgment:'师,众也。贞,丈人吉,无咎',image:'地中有水,师。君子以容民畜众',lines:['师出以律,否臧凶','在师中,吉无咎','师或舆尸,凶','师左次,无咎','田有禽,利执言','大君有命,开国承家']},
// 艮宫八卦 (17-24)
'7,7':{name:'艮为山',judgment:'艮,止也。时止则止,时行则行',image:'兼山,艮。君子以思不出其位',lines:['艮其趾,无咎','艮其腓,不拯其随','艮其限,列其夤','艮其身,无咎','艮其辅,言有序','敦艮,吉']},
'7,3':{name:'山火贲',judgment:'贲亨,柔来而文刚,故亨',image:'山下有火,贲。君子以明庶政无敢折狱',lines:['贲其趾,舍车而徒','贲其须','贲如濡如,永贞吉','贲如皤如,白马翰如','贲于丘园,束帛戋戋','白贲,无咎']},
'7,1':{name:'山天大畜',judgment:'大畜,刚健笃实辉光,日新其德',image:'天在山中,大畜。君子以多识前言往行',lines:['有厉,利已','舆说輹','良马逐,利艰贞','童牛之牿,元吉','豮豕之牙,吉','何天之衢,亨']},
'7,2':{name:'山泽损',judgment:'损,损下益上,其道上行',image:'山下有泽,损。君子以惩忿窒欲',lines:['已事遄往,无咎','利贞,征凶,弗损益之','三人行则损一人','损其疾,使遄有喜','或益之十朋之龟','弗损益之,无咎']},
'3,2':{name:'火泽睽',judgment:'睽,火动而上,泽动而下',image:'上火下泽,睽。君子以同而异',lines:['悔亡,丧马勿逐','遇主于巷,无咎','见舆曳,其牛掣','睽孤,遇元夫','悔亡,厥宗噬肤','睽孤,见豕负涂']},
'1,2':{name:'天泽履',judgment:'履,柔履刚也。说而应乎乾',image:'上天下泽,履。君子以辩上下定民志',lines:['素履往,无咎','履道坦坦,幽人贞吉','眇能视,跛能履','履虎尾,愬愬终吉','夬履,贞厉','视履考祥,其旋元吉']},
'5,2':{name:'风泽中孚',judgment:'中孚,柔在内而刚得中',image:'泽上有风,中孚。君子以议狱缓死',lines:['虞吉,有它不燕','鸣鹤在阴,其子和之','得敌,或鼓或罢','月几望,马匹亡','有孚挛如,无咎','翰音登于天,贞凶']},
'5,7':{name:'风山渐',judgment:'渐,女归吉也。进得位,往有功也',image:'山上有木,渐。君子以居贤德善俗',lines:['鸿渐于干,小子厉','鸿渐于磐,饮食衎衎','鸿渐于陆,夫征不复','鸿渐于木,或得其桷','鸿渐于陵,妇三岁不孕','鸿渐于逵,其羽可用为仪']},
// 震宫八卦 (25-32)
'4,4':{name:'震为雷',judgment:'震亨。震来虩虩,笑言哑哑,震惊百里',image:'洊雷,震。君子以恐惧修省',lines:['震来虩虩,后笑言哑哑','震来厉,亿丧贝','震苏苏,震行无眚','震遂泥','震往来厉,亿无丧','震索索,视矍矍']},
'4,8':{name:'雷地豫',judgment:'豫,刚应而志行,顺以动',image:'雷出地奋,豫。先王以作乐崇德',lines:['鸣豫,凶','介于石,不终日','盱豫悔,迟有悔','由豫,大有得','贞疾,恒不死','冥豫,成有渝']},
'4,6':{name:'雷水解',judgment:'解,险以动,动而免乎险',image:'雷雨作,解。君子以赦过宥罪',lines:['无咎','田获三狐,得黄矢','负且乘,致寇至','解而拇,朋至斯孚','君子维有解,吉','公用射隼于高墉之上']},
'4,5':{name:'雷风恒',judgment:'恒,久也。刚上而柔下',image:'雷风,恒。君子以立不易方',lines:['浚恒,贞凶','悔亡','不恒其德,或承之羞','田无禽','恒其德,贞妇人吉','振恒,凶']},
'8,5':{name:'地风升',judgment:'柔以时升,巽而顺,刚中而应',image:'地中生木,升。君子以顺德积小以高大',lines:['允升,大吉','孚乃利用禴,无咎','升虚邑','王用亨于岐山','贞吉,升阶','冥升,利于不息之贞']},
'6,5':{name:'水风井',judgment:'井,改邑不改井,无丧无得',image:'木上有水,井。君子以劳民劝相',lines:['井泥不食,旧井无禽','井谷射鲋,瓮敝漏','井渫不食,为我心恻','井甃,无咎','井洌,寒泉食','井收勿幕,有孚元吉']},
'2,5':{name:'泽风大过',judgment:'大过,大者过也。栋桡,本末弱也',image:'泽灭木,大过。君子以独立不惧遁世无闷',lines:['藉用白茅,无咎','枯杨生稊,老夫得其女妻','栋桡,凶','栋隆,吉','枯杨生华,老妇得士夫','过涉灭顶,凶']},
'2,4':{name:'泽雷随',judgment:'随,刚来而下柔,动而说',image:'泽中有雷,随。君子以向晦入宴息',lines:['官有渝,贞吉','系小子,失丈夫','系丈夫,失小子','随有获,贞凶','孚于嘉,吉','拘系之,乃从维之']},
// 巽宫八卦 (33-40)
'5,5':{name:'巽为风',judgment:'重巽以申命,刚巽乎中正而志行',image:'随风,巽。君子以申命行事',lines:['进退,利武人之贞','巽在床下,用史巫纷若','频巽,吝','悔亡,田获三品','贞吉,悔亡无不利','巽在床下,丧其资斧']},
'5,1':{name:'风天小畜',judgment:'小畜,柔得位而上下应之',image:'风行天上,小畜。君子以懿文德',lines:['复自道,何其咎','牵复,吉','舆说辐,夫妻反目','有孚,血去惕出','有孚挛如,富以其邻','既雨既处,尚德载']},
'5,3':{name:'风火家人',judgment:'家人,女正位乎内,男正位乎外',image:'风自火出,家人。君子以言有物而行有恒',lines:['闲有家,悔亡','无攸遂,在中馈','家人嗃嗃,悔厉吉','富家,大吉','王假有家,勿恤','有孚威如,终吉']},
'5,4':{name:'风雷益',judgment:'益,损上益下,民说无疆',image:'风雷,益。君子以见善则迁有过则改',lines:['利用为大作,元吉','或益之十朋之龟','益之用凶事,无咎','中行告公从,利用为依迁国','有孚惠心,勿问元吉','莫益之,或击之']},
'1,4':{name:'天雷无妄',judgment:'无妄,刚自外来而为主于内',image:'天下雷行,物与无妄。先王以茂对时育万物',lines:['无妄,往吉','不耕获,不菑畬','无妄之灾,或系之牛','可贞,无咎','无妄之疾,勿药有喜','无妄,行有眚']},
'3,4':{name:'火雷噬嗑',judgment:'噬嗑亨,利用狱。刚柔分动而明',image:'雷电噬嗑,先王以明罚敕法',lines:['屦校灭趾,无咎','噬肤灭鼻,无咎','噬腊肉,遇毒','噬干胏,得金矢','噬干肉,得黄金','何校灭耳,凶']},
'7,4':{name:'山雷颐',judgment:'颐,贞吉。观颐,自求口实',image:'山下有雷,颐。君子以慎言语节饮食',lines:['舍尔灵龟,观我朵颐','颠颐,拂经于丘颐','拂颐,贞凶','颠颐,吉','拂经,居贞吉','由颐,厉吉,利涉大川']},
'7,5':{name:'山风蛊',judgment:'蛊,元亨。利涉大川,先甲三日后甲三日',image:'山下有风,蛊。君子以振民育德',lines:['干父之蛊,有子考无咎','干母之蛊,不可贞','干父之蛊,小有悔','裕父之蛊,往见吝','干父之蛊,用誉','不事王侯,高尚其事']},
// 离宫八卦 (41-48)
'3,3':{name:'离为火',judgment:'离,丽也。日月丽乎天,百谷草木丽乎土',image:'明两作,离。大人以继明照于四方',lines:['履错然,敬之无咎','黄离,元吉','日昃之离,不鼓缶而歌','突如其来如,焚如死如弃如','出涕沱若,戚嗟若','王用出征,有嘉折首']},
'3,7':{name:'火山旅',judgment:'旅,小亨。旅贞吉',image:'山上有火,旅。君子以明慎用刑而不留狱',lines:['旅琐琐,斯其所取灾','旅即次,怀其资','旅焚其次,丧其童仆','旅于处,得其资斧','射雉,一矢亡','鸟焚其巢,旅人先笑后号咷']},
'3,5':{name:'火风鼎',judgment:'鼎,象也。以木巽火,亨饪也',image:'木上有火,鼎。君子以正位凝命',lines:['鼎颠趾,利出否','鼎有实,我仇有疾','鼎耳革,其行塞','鼎折足,覆公餗','鼎黄耳金铉,利贞','鼎玉铉,大吉']},
'3,6':{name:'火水未济',judgment:'未济亨,小狐汔济,濡其尾',image:'火在水上,未济。君子以慎辨物居方',lines:['濡其尾,吝','曳其轮,贞吉','未济,征凶','贞吉,悔亡','贞吉,无悔','有孚于饮酒,无咎']},
'7,6':{name:'山水蒙',judgment:'蒙亨。匪我求童蒙,童蒙求我',image:'山下出泉,蒙。君子以果行育德',lines:['发蒙,利用刑人','包蒙,吉','勿用取女,见金夫','困蒙,吝','童蒙,吉','击蒙,不利为寇']},
'5,6':{name:'风水涣',judgment:'涣亨。王假有庙,利涉大川',image:'风行水上,涣。先王以享于帝立庙',lines:['用拯马壮,吉','涣奔其机,悔亡','涣其躬,无悔','涣其群,元吉','涣汗其大号','涣其血,去逖出']},
'1,6':{name:'天水讼',judgment:'讼,上刚下险,险而健,讼',image:'天与水违行,讼。君子以作事谋始',lines:['不永所事,小有言','不克讼,归而逋','食旧德,贞厉终吉','不克讼,复即命渝','讼,元吉','或锡之鞶带,终朝三褫']},
'1,3':{name:'天火同人',judgment:'同人,柔得位得中而应乎乾',image:'天与火,同人。君子以类族辨物',lines:['同人于门,无咎','同人于宗,吝','伏戎于莽,升其高陵','乘其墉,弗克攻','同人先号咷而后笑','同人于郊,无悔']},
// 坤宫八卦 (49-56)
'8,8':{name:'坤为地',judgment:'至哉坤元,万物资生,乃顺承天',image:'地势坤,君子以厚德载物',lines:['履霜,坚冰至','直方大,不习无不利','含章可贞,或从王事','括囊,无咎无誉','黄裳,元吉','龙战于野,其血玄黄']},
'8,4':{name:'地雷复',judgment:'复亨。出入无疾,朋来无咎',image:'雷在地中,复。先王以至日闭关',lines:['不远复,无祗悔','休复,吉','频复,厉','中行独复','敦复,无悔','迷复,凶有灾眚']},
'8,2':{name:'地泽临',judgment:'临,刚浸而长,说而顺',image:'泽上有地,临。君子以教思无穷容保民无疆',lines:['咸临,贞吉','咸临,吉无不利','甘临,无攸利','至临,无咎','知临,大君之宜','敦临,吉无咎']},
'8,1':{name:'地天泰',judgment:'泰,小往大来,吉亨。天地交而万物通',image:'天地交,泰。后以财成天地之道',lines:['拔茅茹,以其汇','包荒,用冯河','无平不陂,无往不复','翩翩,不富以其邻','帝乙归妹,以祉元吉','城复于隍,勿用师']},
'4,1':{name:'雷天大壮',judgment:'大壮,大者壮也。刚以动,故壮',image:'雷在天上,大壮。君子以非礼勿履',lines:['壮于趾,征凶','贞吉','小人用壮,君子用罔','贞吉,悔亡','丧羊于易,无悔','羝羊触藩,不能退']},
'2,1':{name:'泽天夬',judgment:'夬,决也,刚决柔也。健而说,决而和',image:'泽上于天,夬。君子以施禄及下',lines:['壮于前趾,往不胜为咎','惕号,莫夜有戎','壮于頄,有凶','臀无肤,其行次且','苋陆夬夬,中行无咎','无号,终有凶']},
'6,1':{name:'水天需',judgment:'需,须也。险在前也,刚健而不陷',image:'云上于天,需。君子以饮食宴乐',lines:['需于郊,利用恒','需于沙,小有言','需于泥,致寇至','需于血,出自穴','需于酒食,贞吉','入于穴,有不速之客三人来']},
'6,8':{name:'水地比',judgment:'比,吉也。比,辅也,下顺从也',image:'地上有水,比。先王以建万国亲诸侯',lines:['有孚比之,无咎','比之自内,贞吉','比之匪人','外比之,贞吉','显比,王用三驱','比之无首,凶']},
// 兑宫八卦 (57-64)
'2,2':{name:'兑为泽',judgment:'兑,说也。刚中而柔外,说以利贞',image:'丽泽,兑。君子以朋友讲习',lines:['和兑,吉','孚兑,吉','来兑,凶','商兑未宁,介疾有喜','孚于剥,有厉','引兑']},
'2,6':{name:'泽水困',judgment:'困,刚掩也。险以说,困而不失其所',image:'泽无水,困。君子以致命遂志',lines:['臀困于株木,入于幽谷','困于酒食,朱绂方来','困于石,据于蒺藜','来徐徐,困于金车','劓刖,困于赤绂','困于葛藟,于臲兀']},
'2,8':{name:'泽地萃',judgment:'萃,聚也。顺以说,刚中而应',image:'泽上于地,萃。君子以除戎器戒不虞',lines:['有孚不终,乃乱乃萃','引吉,无咎','萃如嗟如,无攸利','大吉,无咎','萃有位,无咎','赍咨涕洟,无咎']},
'2,7':{name:'泽山咸',judgment:'咸,感也。柔上而刚下,二气感应以相与',image:'山上有泽,咸。君子以虚受人',lines:['咸其拇','咸其腓,凶','咸其股,执其随','贞吉,悔亡','咸其脢,无悔','咸其辅颊舌']},
'6,7':{name:'水山蹇',judgment:'蹇,难也,险在前也。见险而能止',image:'山上有水,蹇。君子以反身修德',lines:['往蹇,来誉','王臣蹇蹇,匪躬之故','往蹇,来反','往蹇,来连','大蹇,朋来','往蹇,来硕']},
'8,7':{name:'地山谦',judgment:'谦亨。天道下济而光明,地道卑而上行',image:'地中有山,谦。君子以裒多益寡称物平施',lines:['谦谦君子,用涉大川','鸣谦,贞吉','劳谦君子,有终吉','无不利,撝谦','不富以其邻,利用侵伐','鸣谦,利用行师']},
'4,7':{name:'雷山小过',judgment:'小过,小者过而亨也。过以利贞',image:'山上有雷,小过。君子以行过乎恭',lines:['飞鸟以凶','过其祖,遇其妣','弗过防之,从或戕之','无咎,弗过遇之','密云不雨,自我西郊','弗遇过之,飞鸟离之']},
'4,2':{name:'雷泽归妹',judgment:'归妹,天地之大义也。天地不交而万物不兴',image:'泽上有雷,归妹。君子以永终知敝',lines:['归妹以娣,跛能履','眇能视,利幽人之贞','归妹以须,反归以娣','归妹愆期,迟归有时','帝乙归妹,其君之袂','女承筐无实,士刲羊无血']},
};
// Generate all 64 hexagrams
function buildHexagramMap() {
const map: Record<string, HexagramInfo> = {};
for (let upper = 1; upper <= 8; upper++) {
for (let lower = 1; lower <= 8; lower++) {
const key = `${upper},${lower}`;
const hName = H[key];
if (hName) {
map[key] = {
number: (upper - 1) * 8 + lower,
name: hName.name,
upperTrigram: TRIGRAMS[upper],
lowerTrigram: TRIGRAMS[lower],
changingLine: 0,
interpretation: hName.judgment,
judgment: hName.judgment,
image: hName.image,
lines: hName.lines,
};
}
}
}
return map;
}
const HEXAGRAM_MAP = buildHexagramMap();
/** Calculate Plum Blossom I-Ching from date and time */
export function calculatePlumBlossom(
year: number,
month: number,
day: number,
hour: number = 12,
): PlumBlossomResult {
// Use full numbers for more entropy
const yearNum = year;
const monthNum = month;
const dayNum = day;
const hourIndex = Math.floor(((hour + 1) % 24) / 2); // 0-11 地支时辰
// Standard Plum Blossom formula:
// Upper trigram: (year + month + day) % 8 → 0-7 → +1 → 1-8
const upperIdx = ((yearNum + monthNum + dayNum) % 8) + 1;
// Lower trigram: (month + day + hourIndex + 1) % 8 + 1
const lowerIdx = ((monthNum + dayNum + hourIndex + 1) % 8) + 1;
// Changing line: (year + month + day + hourIndex + 1) % 6 + 1
const changingLine = ((yearNum + monthNum + dayNum + hourIndex + 1) % 6) + 1;
const upperTrigram = TRIGRAMS[upperIdx];
const lowerTrigram = TRIGRAMS[lowerIdx];
// Original hexagram
const originalKey = `${upperIdx},${lowerIdx}`;
const originalHexagram = HEXAGRAM_MAP[originalKey] || createFallbackHexagram(upperIdx, lowerIdx, changingLine);
// Transformed hexagram (after changing line)
let transUpperIdx = upperIdx;
let transLowerIdx = lowerIdx;
// Changing line 1-3 affects lower trigram, 4-6 affects upper
if (changingLine >= 4) {
transUpperIdx = flipTrigramLine(upperIdx, changingLine - 3);
} else {
transLowerIdx = flipTrigramLine(lowerIdx, changingLine);
}
const transKey = `${transUpperIdx},${transLowerIdx}`;
const transformedHexagram = HEXAGRAM_MAP[transKey] || createFallbackHexagram(transUpperIdx, transLowerIdx, 0);
// Mutual hexagram (互卦): 2-4 lines → lower, 3-5 lines → upper
// Simplified: use middle two trigrams
const mutualUpperIdx = lowerIdx; // simplified
const mutualLowerIdx = upperIdx; // simplified
const mutualKey = `${mutualUpperIdx},${mutualLowerIdx}`;
const mutualHexagram = HEXAGRAM_MAP[mutualKey] || null;
// Constitution (体卦) and Function (用卦)
// 体卦 = lower trigram, 用卦 = upper trigram
const constitution = lowerTrigram.element;
const function_ = upperTrigram.element;
const relationship = getElementRelationship(constitution, function_);
return {
originalHexagram: { ...originalHexagram, changingLine },
transformedHexagram,
mutualHexagram,
upperTrigram,
lowerTrigram,
changingLine,
constitution,
function: function_,
relationship,
};
}
function flipTrigramLine(trigramIdx: number, line: number): number {
// Flip a single line of the trigram
// Trigrams encoded as bits: 乾111=7, 兑110=6, 离101=5, 震100=4, 巽011=3, 坎010=2, 艮001=1, 坤000=0
const encoding = [0, 7, 6, 5, 4, 3, 2, 1, 0]; // index → bit pattern
let bits = encoding[trigramIdx] || 0;
bits ^= (1 << (line - 1)); // flip the line
// Map back
const decoding = [8, 7, 6, 2, 5, 3, 4, 1]; // bit pattern → index
return decoding[bits] || trigramIdx;
}
function getElementRelationship(body: string, func: string): string {
const cycle: Record<string, string> = { '木': '火', '火': '土', '土': '金', '金': '水', '水': '木' };
const reverse: Record<string, string> = { '木': '水', '水': '金', '金': '土', '土': '火', '火': '木' };
if (body === func) return '比和(体用相同,诸事顺利)';
if (cycle[body] === func) return '体生用(泄气,宜守不宜攻)';
if (reverse[body] === func) return '用生体(得力,有贵人相助)';
if (cycle[func] === body) return '用克体(受制,诸事不顺)';
if (reverse[func] === body) return '体克用(主动,需付出努力)';
return '体用相生';
}
function createFallbackHexagram(upper: number, lower: number, changingLine: number): HexagramInfo {
const ut = TRIGRAMS[upper];
const lt = TRIGRAMS[lower];
return {
number: (upper - 1) * 8 + lower,
name: `${ut.name}${lt.name}`,
upperTrigram: ut,
lowerTrigram: lt,
changingLine,
interpretation: '此卦象需结合具体事理参详',
judgment: '',
image: '',
lines: ['','','','','',''],
};
}
@@ -1,116 +0,0 @@
import {
HeavenStem,
EarthBranch,
} from 'tyme4ts';
/** Relationship classification for branch interactions */
export interface BranchRelationship {
combine: boolean; // 六合
threeCombine: boolean; // 三合
opposite: boolean; // 六冲
harm: boolean; // 六害
punish: boolean; // 相刑
formation: string | null; // 三合局名称
}
/** Three-combine formations (三合局) */
const THREE_COMBINES: Record<string, { branches: string[]; name: string; element: string }> = {
'水局': { branches: ['申', '子', '辰'], name: '水局', element: '水' },
'木局': { branches: ['亥', '卯', '未'], name: '木局', element: '木' },
'火局': { branches: ['寅', '午', '戌'], name: '火局', element: '火' },
'金局': { branches: ['巳', '酉', '丑'], name: '金局', element: '金' },
};
/** Check branch relationships between two earth branches */
export function getBranchRelationship(branchA: string, branchB: string): BranchRelationship {
const a = EarthBranch.fromName(branchA);
const b = EarthBranch.fromName(branchB);
// Six combine (六合): each branch's combine partner
const combinePartner = a.getCombine();
const hasCombine = combinePartner ? combinePartner.getName() === b.getName() : false;
// Opposite (六冲): each branch's opposite
const oppositePartner = a.getOpposite();
const hasOpposite = oppositePartner ? oppositePartner.getName() === b.getName() : false;
// Harm (六害): each branch's harm partner
let hasHarm = false;
try {
const harmPartner = a.getHarm();
hasHarm = harmPartner ? harmPartner.getName() === b.getName() : false;
} catch { /* harm may not be available */ }
// Three combine (三合): check if both branches are in the same formation
let hasThreeCombine = false;
let formation: string | null = null;
for (const [name, info] of Object.entries(THREE_COMBINES)) {
if (info.branches.includes(branchA) && info.branches.includes(branchB)) {
hasThreeCombine = true;
formation = name;
break;
}
}
// Punish (相刑)
const hasPunish = checkPunish(branchA, branchB);
return {
combine: hasCombine,
threeCombine: hasThreeCombine,
opposite: hasOpposite,
harm: hasHarm,
punish: hasPunish,
formation,
};
}
/** Check for punishment relationship between two branches */
function checkPunish(a: string, b: string): boolean {
// Self punishment (自刑)
const selfPunish = ['辰', '午', '酉', '亥'];
if (a === b && selfPunish.includes(a)) return true;
// Classic punishment pairs
const punishPairs: [string, string][] = [
['寅', '巳'], ['巳', '申'], ['申', '寅'], // 无恩之刑
['丑', '戌'], ['戌', '未'], ['未', '丑'], // 恃势之刑
['子', '卯'], ['卯', '子'], // 无礼之刑
];
return punishPairs.some(([x, y]) => x === a && y === b);
}
/** Get Ten Star relationship between two heavenly stems */
export function getTenStarRelationship(subjectStem: string, objectStem: string): string {
try {
const s = HeavenStem.fromName(subjectStem);
const o = HeavenStem.fromName(objectStem);
return s.getTenStar(o).getName();
} catch {
return '';
}
}
/** Check if two heavenly stems combine (天干合) */
export function checkStemCombine(stemA: string, stemB: string): boolean {
const combinePairs: Record<string, string> = {
'甲': '己', '己': '甲',
'乙': '庚', '庚': '乙',
'丙': '辛', '辛': '丙',
'丁': '壬', '壬': '丁',
'戊': '癸', '癸': '戊',
};
return combinePairs[stemA] === stemB;
}
/** Check if two heavenly stems oppose (天干冲) */
export function checkStemOpposite(stemA: string, stemB: string): boolean {
const oppositePairs: Record<string, string> = {
'甲': '庚', '庚': '甲',
'乙': '辛', '辛': '乙',
'丙': '壬', '壬': '丙',
'丁': '癸', '癸': '丁',
};
return oppositePairs[stemA] === stemB;
}
@@ -1,359 +0,0 @@
/**
* 八字神煞 (Shen Sha)
* 神煞是固定规则查表 + 四柱匹配的标记,规则来源《三命通会》《渊海子平》。
* 注意:部分神煞网上存在版本差异,本模块采用主流排盘工具通行版本。
*/
import type { EightCharInfo, PillarInfo } from '../types/bazi';
export interface ShenshaInfo {
name: string;
/** 吉/凶/中性 */
type: '吉' | '凶' | '中性';
/** 分类:贵人/文星/财禄/感情/变动/威权/灾煞/孤独/格局 */
category: string;
/** 命中查法说明,如 "日干己查四支" */
anchors: string[];
/** 命中位置,如 ["年支","时支"] */
foundIn: string[];
/** 吉凶含义简述 */
description: string;
}
interface ShenshaRule {
name: string;
type: ShenshaInfo['type'];
category: string;
description: string;
/** 按天干(年干/日干)查四支 */
byStem?: Record<string, string[]>;
/** 按地支(年支/日支)查四支 */
byBranch?: Record<string, string[]>;
/** 按月支查四干 */
byMonthStem?: Record<string, string[]>;
/** 日柱特殊格局 */
byDayPillar?: string[];
}
const PILLAR_KEYS = ['year', 'month', 'day', 'hour'] as const;
const RULES: ShenshaRule[] = [
{
name: '天乙贵人',
type: '吉',
category: '贵人',
description: '最吉之神煞,主逢凶化吉、贵人相助',
byStem: {
'甲': ['丑', '未'], '戊': ['丑', '未'],
'乙': ['子', '申'], '己': ['子', '申'],
'丙': ['亥', '酉'], '丁': ['亥', '酉'],
'壬': ['卯', '巳'], '癸': ['卯', '巳'],
'辛': ['寅', '午'],
},
},
{
name: '天厨贵人',
type: '吉',
category: '贵人',
description: '主口福与衣食之禄,衣食无忧',
byStem: {
'甲': ['巳'], '乙': ['午'], '丙': ['巳'], '丁': ['午'],
'戊': ['申'], '己': ['酉'], '庚': ['亥'], '辛': ['子'],
'壬': ['寅'], '癸': ['卯'],
},
},
{
name: '文昌贵人',
type: '吉',
category: '文星',
description: '主聪明好学、利科名学业',
byStem: {
'甲': ['巳'], '乙': ['午'], '丙': ['申'], '丁': ['酉'],
'戊': ['申'], '己': ['酉'], '庚': ['亥'], '辛': ['子'],
'壬': ['寅'], '癸': ['卯'],
},
},
{
name: '禄神',
type: '吉',
category: '财禄',
description: '日干之禄,主衣禄与财运根基',
byStem: {
'甲': ['寅'], '乙': ['卯'], '丙': ['巳'], '丁': ['午'],
'戊': ['巳'], '己': ['午'], '庚': ['申'], '辛': ['酉'],
'壬': ['亥'], '癸': ['子'],
},
},
{
name: '羊刃',
type: '凶',
category: '灾煞',
description: '刚烈冲动之星,主脾气刚猛,喜用则有权柄',
byStem: {
'甲': ['卯'], '乙': ['寅'], '丙': ['午'], '丁': ['巳'],
'戊': ['午'], '己': ['巳'], '庚': ['酉'], '辛': ['申'],
'壬': ['子'], '癸': ['亥'],
},
},
{
name: '金舆',
type: '吉',
category: '财禄',
description: '禄前二位,主婚恋顺遂、富贵安逸',
byStem: {
'甲': ['辰'], '乙': ['巳'], '丙': ['未'], '丁': ['申'],
'戊': ['未'], '己': ['申'], '庚': ['戌'], '辛': ['亥'],
'壬': ['丑'], '癸': ['寅'],
},
},
{
name: '天德贵人',
type: '吉',
category: '贵人',
description: '主心地仁慈、逢凶化吉,利化解灾厄',
byMonthStem: {
'寅': ['丁'], '卯': ['申'], '辰': ['壬'], '巳': ['辛'],
'午': ['亥'], '未': ['甲'], '申': ['癸'], '酉': ['寅'],
'戌': ['丙'], '亥': ['乙'], '子': ['巳'], '丑': ['庚'],
},
},
{
name: '月德贵人',
type: '吉',
category: '贵人',
description: '主福荫深厚、遇难呈祥',
byMonthStem: {
'寅': ['丙'], '午': ['丙'], '戌': ['丙'],
'申': ['壬'], '子': ['壬'], '辰': ['壬'],
'亥': ['甲'], '卯': ['甲'], '未': ['甲'],
'巳': ['庚'], '酉': ['庚'], '丑': ['庚'],
},
},
{
name: '桃花(咸池)',
type: '中性',
category: '感情',
description: '主异性缘、魅力与风流,利艺术才华',
byBranch: {
'申': ['酉'], '子': ['酉'], '辰': ['酉'],
'寅': ['卯'], '午': ['卯'], '戌': ['卯'],
'巳': ['午'], '酉': ['午'], '丑': ['午'],
'亥': ['子'], '卯': ['子'], '未': ['子'],
},
},
{
name: '驿马',
type: '中性',
category: '变动',
description: '主奔波变动、外出发展,动中得财',
byBranch: {
'申': ['寅'], '子': ['寅'], '辰': ['寅'],
'寅': ['申'], '午': ['申'], '戌': ['申'],
'巳': ['亥'], '酉': ['亥'], '丑': ['亥'],
'亥': ['巳'], '卯': ['巳'], '未': ['巳'],
},
},
{
name: '华盖',
type: '中性',
category: '孤独',
description: '主艺术天赋、悟性高,也主清高孤傲',
byBranch: {
'申': ['辰'], '子': ['辰'], '辰': ['辰'],
'寅': ['戌'], '午': ['戌'], '戌': ['戌'],
'巳': ['丑'], '酉': ['丑'], '丑': ['丑'],
'亥': ['未'], '卯': ['未'], '未': ['未'],
},
},
{
name: '劫煞',
type: '凶',
category: '灾煞',
description: '主突发变故、是非破财,宜谨慎',
byBranch: {
'申': ['巳'], '子': ['巳'], '辰': ['巳'],
'寅': ['亥'], '午': ['亥'], '戌': ['亥'],
'巳': ['寅'], '酉': ['寅'], '丑': ['寅'],
'亥': ['申'], '卯': ['申'], '未': ['申'],
},
},
{
name: '亡神',
type: '凶',
category: '灾煞',
description: '主心机深、谋略强,亦主口舌是非',
byBranch: {
'申': ['亥'], '子': ['亥'], '辰': ['亥'],
'寅': ['巳'], '午': ['巳'], '戌': ['巳'],
'巳': ['申'], '酉': ['申'], '丑': ['申'],
'亥': ['寅'], '卯': ['寅'], '未': ['寅'],
},
},
{
name: '将星',
type: '吉',
category: '威权',
description: '主领导才能与威严,掌权柄之星',
byBranch: {
'申': ['子'], '子': ['子'], '辰': ['子'],
'寅': ['午'], '午': ['午'], '戌': ['午'],
'巳': ['酉'], '酉': ['酉'], '丑': ['酉'],
'亥': ['卯'], '卯': ['卯'], '未': ['卯'],
},
},
{
name: '红鸾',
type: '吉',
category: '感情',
description: '主婚恋喜事、姻缘早成',
byBranch: {
'子': ['卯'], '丑': ['寅'], '寅': ['丑'], '卯': ['子'],
'辰': ['亥'], '巳': ['戌'], '午': ['酉'], '未': ['申'],
'申': ['未'], '酉': ['午'], '戌': ['巳'], '亥': ['辰'],
},
},
{
name: '天喜',
type: '吉',
category: '感情',
description: '红鸾对宫,主喜事临门、人缘佳',
byBranch: {
'子': ['酉'], '丑': ['申'], '寅': ['未'], '卯': ['午'],
'辰': ['巳'], '巳': ['辰'], '午': ['卯'], '未': ['寅'],
'申': ['丑'], '酉': ['子'], '戌': ['亥'], '亥': ['戌'],
},
},
{
name: '孤辰',
type: '凶',
category: '孤独',
description: '主孤独离群、六亲缘薄',
byBranch: {
'亥': ['寅'], '子': ['寅'], '丑': ['寅'],
'寅': ['巳'], '卯': ['巳'], '辰': ['巳'],
'巳': ['申'], '午': ['申'], '未': ['申'],
'申': ['亥'], '酉': ['亥'], '戌': ['亥'],
},
},
{
name: '寡宿',
type: '凶',
category: '孤独',
description: '主孤寡之象,婚恋宜晚',
byBranch: {
'亥': ['戌'], '子': ['戌'], '丑': ['戌'],
'寅': ['丑'], '卯': ['丑'], '辰': ['丑'],
'巳': ['辰'], '午': ['辰'], '未': ['辰'],
'申': ['未'], '酉': ['未'], '戌': ['未'],
},
},
{
name: '天罗',
type: '凶',
category: '灾煞',
description: '戌亥为天罗,主困顿束缚,男命尤忌',
byBranch: { '子': ['戌', '亥'], '丑': ['戌', '亥'], '寅': ['戌', '亥'], '卯': ['戌', '亥'], '辰': ['戌', '亥'], '巳': ['戌', '亥'], '午': ['戌', '亥'], '未': ['戌', '亥'], '申': ['戌', '亥'], '酉': ['戌', '亥'], '戌': ['戌', '亥'], '亥': ['戌', '亥'] },
},
{
name: '地网',
type: '凶',
category: '灾煞',
description: '辰巳为地网,主束缚波折,女命尤忌',
byBranch: { '子': ['辰', '巳'], '丑': ['辰', '巳'], '寅': ['辰', '巳'], '卯': ['辰', '巳'], '辰': ['辰', '巳'], '巳': ['辰', '巳'], '午': ['辰', '巳'], '未': ['辰', '巳'], '申': ['辰', '巳'], '酉': ['辰', '巳'], '戌': ['辰', '巳'], '亥': ['辰', '巳'] },
},
{
name: '魁罡',
type: '中性',
category: '格局',
description: '日柱魁罡,主刚毅果断、聪明果敢,忌刑冲',
byDayPillar: ['庚辰', '庚戌', '壬辰', '戊戌'],
},
{
name: '阴差阳错',
type: '凶',
category: '格局',
description: '日柱阴差阳错,主婚姻不顺、易生波折',
byDayPillar: ['丙子', '丁丑', '戊寅', '辛卯', '壬辰', '癸巳', '丙午', '丁未', '戊申', '辛酉', '壬戌', '癸亥'],
},
];
const PILLAR_LABELS: Record<string, string> = {
yearStem: '年干', monthStem: '月干', dayStem: '日干', hourStem: '时干',
yearBranch: '年支', monthBranch: '月支', dayBranch: '日支', hourBranch: '时支',
};
/** Analyze Shen Sha presence in a Bazi chart */
export function analyzeShensha(bazi: EightCharInfo): ShenshaInfo[] {
const pillars: Record<string, PillarInfo> = {
year: bazi.yearPillar, month: bazi.monthPillar, day: bazi.dayPillar, hour: bazi.hourPillar,
};
const stems: Record<string, string> = {};
const branches: Record<string, string> = {};
for (const k of PILLAR_KEYS) {
stems[`${k}Stem`] = pillars[k].heavenStem;
branches[`${k}Branch`] = pillars[k].earthBranch;
}
const dayGanzhi = pillars.day.ganzhi;
const result: ShenshaInfo[] = [];
for (const rule of RULES) {
const anchors: string[] = [];
const foundIn = new Set<string>();
if (rule.byStem) {
// 年干、日干查四支
for (const anchorKey of ['yearStem', 'dayStem'] as const) {
const targets = rule.byStem[stems[anchorKey]];
if (!targets) continue;
const hits = PILLAR_KEYS.filter(k => targets.includes(branches[`${k}Branch`]));
if (hits.length > 0) {
anchors.push(PILLAR_LABELS[anchorKey]);
hits.forEach(k => foundIn.add(PILLAR_LABELS[`${k}Branch`]));
}
}
}
if (rule.byBranch) {
// 年支、日支查四支
for (const anchorKey of ['yearBranch', 'dayBranch'] as const) {
const targets = rule.byBranch[branches[anchorKey]];
if (!targets) continue;
const hits = PILLAR_KEYS.filter(k => targets.includes(branches[`${k}Branch`]));
if (hits.length > 0) {
anchors.push(PILLAR_LABELS[anchorKey]);
hits.forEach(k => foundIn.add(PILLAR_LABELS[`${k}Branch`]));
}
}
}
if (rule.byMonthStem) {
// 月支查四干
const targets = rule.byMonthStem[branches.monthBranch];
if (targets) {
const hits = PILLAR_KEYS.filter(k => targets.includes(stems[`${k}Stem`]));
if (hits.length > 0) {
anchors.push('月支');
hits.forEach(k => foundIn.add(PILLAR_LABELS[`${k}Stem`]));
}
}
}
if (rule.byDayPillar && rule.byDayPillar.includes(dayGanzhi)) {
anchors.push('日柱');
foundIn.add('日柱');
}
if (foundIn.size > 0) {
result.push({
name: rule.name,
type: rule.type,
category: rule.category,
anchors,
foundIn: [...foundIn],
description: rule.description,
});
}
}
return result;
}
-84
View File
@@ -1,84 +0,0 @@
// Types
export type {
DayInfo,
AlmanacInfo,
HourAlmanac,
PillarInfo,
HideStemInfo,
EightCharInfo,
DecadeFortuneInfo,
FortuneInfo,
ChildLimitInfo,
BaziFullResult,
PillarRelationship,
DailyFortuneResult,
} from './types';
// Transformers
export {
solarDayToDayInfo,
getMonthCalendar,
getDayInfo,
getTodayInfo,
} from './transformers/day';
export {
solarDayToAlmanacInfo,
getAlmanacInfo,
} from './transformers/almanac';
export {
birthInfoToBazi,
} from './transformers/bazi';
export type { BirthParams } from './transformers/bazi';
export {
getYearMonths,
} from './transformers/yearMonths';
export type { YearMonthInfo } from './transformers/yearMonths';
// Calculators
export {
getBranchRelationship,
getTenStarRelationship,
checkStemCombine,
checkStemOpposite,
} from './calculators/relationship';
export type { BranchRelationship } from './calculators/relationship';
export {
calculateDailyFortune,
} from './calculators/dailyMatch';
export {
analyzeElementBalance,
} from './calculators/elementStrength';
export type { ElementProfile } from './calculators/elementStrength';
export {
calculatePlumBlossom,
} from './calculators/plumBlossom';
export type {
TrigramInfo,
HexagramInfo,
PlumBlossomResult,
} from './calculators/plumBlossom';
export {
calculateBoneWeight,
} from './calculators/boneWeight';
export type { BoneWeightResult } from './calculators/boneWeight';
export {
getBuddhistFestival,
} from './calculators/buddhistDates';
export {
analyzeShensha,
} from './calculators/shensha';
export type { ShenshaInfo } from './calculators/shensha';
export {
analyzeFortuneGanzhi,
} from './calculators/fortuneLuck';
export type { FortuneLuck } from './calculators/fortuneLuck';
@@ -1,186 +0,0 @@
import {
SolarDay,
type LunarHour,
} from 'tyme4ts';
import type { AlmanacInfo, HourAlmanac } from '../types/almanac';
/** Transform a SolarDay into a full AlmanacInfo object */
export function solarDayToAlmanacInfo(solarDay: SolarDay): AlmanacInfo {
const lunarDay = solarDay.getLunarDay();
const sixtyCycle = lunarDay.getSixtyCycle();
const stem = sixtyCycle.getHeavenStem();
const branch = sixtyCycle.getEarthBranch();
// Duty officer
const duty = lunarDay.getDuty();
// Twelve star
const twelveStar = lunarDay.getTwelveStar();
const ecliptic = twelveStar.getEcliptic();
// Twenty-eight star
const twentyEightStar = lunarDay.getTwentyEightStar();
// Nine star
const nineStar = lunarDay.getNineStar();
// Six star
const sixStar = lunarDay.getSixStar ? lunarDay.getSixStar().getName() : '';
// Minor Ren
const minorRen = lunarDay.getMinorRen ? lunarDay.getMinorRen() : null;
// Fetus
const fetusDay = lunarDay.getFetusDay();
// Recommendations and avoidances
let recommends: string[] = [];
let avoids: string[] = [];
try {
recommends = lunarDay.getRecommends().map(r => r.getName());
avoids = lunarDay.getAvoids().map(a => a.getName());
} catch { /* may throw for some dates */ }
// Gods
const goodGods: string[] = [];
const badGods: string[] = [];
try {
const gods = lunarDay.getGods();
for (const god of gods) {
const luck = god.getLuck();
if (luck) {
if (luck.getName() === '吉') {
goodGods.push(god.getName());
} else {
badGods.push(god.getName());
}
}
}
} catch { /* may throw */ }
// Peng Zu taboos
const pengZu = sixtyCycle.getPengZu();
// Branch relationships
const opposite = branch.getOpposite();
const harm = branch.getHarm();
const combine = branch.getCombine();
// Evil direction
const ominous = branch.getOminous ? branch.getOminous() : null;
// Na Yin
const nayin = sixtyCycle.getSound().getName();
// Moon phase
let phase = '';
try {
const p = lunarDay.getPhase();
if (p) phase = p.getName();
} catch { /* no phase info */ }
// Hourly almanac
const hourDetails = buildHourlyAlmanac(lunarDay.getHours(), recommends, avoids);
// Determine duty luck
const dutyName = duty.getName();
const luckyDuties = ['除', '执', '危', '成', '开'];
const unluckyDuties = ['建', '满', '平', '破', '收', '闭'];
let dutyLuck: 'good' | 'bad' | 'neutral' = 'neutral';
if (luckyDuties.includes(dutyName)) dutyLuck = 'good';
else if (unluckyDuties.includes(dutyName)) dutyLuck = 'bad';
// Note: duty luck also depends on day branch; simplified here
return {
duty: dutyName,
dutyLuck,
twelveStar: {
name: twelveStar.getName(),
ecliptic: ecliptic ? ecliptic.getName() : '',
luck: ecliptic && ecliptic.getName() === '黄道' ? 'good' : 'bad',
},
twentyEightStar: {
name: twentyEightStar.getName(),
luck: twentyEightStar.getLuck()?.getName() === '吉' ? 'good' : 'bad',
animal: twentyEightStar.getAnimal()?.getName() || '',
},
nineStar: {
name: nineStar.getName(),
color: nineStar.getColor ? nineStar.getColor() : '',
element: nineStar.getElement ? nineStar.getElement().getName() : '',
},
sixStar,
minorRen: minorRen ? {
name: minorRen.getName(),
luck: minorRen.getLuck()?.getName() === '吉' ? 'good' : 'bad',
element: minorRen.getElement()?.getName() || '',
} : { name: '', luck: 'bad' as const, element: '' },
phase,
fetus: {
direction: fetusDay.getDirection()?.getName() || '',
side: fetusDay.getSide() !== undefined ? (fetusDay.getSide() as unknown as number === 0 ? '房内' : '房外') : '',
position: fetusDay.getName(),
},
recommends,
avoids,
goodGods,
badGods,
dayStem: stem.getName(),
dayBranch: branch.getName(),
dayGanzhi: sixtyCycle.getName(),
pengZu: pengZu.getName(),
pengZuStem: pengZu.getPengZuHeavenStem()?.getName() || '',
pengZuBranch: pengZu.getPengZuEarthBranch()?.getName() || '',
clash: `${opposite.getZodiac().getName()}(${opposite.getName()})`,
harm: harm ? `${harm.getZodiac().getName()}(${harm.getName()})` : '',
combine: combine ? `${combine.getZodiac().getName()}(${combine.getName()})` : '',
evilDirection: ominous ? ominous.getName() : '',
nayin,
hourDetails,
};
}
function buildHourlyAlmanac(hours: LunarHour[], _dayRecommends: string[], _dayAvoids: string[]): HourAlmanac[] {
return hours.map(hour => {
const hourSixtyCycle = hour.getSixtyCycle();
const twelveStar = hour.getTwelveStar ? hour.getTwelveStar() : null;
const nineStar = hour.getNineStar ? hour.getNineStar() : null;
let hourRecommends: string[] = [];
let hourAvoids: string[] = [];
try {
hourRecommends = hour.getRecommends().map(r => r.getName());
hourAvoids = hour.getAvoids().map(a => a.getName());
} catch { /* may throw */ }
const branchName = hourSixtyCycle.getEarthBranch().getName();
const hourNames: Record<string, string> = {
'子': '子时', '丑': '丑时', '寅': '寅时', '卯': '卯时',
'辰': '辰时', '巳': '巳时', '午': '午时', '未': '未时',
'申': '申时', '酉': '酉时', '戌': '戌时', '亥': '亥时',
};
const hourRanges: Record<string, string> = {
'子': '23:00-01:00', '丑': '01:00-03:00', '寅': '03:00-05:00',
'卯': '05:00-07:00', '辰': '07:00-09:00', '巳': '09:00-11:00',
'午': '11:00-13:00', '未': '13:00-15:00', '申': '15:00-17:00',
'酉': '17:00-19:00', '戌': '19:00-21:00', '亥': '21:00-23:00',
};
return {
branch: branchName,
name: hourNames[branchName] || branchName,
range: hourRanges[branchName] || '',
ganzhi: hourSixtyCycle.getName(),
recommends: hourRecommends,
avoids: hourAvoids,
twelveStar: twelveStar?.getName() || '',
nineStar: nineStar?.getName() || '',
};
});
}
/** Get AlmanacInfo for a specific date */
export function getAlmanacInfo(year: number, month: number, day: number): AlmanacInfo {
const solarDay = SolarDay.fromYmd(year, month, day);
return solarDayToAlmanacInfo(solarDay);
}
-212
View File
@@ -1,212 +0,0 @@
import {
SolarTime,
Gender,
ChildLimit,
HideHeavenStemType,
YinYang,
type SixtyCycle,
type HeavenStem,
} from 'tyme4ts';
import type {
PillarInfo,
HideStemInfo,
DecadeFortuneInfo,
FortuneInfo,
BaziFullResult,
} from '../types/bazi';
export interface BirthParams {
year: number;
month: number;
day: number;
hour: number;
minute: number;
gender: 'male' | 'female';
/** 八字流派:lateZiNextDay=晚子时算次日(23点换日,默认);earlyZiSameDay=晚子时算当日(0点换日) */
ziSect?: 'lateZiNextDay' | 'earlyZiSameDay';
}
/** Transform birth parameters into full Bazi result */
export function birthInfoToBazi(params: BirthParams): BaziFullResult {
const { year, month, day, hour, minute, gender, ziSect = 'lateZiNextDay' } = params;
const solarTime = SolarTime.fromYmdHms(year, month, day, hour, minute, 0);
// 早子时流派:23:00 后出生按当日早子时排四柱(日柱不换日),起运仍按真实出生时间
const ziHour =
ziSect === 'earlyZiSameDay' && hour >= 23
? SolarTime.fromYmdHms(year, month, day, 0, minute, 0)
: solarTime;
const lunarHour = ziHour.getLunarHour();
const eightChar = lunarHour.getEightChar();
const yearPillar = eightChar.getYear();
const monthPillar = eightChar.getMonth();
const dayPillar = eightChar.getDay();
const hourPillar = eightChar.getHour();
// Day master
const dayStem = dayPillar.getHeavenStem();
const dayMasterStem = dayStem.getName();
const dayMasterElement = dayStem.getElement().getName();
// Extract pillars with Ten Star relative to day master
const yearPillarInfo = extractPillarInfo(yearPillar, dayStem);
const monthPillarInfo = extractPillarInfo(monthPillar, dayStem);
const dayPillarInfo = extractPillarInfo(dayPillar, dayStem);
const hourPillarInfo = extractPillarInfo(hourPillar, dayStem);
// Fetal origin, fetal breath, own sign, body sign
const fetalOrigin = eightChar.getFetalOrigin();
const fetalBreath = eightChar.getFetalBreath();
const ownSign = eightChar.getOwnSign();
const bodySign = eightChar.getBodySign();
// Empty branches
const emptyTen = dayPillar.getTen();
const emptyBranches = emptyTen ? dayPillar.getExtraEarthBranches().map(b => b.getName()) : [];
// Child limit
const genderEnum = gender === 'male' ? Gender.MAN : Gender.WOMAN;
const childLimit = ChildLimit.fromSolarTime(solarTime, genderEnum);
const startDecade = childLimit.getStartDecadeFortune();
const startFortune = childLimit.getStartFortune();
// Decade fortunes (大运) — 10 decades
const decadeFortunes: DecadeFortuneInfo[] = [];
let currentDecade = startDecade;
for (let i = 0; i < 10 && currentDecade; i++) {
const sc = currentDecade.getSixtyCycle();
decadeFortunes.push({
index: i,
ganzhi: sc.getName(),
startAge: currentDecade.getStartAge(),
endAge: currentDecade.getEndAge(),
startYear: currentDecade.getStartLunarYear().getYear(),
endYear: currentDecade.getEndLunarYear().getYear(),
heavenStem: sc.getHeavenStem().getName(),
earthBranch: sc.getEarthBranch().getName(),
nayin: sc.getSound().getName(),
});
currentDecade = currentDecade.next(1) as typeof currentDecade;
}
// Annual fortunes (流年) — 10 years
const annualFortunes: FortuneInfo[] = [];
let currentFortune = startFortune;
for (let i = 0; i < 10 && currentFortune; i++) {
const sc = currentFortune.getSixtyCycle();
annualFortunes.push({
age: currentFortune.getAge(),
year: currentFortune.getLunarYear().getYear(),
ganzhi: sc.getName(),
nayin: sc.getSound().getName(),
});
currentFortune = currentFortune.next(1) as typeof currentFortune;
}
return {
eightChar: {
birthDate: `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`,
birthTime: `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`,
gender,
yearPillar: yearPillarInfo,
monthPillar: monthPillarInfo,
dayPillar: dayPillarInfo,
hourPillar: hourPillarInfo,
dayMaster: `${dayMasterStem}${dayMasterElement}`,
dayMasterStem,
dayMasterElement,
fetalOrigin: fetalOrigin.getName(),
fetalBreath: fetalBreath.getName(),
ownSign: ownSign.getName(),
bodySign: bodySign.getName(),
emptyBranches,
emptyTen: emptyTen ? emptyTen.getName() : '',
},
childLimit: {
startTime: childLimit.getStartTime().toString(),
endTime: childLimit.getEndTime().toString(),
yearCount: childLimit.getYearCount(),
monthCount: childLimit.getMonthCount(),
dayCount: childLimit.getDayCount(),
hourCount: childLimit.getHourCount(),
minuteCount: childLimit.getMinuteCount(),
forward: childLimit.isForward(),
startAge: childLimit.getStartAge(),
endAge: childLimit.getEndAge(),
},
decadeFortunes,
annualFortunes,
};
}
/** Extract pillar info from a SixtyCycle, with Ten Star relative to day master */
function extractPillarInfo(sixtyCycle: SixtyCycle, dayMasterStem: HeavenStem): PillarInfo {
const stem = sixtyCycle.getHeavenStem();
const branch = sixtyCycle.getEarthBranch();
const sound = sixtyCycle.getSound();
// Hidden stems
const hideStems: HideStemInfo[] = [];
try {
const allHideStems = branch.getHideHeavenStems();
if (allHideStems) {
for (const hs of allHideStems) {
let typeName = '';
const type = hs.getType();
if (type === HideHeavenStemType.MAIN) typeName = '本气';
else if (type === HideHeavenStemType.MIDDLE) typeName = '中气';
else if (type === HideHeavenStemType.RESIDUAL) typeName = '余气';
let tenStarName: string | null = null;
try {
tenStarName = hs.getHeavenStem().getTenStar(dayMasterStem).getName();
} catch { /* ten star may not be available */ }
hideStems.push({
stem: hs.getHeavenStem().getName(),
type: typeName,
tenStar: tenStarName,
});
}
}
} catch { /* hide stems may not be available */ }
// Terrain (十二长生)
let terrainName = '';
let terrainFortune: 'good' | 'bad' | 'neutral' = 'neutral';
try {
const terrain = stem.getTerrain(branch);
terrainName = terrain.getName();
const goodTerrain = ['长生', '冠带', '临官', '帝旺', '胎', '养'];
const badTerrain = ['死', '墓', '绝'];
if (goodTerrain.includes(terrainName)) terrainFortune = 'good';
else if (badTerrain.includes(terrainName)) terrainFortune = 'bad';
} catch { /* terrain might fail */ }
// Ten Star
let tenStarName: string | null = null;
try {
tenStarName = stem.getTenStar(dayMasterStem).getName();
} catch { /* ten star may not be available */ }
const yinYang = stem.getYinYang();
const branchYinYang = branch.getYinYang();
return {
ganzhi: sixtyCycle.getName(),
heavenStem: stem.getName(),
earthBranch: branch.getName(),
elementStem: stem.getElement().getName(),
elementBranch: branch.getElement().getName(),
yinYangStem: yinYang === YinYang.YANG ? 'yang' : 'yin',
yinYangBranch: branchYinYang === YinYang.YANG ? 'yang' : 'yin',
hideStems,
nayin: sound.getName(),
terrain: {
name: terrainName,
fortune: terrainFortune,
},
tenStar: tenStarName,
};
}
-201
View File
@@ -1,201 +0,0 @@
import {
SolarDay,
SolarMonth,
} from 'tyme4ts';
import type { DayInfo } from '../types/calendar';
import { getBuddhistFestival } from '../calculators/buddhistDates';
const SEASON_BY_MONTH: Record<number, string> = {
3: '春季', 4: '春季', 5: '春季',
6: '夏季', 7: '夏季', 8: '夏季',
9: '秋季', 10: '秋季', 11: '秋季',
12: '冬季', 1: '冬季', 2: '冬季',
};
/** Transform a SolarDay into a plain DayInfo object */
export function solarDayToDayInfo(solarDay: SolarDay): DayInfo {
const lunarDay = solarDay.getLunarDay();
const lunarMonth = lunarDay.getLunarMonth();
const week = solarDay.getWeek();
const constellation = solarDay.getConstellation();
const term = solarDay.getTerm();
const termDay = solarDay.getTermDay();
const month = solarDay.getSolarMonth().getMonth();
const solarYear = solarDay.getSolarMonth().getSolarYear().getYear();
// Solar term
const isTermDay = termDay !== null;
const solarTerm = isTermDay ? term.getName() : null;
let solarTermTime: string | null = null;
if (isTermDay) {
try {
const jd = term.getJulianDay();
if (jd) {
const st = jd.getSolarTime();
solarTermTime = `${String(st.getHour()).padStart(2,'0')}:${String(st.getMinute()).padStart(2,'0')}`;
}
} catch { /* time not available */ }
}
// Season + term progress (every day belongs to a solar term)
const season = SEASON_BY_MONTH[month] || '';
let currentSolarTerm: string | null = null;
let termDayIndex: number | null = null;
let nextSolarTerm: string | null = null;
let daysToNextTerm: number | null = null;
try {
const currentTerm = solarDay.getTerm();
const nextTerm = currentTerm.next(1);
currentSolarTerm = currentTerm.getName();
termDayIndex = solarDay.subtract(currentTerm.getSolarDay()) + 1;
nextSolarTerm = nextTerm.getName();
daysToNextTerm = nextTerm.getSolarDay().subtract(solarDay);
} catch { /* term may fail */ }
// Julian day, Buddhist era, Islamic/Hijri date
let julianDay: number | null = null;
try { julianDay = solarDay.getJulianDay().getDay(); } catch { /* */ }
const buddhistYear = solarYear + 543;
let hijriDate: string | null = null;
try {
const hd = solarDay.getHijriDay();
const hm = hd.getHijriMonth();
hijriDate = `${hm.getHijriYear().getYear()}${String(hm.getIndexInYear()).padStart(2, '0')}${String(hd.getDay()).padStart(2, '0')}`;
} catch { /* */ }
const buddhistFestival = getBuddhistFestival(lunarMonth.getMonth(), lunarDay.getDay());
// Phenology
let phenology: string | null = null;
try {
const pd = solarDay.getPhenologyDay();
if (pd) phenology = pd.getPhenology().getName();
} catch { /* not available for all dates */ }
// Dog days
let dogDay: string | null = null;
try {
const dd = solarDay.getDogDay();
if (dd) dogDay = dd.getDog().getName();
} catch { /* not in dog days */ }
// Nine-day cold
let nineDay: string | null = null;
try {
const nd = solarDay.getNineDay();
if (nd) nineDay = nd.getNine().getName();
} catch { /* not in nine days */ }
// Moon phase
let moonPhase: string | null = null;
try {
const phase = solarDay.getPhase();
if (phase) moonPhase = phase.getName();
} catch { /* not available */ }
// Festivals
let lunarFestival: string | null = null;
try {
const lf = lunarDay.getFestival();
if (lf) lunarFestival = lf.getName();
} catch { /* no festival */ }
let solarFestival: string | null = null;
try {
const sf = solarDay.getFestival();
if (sf) solarFestival = sf.getName();
} catch { /* no festival */ }
let legalHoliday: { name: string; isWork: boolean } | null = null;
try {
const lh = solarDay.getLegalHoliday();
if (lh) legalHoliday = { name: lh.getName(), isWork: lh.isWork() };
} catch { /* not a legal holiday */ }
// Gan-Zhi
const daySixtyCycle = lunarDay.getSixtyCycle();
const yearSixtyCycle = lunarDay.getYearSixtyCycle();
const monthSixtyCycle = lunarDay.getMonthSixtyCycle();
// Today check
const now = new Date();
const isToday =
solarDay.getSolarMonth().getSolarYear().getYear() === now.getFullYear() &&
solarDay.getSolarMonth().getMonth() === now.getMonth() + 1 &&
solarDay.getDay() === now.getDate();
const weekDayIndex = week.getIndex();
const isWeekend = weekDayIndex === 0 || weekDayIndex === 6;
return {
solarDate: `${solarDay.getSolarMonth().getSolarYear().getYear()}-${String(solarDay.getSolarMonth().getMonth()).padStart(2, '0')}-${String(solarDay.getDay()).padStart(2, '0')}`,
solarDay: solarDay.getDay(),
solarMonth: solarDay.getSolarMonth().getMonth(),
solarYear: solarDay.getSolarMonth().getSolarYear().getYear(),
weekDay: week.getName(),
weekDayIndex,
constellation: constellation.getName(),
solarTerm,
solarTermTime,
isTermDay,
currentSolarTerm,
season,
termDayIndex,
nextSolarTerm,
daysToNextTerm,
julianDay,
buddhistYear,
hijriDate,
buddhistFestival,
phenology,
dogDay,
nineDay,
lunarYear: lunarMonth.getLunarYear().getYear(),
lunarMonth: lunarMonth.getMonth(),
lunarMonthName: lunarMonth.getName(),
lunarDay: lunarDay.getDay(),
lunarDayName: lunarDay.getName(),
isLeapMonth: lunarMonth.isLeap(),
lunarYearGanzhi: yearSixtyCycle.getName(),
lunarMonthGanzhi: monthSixtyCycle.getName(),
lunarDayGanzhi: daySixtyCycle.getName(),
zodiac: daySixtyCycle.getEarthBranch().getZodiac().getName(),
lunarFestival,
solarFestival,
legalHoliday,
moonPhase,
isToday,
isWeekend,
dayOfWeek: weekDayIndex,
};
}
/** Get calendar days for a month as a 2D array (weeks × days) */
export function getMonthCalendar(year: number, month: number, weekStart: 0 | 1 = 0): DayInfo[][] {
const solarMonth = SolarMonth.fromYm(year, month);
const weekCount = solarMonth.getWeekCount(weekStart);
const weeks = solarMonth.getWeeks(weekStart);
const result: DayInfo[][] = [];
for (let w = 0; w < weekCount; w++) {
const week = weeks[w];
const days = week.getDays();
const row: DayInfo[] = [];
for (const day of days) {
row.push(solarDayToDayInfo(day));
}
result.push(row);
}
return result;
}
/** Get DayInfo for a specific date */
export function getDayInfo(year: number, month: number, day: number): DayInfo {
const solarDay = SolarDay.fromYmd(year, month, day);
return solarDayToDayInfo(solarDay);
}
/** Get today's DayInfo */
export function getTodayInfo(): DayInfo {
const now = new Date();
return getDayInfo(now.getFullYear(), now.getMonth() + 1, now.getDate());
}
@@ -1,59 +0,0 @@
/**
* 流月计算:按节气月(立春起 12 节)划分某公历年的 12 个流月
*/
import { SolarTerm } from 'tyme4ts';
import { getDayInfo } from './day';
export interface YearMonthInfo {
/** 0-11,从寅月(正月/立春)起 */
index: number;
/** 正月..腊月 */
name: string;
/** 起始公历月 */
solarMonth: number;
/** 节日期 YYYY-MM-DD */
startDate: string;
/** 月末 YYYY-MM-DD(下一节前一天) */
endDate: string;
/** 月柱干支 */
ganzhi: string;
}
// SolarTerm 索引:冬至0 小寒1 大寒2 立春3 雨水4 惊蛰5 春分6 清明7 谷雨8 立夏9 小满10 芒种11 夏至12 小暑13 大暑14 立秋15 处暑16 白露17 秋分18 寒露19 霜降20 立冬21 小雪22 大雪23
const JIE_INDICES = [3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 1]; // 立春..小寒(次年)
const MONTH_NAME_BY_BRANCH: Record<string, string> = {
'寅': '正月', '卯': '二月', '辰': '三月', '巳': '四月', '午': '五月', '未': '六月',
'申': '七月', '酉': '八月', '戌': '九月', '亥': '十月', '子': '冬月', '丑': '腊月',
};
function pad(n: number): string {
return String(n).padStart(2, '0');
}
function toDateStr(day: { getYear(): number; getMonth(): number; getDay(): number }): string {
return `${day.getYear()}-${pad(day.getMonth())}-${pad(day.getDay())}`;
}
/** Get the 12 节气月(流月)of a solar year, starting from 立春 */
export function getYearMonths(year: number): YearMonthInfo[] {
const months: YearMonthInfo[] = [];
for (let k = 0; k < 12; k++) {
const termYear = k === 11 ? year + 1 : year;
const start = SolarTerm.fromIndex(termYear, JIE_INDICES[k]).getSolarDay();
const end = k === 11
? start
: SolarTerm.fromIndex(year, JIE_INDICES[k + 1]).getSolarDay().next(-1);
const di = getDayInfo(start.getYear(), start.getMonth(), start.getDay());
const branch = di.lunarMonthGanzhi[1];
months.push({
index: k,
name: MONTH_NAME_BY_BRANCH[branch] || di.lunarMonthName || `${k + 1}`,
solarMonth: start.getMonth(),
startDate: toDateStr(start),
endDate: toDateStr(end),
ganzhi: di.lunarMonthGanzhi,
});
}
return months;
}
-89
View File
@@ -1,89 +0,0 @@
/** Full almanac (黄历) information for a single day */
export interface AlmanacInfo {
// Duty officer (建除十二值神)
duty: string;
dutyLuck: 'good' | 'bad' | 'neutral';
// Twelve star (黄道黑道十二神)
twelveStar: {
name: string;
ecliptic: string; // 黄道 or 黑道
luck: 'good' | 'bad';
};
// Twenty-eight lunar mansion (二十八星宿)
twentyEightStar: {
name: string;
luck: 'good' | 'bad';
animal: string;
};
// Nine star (九星)
nineStar: {
name: string;
color: string;
element: string;
};
// Six star (六曜)
sixStar: string;
// Minor Ren (小六壬)
minorRen: {
name: string;
luck: 'good' | 'bad';
element: string;
};
// Moon phase
phase: string;
// Fetus god (胎神)
fetus: {
direction: string;
side: string; // 房内/房外
position: string; // Full position description
};
// Recommendations and avoidances (宜忌)
recommends: string[];
avoids: string[];
// Gods (神煞)
goodGods: string[];
badGods: string[];
// Day stem-branch info
dayStem: string; // 天干 e.g. "甲"
dayBranch: string; // 地支 e.g. "子"
dayGanzhi: string; // 干支 e.g. "甲子"
// Peng Zu taboo (彭祖百忌)
pengZu: string;
pengZuStem: string; // 天干禁忌
pengZuBranch: string; // 地支禁忌
// Chong/Sha/Harm/Combine (冲煞害合)
clash: string; // 冲 e.g. "马(午)"
harm: string; // 害 e.g. "羊(未)"
combine: string; // 合 e.g. "牛(丑)"
evilDirection: string;// 煞 e.g. "北"
// Na Yin sound (纳音)
nayin: string;
// Hourly almanac
hourDetails: HourAlmanac[];
}
/** Hourly almanac for each of the 12 two-hour periods (时辰) */
export interface HourAlmanac {
branch: string; // 地支 e.g. "子"
name: string; // 时辰名 e.g. "子时"
range: string; // Time range e.g. "23:00-01:00"
ganzhi: string; // Hour pillar e.g. "甲子"
recommends: string[];
avoids: string[];
twelveStar: string;
nineStar: string;
}
-93
View File
@@ -1,93 +0,0 @@
/** A single pillar (柱) in the Bazi — year, month, day, or hour */
export interface PillarInfo {
ganzhi: string; // "甲子"
heavenStem: string; // "甲"
earthBranch: string; // "子"
elementStem: string; // Stem's five element "木"
elementBranch: string; // Branch's five element "水"
yinYangStem: 'yin' | 'yang';
yinYangBranch: 'yin' | 'yang';
hideStems: HideStemInfo[];
nayin: string; // Na Yin sound "海中金"
terrain: {
name: string; // 十二长生 stage
fortune: 'good' | 'bad' | 'neutral';
};
tenStar: string | null; // Ten Star relative to day master
}
/** Hidden stem within an earth branch (藏干) */
export interface HideStemInfo {
stem: string; // "甲"
type: string; // "本气" | "中气" | "余气"
tenStar: string | null; // Ten Star relative to day master
}
/** Complete Bazi (八字) result for a birth date/time */
export interface EightCharInfo {
birthDate: string; // ISO date
birthTime: string; // HH:mm
gender: 'male' | 'female';
yearPillar: PillarInfo;
monthPillar: PillarInfo;
dayPillar: PillarInfo; // Day master pillar
hourPillar: PillarInfo;
// Derived
dayMaster: string; // "甲木" — day stem + element
dayMasterStem: string; // "甲"
dayMasterElement: string; // "木"
fetalOrigin: string; // 胎元
fetalBreath: string; // 胎息
ownSign: string; // 命宫
bodySign: string; // 身宫
emptyBranches: string[]; // 空亡 branches
emptyTen: string; // 旬
}
/** Decade fortune (大运) */
export interface DecadeFortuneInfo {
index: number;
ganzhi: string;
startAge: number;
endAge: number;
startYear: number;
endYear: number;
heavenStem: string;
earthBranch: string;
nayin: string;
}
/** Annual fortune (流年/小运) */
export interface FortuneInfo {
age: number;
year: number;
ganzhi: string;
nayin: string;
}
/** Child limit (起运) information */
export interface ChildLimitInfo {
startTime: string; // ISO datetime
endTime: string;
yearCount: number;
monthCount: number;
dayCount: number;
hourCount: number;
minuteCount: number;
forward: boolean; // 顺排/逆排
startAge: number;
endAge: number;
}
/** Full Bazi analysis result */
export interface BaziFullResult {
eightChar: EightCharInfo;
childLimit: ChildLimitInfo;
decadeFortunes: DecadeFortuneInfo[];
annualFortunes: FortuneInfo[];
/** True when the caller applied solar-time longitude correction to the birth time */
solarAdjusted?: boolean;
}
-76
View File
@@ -1,76 +0,0 @@
/** Core calendar day information — framework-agnostic plain object */
export interface DayInfo {
/** ISO date string YYYY-MM-DD */
solarDate: string;
solarDay: number;
solarMonth: number;
solarYear: number;
/** Chinese weekday name: 日,一,二,三,四,五,六 */
weekDay: string;
/** 0=Sunday ... 6=Saturday */
weekDayIndex: number;
/** Western zodiac constellation name */
constellation: string;
/** Solar term name if this day is a term day */
solarTerm: string | null;
/** Exact solar term time (HH:mm) */
solarTermTime: string | null;
/** Whether this day is the exact solar term transition day */
isTermDay: boolean;
/** The solar term this day belongs to (e.g. 大暑) */
currentSolarTerm: string | null;
/** Season name: 春季/夏季/秋季/冬季 */
season: string;
/** 1-based day index within the current solar term (节气第几天) */
termDayIndex: number | null;
/** Next solar term name */
nextSolarTerm: string | null;
/** Days until the next solar term */
daysToNextTerm: number | null;
/** Julian Day number (儒略日) */
julianDay: number | null;
/** Buddhist Era year (佛历年 = 公历年 + 543) */
buddhistYear: number | null;
/** Islamic/Hijri date as "1448年02月18日" */
hijriDate: string | null;
/** Buddhist festival name (农历) if applicable */
buddhistFestival: string | null;
/** 72 phenology name if applicable */
phenology: string | null;
/** Three periods (三伏) if applicable */
dogDay: string | null;
/** Nine-day cold period (数九) if applicable */
nineDay: string | null;
// Lunar calendar
lunarYear: number;
lunarMonth: number;
/** Chinese lunar month name e.g. "五月" */
lunarMonthName: string;
lunarDay: number;
/** Chinese lunar day name e.g. "初十", "廿一" */
lunarDayName: string;
isLeapMonth: boolean;
/** Gan-Zhi of the lunar year e.g. "丙午" */
lunarYearGanzhi: string;
/** Gan-Zhi of the lunar month */
lunarMonthGanzhi: string;
/** Gan-Zhi of the lunar day */
lunarDayGanzhi: string;
/** Chinese zodiac animal */
zodiac: string;
// Festivals & holidays
lunarFestival: string | null;
solarFestival: string | null;
legalHoliday: { name: string; isWork: boolean } | null;
// Moon phase
moonPhase: string | null;
// Metadata
isToday: boolean;
isWeekend: boolean;
/** Day-of-week position within the month grid (0-based column) */
dayOfWeek: number;
}
-66
View File
@@ -1,66 +0,0 @@
/** Relationship between a single pillar in user's Bazi and day's Bazi */
export interface PillarRelationship {
pillar: 'year' | 'month' | 'day' | 'hour';
pillarLabel: string; // "年柱", "月柱", "日柱", "时柱"
userGanzhi: string;
dayGanzhi: string;
// Heaven stem relationships
stemTenStar: string; // Ten Star: day stem vs user stem
stemCombine: boolean; // 天干合
stemOpposite: boolean; // 天干冲
// Earth branch relationships
branchCombine: boolean; // 六合
branchThreeCombine: boolean; // 三合
branchOpposite: boolean; // 六冲
branchHarm: boolean; // 六害
branchPunish: boolean; // 相刑
branchFormation: string | null;// 三合局名
// Score contribution
score: number; // -10 to +10
}
/** Complete daily fortune result for a user on a specific day */
export interface DailyFortuneResult {
date: string; // ISO date
lunarDate: string; // Lunar date description
dayGanzhi: string; // Day's Gan-Zhi
/** Overall score from -100 to +100 */
overallScore: number;
/** Score level classification */
scoreLevel: 'great' | 'good' | 'fair' | 'poor' | 'bad';
/** Pillar-by-pillar relationship analysis */
pillarRelationships: PillarRelationship[];
/** Positive aspects of the day */
luckyAspects: string[];
/** Negative aspects / warnings */
unluckyAspects: string[];
/** Actionable suggestions */
suggestions: string[];
/** Primary affected life area */
affectedAreas: string[];
/** Lucky meta info for the day (personalized) */
luckyMeta: {
colors: string[];
numbers: number[];
direction: string;
element: string;
activity: string;
};
/** Category scores (-100 to +100) */
categoryScores: {
love: number;
career: number;
wealth: number;
health: number;
};
}
-15
View File
@@ -1,15 +0,0 @@
export type { DayInfo } from './calendar';
export type { AlmanacInfo, HourAlmanac } from './almanac';
export type {
PillarInfo,
HideStemInfo,
EightCharInfo,
DecadeFortuneInfo,
FortuneInfo,
ChildLimitInfo,
BaziFullResult,
} from './bazi';
export type {
PillarRelationship,
DailyFortuneResult,
} from './fortune';
-9
View File
@@ -1,9 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"lib": ["ES2022"]
},
"include": ["src"]
}
-11
View File
@@ -1,11 +0,0 @@
import { defineConfig } from 'tsup';
export default defineConfig({
entry: ['src/index.ts'],
format: ['esm', 'cjs'],
dts: true,
clean: true,
sourcemap: true,
splitting: false,
treeshake: true,
});
-24
View File
@@ -1,24 +0,0 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#FFFBF5" />
<meta name="description" content="万年历 - 农历黄历八字运势" />
<title>万年历</title>
<script>
// Prevent dark mode flicker
(function() {
const theme = localStorage.getItem('lunar-theme');
if (theme === 'dark' || (!theme && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
document.documentElement.classList.add('dark');
}
})();
</script>
</head>
<body class="bg-background text-foreground antialiased">
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
-34
View File
@@ -1,34 +0,0 @@
{
"name": "@lunar/web",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"lint": "eslint .",
"clean": "rm -rf dist"
},
"dependencies": {
"@lunar/core": "workspace:*",
"framer-motion": "^12.0.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-router-dom": "^7.0.0",
"zustand": "^5.0.0",
"lucide-react": "^0.468.0",
"clsx": "^2.1.0",
"tailwind-variants": "^0.3.0"
},
"devDependencies": {
"@tailwindcss/vite": "^4.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"tailwindcss": "^4.0.0",
"typescript": "^5.7.0",
"vite": "^6.0.0",
"@vitejs/plugin-react": "^4.4.0",
"vite-plugin-pwa": "^0.21.0"
}
}
-4
View File
@@ -1,4 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="12" fill="#C41E3A"/>
<text x="32" y="44" text-anchor="middle" font-size="36" font-family="serif" fill="white"></text>
</svg>

Before

Width:  |  Height:  |  Size: 226 B

-68
View File
@@ -1,68 +0,0 @@
import { Routes, Route, Navigate, useLocation } from 'react-router-dom';
import { lazy, Suspense } from 'react';
import { AnimatePresence, motion } from 'framer-motion';
import { AppShell } from './components/layout/AppShell';
import { ErrorBoundary } from './components/ui/ErrorBoundary';
import { PageSkeleton } from './components/ui/Skeleton';
// Lazy load pages
const HomePage = lazy(() => import('./pages/HomePage'));
const CalendarPage = lazy(() => import('./pages/CalendarPage'));
const DayDetailPage = lazy(() => import('./pages/DayDetailPage'));
const BaziPage = lazy(() => import('./pages/BaziPage'));
const DailyFortunePage = lazy(() => import('./pages/DailyFortunePage'));
const SettingsPage = lazy(() => import('./pages/SettingsPage'));
const DivinationPage = lazy(() => import('./pages/DivinationPage'));
const SolarTermsPage = lazy(() => import('./pages/SolarTermsPage'));
const pageVariants = {
initial: { opacity: 0, y: 12 },
animate: { opacity: 1, y: 0 },
exit: { opacity: 0, y: -12 },
};
function PageTransition({ children }: { children: React.ReactNode }) {
return (
<motion.div
variants={pageVariants}
initial="initial"
animate="animate"
exit="exit"
transition={{ duration: 0.2, ease: 'easeOut' }}
>
{children}
</motion.div>
);
}
function SafePage({ children }: { children: React.ReactNode }) {
return (
<PageTransition>
<ErrorBoundary>{children}</ErrorBoundary>
</PageTransition>
);
}
export default function App() {
const location = useLocation();
return (
<AppShell>
<AnimatePresence mode="wait">
<Suspense fallback={<PageSkeleton />}>
<Routes location={location} key={location.pathname}>
<Route path="/" element={<SafePage><HomePage /></SafePage>} />
<Route path="/calendar" element={<SafePage><CalendarPage /></SafePage>} />
<Route path="/calendar/:date" element={<SafePage><DayDetailPage /></SafePage>} />
<Route path="/bazi" element={<SafePage><BaziPage /></SafePage>} />
<Route path="/daily-fortune" element={<SafePage><DailyFortunePage /></SafePage>} />
<Route path="/settings" element={<SafePage><SettingsPage /></SafePage>} />
<Route path="/divination" element={<SafePage><DivinationPage /></SafePage>} />
<Route path="/solar-terms" element={<SafePage><SolarTermsPage /></SafePage>} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</Suspense>
</AnimatePresence>
</AppShell>
);
}
@@ -1,122 +0,0 @@
import { cn } from '../../lib/utils';
import { motion } from 'framer-motion';
import { Star } from 'lucide-react';
import type { DayInfo } from '@lunar/core';
interface CalendarCellProps {
dayInfo: DayInfo;
isSelected: boolean;
isCurrentMonth: boolean;
fortuneScore?: number;
hasBookmark?: boolean;
expanded?: boolean;
onClick: () => void;
}
// Short festival abbreviations
function shortFestival(di: DayInfo): string | null {
if (di.lunarFestival) {
if (di.lunarFestival.includes('春节')) return '春节';
if (di.lunarFestival.includes('元宵')) return '元宵';
if (di.lunarFestival.includes('清明')) return '清明';
if (di.lunarFestival.includes('端午')) return '端午';
if (di.lunarFestival.includes('七夕')) return '七夕';
if (di.lunarFestival.includes('中秋')) return '中秋';
if (di.lunarFestival.includes('重阳')) return '重阳';
if (di.lunarFestival.includes('除夕')) return '除夕';
if (di.lunarFestival.includes('腊八')) return '腊八';
if (di.lunarFestival.includes('冬至')) return '冬至';
if (di.lunarFestival.includes('小年') || di.lunarFestival.includes('灶')) return '小年';
return '节';
}
if (di.solarFestival) {
if (di.solarFestival.includes('元旦')) return '元旦';
if (di.solarFestival.includes('国庆')) return '国庆';
if (di.solarFestival.includes('劳动')) return '劳动';
if (di.solarFestival.includes('妇女')) return '妇女';
if (di.solarFestival.includes('儿童')) return '儿童';
if (di.solarFestival.includes('情人')) return '情人';
return '节';
}
if (di.legalHoliday && !di.legalHoliday.isWork) return '休';
return null;
}
export function CalendarCell({ dayInfo, isSelected, isCurrentMonth, fortuneScore, hasBookmark, expanded, onClick }: CalendarCellProps) {
const fest = shortFestival(dayInfo);
const hasTerm = !!dayInfo.solarTerm;
return (
<motion.button
whileTap={{ scale: 0.92 }}
onClick={onClick}
className={cn(
'relative flex flex-col items-center justify-center aspect-square p-0.5',
'border-b border-r border-border/50',
!isCurrentMonth && 'opacity-30',
isSelected && !dayInfo.isToday && 'bg-primary/10 rounded-lg',
dayInfo.isToday && 'bg-primary rounded-md',
)}
>
{/* Festival / Solar term label at top */}
{(fest || hasTerm) && (
<span className={cn(
'text-[8px] leading-none font-medium relative z-10 truncate max-w-full px-0.5',
fest ? 'text-red-500' : 'text-green-600',
)}>
{fest || (hasTerm ? dayInfo.solarTerm!.slice(0, 2) : '')}
</span>
)}
{/* Fortune dot (if user has bazi) */}
{fortuneScore !== undefined && (
<div className={`absolute top-0.5 left-0.5 w-1.5 h-1.5 rounded-full z-10 ${
fortuneScore >= 20 ? 'bg-red-500' : fortuneScore <= -20 ? 'bg-slate-500' : 'bg-amber-400'
}`} />
)}
{/* Bookmark star */}
{hasBookmark && (
<Star size={8} className="absolute top-0.5 right-0.5 text-amber-500 fill-amber-500 z-10" />
)}
{/* Solar day number */}
<span className={cn(
'text-sm font-semibold leading-tight relative z-10',
dayInfo.isToday && 'text-white',
dayInfo.isWeekend && !dayInfo.isToday && 'text-red-500',
!isCurrentMonth && 'text-muted',
)}>
{dayInfo.solarDay}
</span>
{/* Lunar day name or festival */}
<span className={cn(
'text-[10px] leading-tight relative z-10 truncate max-w-full px-0.5',
dayInfo.isToday && 'text-white/80',
!dayInfo.isToday && 'text-secondary',
dayInfo.lunarDay === 1 && !dayInfo.isToday && 'text-primary font-medium',
dayInfo.lunarDay === 15 && !dayInfo.isToday && 'text-primary font-medium',
)}>
{dayInfo.lunarDayName}
</span>
{/* Extra info in week view */}
{expanded && (
<div className="relative z-10 mt-0.5 space-y-0.5">
{dayInfo.lunarFestival && (
<span className="text-[8px] text-red-500 block truncate">{dayInfo.lunarFestival}</span>
)}
{dayInfo.solarTerm && (
<span className="text-[8px] text-green-600 block truncate">{dayInfo.solarTerm}</span>
)}
{fortuneScore !== undefined && (
<span className={`text-[8px] font-medium ${fortuneScore>=20?'text-red-500':fortuneScore<=-20?'text-slate-500':'text-amber-500'}`}>
{fortuneScore>=20?'吉':fortuneScore<=-20?'凶':'平'} {fortuneScore}
</span>
)}
</div>
)}
</motion.button>
);
}
@@ -1,113 +0,0 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';
import type { DayInfo } from '@lunar/core';
import { CalendarCell } from './CalendarCell';
import { WeekDayBar } from './WeekDayBar';
import { MonthYearPicker } from './MonthYearPicker';
interface CalendarGridProps {
days: DayInfo[][];
viewDate: Date;
selectedDate: Date | null;
weekStart?: 0 | 1;
fortuneScores?: Record<string, number> | null;
bookmarkedDates?: Set<string>;
onPrevMonth: () => void;
onNextMonth: () => void;
onPrevYear: () => void;
onNextYear: () => void;
onSelectDate: (d: Date) => void;
}
export function CalendarGrid({
days, viewDate, selectedDate, weekStart = 0, fortuneScores, bookmarkedDates,
onPrevMonth, onNextMonth, onPrevYear, onNextYear, onSelectDate,
}: CalendarGridProps) {
const navigate = useNavigate();
const [viewMode, setViewMode] = useState<'month'|'week'>('month');
const monthKey = `${viewDate.getFullYear()}-${viewDate.getMonth()}`;
const handleDayClick = (dayInfo: DayInfo) => {
const [y, m, d] = dayInfo.solarDate.split('-').map(Number);
onSelectDate(new Date(y, m - 1, d));
navigate(`/calendar/${dayInfo.solarDate}`);
};
const isSelected = (di: DayInfo): boolean => {
if (!selectedDate) return false;
const [y, m, d] = di.solarDate.split('-').map(Number);
return selectedDate.getFullYear()===y && selectedDate.getMonth()===m-1 && selectedDate.getDate()===d;
};
// Week view: show the week containing the selected date, or current week
const selectedWeek = selectedDate
? days.findIndex(w => w.some(d => {
const [y,m,day] = d.solarDate.split('-').map(Number);
return selectedDate.getFullYear()===y && selectedDate.getMonth()===m-1 && selectedDate.getDate()===day;
}))
: -1;
const displayWeek = selectedWeek >= 0 ? selectedWeek : 0;
const displayDays = viewMode === 'week' ? (days[displayWeek] || days[0] || []) : days.flat();
return (
<div className="space-y-2">
<MonthYearPicker viewDate={viewDate}
onPrevMonth={onPrevMonth} onNextMonth={onNextMonth}
onPrevYear={onPrevYear} onNextYear={onNextYear} />
{/* View mode toggle */}
<div className="flex rounded-lg bg-card border border-border p-0.5">
<button onClick={() => setViewMode('month')}
className={`flex-1 py-1 text-xs rounded-md font-medium transition-colors ${viewMode==='month'?'bg-primary text-white':'text-secondary'}`}></button>
<button onClick={() => setViewMode('week')}
className={`flex-1 py-1 text-xs rounded-md font-medium transition-colors ${viewMode==='week'?'bg-primary text-white':'text-secondary'}`}></button>
</div>
<div className="bg-card rounded-xl border border-border overflow-hidden shadow-sm">
<WeekDayBar weekStart={weekStart} />
<motion.div key={`${monthKey}-${viewMode}`} initial={{opacity:0}} animate={{opacity:1}} transition={{duration:0.12}}
className={`grid grid-cols-7 ${viewMode==='week'?'auto-rows-fr':''}`}>
{displayDays.map((dayInfo, idx) => (
<CalendarCell key={`${dayInfo.solarDate}-${idx}`} dayInfo={dayInfo}
isSelected={isSelected(dayInfo)}
isCurrentMonth={dayInfo.solarMonth===viewDate.getMonth()+1 && dayInfo.solarYear===viewDate.getFullYear()}
fortuneScore={fortuneScores?.[dayInfo.solarDate]}
hasBookmark={bookmarkedDates?.has(dayInfo.solarDate)}
expanded={viewMode === 'week'}
onClick={() => handleDayClick(dayInfo)} />
))}
</motion.div>
</div>
{/* Month summary (fortune) */}
{fortuneScores && (
<MonthSummary scores={fortuneScores} days={days} />
)}
</div>
);
}
function MonthSummary({ scores, days }: { scores: Record<string, number>; days: DayInfo[][] }) {
const allDays = days.flat().filter(d => scores[d.solarDate] !== undefined);
if (allDays.length === 0) return null;
const good = allDays.filter(d => scores[d.solarDate] >= 20).length;
const bad = allDays.filter(d => scores[d.solarDate] <= -20).length;
const fair = allDays.length - good - bad;
const best = allDays.reduce((a, b) => (scores[a.solarDate] > scores[b.solarDate]) ? a : b);
const worst = allDays.reduce((a, b) => (scores[a.solarDate] < scores[b.solarDate]) ? a : b);
return (
<div className="bg-card rounded-xl border border-border p-2.5">
<p className="text-xs font-medium mb-1.5"></p>
<div className="flex items-center gap-3 text-xs mb-1.5">
<span className="text-red-500"> {good}</span>
<span className="text-amber-500"> {fair}</span>
<span className="text-slate-500"> {bad}</span>
</div>
<div className="flex justify-between text-[10px] text-muted">
<span>: {best.lunarMonthName}{best.lunarDayName} ({scores[best.solarDate]})</span>
<span>: {worst.lunarMonthName}{worst.lunarDayName} ({scores[worst.solarDate]})</span>
</div>
</div>
);
}
@@ -1,45 +0,0 @@
import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-react';
interface MonthYearPickerProps {
viewDate: Date;
onPrevMonth: () => void;
onNextMonth: () => void;
onPrevYear: () => void;
onNextYear: () => void;
}
export function MonthYearPicker({
viewDate,
onPrevMonth,
onNextMonth,
onPrevYear,
onNextYear,
}: MonthYearPickerProps) {
const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
return (
<div className="flex items-center justify-between gap-1">
<div className="flex items-center gap-0.5">
<button onClick={onPrevYear} className="p-1.5 rounded-lg hover:bg-foreground/5 text-muted shrink-0" title="上一年">
<ChevronsLeft size={15} />
</button>
<button onClick={onPrevMonth} className="p-1 rounded-lg hover:bg-foreground/5 text-secondary shrink-0" title="上一月">
<ChevronLeft size={17} />
</button>
</div>
<h2 className="text-sm sm:text-base font-bold font-chinese text-foreground select-none text-center whitespace-nowrap mx-1">
{viewDate.getFullYear()}{monthNames[viewDate.getMonth()]}
</h2>
<div className="flex items-center gap-0.5">
<button onClick={onNextMonth} className="p-1 rounded-lg hover:bg-foreground/5 text-secondary shrink-0" title="下一月">
<ChevronRight size={17} />
</button>
<button onClick={onNextYear} className="p-1.5 rounded-lg hover:bg-foreground/5 text-muted shrink-0" title="下一年">
<ChevronsRight size={15} />
</button>
</div>
</div>
);
}
@@ -1,24 +0,0 @@
const DAY_LABELS = ['日', '一', '二', '三', '四', '五', '六'];
export function WeekDayBar({ weekStart = 0 }: { weekStart?: 0 | 1 }) {
const labels = weekStart === 1 ? [...DAY_LABELS.slice(1), DAY_LABELS[0]] : DAY_LABELS;
return (
<div className="grid grid-cols-7 border-b border-border">
{labels.map((label, idx) => {
const weekIdx = (idx + weekStart) % 7;
const isWeekend = weekIdx === 0 || weekIdx === 6;
return (
<div
key={idx}
className={`
flex items-center justify-center py-2 text-xs font-medium
${isWeekend ? 'text-red-400' : 'text-muted'}
`}
>
{label}
</div>
);
})}
</div>
);
}
@@ -1,21 +0,0 @@
import type { ReactNode } from 'react';
import { Header } from './Header';
import { BottomNav } from './BottomNav';
interface AppShellProps {
children: ReactNode;
}
export function AppShell({ children }: AppShellProps) {
return (
<div className="min-h-screen bg-background">
<Header />
<main className="pt-12 pb-16 md:pb-4">
<div className="container-page">
{children}
</div>
</main>
<BottomNav />
</div>
);
}
@@ -1,43 +0,0 @@
import { useNavigate, useLocation } from 'react-router-dom';
import { Home, CalendarDays, Stars, TrendingUp, Settings } from 'lucide-react';
import { cn } from '../../lib/utils';
const NAV_ITEMS = [
{ path: '/', label: '首页', icon: Home, exact: true },
{ path: '/calendar', label: '日历', icon: CalendarDays },
{ path: '/bazi', label: '八字', icon: Stars },
{ path: '/daily-fortune', label: '运势', icon: TrendingUp },
{ path: '/settings', label: '设置', icon: Settings },
];
export function BottomNav() {
const navigate = useNavigate();
const location = useLocation();
return (
<nav className="fixed bottom-0 left-0 right-0 z-30 md:hidden bg-background/80 backdrop-blur-lg border-t border-border safe-area-bottom">
<div className="flex items-center justify-around h-14">
{NAV_ITEMS.map((item) => {
const isActive = item.exact
? location.pathname === '/'
: location.pathname === item.path || location.pathname.startsWith(item.path + '/');
const Icon = item.icon;
return (
<button
key={item.path}
onClick={() => navigate(item.path)}
className={cn(
'flex flex-col items-center justify-center gap-0.5 min-w-0 px-2 py-1 rounded-lg transition-colors',
isActive ? 'text-primary' : 'text-muted hover:text-secondary',
)}
>
<Icon size={18} strokeWidth={isActive ? 2.5 : 2} />
<span className="text-[10px] font-medium">{item.label}</span>
</button>
);
})}
</div>
</nav>
);
}
@@ -1,43 +0,0 @@
import { useNavigate, useLocation } from 'react-router-dom';
import { Sun, Moon, Calendar, Home } from 'lucide-react';
import { useSettingsStore } from '../../stores/settings';
interface HeaderProps {
title?: string;
}
export function Header({ title = '万年历' }: HeaderProps) {
const navigate = useNavigate();
const location = useLocation();
const { theme, setTheme } = useSettingsStore();
const toggleTheme = () => setTheme(theme === 'dark' ? 'light' : 'dark');
const isHome = location.pathname === '/';
return (
<header className="fixed top-0 left-0 right-0 z-30 h-12 bg-background/80 backdrop-blur-lg border-b border-border">
<div className="container-page h-full flex items-center justify-between">
<button
onClick={() => navigate('/')}
className="p-1.5 -ml-1.5 rounded-lg hover:bg-foreground/5 flex items-center gap-1"
>
<span className="text-base font-bold font-chinese text-primary">{title}</span>
</button>
<div className="flex items-center gap-0.5">
{!isHome && (
<button onClick={() => navigate('/')} className="p-1.5 rounded-lg hover:bg-foreground/5 text-secondary" title="首页">
<Home size={16} />
</button>
)}
<button onClick={() => navigate('/calendar')} className="p-1.5 rounded-lg hover:bg-foreground/5 text-secondary" title="日历">
<Calendar size={16} />
</button>
<button onClick={toggleTheme} className="p-1.5 rounded-lg hover:bg-foreground/5 text-secondary" title="切换主题">
{theme === 'dark' ? <Sun size={16} /> : <Moon size={16} />}
</button>
</div>
</div>
</header>
);
}
@@ -1,54 +0,0 @@
import { motion, AnimatePresence } from 'framer-motion';
import type { ReactNode } from 'react';
interface AnimatedPanelProps {
children: ReactNode;
isOpen: boolean;
onClose: () => void;
position?: 'bottom' | 'right';
}
export function AnimatedPanel({
children,
isOpen,
onClose,
position = 'bottom',
}: AnimatedPanelProps) {
return (
<AnimatePresence>
{isOpen && (
<>
{/* Backdrop */}
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
onClick={onClose}
className="fixed inset-0 bg-black/30 z-40"
/>
{/* Panel */}
<motion.div
initial={position === 'bottom' ? { y: '100%' } : { x: '100%' }}
animate={position === 'bottom' ? { y: 0 } : { x: 0 }}
exit={position === 'bottom' ? { y: '100%' } : { x: '100%' }}
transition={{ type: 'spring', damping: 30, stiffness: 300 }}
className={
position === 'bottom'
? 'fixed bottom-0 left-0 right-0 z-50 max-h-[85vh] overflow-y-auto rounded-t-2xl bg-card shadow-xl'
: 'fixed right-0 top-0 h-full z-50 w-80 overflow-y-auto bg-card shadow-xl'
}
>
{/* Drag handle for bottom sheet */}
{position === 'bottom' && (
<div className="flex justify-center pt-3 pb-1 sticky top-0 bg-card z-10">
<div className="w-10 h-1 rounded-full bg-border" />
</div>
)}
{children}
</motion.div>
</>
)}
</AnimatePresence>
);
}
@@ -1,41 +0,0 @@
import { cn } from '../../lib/utils';
import type { ReactNode } from 'react';
interface BadgeProps {
children: ReactNode;
variant?: 'default' | 'lucky' | 'unlucky' | 'element' | 'outline' | 'festival';
size?: 'sm' | 'md';
className?: string;
element?: string; // 'wood' | 'fire' | 'earth' | 'metal' | 'water'
}
const elementStyles: Record<string, string> = {
wood: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
fire: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
earth: 'bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400',
metal: 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400',
water: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
};
export function Badge({ children, variant = 'default', size = 'sm', className, element }: BadgeProps) {
const baseStyles = 'inline-flex items-center font-medium rounded-full';
const sizeStyles = {
sm: 'px-2 py-0.5 text-xs',
md: 'px-3 py-1 text-sm',
};
const variantStyles = {
default: 'bg-primary/10 text-primary',
lucky: 'bg-red-50 text-red-600 dark:bg-red-900/20 dark:text-red-400',
unlucky: 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400',
element: element ? elementStyles[element] || '' : '',
outline: 'border border-border text-secondary bg-transparent',
festival: 'bg-red-500 text-white',
};
return (
<span className={cn(baseStyles, sizeStyles[size], variantStyles[variant], className)}>
{children}
</span>
);
}
@@ -1,43 +0,0 @@
import { cn } from '../../lib/utils';
import type { ButtonHTMLAttributes, ReactNode } from 'react';
interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
children: ReactNode;
variant?: 'primary' | 'secondary' | 'ghost' | 'outline';
size?: 'sm' | 'md' | 'lg';
className?: string;
}
export function Button({
children,
variant = 'primary',
size = 'md',
className,
disabled,
...props
}: ButtonProps) {
const baseStyles = 'inline-flex items-center justify-center font-medium rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-primary/30 disabled:opacity-50 disabled:pointer-events-none';
const variantStyles = {
primary: 'bg-primary text-white hover:bg-primary-dark active:bg-primary-dark',
secondary: 'bg-accent text-white hover:bg-amber-600 active:bg-amber-700',
ghost: 'bg-transparent text-foreground hover:bg-foreground/5 active:bg-foreground/10',
outline: 'border-2 border-border bg-transparent text-foreground hover:bg-foreground/5',
};
const sizeStyles = {
sm: 'h-8 px-3 text-xs gap-1.5',
md: 'h-10 px-4 text-sm gap-2',
lg: 'h-12 px-6 text-base gap-2.5',
};
return (
<button
className={cn(baseStyles, variantStyles[variant], sizeStyles[size], className)}
disabled={disabled}
{...props}
>
{children}
</button>
);
}
@@ -1,58 +0,0 @@
import { cn } from '../../lib/utils';
import type { HTMLAttributes, ReactNode } from 'react';
interface CardProps extends HTMLAttributes<HTMLDivElement> {
children: ReactNode;
variant?: 'default' | 'elevated' | 'outlined';
padding?: 'none' | 'sm' | 'md' | 'lg';
className?: string;
}
export function Card({
children,
variant = 'default',
padding = 'md',
className,
...props
}: CardProps) {
const baseStyles = 'rounded-xl overflow-hidden';
const variantStyles = {
default: 'bg-card shadow-sm border border-border/60',
elevated: 'bg-card shadow-md border border-border/60 chinese-pattern',
outlined: 'bg-transparent border border-border',
};
const paddingStyles = {
none: '',
sm: 'p-2.5',
md: 'p-3',
lg: 'p-5',
};
return (
<div
className={cn(baseStyles, variantStyles[variant], paddingStyles[padding], className)}
{...props}
>
{children}
</div>
);
}
interface CardHeaderProps {
title: ReactNode;
subtitle?: string;
action?: ReactNode;
className?: string;
}
export function CardHeader({ title, subtitle, action, className }: CardHeaderProps) {
return (
<div className={cn('flex items-center justify-between mb-3', className)}>
<div>
<h3 className="text-base font-semibold text-foreground">{title}</h3>
{subtitle && <p className="text-xs text-secondary mt-0.5">{subtitle}</p>}
</div>
{action && <div>{action}</div>}
</div>
);
}
@@ -1,56 +0,0 @@
import { Component, type ReactNode } from 'react';
import { AlertTriangle, RefreshCw } from 'lucide-react';
import { Button } from './Button';
interface Props {
children: ReactNode;
fallback?: ReactNode;
}
interface State {
hasError: boolean;
error: Error | null;
}
export class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
console.error('ErrorBoundary caught:', error, errorInfo);
}
handleReset = () => {
this.setState({ hasError: false, error: null });
};
render() {
if (this.state.hasError) {
if (this.props.fallback) return this.props.fallback;
return (
<div className="flex flex-col items-center justify-center py-16 px-4 text-center">
<div className="w-16 h-16 rounded-full bg-red-50 dark:bg-red-900/20 flex items-center justify-center mb-4">
<AlertTriangle size={28} className="text-red-500" />
</div>
<h2 className="text-lg font-semibold mb-2"></h2>
<p className="text-sm text-secondary mb-6 max-w-xs">
{this.state.error?.message || '页面加载失败,请刷新重试'}
</p>
<Button variant="primary" onClick={this.handleReset}>
<RefreshCw size={16} className="mr-2" />
</Button>
</div>
);
}
return this.props.children;
}
}
@@ -1,132 +0,0 @@
import { cn } from '../../lib/utils';
interface SkeletonProps {
className?: string;
}
export function Skeleton({ className }: SkeletonProps) {
return (
<div
className={cn(
'animate-pulse rounded-lg bg-border/60',
className,
)}
/>
);
}
export function PageSkeleton() {
return (
<div className="py-3 space-y-5">
{/* Hero skeleton */}
<div className="rounded-xl bg-card border border-border p-6 space-y-3">
<Skeleton className="h-3 w-24 mx-auto" />
<Skeleton className="h-8 w-48 mx-auto" />
<Skeleton className="h-4 w-32 mx-auto" />
</div>
{/* Grid skeleton */}
<div className="grid grid-cols-2 gap-3">
{[...Array(4)].map((_, i) => (
<div key={i} className="rounded-xl bg-card border border-border p-4 space-y-2">
<Skeleton className="h-3 w-16 mx-auto" />
<Skeleton className="h-6 w-20 mx-auto" />
</div>
))}
</div>
{/* Card skeleton */}
<div className="rounded-xl bg-card border border-border p-4 space-y-3">
<Skeleton className="h-4 w-24" />
<div className="grid grid-cols-2 gap-3">
<div className="space-y-2">
<Skeleton className="h-3 w-8" />
<div className="flex gap-1.5">
{[...Array(5)].map((_, i) => (
<Skeleton key={i} className="h-6 w-12 rounded-full" />
))}
</div>
</div>
<div className="space-y-2">
<Skeleton className="h-3 w-8" />
<div className="flex gap-1.5">
{[...Array(5)].map((_, i) => (
<Skeleton key={i} className="h-6 w-12 rounded-full" />
))}
</div>
</div>
</div>
</div>
{/* Button skeleton */}
<Skeleton className="h-12 w-full rounded-xl" />
<div className="grid grid-cols-2 gap-2">
<Skeleton className="h-10 rounded-xl" />
<Skeleton className="h-10 rounded-xl" />
</div>
</div>
);
}
export function CalendarSkeleton() {
return (
<div className="py-3 space-y-3">
{/* Month picker skeleton */}
<div className="flex items-center justify-between">
<Skeleton className="h-8 w-20" />
<Skeleton className="h-6 w-32" />
<Skeleton className="h-8 w-20" />
</div>
{/* Grid skeleton */}
<div className="rounded-xl bg-card border border-border overflow-hidden">
<div className="grid grid-cols-7 border-b border-border">
{[...Array(7)].map((_, i) => (
<div key={i} className="py-2 text-center">
<Skeleton className="h-3 w-4 mx-auto" />
</div>
))}
</div>
<div className="grid grid-cols-7">
{[...Array(42)].map((_, i) => (
<div key={i} className="aspect-square p-1 border-b border-r border-border/50">
<Skeleton className="h-4 w-5 mx-auto mb-0.5" />
<Skeleton className="h-2.5 w-6 mx-auto" />
</div>
))}
</div>
</div>
</div>
);
}
export function BaziSkeleton() {
return (
<div className="py-3 space-y-5">
<Skeleton className="h-6 w-24" />
{/* Form skeleton */}
<div className="rounded-xl bg-card border border-border p-4 space-y-3">
<Skeleton className="h-4 w-20" />
<div className="grid grid-cols-3 gap-2">
{[...Array(6)].map((_, i) => (
<Skeleton key={i} className="h-10 rounded-lg" />
))}
</div>
<Skeleton className="h-12 w-full rounded-xl" />
</div>
{/* Result skeleton */}
<div className="rounded-xl bg-card border border-border p-4 space-y-3">
<Skeleton className="h-4 w-24" />
<div className="grid grid-cols-4 gap-2">
{[...Array(4)].map((_, i) => (
<div key={i} className="flex flex-col items-center gap-2 p-2">
<Skeleton className="h-3 w-8" />
<Skeleton className="h-10 w-10 rounded-full" />
<Skeleton className="h-4 w-12" />
<Skeleton className="h-3 w-8" />
</div>
))}
</div>
</div>
</div>
);
}
-37
View File
@@ -1,37 +0,0 @@
import { useCallback } from 'react';
import { birthInfoToBazi } from '@lunar/core';
import { useUserStore, type UserProfile } from '../stores/user';
export function useBazi() {
const {
profiles, activeIndex, activeProfile, activeBazi, isLoading, error,
addProfile, updateProfile, removeProfile, setActiveIndex, setBaziResult, setLoading, setError, clearAll,
} = useUserStore();
const calculate = useCallback((p?: UserProfile, idx?: number) => {
const target = p || activeProfile;
const index = idx ?? activeIndex;
if (!target) { setError('请先输入出生信息'); return null; }
setLoading(true); setError(null);
try {
const result = birthInfoToBazi({
year: target.birthYear, month: target.birthMonth, day: target.birthDay,
hour: target.birthHour, minute: target.birthMinute, gender: target.gender,
});
setBaziResult(index, result);
return result;
} catch (e) {
setError(e instanceof Error ? e.message : '八字计算失败');
return null;
}
}, [activeProfile, activeIndex, setBaziResult, setLoading, setError]);
return {
profiles, activeIndex, profile: activeProfile, baziResult: activeBazi, isLoading, error,
setProfile: (p: UserProfile) => updateProfile(activeIndex, p),
addProfile, updateProfile, removeProfile, setActiveIndex,
calculate, clearAll,
hasProfile: profiles.length > 0,
profileCount: profiles.length,
};
}
-40
View File
@@ -1,40 +0,0 @@
import { useMemo } from 'react';
import { getMonthCalendar } from '@lunar/core';
import { useCalendarStore } from '../stores/calendar';
import { useSettingsStore } from '../stores/settings';
export function useCalendar() {
const {
viewDate,
selectedDate,
goToToday,
goToNextMonth,
goToPrevMonth,
goToNextYear,
goToPrevYear,
selectDate,
} = useCalendarStore();
const weekStart = useSettingsStore(s => s.weekStartDay);
const days = useMemo(() => {
const year = viewDate.getFullYear();
const month = viewDate.getMonth() + 1;
return getMonthCalendar(year, month, weekStart);
}, [viewDate, weekStart]);
const today = useMemo(() => new Date(), []); // stable today ref
return {
viewDate,
selectedDate,
weekStart,
days,
today,
goToToday,
goToNextMonth,
goToPrevMonth,
goToNextYear,
goToPrevYear,
selectDate,
};
}
@@ -1,23 +0,0 @@
import { useMemo, useState, useEffect } from 'react';
import { calculateDailyFortune, type DailyFortuneResult } from '@lunar/core';
import { useUserStore } from '../stores/user';
export function useDailyFortune(date: Date) {
const { eightChar, activeProfile } = useUserStore();
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fortune: DailyFortuneResult | null = useMemo(() => {
if (!eightChar) return null;
try {
return calculateDailyFortune(eightChar, date);
} catch (e) {
setError(e instanceof Error ? e.message : '运势计算失败');
return null;
}
}, [eightChar, date.getFullYear(), date.getMonth(), date.getDate()]);
useEffect(() => { setIsLoading(false); }, [fortune]);
return { fortune, isLoading, error, hasProfile: !!activeProfile, needsProfile: !activeProfile };
}
@@ -1,26 +0,0 @@
import { useMemo, useState, useEffect } from 'react';
import { getDayInfo, getAlmanacInfo, type DayInfo, type AlmanacInfo } from '@lunar/core';
export function useDayDetail(date: Date) {
const [isLoading, setIsLoading] = useState(true);
const dayInfo: DayInfo = useMemo(() => {
const y = date.getFullYear();
const m = date.getMonth() + 1;
const d = date.getDate();
return getDayInfo(y, m, d);
}, [date.getFullYear(), date.getMonth(), date.getDate()]);
const almanac: AlmanacInfo = useMemo(() => {
const y = date.getFullYear();
const m = date.getMonth() + 1;
const d = date.getDate();
return getAlmanacInfo(y, m, d);
}, [date.getFullYear(), date.getMonth(), date.getDate()]);
useEffect(() => {
setIsLoading(false);
}, [dayInfo]);
return { dayInfo, almanac, isLoading };
}
-47
View File
@@ -1,47 +0,0 @@
import { clsx, type ClassValue } from 'clsx';
/** Merge class names with clsx */
export function cn(...inputs: ClassValue[]): string {
return clsx(inputs);
}
/** Format a Date object to YYYY-MM-DD string */
export function formatDate(date: Date): string {
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, '0');
const d = String(date.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
/** Parse a YYYY-MM-DD string to Date */
export function parseDate(dateStr: string): Date {
const [y, m, d] = dateStr.split('-').map(Number);
return new Date(y, m - 1, d);
}
/** Get today as YYYY-MM-DD string */
export function getTodayString(): string {
return formatDate(new Date());
}
/** Chinese number mapping for days 1-30 */
export function getChineseDayName(day: number): string {
const tens = ['', '十', '廿', '三十'];
const ones = ['', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
if (day === 10) return '初十';
if (day === 20) return '二十';
if (day === 30) return '三十';
const ten = Math.floor(day / 10);
const one = day % 10;
const prefix = tens[ten];
const suffix = ones[one];
return `${prefix}${suffix}`;
}
/** Chinese month names */
export function getChineseMonthName(month: number, isLeap: boolean): string {
const names = ['', '正', '二', '三', '四', '五', '六', '七', '八', '九', '十', '冬', '腊'];
return `${isLeap ? '闰' : ''}${names[month]}`;
}
-13
View File
@@ -1,13 +0,0 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import './styles/globals.css';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
);
-529
View File
@@ -1,529 +0,0 @@
import { useState, useCallback, useMemo, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';
import { Sparkles, Clock, Scale, MapPin, Plus, X, User } from 'lucide-react';
import { useUserStore, type UserProfile, type SavedProfile } from '../stores/user';
import { useSettingsStore } from '../stores/settings';
import { Card } from '../components/ui/Card';
import { Badge } from '../components/ui/Badge';
import { Button } from '../components/ui/Button';
import {
birthInfoToBazi, analyzeElementBalance, analyzeShensha, analyzeFortuneGanzhi, calculateBoneWeight, getDayInfo, getTodayInfo, getYearMonths,
checkStemCombine, checkStemOpposite, getBranchRelationship,
} from '@lunar/core';
import type { BaziFullResult, EightCharInfo, PillarInfo, FortuneLuck } from '@lunar/core';
const TP = [
['子','23-01',0],['丑','01-03',2],['寅','03-05',4],['卯','05-07',6],
['辰','07-09',8],['巳','09-11',10],['午','11-13',12],['未','13-15',14],
['申','15-17',16],['酉','17-19',18],['戌','19-21',20],['亥','21-23',22],
] as const;
const PROVINCES: { name: string; lng: number }[] = [
{ name:'北京', lng:116.4 }, { name:'上海', lng:121.5 }, { name:'天津', lng:117.2 }, { name:'重庆', lng:106.5 },
{ name:'石家庄', lng:114.5 }, { name:'太原', lng:112.5 }, { name:'呼和浩特', lng:111.7 }, { name:'沈阳', lng:123.4 },
{ name:'长春', lng:125.3 }, { name:'哈尔滨', lng:126.6 }, { name:'南京', lng:118.8 }, { name:'杭州', lng:120.2 },
{ name:'合肥', lng:117.3 }, { name:'福州', lng:119.3 }, { name:'南昌', lng:115.9 }, { name:'济南', lng:117.0 },
{ name:'郑州', lng:113.7 }, { name:'武汉', lng:114.3 }, { name:'长沙', lng:113.0 }, { name:'广州', lng:113.3 },
{ name:'南宁', lng:108.3 }, { name:'海口', lng:110.3 }, { name:'成都', lng:104.1 }, { name:'贵阳', lng:106.7 },
{ name:'昆明', lng:102.7 }, { name:'拉萨', lng:91.1 }, { name:'西安', lng:108.9 }, { name:'兰州', lng:103.8 },
{ name:'西宁', lng:101.8 }, { name:'银川', lng:106.2 }, { name:'乌鲁木齐', lng:87.6 }, { name:'台北', lng:121.5 },
{ name:'香港', lng:114.2 }, { name:'澳门', lng:113.5 },
];
const TIMEZONES: number[] = [-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,3.5,4,4.5,5,5.5,6,6.5,7,8,9,9.5,10,11,12,13,14];
const TZ_EXAMPLES: Record<number, string> = {
'-5': '纽约/多伦多', '-8': '洛杉矶/温哥华', '0': '伦敦', '1': '巴黎/柏林', '9': '东京/首尔',
'7': '曼谷/雅加达', '10': '悉尼/墨尔本', '13': '奥克兰', '4': '迪拜', '5.5': '新德里', '6.5': '仰光',
};
function fmtTz(tz: number): string {
const sign = tz >= 0 ? '+' : '-';
const abs = Math.abs(tz);
const h = Math.floor(abs);
const m = Math.round((abs - h) * 60);
return `UTC${sign}${h}${m ? ':' + String(m).padStart(2, '0') : ''}`;
}
const PK = ['year','month','day','hour'] as const;
const PL: Record<string,string> = { year:'年柱', month:'月柱', day:'日柱', hour:'时柱' };
const EC: Record<string,string> = { '木':'#4CAF50','火':'#E53935','土':'#F9A825','金':'#90A4AE','水':'#1E88E5' };
const ET: Record<string,string> = { '木':'text-green-700 dark:text-green-400','火':'text-red-700 dark:text-red-400','土':'text-amber-700 dark:text-amber-400','金':'text-slate-600 dark:text-slate-400','水':'text-blue-700 dark:text-blue-400' };
export default function BaziPage() {
const { profiles, activeIndex, activeProfile, activeBazi: baziResult, setActiveIndex,
updateProfile, addProfile, removeProfile, setBaziResult, setLoading, setError, isLoading, error } = useUserStore();
const ziHourSect = useSettingsStore(s => s.ziHourSect);
const solarTime = useSettingsStore(s => s.solarTime);
const defaultForm: UserProfile = activeProfile || { name:'', birthYear:1990, birthMonth:1, birthDay:1, birthHour:12, birthMinute:0, gender:'male', longitude:116.4 };
const [fd, setFd] = useState<UserProfile>(defaultForm);
useEffect(() => { if (activeProfile) setFd(activeProfile); }, [activeIndex]);
const update = (k: keyof UserProfile, v: string|number) => setFd(p => ({...p, [k]: v}));
const doCalc = useCallback(() => {
updateProfile(activeIndex, fd);
setLoading(true); setError(null);
try {
let h = fd.birthHour, min = fd.birthMinute;
let yy = fd.birthYear, mm = fd.birthMonth, dd = fd.birthDay;
let adjusted = false;
if (fd.tzOffset !== undefined && fd.tzOffset !== 8) {
// 海外出生:本地时间 → 北京时间(UTC+8),可能跨日
const d = new Date(Date.UTC(yy, mm - 1, dd, h, min) - (fd.tzOffset - 8) * 3600000);
yy = d.getUTCFullYear(); mm = d.getUTCMonth() + 1; dd = d.getUTCDate(); h = d.getUTCHours(); min = d.getUTCMinutes();
adjusted = true;
} else if (solarTime && fd.longitude && fd.longitude !== 120) {
// 中国城市:北京时间 → 真太阳时(经度校正),可能跨日
const offsetMin = Math.round((fd.longitude - 120) * 4);
const d = new Date(Date.UTC(yy, mm - 1, dd, h, min) + offsetMin * 60000);
yy = d.getUTCFullYear(); mm = d.getUTCMonth() + 1; dd = d.getUTCDate(); h = d.getUTCHours(); min = d.getUTCMinutes();
adjusted = true;
}
const r = birthInfoToBazi({ year: yy, month: mm, day: dd, hour: h, minute: min, gender: fd.gender, ziSect: ziHourSect });
r.solarAdjusted = adjusted;
setBaziResult(activeIndex, r);
} catch(e) { setError(e instanceof Error ? e.message : '计算失败'); }
}, [fd, activeIndex, ziHourSect, solarTime, updateProfile, setBaziResult, setLoading, setError]);
const solarAdjusted = baziResult?.solarAdjusted;
const profileLabel = (p: SavedProfile) =>
`${p.profile.gender==='male'?'♂':'♀'} ${p.profile.birthYear}/${p.profile.birthMonth}/${p.profile.birthDay}`;
return (
<div className="py-1 space-y-2 max-w-lg mx-auto">
{/* Header + profile tabs */}
<div className="flex items-center gap-1">
<h1 className="text-base font-bold font-chinese flex-1"></h1>
{profiles.length < 3 && (
<button onClick={() => addProfile({ name:'', birthYear:1990, birthMonth:1, birthDay:1, birthHour:12, birthMinute:0, gender:'male', longitude:116.4 })}
className="p-1.5 rounded-lg hover:bg-foreground/5 text-muted flex items-center gap-1 text-xs" title="新增八字">
<Plus size={14}/>
</button>
)}
</div>
{profiles.length > 0 && (
<div className="flex gap-1 overflow-x-auto pb-1">
{profiles.map((p, i) => (
<div key={i} onClick={() => setActiveIndex(i)}
className={`flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs whitespace-nowrap shrink-0 cursor-pointer transition-colors ${
i === activeIndex ? 'bg-primary text-white' : 'bg-card border border-border text-secondary hover:bg-foreground/5'
}`}>
<User size={11}/>
<span>{profileLabel(p)}</span>
{profiles.length > 1 && (
<button onClick={e => { e.stopPropagation(); removeProfile(i); }}
className="ml-0.5 p-0.5 rounded-full hover:bg-white/20"><X size={9}/></button>
)}
</div>
))}
</div>
)}
{/* Birth form */}
<Card padding="sm">
<div className="space-y-2">
{/* Year with stepper */}
<div>
<label className="text-[10px] text-muted block mb-1"></label>
<div className="flex items-center gap-1">
<button onClick={()=>update('birthYear',fd.birthYear-1)} className="px-2 py-2 rounded-lg border border-border hover:bg-foreground/5 text-sm"></button>
<span className="flex-1 text-center text-base font-bold font-chinese min-w-[50px]">{fd.birthYear}</span>
<button onClick={()=>update('birthYear',fd.birthYear+1)} className="px-2 py-2 rounded-lg border border-border hover:bg-foreground/5 text-sm">+</button>
<span className="text-xs text-muted mx-1"></span>
<select value={fd.birthMonth} onChange={e=>update('birthMonth',parseInt(e.target.value))}
className="flex-1 px-1 py-2 rounded-lg border border-border bg-background text-sm text-center">
{Array.from({length:12},(_,i)=><option key={i+1} value={i+1}>{i+1}</option>)}
</select>
<select value={fd.birthDay} onChange={e=>update('birthDay',parseInt(e.target.value))}
className="flex-1 px-1 py-2 rounded-lg border border-border bg-background text-sm text-center">
{Array.from({length:31},(_,i)=><option key={i+1} value={i+1}>{i+1}</option>)}
</select>
</div>
</div>
{/* Time */}
<div>
<label className="text-[10px] text-muted flex items-center gap-1 mb-1"><Clock size={10}/></label>
<div className="flex items-center gap-1.5 mb-2">
<select value={fd.birthHour} onChange={e=>update('birthHour',parseInt(e.target.value))}
className="flex-1 px-1 py-2 rounded-lg border border-border bg-background text-sm text-center">
{Array.from({length:24},(_,i)=><option key={i} value={i}>{String(i).padStart(2,'0')}</option>)}
</select>
<span className="text-muted font-bold">:</span>
<select value={fd.birthMinute} onChange={e=>update('birthMinute',parseInt(e.target.value))}
className="flex-1 px-1 py-2 rounded-lg border border-border bg-background text-sm text-center">
{Array.from({length:60},(_,i)=><option key={i} value={i}>{String(i).padStart(2,'0')}</option>)}
</select>
<span className="text-xs text-muted">:</span>
</div>
<div className="grid grid-cols-6 gap-1">
{TP.map(([l,range,h]) => {
const currentHourIdx = Math.floor(((fd.birthHour + 1) % 24) / 2);
const isActive = currentHourIdx === (h/2);
return (
<button key={h} type="button" onClick={()=>update('birthHour',h)}
className={`py-1 rounded text-[10px] text-center ${isActive ? 'bg-primary/10 text-primary font-medium ring-1 ring-primary/30' : 'text-muted'}`}>
{l}<span className="block text-[8px] opacity-60">{range}</span>
</button>
);
})}
</div>
</div>
{/* Birthplace */}
<div>
<label className="text-[10px] text-muted flex items-center gap-1 mb-1"><MapPin size={10}/></label>
<div className="flex gap-1.5 mb-2">
<button type="button" onClick={()=>setFd(f => ({...f, tzOffset: undefined, longitude: f.longitude ?? 116.4}))}
className={`flex-1 py-1.5 rounded-lg border text-[10px] ${fd.tzOffset === undefined ? 'border-primary bg-primary/5 text-primary' : 'border-border text-secondary'}`}></button>
<button type="button" onClick={()=>setFd(f => ({...f, longitude: undefined, tzOffset: f.tzOffset ?? -5}))}
className={`flex-1 py-1.5 rounded-lg border text-[10px] ${fd.tzOffset !== undefined ? 'border-primary bg-primary/5 text-primary' : 'border-border text-secondary'}`}></button>
</div>
{fd.tzOffset === undefined ? (
<select value={PROVINCES.find(p => p.lng === fd.longitude)?.name ?? '北京'}
onChange={e => { const p = PROVINCES.find(x => x.name === e.target.value); setFd(f => ({...f, longitude: p ? p.lng : f.longitude, tzOffset: undefined})); }}
className="w-full px-2 py-2 rounded-lg border border-border bg-background text-sm text-center">
{PROVINCES.map(p => <option key={p.name} value={p.name}>{p.name}</option>)}
</select>
) : (
<select value={fd.tzOffset}
onChange={e => setFd(f => ({...f, tzOffset: parseFloat(e.target.value), longitude: undefined}))}
className="w-full px-2 py-2 rounded-lg border border-border bg-background text-sm text-center">
{TIMEZONES.map(tz => <option key={tz} value={tz}>{fmtTz(tz)}{TZ_EXAMPLES[tz] ? `${TZ_EXAMPLES[tz]}` : ''}</option>)}
</select>
)}
{solarAdjusted && (
<p className="text-[9px] text-primary font-medium mt-1">
{fd.tzOffset !== undefined && fd.tzOffset !== 8
? `✓ 已按${fmtTz(fd.tzOffset)}换算为北京时间(UTC+8)排盘`
: fd.longitude && fd.longitude !== 120
? `✓ 已按${fd.longitude}°E换算真太阳时(比北京时间${fd.longitude > 120 ? '晚' : '早'}${Math.abs(Math.round((fd.longitude - 120) * 4))}分钟)`
: ''}
</p>
)}
</div>
<div className="flex gap-2">
<button onClick={()=>update('gender','male')} className={`flex-1 py-2 rounded-lg border text-xs font-medium ${fd.gender==='male'?'bg-blue-500 text-white border-blue-500':'border-border text-secondary'}`}> </button>
<button onClick={()=>update('gender','female')} className={`flex-1 py-2 rounded-lg border text-xs font-medium ${fd.gender==='female'?'bg-pink-500 text-white border-pink-500':'border-border text-secondary'}`}> </button>
</div>
{error && <p className="text-[11px] text-red-500 text-center">{error}</p>}
<Button variant="primary" size="md" className="w-full" onClick={doCalc} disabled={isLoading}>
{isLoading ? '计算中...' : <><Sparkles size={14} className="mr-1"/></>}
</Button>
</div>
</Card>
{baziResult && <BaziResult result={baziResult} birth={fd} />}
</div>
);
}
/* ========= RESULT ========= */
function BaziResult({ result, birth }: { result: BaziFullResult; birth: UserProfile }) {
const ec = result.eightChar;
const ep = useMemo(() => analyzeElementBalance(ec), [ec]);
const shensha = useMemo(() => analyzeShensha(ec), [ec]);
const today = useMemo(() => getTodayInfo(), []);
const decadeLuck = useMemo(
() => result.decadeFortunes.map(df => ({ ...df, luck: analyzeFortuneGanzhi(df.ganzhi, ec.dayMasterStem, ec.dayPillar.earthBranch) })),
[result, ec],
);
// —— 大运·流年·流月·流日 交互下钻 ——
const navigate = useNavigate();
const [selDecade, setSelDecade] = useState<number | null>(null);
const [selYear, setSelYear] = useState<number | null>(null);
const [selMonth, setSelMonth] = useState<number | null>(null);
const defaultDecadeIdx = Math.max(0, decadeLuck.findIndex(d => today.solarYear >= d.startYear && today.solarYear <= d.endYear));
const effDecadeIdx = selDecade ?? defaultDecadeIdx;
const effDecade = decadeLuck[effDecadeIdx] ?? decadeLuck[0];
const decadeYears = useMemo(() => {
if (!effDecade) return [];
const ys: { year: number; ganzhi: string; luck: FortuneLuck }[] = [];
for (let y = effDecade.startYear; y <= effDecade.endYear; y++) {
const gz = getDayInfo(y, 6, 15).lunarYearGanzhi;
ys.push({ year: y, ganzhi: gz, luck: analyzeFortuneGanzhi(gz, ec.dayMasterStem, ec.dayPillar.earthBranch) });
}
return ys;
}, [effDecade, ec]);
const effYear = selYear
?? Math.min(Math.max(today.solarYear, decadeYears[0]?.year ?? today.solarYear), decadeYears[decadeYears.length - 1]?.year ?? today.solarYear);
const selYearGanzhi = getDayInfo(effYear, 6, 15).lunarYearGanzhi;
const selYearLuck = useMemo(
() => analyzeFortuneGanzhi(selYearGanzhi, ec.dayMasterStem, ec.dayPillar.earthBranch),
[selYearGanzhi, ec],
);
const yearMonths = useMemo(
() => getYearMonths(effYear).map(m => ({ ...m, luck: analyzeFortuneGanzhi(m.ganzhi, ec.dayMasterStem, ec.dayPillar.earthBranch) })),
[effYear, ec],
);
const effMonthIdx = selMonth ?? Math.max(0, yearMonths.findIndex(m => today.solarDate >= m.startDate && today.solarDate <= m.endDate));
const effMonth = yearMonths[effMonthIdx];
const selMonthDays = useMemo(() => {
if (!effMonth) return [];
const [y1, m1, d1] = effMonth.startDate.split('-').map(Number);
const [y2, m2, d2] = effMonth.endDate.split('-').map(Number);
const days: { date: string; day: number; ganzhi: string; luck: FortuneLuck }[] = [];
const cur = new Date(y1, m1 - 1, d1);
const end = new Date(y2, m2 - 1, d2);
while (cur <= end) {
const di = getDayInfo(cur.getFullYear(), cur.getMonth() + 1, cur.getDate());
days.push({
date: di.solarDate,
day: di.solarDay,
ganzhi: di.lunarDayGanzhi,
luck: analyzeFortuneGanzhi(di.lunarDayGanzhi, ec.dayMasterStem, ec.dayPillar.earthBranch),
});
cur.setDate(cur.getDate() + 1);
}
return days;
}, [effMonth, ec]);
const bone = useMemo(() => {
try {
const yearGz = ec.yearPillar.ganzhi;
const sixtyCycle = ['甲子','乙丑','丙寅','丁卯','戊辰','己巳','庚午','辛未','壬申','癸酉','甲戌','乙亥','丙子','丁丑','戊寅','己卯','庚辰','辛巳','壬午','癸未','甲申','乙酉','丙戌','丁亥','戊子','己丑','庚寅','辛卯','壬辰','癸巳','甲午','乙未','丙申','丁酉','戊戌','己亥','庚子','辛丑','壬寅','癸卯','甲辰','乙巳','丙午','丁未','戊申','己酉','庚戌','辛亥','壬子','癸丑','甲寅','乙卯','丙辰','丁巳','戊午','己未','庚申','辛酉','壬戌','癸亥'];
const yearIdx = sixtyCycle.indexOf(yearGz);
const hi = Math.floor(((birth.birthHour + 1) % 24) / 2);
const di = getDayInfo(birth.birthYear, birth.birthMonth, birth.birthDay);
return calculateBoneWeight(yearIdx >= 0 ? yearIdx : 0, di.lunarMonth, di.lunarDay, hi);
} catch { return null; }
}, [ec, birth]);
const mingGe = useMemo(() => {
const dm = ec.dayMasterElement;
const counts: Record<string,number> = { '木':0,'火':0,'土':0,'金':0,'水':0 };
const pillars = PK.map(k => ec[`${k}Pillar` as keyof EightCharInfo] as PillarInfo);
for (const p of pillars) { counts[p.elementStem] = (counts[p.elementStem]||0)+1; counts[p.elementBranch] = (counts[p.elementBranch]||0)+1; }
const dmCount = counts[dm]||0;
let pattern = dmCount >= 4 ? `${dm}旺(身强)` : dmCount <= 2 ? `${dm}弱(身弱)` : `${dm}中和`;
const hasWater=counts['水']>=3, hasFire=counts['火']>=3, hasWood=counts['木']>=3, hasMetal=counts['金']>=3;
if (hasWater&&hasFire) pattern += ' · 水火既济';
else if (hasWood&&hasFire) pattern += ' · 木火通明';
else if (hasMetal&&hasWater) pattern += ' · 金水相生';
return pattern;
}, [ec]);
const siLing = useMemo(() => {
const mb = ec.monthPillar.earthBranch;
const be: Record<string,string> = { '寅':'木','卯':'木','辰':'土','巳':'火','午':'火','未':'土','申':'金','酉':'金','戌':'土','亥':'水','子':'水','丑':'土' };
const bs: Record<string,string> = { '寅':'甲','卯':'乙','辰':'戊','巳':'丙','午':'丁','未':'己','申':'庚','酉':'辛','戌':'戊','亥':'壬','子':'癸','丑':'己' };
return `月令${mb}${be[mb]||''})司令${bs[mb]||''}`;
}, [ec]);
return (
<motion.div className="space-y-2" initial={{opacity:0}} animate={{opacity:1}}>
<Card padding="sm" className="chinese-pattern">
<div className="text-center mb-2">
<span className="text-[10px] text-muted"> </span>
<span className="text-lg font-bold font-chinese text-primary">{ec.dayMaster}</span>
<span className="text-[10px] text-muted ml-2">{mingGe}</span>
</div>
<div className="grid grid-cols-4 gap-1.5">
{PK.map(k => {
const p = ec[`${k}Pillar` as keyof EightCharInfo] as PillarInfo;
return (
<div key={k} className={`text-center p-1.5 rounded-lg ${k==='day'?'ring-2 ring-primary bg-primary/[0.03]':'bg-background'}`}>
<p className="text-[10px] text-muted">{PL[k]}</p>
<p className="text-sm font-bold font-chinese">{p.heavenStem}{p.earthBranch}</p>
<p className="text-[9px] text-muted">{p.nayin}</p>
<p className="text-[9px]"><span className={ET[p.elementStem]||''}>{p.elementStem}</span>/<span className={ET[p.elementBranch]||''}>{p.elementBranch}</span></p>
</div>
);
})}
</div>
<div className="grid grid-cols-4 gap-1 mt-2 pt-2 border-t border-border text-center">
<div><p className="text-[9px] text-muted"></p><p className="text-[10px] font-chinese">{ec.fetalOrigin}</p></div>
<div><p className="text-[9px] text-muted"></p><p className="text-[10px] font-chinese">{ec.ownSign}</p></div>
<div><p className="text-[9px] text-muted"></p><p className="text-[10px] font-chinese">{ec.bodySign}</p></div>
<div><p className="text-[9px] text-muted"></p><p className="text-[10px] font-chinese">{ec.emptyBranches[0]||'-'}</p></div>
</div>
<div className="mt-2 pt-2 border-t border-border"><p className="text-[10px] text-muted text-center">{siLing}</p></div>
</Card>
{/* Interactions */}
<Card padding="sm">
<p className="text-xs font-medium mb-1"></p>
<div className="space-y-0.5">
{computeInteractions(ec).map((x) => (
<div key={x.key} className="flex items-center gap-1.5 py-0.5 px-1.5 rounded bg-background text-[10px]">
<span className="text-muted shrink-0 w-12">{x.pair}</span>
<span className="text-secondary flex-1">{x.detail}</span>
{x.significant && <span className={`text-[9px] font-medium ${x.good?'text-red-500':'text-slate-500'}`}>{x.good?'吉':'冲'}</span>}
</div>
))}
</div>
</Card>
<div className="grid grid-cols-2 gap-2">
<Card padding="sm">
<p className="text-xs font-medium mb-1"></p>
{PK.map(k => {
const p = ec[`${k}Pillar` as keyof EightCharInfo] as PillarInfo;
return <div key={k} className="flex justify-between py-0.5 px-1.5 rounded bg-background text-[10px]"><span className="text-muted">{PL[k]}</span><span className="font-chinese">{k==='day'?'日主':p.tenStar||'-'}</span></div>;
})}
</Card>
<Card padding="sm">
<p className="text-xs font-medium mb-1"></p>
{PK.map(k => {
const p = ec[`${k}Pillar` as keyof EightCharInfo] as PillarInfo;
return <div key={k} className="flex items-center gap-1 py-0.5 px-1.5 rounded bg-background text-[10px]"><span className="text-muted w-5">{PL[k]}</span><span className="font-medium">{p.earthBranch}</span><span className="text-muted"></span><span className="text-[9px]">{p.hideStems.map(h=>`${h.stem}(${h.type})`).join(' ')}</span></div>;
})}
</Card>
<Card padding="sm">
<p className="text-xs font-medium mb-1"> ({mingGe})</p>
{(['木','火','土','金','水'] as const).map(el => {
const c = ep[el.toLowerCase() as keyof typeof ep] as number;
const pct = ep.total>0?Math.round(c/ep.total*100):0;
return (
<div key={el} className="flex items-center gap-1.5 mb-1">
<span className="text-[10px] w-4 text-muted">{el}</span>
<div className="flex-1 h-2 bg-border rounded-full overflow-hidden">
<motion.div initial={{width:0}} animate={{width:`${Math.max(pct,2)}%`}} transition={{duration:0.5}} className="h-full rounded-full" style={{backgroundColor:EC[el]}}/>
</div>
<span className="text-[9px] text-muted w-10 text-right">{c} ({pct}%)</span>
</div>
);
})}
</Card>
</div>
{/* Shen Sha */}
{shensha.length > 0 && (
<Card padding="sm">
<p className="text-xs font-medium mb-1"> <span className="text-[9px] text-muted font-normal">{shensha.length}</span></p>
<div className="space-y-0.5">
{shensha.map(s => (
<div key={s.name} className="flex items-start gap-1.5 py-1 px-1.5 rounded bg-background text-[10px]">
<span className={`shrink-0 font-medium ${s.type==='吉'?'text-red-500':s.type==='凶'?'text-slate-500':'text-amber-600'}`}>{s.name}</span>
<span className="text-muted shrink-0">[{s.foundIn.join('、')}]</span>
<span className="text-secondary flex-1">{s.description}</span>
</div>
))}
</div>
<p className="text-[9px] text-muted mt-1.5"></p>
</Card>
)}
{/* 大运·流年·流月·流日(交互下钻) */}
<Card padding="sm">
<p className="text-xs font-medium mb-1">···</p>
<p className="text-[9px] text-muted mb-1">{result.childLimit.yearCount}{result.childLimit.monthCount}{result.childLimit.forward?'顺':'逆'}· </p>
{/* 大运 */}
<div className="flex gap-1 overflow-x-auto pb-1">
{decadeLuck.map((df, i) => (
<button key={df.index} onClick={() => { setSelDecade(i); setSelYear(null); setSelMonth(null); }}
className={`shrink-0 px-2 py-1 rounded-lg text-[10px] transition-colors ${effDecadeIdx===i?'bg-primary text-white':'bg-background border border-border text-secondary'}`}>
{df.ganzhi}<span className="opacity-70"> {df.startAge}-{df.endAge}</span>
</button>
))}
</div>
{/* 流年 */}
<div className="flex gap-1 overflow-x-auto pb-1 mt-1">
{decadeYears.map(y => (
<button key={y.year} onClick={() => { setSelYear(y.year); setSelMonth(null); }}
className={`shrink-0 px-2 py-1 rounded-lg text-[10px] transition-colors ${effYear===y.year?'bg-primary text-white':'bg-background border border-border text-secondary'}`}>
{y.year}<span className="opacity-70"> {y.ganzhi}</span>
</button>
))}
</div>
{/* 选中流年 vs 日主 */}
<div className="mt-1">
{selYearLuck && <LuckRow ganzhi={selYearLuck.ganzhi} meta={`${effYear}年 流年`} luck={selYearLuck} />}
</div>
{/* 流月 */}
<div className="flex gap-1 overflow-x-auto pb-1 mt-1">
{yearMonths.map((m, i) => (
<button key={m.index} onClick={() => setSelMonth(i)}
className={`shrink-0 px-2 py-1 rounded-lg text-[10px] transition-colors ${effMonthIdx===i?'bg-primary text-white':'bg-background border border-border text-secondary'}`}>
{m.name}<span className="opacity-70"> {m.ganzhi}</span>
</button>
))}
</div>
{/* 选中流月:每日流日 */}
{selMonthDays.length > 0 && effMonth && (
<div className="max-h-52 overflow-y-auto rounded-lg bg-background p-1 mt-1">
<p className="text-[9px] text-muted px-1 pb-1">{effMonth.name}{effMonth.startDate} ~ {effMonth.endDate}· </p>
<div className="grid grid-cols-3 gap-1">
{selMonthDays.map(d => (
<button key={d.date} onClick={() => navigate(`/calendar/${d.date}`)}
className="flex items-center gap-1 text-[9px] py-1 px-1 rounded bg-card border border-border hover:border-primary/40 text-left">
<span className={`w-1 h-1 rounded-full shrink-0 ${d.luck.level==='吉'?'bg-red-500':d.luck.level==='凶'?'bg-slate-500':'bg-amber-400'}`} />
<span className="font-medium shrink-0">{d.day}</span>
<span className="font-chinese">{d.ganzhi}</span>
<span className="text-muted truncate">{d.luck.tenStar || ''}</span>
</button>
))}
</div>
</div>
)}
</Card>
{bone && (
<Card padding="sm">
<p className="text-xs font-medium mb-1 flex items-center gap-1"><Scale size={12}/></p>
<div className="text-center"><span className="text-lg font-bold font-chinese">{bone.totalLiang}{bone.totalQian}</span><Badge size="sm" variant={bone.fortune.includes('上')?'lucky':'unlucky'} className="ml-2">{bone.fortune}</Badge>
<p className="text-[10px] text-secondary mt-1 leading-relaxed">{bone.interpretation}</p></div>
</Card>
)}
<Card padding="sm">
<p className="text-xs font-medium mb-1"></p>
<div className="grid grid-cols-4 gap-1 text-center">
{PK.map(k => {
const p = ec[`${k}Pillar` as keyof EightCharInfo] as PillarInfo;
return <div key={k}><p className="text-[9px] text-muted">{PL[k]}</p><p className={`text-[10px] font-chinese font-medium ${p.terrain.fortune==='good'?'text-red-500':p.terrain.fortune==='bad'?'text-slate-500':'text-secondary'}`}>{p.terrain.name||'-'}</p></div>;
})}
</div>
</Card>
</motion.div>
);
}
/* ====== HELPERS ====== */
interface PillarInteraction { key:string; pair:string; detail:string; significant:boolean; good:boolean; }
function computeInteractions(ec: EightCharInfo): PillarInteraction[] {
const r: PillarInteraction[] = [];
const pillars = PK.map(k => ec[`${k}Pillar` as keyof EightCharInfo] as PillarInfo);
const pairs = [[0,1,'年·月'],[0,2,'年·日'],[0,3,'年·时'],[1,2,'月·日'],[1,3,'月·时'],[2,3,'日·时']] as const;
for (const [a,b,name] of pairs) {
const pa=pillars[a], pb=pillars[b];
if (checkStemCombine(pa.heavenStem,pb.heavenStem)) r.push({key:`${name}-sc`,pair:name,detail:`天干五合:${pa.heavenStem}${pb.heavenStem}`,significant:true,good:true});
if (checkStemOpposite(pa.heavenStem,pb.heavenStem)) r.push({key:`${name}-so`,pair:name,detail:`天干相冲:${pa.heavenStem}${pb.heavenStem}`,significant:true,good:false});
const br = getBranchRelationship(pa.earthBranch,pb.earthBranch);
if (br.combine) r.push({key:`${name}-bc`,pair:name,detail:`地支六合:${pa.earthBranch}${pb.earthBranch}`,significant:true,good:true});
if (br.threeCombine&&br.formation) r.push({key:`${name}-b3`,pair:name,detail:`三合局${br.formation}${pa.earthBranch}${pb.earthBranch}`,significant:true,good:true});
if (br.opposite) r.push({key:`${name}-bo`,pair:name,detail:`地支六冲:${pa.earthBranch}${pb.earthBranch}`,significant:true,good:false});
if (br.harm) r.push({key:`${name}-bh`,pair:name,detail:`地支六害:${pa.earthBranch}${pb.earthBranch}`,significant:true,good:false});
if (br.punish) r.push({key:`${name}-bp`,pair:name,detail:`地支相刑:${pa.earthBranch}${pb.earthBranch}`,significant:true,good:false});
}
return r;
}
function LuckRow({ ganzhi, meta, luck }: { ganzhi: string; meta: string; luck: FortuneLuck }) {
const markers = [
luck.stemCombine || luck.branchCombine || luck.branchThreeCombine ? '合' : null,
luck.stemOpposite || luck.branchOpposite ? '冲' : null,
luck.branchHarm ? '害' : null,
luck.branchPunish ? '刑' : null,
].filter(Boolean);
return (
<div className="flex items-center gap-1 text-[10px] py-0.5 px-1 rounded bg-background">
<span className={`w-1.5 h-1.5 rounded-full shrink-0 ${luck.level==='吉'?'bg-red-500':luck.level==='凶'?'bg-slate-500':'bg-amber-400'}`} />
<span className="font-chinese font-medium shrink-0">{ganzhi}</span>
<span className="text-muted shrink-0">{meta}</span>
<span className="text-secondary truncate">{luck.tenStar ? `${luck.tenStar}·${luck.elementRelation}` : luck.elementRelation}</span>
{markers.length > 0 && <span className="text-slate-500 shrink-0">{markers.join('')}</span>}
</div>
);
}
-110
View File
@@ -1,110 +0,0 @@
import { useRef, useCallback, useMemo } from 'react';
import { motion } from 'framer-motion';
import { CalendarGrid } from '../components/calendar/CalendarGrid';
import { useCalendar } from '../hooks/useCalendar';
import { getTodayInfo, getAlmanacInfo, calculateDailyFortune } from '@lunar/core';
import { Badge } from '../components/ui/Badge';
import { useUserStore } from '../stores/user';
import { useBookmarkStore } from '../stores/bookmarks';
import { useNavigate } from 'react-router-dom';
export default function CalendarPage() {
const navigate = useNavigate();
const { viewDate, selectedDate, weekStart, days, goToToday, goToPrevMonth, goToNextMonth, goToPrevYear, goToNextYear, selectDate } = useCalendar();
const eightChar = useUserStore(s => s.eightChar);
const ec = eightChar;
const bookmarks = useBookmarkStore(s => s.items);
// Bookmarked dates as Set for quick lookup
const bookmarkedDates = useMemo(() => {
const set = new Set<string>();
for (const bm of bookmarks) {
if (!bm.isLunar) set.add(bm.solarDate);
else {
// For lunar recurring, find matching solar dates in current view
for (const week of days) {
for (const d of week) {
if (d.lunarMonth === bm.lunarMonth && d.lunarDay === bm.lunarDay && !d.isLeapMonth) {
set.add(d.solarDate);
}
}
}
}
}
return set;
}, [bookmarks, days]);
const touchRef = useRef({ startX: 0, startY: 0 });
const onTouchStart = useCallback((e: React.TouchEvent) => { touchRef.current = { startX: e.touches[0].clientX, startY: e.touches[0].clientY }; }, []);
const onTouchEnd = useCallback((e: React.TouchEvent) => {
const { startX, startY } = touchRef.current;
const dx = e.changedTouches[0].clientX - startX;
const dy = e.changedTouches[0].clientY - startY;
if (Math.abs(dx) > Math.abs(dy) && Math.abs(dx) > 50) {
if (dx > 0) goToPrevMonth(); else goToNextMonth();
}
}, [goToPrevMonth, goToNextMonth]);
// Today's quick summary
const todaySummary = useMemo(() => {
const now = new Date();
return { di: getTodayInfo(), al: getAlmanacInfo(now.getFullYear(), now.getMonth() + 1, now.getDate()) };
}, []);
// "回到今天" shows only when the viewed date is not today
const isViewingToday = useMemo(() => {
const now = new Date();
return (
viewDate.getFullYear() === now.getFullYear() &&
viewDate.getMonth() === now.getMonth() &&
viewDate.getDate() === now.getDate()
);
}, [viewDate]);
// Fortune scores for visible days (if user has bazi)
const fortuneScores = useMemo(() => {
if (!ec) return null;
const scores: Record<string, number> = {};
for (const week of days) {
for (const d of week) {
try {
const [y, m, day] = d.solarDate.split('-').map(Number);
scores[d.solarDate] = calculateDailyFortune(ec, new Date(y, m-1, day)).overallScore;
} catch { scores[d.solarDate] = 0; }
}
}
return scores;
}, [days, ec]);
return (
<motion.div className="py-1 space-y-2" onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>
{/* Today quick info — compact */}
<button onClick={() => navigate('/calendar/' + todaySummary.di.solarDate)}
className="w-full bg-card rounded-xl border border-border p-2.5 flex items-center justify-between gap-2 text-left hover:bg-foreground/[0.02] transition-colors">
<div className="min-w-0">
<p className="text-xs text-muted"></p>
<p className="text-sm font-bold font-chinese">{todaySummary.di.lunarMonthName}{todaySummary.di.lunarDayName}</p>
<p className="text-[10px] text-secondary truncate">{todaySummary.di.lunarYearGanzhi} · {todaySummary.al.dayGanzhi} · {todaySummary.al.duty}</p>
</div>
<div className="shrink-0 text-right">
<p className="text-[10px] text-muted">{todaySummary.al.nayin}</p>
<div className="flex gap-1 justify-end mt-0.5">
<Badge size="sm" variant="lucky">{todaySummary.al.twelveStar.name}</Badge>
</div>
</div>
</button>
<CalendarGrid days={days} viewDate={viewDate} selectedDate={selectedDate} weekStart={weekStart}
onPrevMonth={goToPrevMonth} onNextMonth={goToNextMonth}
onPrevYear={goToPrevYear} onNextYear={goToNextYear} onSelectDate={selectDate}
fortuneScores={fortuneScores} bookmarkedDates={bookmarkedDates} />
{/* Floating Today button */}
{!isViewingToday && (
<button onClick={goToToday}
className="fixed bottom-20 right-4 z-20 px-3 py-2 rounded-full bg-primary text-white text-xs font-medium shadow-lg hover:bg-primary-dark transition-colors">
</button>
)}
</motion.div>
);
}
@@ -1,197 +0,0 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Stars, AlertTriangle, ChevronLeft, ChevronRight, Sparkles } from 'lucide-react';
import { motion } from 'framer-motion';
import { useDailyFortune } from '../hooks/useDailyFortune';
import { useUserStore } from '../stores/user';
import { Badge } from '../components/ui/Badge';
import { Button } from '../components/ui/Button';
import { formatDate } from '../lib/utils';
import type { DailyFortuneResult } from '@lunar/core';
const LC: Record<string,{label:string;color:string;emoji:string}> = {
great:{label:'大吉',color:'#E53935',emoji:'🎉'}, good:{label:'吉',color:'#FB8C00',emoji:'👍'},
fair:{label:'平',color:'#FDD835',emoji:'😐'}, poor:{label:'凶',color:'#78909C',emoji:'😟'}, bad:{label:'大凶',color:'#424242',emoji:'⚠️'},
};
const RE: Record<string,string> = { '正印':'📚','偏印':'🧠','食神':'🎨','伤官':'💬','正财':'💰','偏财':'💎','正官':'👔','七杀':'⚔️','比肩':'🤝','劫财':'🏃' };
export default function DailyFortunePage() {
const navigate = useNavigate();
const [targetDate, setTargetDate] = useState(new Date());
const { fortune, needsProfile } = useDailyFortune(targetDate);
const profile = useUserStore(s => s.activeProfile);
const goToday = () => setTargetDate(new Date());
const goNext = () => { const d = new Date(targetDate); d.setDate(d.getDate()+1); setTargetDate(d); };
const goPrev = () => { const d = new Date(targetDate); d.setDate(d.getDate()-1); setTargetDate(d); };
const isToday = targetDate.toDateString() === new Date().toDateString();
if (needsProfile) {
return (
<motion.div initial={{opacity:0,y:20}} animate={{opacity:1,y:0}} className="py-10 text-center space-y-4">
<motion.div animate={{rotate:[0,10,-10,0]}} transition={{repeat:Infinity,duration:3}} className="w-16 h-16 mx-auto rounded-full bg-primary/10 flex items-center justify-center">
<Stars size={30} className="text-primary" />
</motion.div>
<h2 className="text-base font-bold font-chinese"></h2>
<p className="text-xs text-secondary max-w-xs mx-auto"></p>
<Button variant="primary" size="sm" onClick={() => navigate('/bazi')}><Sparkles size={14} className="mr-1"/></Button>
</motion.div>
);
}
return (
<div className="py-1 space-y-2 max-w-lg mx-auto">
<div className="flex items-center justify-between">
<h1 className="text-base font-bold font-chinese"></h1>
{profile && <Badge variant="outline" size="sm">{profile.gender==='male'?'♂':'♀'} {profile.birthYear}</Badge>}
</div>
{/* Date selector */}
<div className="flex items-center justify-between bg-card rounded-xl border border-border p-2">
<button onClick={goPrev} className="p-1.5 rounded-lg hover:bg-foreground/5"><ChevronLeft size={18}/></button>
<div className="text-center">
<button onClick={goToday} className="text-sm font-semibold font-chinese">{formatDate(targetDate)}</button>
<p className="text-[10px] text-muted">{isToday?'今天':''}</p>
</div>
<button onClick={goNext} className="p-1.5 rounded-lg hover:bg-foreground/5"><ChevronRight size={18}/></button>
</div>
{fortune && <FortuneView fortune={fortune} />}
</div>
);
}
function FortuneView({ fortune }: { fortune: DailyFortuneResult }) {
const cfg = LC[fortune.scoreLevel];
const pct = (fortune.overallScore+100)/2;
return (
<motion.div className="space-y-2" initial="initial" animate="animate" variants={{animate:{transition:{staggerChildren:0.05}}}}>
{/* Score card */}
<motion.div variants={{initial:{opacity:0,scale:0.95},animate:{opacity:1,scale:1}}}
className="bg-card rounded-xl border border-border p-3 text-center relative overflow-hidden">
<div className="absolute top-0 right-0 w-32 h-32 rounded-full" style={{background:`radial-gradient(circle,${cfg.color}08,transparent 70%)`}}/>
<div className="relative">
<p className="text-xs text-secondary">{fortune.lunarDate}</p>
<div className="relative w-20 h-20 mx-auto my-2">
<svg className="w-20 h-20 -rotate-90" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="42" fill="none" stroke="currentColor" className="text-border" strokeWidth="6"/>
<motion.circle cx="50" cy="50" r="42" fill="none" stroke={cfg.color} strokeWidth="6" strokeLinecap="round"
initial={{strokeDashoffset:2*Math.PI*42}} animate={{strokeDashoffset:2*Math.PI*42*(1-pct/100)}} transition={{duration:1,ease:'easeOut'}}
strokeDasharray={2*Math.PI*42}/>
</svg>
<div className="absolute inset-0 flex flex-col items-center justify-center">
<motion.span className="text-xl font-bold" initial={{opacity:0}} animate={{opacity:1}} transition={{delay:0.4}}>{fortune.overallScore}</motion.span>
<motion.span className="text-[10px] font-medium" style={{color:cfg.color}} initial={{opacity:0,y:4}} animate={{opacity:1,y:0}} transition={{delay:0.5}}>{cfg.emoji} {cfg.label}</motion.span>
</div>
</div>
</div>
</motion.div>
{/* Category Scores */}
<motion.div variants={{initial:{opacity:0,y:8},animate:{opacity:1,y:0}}}
className="bg-card rounded-xl border border-border p-2.5">
<p className="text-xs font-medium mb-2"></p>
<div className="grid grid-cols-4 gap-2 mb-2">
{([
{e:'💕',l:'爱情',s: fortune.categoryScores.love, hi:'感情运佳,适合约会表白', mid:'感情平稳,适合日常相处', lo:'感情需注意沟通,避免误会'},
{e:'💼',l:'事业',s: fortune.categoryScores.career, hi:'事业运势旺盛,适合推进重要项目', mid:'工作平稳,按部就班即可', lo:'职场多注意,避免冲突和失误'},
{e:'💰',l:'财运',s: fortune.categoryScores.wealth, hi:'财运亨通,适合投资理财', mid:'财运平稳,量入为出', lo:'财运低迷,避免大额支出'},
{e:'💪',l:'健康',s: fortune.categoryScores.health, hi:'精力充沛,适合运动锻炼', mid:'身体状态尚可,注意休息', lo:'容易疲劳,注意劳逸结合'},
] as const).map(({e,l,s,hi,mid,lo}) => (
<div key={l} className="text-center">
<p className="text-sm">{e}</p>
<p className="text-[10px] text-muted">{l}</p>
<p className={`text-xs font-bold ${s>=20?'text-red-500':s<=-20?'text-slate-500':'text-amber-500'}`}>{s}</p>
<div className="h-1 bg-border rounded-full mt-0.5 overflow-hidden">
<div className={`h-full rounded-full ${s>=20?'bg-red-500':s<=-20?'bg-slate-400':'bg-amber-400'}`} style={{width:`${(s+100)/2}%`}}/>
</div>
<p className="text-[9px] text-muted mt-0.5 leading-tight">{s>=20?hi:s<=-20?lo:mid}</p>
</div>
))}
</div>
</motion.div>
{/* Lucky Meta */}
<motion.div variants={{initial:{opacity:0,y:8},animate:{opacity:1,y:0}}}
className="bg-card rounded-xl border border-border p-2.5">
<p className="text-xs font-medium mb-2"></p>
<div className="grid grid-cols-3 gap-2 text-center">
<div className="p-2 rounded-lg bg-background">
<p className="text-[10px] text-muted mb-0.5"></p>
<div className="flex gap-1 justify-center">
{fortune.luckyMeta.colors.map(c => <Badge key={c} size="sm" variant="outline">{c}</Badge>)}
</div>
</div>
<div className="p-2 rounded-lg bg-background">
<p className="text-[10px] text-muted mb-0.5"></p>
<p className="text-sm font-bold font-chinese">{fortune.luckyMeta.numbers.join(' · ')}</p>
</div>
<div className="p-2 rounded-lg bg-background">
<p className="text-[10px] text-muted mb-0.5"></p>
<p className="text-sm font-chinese font-medium">{fortune.luckyMeta.direction}</p>
</div>
</div>
</motion.div>
{/* Pillar comparison */}
<motion.div variants={{initial:{opacity:0,y:8},animate:{opacity:1,y:0}}}
className="bg-card rounded-xl border border-border p-2.5">
<p className="text-xs font-medium mb-1.5"></p>
{fortune.pillarRelationships.map((rel,idx) => (
<motion.div key={rel.pillar} initial={{opacity:0,x:-8}} animate={{opacity:1,x:0}} transition={{delay:idx*0.04}}
className="flex items-center gap-2 py-1.5 px-2 rounded-lg bg-background mb-1 last:mb-0">
<span className="text-[10px] text-muted w-8 shrink-0">{rel.pillarLabel}</span>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1 text-[11px]">
<span className="font-chinese font-medium">{rel.userGanzhi}</span>
<span className="text-muted">vs</span>
<span className="font-chinese font-medium">{rel.dayGanzhi}</span>
</div>
<div className="flex flex-wrap gap-0.5 mt-0.5">
{rel.stemTenStar && <span className="text-[9px] text-secondary">{RE[rel.stemTenStar]||''}{rel.stemTenStar}</span>}
{rel.stemCombine && <span className="text-[9px] text-red-500 font-medium"></span>}
{rel.stemOpposite && <span className="text-[9px] text-slate-600 font-medium"></span>}
{rel.branchCombine && <span className="text-[9px] text-red-500 font-medium"></span>}
{rel.branchThreeCombine && <span className="text-[9px] text-green-500 font-medium">{rel.branchFormation}</span>}
{rel.branchOpposite && <span className="text-[9px] text-slate-600 font-medium"></span>}
{rel.branchHarm && <span className="text-[9px] text-amber-600 font-medium"></span>}
{rel.branchPunish && <span className="text-[9px] text-amber-600 font-medium"></span>}
</div>
</div>
<span className={`text-sm font-bold shrink-0 ${rel.score>0?'text-red-500':rel.score<0?'text-slate-500':'text-muted'}`}>
{rel.score>0?'+':''}{rel.score}
</span>
</motion.div>
))}
</motion.div>
{/* Lucky & Unlucky */}
<div className="grid grid-cols-1 gap-2">
<motion.div variants={{initial:{opacity:0,y:8},animate:{opacity:1,y:0}}}
className="bg-card rounded-xl border border-border p-2.5 border-l-[3px] border-l-red-500">
<p className="text-xs font-semibold text-red-500 mb-1.5 flex items-center gap-1"><Sparkles size={12}/>吉利</p>
{fortune.luckyAspects.map((a,i)=><p key={i} className="text-[11px] flex items-start gap-1 mb-1"><span className="text-red-500 shrink-0">✦</span>{a}</p>)}
</motion.div>
{fortune.unluckyAspects.length>0 && (
<motion.div variants={{initial:{opacity:0,y:8},animate:{opacity:1,y:0}}}
className="bg-card rounded-xl border border-border p-2.5 border-l-[3px] border-l-slate-400">
<p className="text-xs font-semibold text-slate-500 mb-1.5 flex items-center gap-1"><AlertTriangle size={12}/>注意</p>
{fortune.unluckyAspects.map((a,i)=><p key={i} className="text-[11px] flex items-start gap-1 mb-1 text-secondary"><span className="text-slate-400 shrink-0">⚠</span>{a}</p>)}
</motion.div>
)}
</div>
{/* Suggestions */}
<motion.div variants={{initial:{opacity:0,y:8},animate:{opacity:1,y:0}}}
className="bg-card rounded-xl border border-border p-2.5">
<p className="text-xs font-medium mb-1.5">今日建议</p>
{fortune.suggestions.map((s,i)=>(
<motion.div key={i} initial={{opacity:0,y:4}} animate={{opacity:1,y:0}} transition={{delay:0.06*i}}
className="flex items-center gap-2 py-1.5 px-2 rounded-lg bg-background mb-1 last:mb-0">
<span className="w-5 h-5 rounded-full bg-primary/10 text-primary text-[10px] font-bold flex items-center justify-center shrink-0">{i+1}</span>
<span className="text-[11px]">{s}</span>
</motion.div>
))}
</motion.div>
</motion.div>
);
}
@@ -1,225 +0,0 @@
import { useParams, useNavigate } from 'react-router-dom';
import { useMemo } from 'react';
import { ArrowLeft, ChevronLeft, ChevronRight, Moon, AlertTriangle, TrendingUp, Star } from 'lucide-react';
import { motion } from 'framer-motion';
import { getDayInfo, getAlmanacInfo, birthInfoToBazi, calculateDailyFortune } from '@lunar/core';
import { Badge } from '../components/ui/Badge';
import { Button } from '../components/ui/Button';
import { useUserStore } from '../stores/user';
import { useBookmarkStore } from '../stores/bookmarks';
import type { DailyFortuneResult } from '@lunar/core';
function dateAddDays(dateStr: string, days: number): string {
const [y, m, d] = dateStr.split('-').map(Number);
const dt = new Date(y, m - 1, d);
dt.setDate(dt.getDate() + days);
return `${dt.getFullYear()}-${String(dt.getMonth()+1).padStart(2,'0')}-${String(dt.getDate()).padStart(2,'0')}`;
}
export default function DayDetailPage() {
const { date } = useParams<{ date: string }>(); const navigate = useNavigate();
const eightChar = useUserStore(s => s.eightChar);
const ec = eightChar;
const { items: bookmarks, add: addBookmark, remove: removeBookmark } = useBookmarkStore();
const { dayInfo, almanac, dayBazi, prevDate, nextDate, fortune } = useMemo(() => {
if (!date) return { dayInfo: null, almanac: null, dayBazi: null, prevDate: null, nextDate: null, fortune: null };
const [y, m, d] = date.split('-').map(Number);
const bz = birthInfoToBazi({ year: y, month: m, day: d, hour: 12, minute: 0, gender: 'male' });
let ft: DailyFortuneResult | null = null;
if (ec) { try { ft = calculateDailyFortune(ec, new Date(y, m-1, d)); } catch { /* */ } }
return {
dayInfo: getDayInfo(y, m, d), almanac: getAlmanacInfo(y, m, d), dayBazi: bz.eightChar,
prevDate: dateAddDays(date, -1), nextDate: dateAddDays(date, 1), fortune: ft,
};
}, [date, ec]);
if (!dayInfo || !almanac) {
return <div className="py-8 text-center"><p className="text-secondary"></p><Button variant="ghost" className="mt-2" onClick={() => navigate('/calendar')}></Button></div>;
}
return (
<motion.div className="py-1 space-y-2" initial="initial" animate="animate">
{/* Navigation row */}
<div className="flex items-center justify-between">
<button onClick={() => navigate('/calendar')} className="flex items-center gap-1 text-xs text-secondary"><ArrowLeft size={14} /></button>
<div className="flex items-center gap-1">
{prevDate && <button onClick={() => navigate(`/calendar/${prevDate}`)} className="p-1 rounded hover:bg-foreground/5"><ChevronLeft size={16}/></button>}
<span className="text-xs text-muted px-1">{dayInfo.solarDate}</span>
{nextDate && <button onClick={() => navigate(`/calendar/${nextDate}`)} className="p-1 rounded hover:bg-foreground/5"><ChevronRight size={16}/></button>}
</div>
<div className="w-10" />
</div>
{/* Header */}
<div className="bg-card rounded-xl border border-border p-3 text-center chinese-pattern">
<p className="text-[11px] text-muted">{dayInfo.weekDay}</p>
<h1 className="text-xl font-bold font-chinese">{dayInfo.lunarMonthName}{dayInfo.lunarDayName}</h1>
<p className="text-xs text-secondary">{dayInfo.lunarYearGanzhi} · {dayInfo.zodiac} · {dayInfo.constellation}</p>
<BookmarkButton date={dayInfo.solarDate}
bookmarks={bookmarks} add={addBookmark} remove={removeBookmark} />
<div className="flex flex-wrap justify-center gap-1 mt-1">
{dayInfo.solarTerm && <Badge size="sm" variant="outline">{dayInfo.solarTerm}{dayInfo.solarTermTime ? ` ${dayInfo.solarTermTime}` : ''}</Badge>}
{dayInfo.lunarFestival && <Badge size="sm" variant="festival">{dayInfo.lunarFestival}</Badge>}
{dayInfo.buddhistFestival && <Badge size="sm" variant="festival">🪷 {dayInfo.buddhistFestival}</Badge>}
{dayInfo.moonPhase && <Badge size="sm" variant="outline"><Moon size={10} className="inline mr-0.5"/>{dayInfo.moonPhase}</Badge>}
</div>
</div>
{/* Personalized fortune (if user has bazi) */}
{fortune && (
<button onClick={() => navigate('/daily-fortune')} className="w-full bg-card rounded-xl border border-l-[3px] border-l-primary p-2.5 flex items-center justify-between gap-2 hover:bg-foreground/[0.02] transition-colors text-left">
<div className="min-w-0">
<p className="text-xs font-medium flex items-center gap-1"><TrendingUp size={12} className="text-primary"/></p>
<p className="text-[10px] text-secondary truncate mt-0.5">{fortune.luckyAspects[0]||fortune.suggestions[0]}</p>
</div>
<div className="shrink-0 text-center">
<span className={`text-lg font-bold ${fortune.overallScore>0?'text-red-500':fortune.overallScore<0?'text-slate-500':'text-muted'}`}>{fortune.overallScore}</span>
<p className="text-[9px] text-muted">{fortune.scoreLevel==='great'?'大吉':fortune.scoreLevel==='good'?'吉':fortune.scoreLevel==='bad'?'大凶':fortune.scoreLevel==='poor'?'凶':'平'}</p>
</div>
</button>
)}
{/* Day's Four Pillars */}
{dayBazi && (
<div className="bg-card rounded-xl border border-border p-2.5 text-center">
<p className="text-[10px] text-muted mb-1.5">当日四柱</p>
<div className="grid grid-cols-4 gap-1.5">
{[
['年', dayBazi.yearPillar.ganzhi],['月', dayBazi.monthPillar.ganzhi],
['日', dayBazi.dayPillar.ganzhi],['时', dayBazi.hourPillar.ganzhi],
].map(([l, v]) => (
<div key={l} className="py-1 rounded bg-background">
<p className="text-[9px] text-muted">{l}柱</p>
<p className="text-xs font-chinese font-bold">{v}</p>
</div>
))}
</div>
</div>
)}
{/* NaYin */}
<div className="bg-card rounded-xl border border-border p-2.5 text-center chinese-pattern">
<p className="text-[10px] text-muted">纳音</p>
<p className="text-2xl font-bold font-chinese text-primary">{almanac.nayin}</p>
<p className="text-xs text-secondary">{almanac.dayGanzhi} · {almanac.dayStem}{almanac.dayBranch}</p>
</div>
{/* Calendar extras */}
<div className="bg-card rounded-xl border border-border p-2.5">
<p className="text-[10px] text-muted mb-1.5">历法信息</p>
<div className="grid grid-cols-2 gap-x-3 gap-y-1 text-[10px]">
<span className="text-muted">季节</span><span>{dayInfo.season || '—'}</span>
<span className="text-muted">节气</span>
<span>
{dayInfo.currentSolarTerm
? `${dayInfo.currentSolarTerm} ${dayInfo.termDayIndex ?? '?'}${dayInfo.daysToNextTerm != null ? `(距${dayInfo.nextSolarTerm}还有${dayInfo.daysToNextTerm}天)` : ''}`
: '—'}
</span>
<span className="text-muted">儒略日</span><span>{dayInfo.julianDay ?? '—'}</span>
<span className="text-muted">佛历</span><span>{dayInfo.buddhistYear ? `${dayInfo.buddhistYear}` : '—'}</span>
<span className="text-muted">伊斯兰历</span><span>{dayInfo.hijriDate || '—'}</span>
</div>
</div>
{/* Stars grid */}
<div className="grid grid-cols-3 gap-1.5">
{[
['建除', almanac.duty], ['黄道', almanac.twelveStar.name], ['星宿', almanac.twentyEightStar.name],
['九星', almanac.nineStar.name], ['六曜', almanac.sixStar], ['小六壬', almanac.minorRen.name],
].map(([l, v]) => (
<div key={l as string} className="bg-card rounded-lg border border-border p-2 text-center">
<p className="text-[10px] text-muted">{l}</p><p className="text-xs font-chinese font-medium">{v}</p>
</div>
))}
</div>
{/* Chong Sha */}
<div className="bg-card rounded-xl border border-border p-2.5">
<p className="text-xs font-medium mb-1.5">冲·合·害·煞</p>
<div className="grid grid-cols-4 gap-1.5 text-center">
<div className="p-1.5 rounded bg-red-50 dark:bg-red-900/10"><p className="text-[10px] text-muted">冲</p><p className="text-xs font-bold">{almanac.clash}</p></div>
<div className="p-1.5 rounded bg-slate-50 dark:bg-slate-900/10"><p className="text-[10px] text-muted">煞</p><p className="text-xs font-bold">{almanac.evilDirection}</p></div>
<div className="p-1.5 rounded bg-red-50 dark:bg-red-900/10"><p className="text-[10px] text-muted">合</p><p className="text-xs font-bold">{almanac.combine}</p></div>
<div className="p-1.5 rounded bg-amber-50 dark:bg-amber-900/10"><p className="text-[10px] text-muted">害</p><p className="text-xs font-bold">{almanac.harm}</p></div>
</div>
</div>
{/* Yi Ji */}
<div className="grid grid-cols-2 gap-2">
<div className="bg-card rounded-xl border border-border p-2.5">
<p className="text-xs font-medium text-red-500 mb-1">宜</p>
<div className="flex flex-wrap gap-1">
{almanac.recommends.map((r,i)=><Badge key={i} variant="lucky" size="sm">{r}</Badge>)}
{almanac.recommends.length===0 && <span className="text-[10px] text-muted">无</span>}
</div>
</div>
<div className="bg-card rounded-xl border border-border p-2.5">
<p className="text-xs font-medium text-slate-500 mb-1">忌</p>
<div className="flex flex-wrap gap-1">
{almanac.avoids.map((a,i)=><Badge key={i} variant="unlucky" size="sm">{a}</Badge>)}
{almanac.avoids.length===0 && <span className="text-[10px] text-muted">无</span>}
</div>
</div>
</div>
{/* Gods */}
<div className="bg-card rounded-xl border border-border p-2.5">
<div className="grid grid-cols-2 gap-2">
<div><p className="text-xs font-medium text-red-500 mb-1">吉神</p>
<div className="flex flex-wrap gap-1">{almanac.goodGods.slice(0,6).map((g,i)=><Badge key={i} variant="lucky" size="sm">{g}</Badge>)}</div>
</div>
<div><p className="text-xs font-medium text-slate-500 mb-1">凶神</p>
<div className="flex flex-wrap gap-1">{almanac.badGods.slice(0,6).map((b,i)=><Badge key={i} variant="unlucky" size="sm">{b}</Badge>)}</div>
</div>
</div>
</div>
{/* PengZu + Fetus */}
<div className="bg-card rounded-xl border border-border p-2.5">
<div className="flex items-start gap-2">
<AlertTriangle size={14} className="text-amber-500 shrink-0 mt-0.5" />
<div>
<p className="text-xs font-medium">彭祖百忌</p>
<p className="text-[11px] text-secondary">{almanac.pengZu}</p>
<p className="text-[10px] text-muted">天干:{almanac.pengZuStem} · 地支:{almanac.pengZuBranch} · 胎神:{almanac.fetus.position}</p>
</div>
</div>
</div>
{/* Hourly */}
{almanac.hourDetails.length > 0 && (
<div className="bg-card rounded-xl border border-border p-2.5">
<p className="text-xs font-medium mb-1.5">时辰吉凶</p>
<div className="grid grid-cols-3 gap-1">
{almanac.hourDetails.map(h => (
<div key={h.ganzhi} className="text-center py-1 px-1 rounded bg-background">
<p className="text-[11px] font-chinese font-medium">{h.name}</p>
<p className="text-[10px] text-muted">{h.ganzhi}</p>
</div>
))}
</div>
</div>
)}
</motion.div>
);
}
function BookmarkButton({ date, bookmarks, add, remove }: {
date: string;
bookmarks: import('../stores/bookmarks').Bookmark[];
add: (b: Omit<import('../stores/bookmarks').Bookmark, 'id'>) => void;
remove: (id: string) => void;
}) {
const existing = bookmarks.find(b => b.solarDate === date);
const toggle = () => {
if (existing) { remove(existing.id); }
else { add({ solarDate: date, label: '', isLunar: false, color: '#E53935' }); }
};
return (
<button onClick={toggle} className={`mt-1 px-2 py-0.5 rounded-full text-[10px] inline-flex items-center gap-1 transition-colors ${existing ? 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400' : 'bg-background text-muted border border-border hover:border-amber-300'}`}>
<Star size={10} className={existing ? 'fill-amber-500 text-amber-500' : ''} />
{existing ? '已收藏' : '收藏'}
</button>
);
}
@@ -1,144 +0,0 @@
import { useMemo } from 'react';
import { motion } from 'framer-motion';
import { Compass, Scale } from 'lucide-react';
import { calculatePlumBlossom, calculateBoneWeight, getTodayInfo } from '@lunar/core';
import { Badge } from '../components/ui/Badge';
import { useUserStore } from '../stores/user';
// Hexagram line rendering
const TRIGRAM_BITS: Record<number, number[]> = {
1:[1,1,1],2:[1,1,0],3:[1,0,1],4:[1,0,0],5:[0,1,1],6:[0,1,0],7:[0,0,1],8:[0,0,0],
};
function HexagramLines({ upperIdx, lowerIdx, changingLine }: { upperIdx: number; lowerIdx: number; changingLine: number }) {
const upper = TRIGRAM_BITS[upperIdx] || [0,0,0];
const lower = TRIGRAM_BITS[lowerIdx] || [0,0,0];
// Lines from top (6) to bottom (1): upper[2],upper[1],upper[0], lower[2],lower[1],lower[0]
const lines = [upper[2], upper[1], upper[0], lower[2], lower[1], lower[0]];
return (
<div className="flex flex-col items-center gap-1 my-2">
{lines.map((isYang, i) => {
const lineNum = 6 - i; // line numbers: 6,5,4,3,2,1
const isChanging = lineNum === changingLine;
return (
<div key={i} className={`flex items-center gap-2 ${isChanging ? 'text-primary font-bold' : ''}`}>
<span className="text-[9px] text-muted w-4 text-right">{lineNum}</span>
{isYang ? (
<div className={`w-16 h-1.5 rounded-full ${isChanging ? 'bg-primary' : 'bg-foreground'}`} />
) : (
<div className="w-16 flex gap-1.5">
<div className={`flex-1 h-1.5 rounded-full ${isChanging ? 'bg-primary' : 'bg-foreground'}`} />
<div className={`flex-1 h-1.5 rounded-full ${isChanging ? 'bg-primary' : 'bg-foreground'}`} />
</div>
)}
{isChanging && <span className="text-[9px] text-primary"></span>}
</div>
);
})}
</div>
);
}
export default function DivinationPage() {
const ec = useUserStore(s => s.eightChar);
const { plum, bone } = useMemo(() => {
const now = new Date(); const y=now.getFullYear(), m=now.getMonth()+1, d=now.getDate(), h=now.getHours();
const plumResult = calculatePlumBlossom(y,m,d,h);
let boneResult = null;
if (ec) {
try {
const di = getTodayInfo();
const hi = Math.floor(((h+1)%24)/2);
const yi = getLunarYearIdx(ec.yearPillar.ganzhi);
boneResult = calculateBoneWeight(yi, di.lunarMonth, di.lunarDay, hi);
} catch { /* */ }
}
return { plum: plumResult, bone: boneResult };
}, [ec]);
return (
<div className="py-1 space-y-2 max-w-lg mx-auto">
<h1 className="text-base font-bold font-chinese"></h1>
{!ec && (
<motion.div initial={{opacity:0}} animate={{opacity:1}} className="text-center py-8">
<Compass size={32} className="mx-auto text-muted mb-2" />
<p className="text-sm text-secondary"></p>
<p className="text-xs text-muted mt-1"></p>
</motion.div>
)}
{/* 梅花易数 */}
{plum && (
<motion.div initial={{opacity:0,y:8}} animate={{opacity:1,y:0}} className="bg-card rounded-xl border border-border p-3">
<p className="text-xs font-medium mb-2 flex items-center gap-1"><Compass size={12}/> <span className="text-muted font-normal"></span></p>
<div className="flex items-center justify-center gap-4 mb-3">
<div className="text-center"><p className="text-[9px] text-muted"></p><p className="text-3xl">{plum.lowerTrigram.symbol}</p><p className="text-xs font-chinese font-medium">{plum.lowerTrigram.name}</p></div>
<span className="text-lg text-muted">+</span>
<div className="text-center"><p className="text-[9px] text-muted"></p><p className="text-3xl">{plum.upperTrigram.symbol}</p><p className="text-xs font-chinese font-medium">{plum.upperTrigram.name}</p></div>
<span className="text-lg text-muted">=</span>
<div className="text-center"><p className="text-[9px] text-muted"></p>
<div className="text-2xl">{plum.originalHexagram.upperTrigram.symbol}{plum.originalHexagram.lowerTrigram.symbol}</div>
<p className="text-xs font-bold font-chinese">{plum.originalHexagram.name}</p>
</div>
</div>
{/* Hexagram line visualization */}
<HexagramLines upperIdx={plum.upperTrigram.index} lowerIdx={plum.lowerTrigram.index} changingLine={plum.changingLine} />
<div className="grid grid-cols-3 gap-2 mb-3 p-2 rounded-lg bg-background text-center">
<div><p className="text-[9px] text-muted"></p><p className="text-xs font-chinese font-bold">{plum.originalHexagram.name}</p><p className="text-[9px] text-muted">{plum.originalHexagram.number}</p></div>
<div><p className="text-[9px] text-muted"></p><p className="text-xs font-chinese font-bold">{plum.mutualHexagram?.name||'—'}</p></div>
<div><p className="text-[9px] text-muted"></p><p className="text-xs font-chinese font-bold">{plum.transformedHexagram?.name||'—'}</p></div>
</div>
<div className="flex items-center justify-between p-2 rounded-lg bg-background mb-2 text-[10px]">
<span><span className="text-muted"></span>{plum.lowerTrigram.name}{plum.constitution}</span>
<span><span className="text-muted"></span>{plum.upperTrigram.name}{plum.function}</span>
<span className="text-muted">{plum.changingLine}</span>
</div>
<p className="text-[11px] text-secondary mb-2">{plum.relationship}</p>
<div className="space-y-1">
<p className="text-[10px] font-medium text-muted"></p>
<p className="text-[11px] text-secondary leading-relaxed">{plum.originalHexagram.judgment}</p>
<p className="text-[10px] font-medium text-muted mt-1"></p>
<p className="text-[11px] text-secondary leading-relaxed">{plum.originalHexagram.image}</p>
</div>
<div className="mt-2 space-y-0.5">
<p className="text-[10px] font-medium text-muted"></p>
{plum.originalHexagram.lines.map((line,i)=>line?(
<p key={i} className={`text-[10px] py-0.5 px-1.5 rounded ${i+1===plum.changingLine?'bg-primary/10 text-primary font-medium':''}`}>{i+1}{line}{i+1===plum.changingLine?' ←':''}</p>
):null)}
</div>
</motion.div>
)}
{/* 称骨 */}
{bone && (
<motion.div initial={{opacity:0,y:8}} animate={{opacity:1,y:0}} className="bg-card rounded-xl border border-border p-3">
<p className="text-xs font-medium mb-2 flex items-center gap-1"><Scale size={12}/></p>
<div className="grid grid-cols-4 gap-1.5 mb-3 text-center">
{[{l:'年',w:bone.yearWeight},{l:'月',w:bone.monthWeight},{l:'日',w:bone.dayWeight},{l:'时',w:bone.hourWeight}].map(x=>(
<div key={x.l} className="p-1.5 rounded bg-background"><p className="text-[9px] text-muted">{x.l}</p><p className="text-sm font-bold font-chinese">{x.w}<span className="text-[9px] font-normal"></span></p></div>
))}
</div>
<div className="text-center p-3 bg-primary/5 rounded-xl mb-2">
<p className="text-xl font-bold font-chinese">{bone.totalLiang}{bone.totalQian}</p>
<Badge size="sm" variant={bone.fortune.includes('上')?'lucky':'unlucky'} className="mt-1">{bone.fortune}</Badge>
</div>
<p className="text-[11px] text-secondary leading-relaxed">{bone.interpretation}</p>
</motion.div>
)}
</div>
);
}
function getLunarYearIdx(gz: string): number {
const t = ['甲子','乙丑','丙寅','丁卯','戊辰','己巳','庚午','辛未','壬申','癸酉','甲戌','乙亥','丙子','丁丑','戊寅','己卯','庚辰','辛巳','壬午','癸未','甲申','乙酉','丙戌','丁亥','戊子','己丑','庚寅','辛卯','壬辰','癸巳','甲午','乙未','丙申','丁酉','戊戌','己亥','庚子','辛丑','壬寅','癸卯','甲辰','乙巳','丙午','丁未','戊申','己酉','庚戌','辛亥','壬子','癸丑','甲寅','乙卯','丙辰','丁巳','戊午','己未','庚申','辛酉','壬戌','癸亥'];
return t.indexOf(gz);
}
-164
View File
@@ -1,164 +0,0 @@
import { useNavigate } from 'react-router-dom';
import { Stars, TrendingUp, CalendarDays, Sparkles, AlertTriangle, Compass } from 'lucide-react';
import { motion } from 'framer-motion';
import { getTodayInfo, getAlmanacInfo, calculateDailyFortune } from '@lunar/core';
import { useMemo } from 'react';
import { Badge } from '../components/ui/Badge';
import { useUserStore } from '../stores/user';
export default function HomePage() {
const navigate = useNavigate();
const eightChar = useUserStore(s => s.eightChar);
const { dayInfo, almanac, fortune } = useMemo(() => {
const now = new Date(); const y=now.getFullYear(), m=now.getMonth()+1, d=now.getDate();
const di = getTodayInfo(), al = getAlmanacInfo(y,m,d);
let ft = null; if (eightChar) { try { ft = calculateDailyFortune(eightChar, now); } catch { /* */ } }
return { dayInfo: di, almanac: al, fortune: ft };
}, [eightChar]);
const solarDate = `${dayInfo.solarYear}${dayInfo.solarMonth}${dayInfo.solarDay}日 星期${dayInfo.weekDay}`;
return (
<div className="py-1 space-y-2 max-w-lg mx-auto">
{/* === HERO: Today's lunar date === */}
<motion.div initial={{opacity:0,y:-6}} animate={{opacity:1,y:0}}
className="bg-card rounded-xl border border-border p-4 text-center chinese-pattern">
<p className="text-xs text-muted mb-1">{solarDate}</p>
<h1 className="text-3xl font-bold font-chinese text-primary">{dayInfo.lunarMonthName}{dayInfo.lunarDayName}</h1>
<p className="text-sm text-secondary mt-1 font-chinese">{dayInfo.lunarYearGanzhi} · {dayInfo.zodiac} · {almanac.dayGanzhi}</p>
<div className="flex flex-wrap justify-center gap-1.5 mt-2">
{dayInfo.solarTerm && <Badge size="sm" variant="outline">🌿 {dayInfo.solarTerm}</Badge>}
{dayInfo.lunarFestival && <Badge size="sm" variant="festival">{dayInfo.lunarFestival}</Badge>}
{dayInfo.solarFestival && <Badge size="sm" variant="festival">{dayInfo.solarFestival}</Badge>}
{dayInfo.moonPhase && <Badge size="sm" variant="outline">{dayInfo.moonPhase}</Badge>}
</div>
</motion.div>
{/* === FORTUNE (if bazi set) === */}
{fortune ? (
<motion.div initial={{opacity:0}} animate={{opacity:1}} className="space-y-2">
{/* Score + quick actions */}
<div className="flex items-center gap-3 bg-card rounded-xl border border-border p-3">
<button onClick={()=>navigate('/daily-fortune')} className="shrink-0 text-center">
<div className="relative w-16 h-16"><ScoreRing score={fortune.overallScore}/></div>
<span className="text-[10px] text-muted"></span>
</button>
<div className="min-w-0 flex-1">
<p className="text-sm font-semibold flex items-center gap-1"><Sparkles size={14} className="text-primary"/></p>
<div className="text-xs text-secondary mt-1 space-y-0.5">
{fortune.luckyAspects.slice(0,1).map((a,i)=><p key={i} className="flex items-start gap-1"><span className="text-red-500"></span>{a}</p>)}
{fortune.unluckyAspects.slice(0,1).map((a,i)=><p key={i} className="flex items-start gap-1"><AlertTriangle size={10} className="text-amber-500 shrink-0 mt-0.5"/>{a}</p>)}
</div>
<div className="flex gap-2 mt-1.5 text-[10px] text-muted">
<span>🎨 {fortune.luckyMeta.colors[0]}</span>
<span>🔢 {fortune.luckyMeta.numbers.join('/')}</span>
<span>🧭 {fortune.luckyMeta.direction}</span>
</div>
</div>
</div>
</motion.div>
) : (
<motion.button initial={{opacity:0}} animate={{opacity:1}}
onClick={()=>navigate('/bazi')}
className="w-full bg-card rounded-xl border border-dashed border-border p-4 text-center hover:bg-foreground/[0.02] transition-colors">
<Stars size={24} className="mx-auto text-muted mb-2"/>
<p className="text-sm font-medium"></p>
<p className="text-xs text-muted mt-1"></p>
</motion.button>
)}
{/* === ALMANAC KEY INFO === */}
<motion.div initial={{opacity:0}} animate={{opacity:1}} className="grid grid-cols-2 gap-1.5">
<InfoCard label="建除" value={almanac.duty} sub={almanac.twelveStar.name} />
<InfoCard label="纳音" value={almanac.nayin} sub={almanac.dayGanzhi} />
<InfoCard label="冲煞" value={`${almanac.clash}`} sub={`${almanac.evilDirection}`} highlight />
<InfoCard label="二十八宿" value={almanac.twentyEightStar.name} sub={almanac.twentyEightStar.luck==='good'?'吉':'凶'} />
</motion.div>
{/* === YI JI === */}
<motion.div initial={{opacity:0}} animate={{opacity:1}} className="grid grid-cols-2 gap-2">
<div className="bg-card rounded-xl border border-border p-2.5">
<p className="text-xs font-medium text-red-500 mb-1"> {almanac.recommends.length > 0 && `· ${almanac.recommends.length}`}</p>
<div className="flex flex-wrap gap-1">
{almanac.recommends.slice(0,10).map((r,i)=><Badge key={i} variant="lucky" size="sm">{r}</Badge>)}
{almanac.recommends.length > 10 && <span className="text-[9px] text-muted self-center">{almanac.recommends.length}</span>}
{almanac.recommends.length===0 && <span className="text-[10px] text-muted"></span>}
</div>
</div>
<div className="bg-card rounded-xl border border-border p-2.5">
<p className="text-xs font-medium text-slate-500 mb-1"> {almanac.avoids.length > 0 && `· ${almanac.avoids.length}`}</p>
<div className="flex flex-wrap gap-1">
{almanac.avoids.slice(0,8).map((a,i)=><Badge key={i} variant="unlucky" size="sm">{a}</Badge>)}
{almanac.avoids.length > 8 && <span className="text-[9px] text-muted self-center">{almanac.avoids.length}</span>}
{almanac.avoids.length===0 && <span className="text-[10px] text-muted"></span>}
</div>
</div>
</motion.div>
{/* === QUICK NAV === */}
<motion.div initial={{opacity:0}} animate={{opacity:1}} className="grid grid-cols-4 gap-1.5">
<QuickBtn icon={<CalendarDays size={18}/>} label="日历" onClick={()=>navigate('/calendar')}/>
<QuickBtn icon={<Stars size={18}/>} label="八字" onClick={()=>navigate('/bazi')}/>
<QuickBtn icon={<TrendingUp size={18}/>} label="运势" onClick={()=>navigate('/daily-fortune')}/>
<QuickBtn icon={<Compass size={18}/>} label="占卜" onClick={()=>navigate('/divination')}/>
</motion.div>
<motion.div initial={{opacity:0}} animate={{opacity:1}} className="text-center">
<button onClick={()=>navigate('/solar-terms')} className="text-[10px] text-muted hover:text-primary transition-colors">
🌿 {dayInfo.solarYear}
</button>
</motion.div>
{/* === GODS === */}
<motion.div initial={{opacity:0}} animate={{opacity:1}} className="bg-card rounded-xl border border-border p-2.5">
<div className="flex items-center gap-2 text-xs">
<span className="text-red-500 shrink-0"></span>
<span className="text-secondary truncate">{almanac.goodGods.slice(0,5).join('、')||'无'}</span>
</div>
<div className="flex items-center gap-2 text-xs mt-1">
<span className="text-slate-500 shrink-0"></span>
<span className="text-secondary truncate">{almanac.badGods.slice(0,5).join('、')||'无'}</span>
</div>
<div className="flex items-center gap-2 text-xs mt-1">
<span className="text-muted shrink-0"></span>
<span className="text-secondary truncate">{almanac.pengZu}</span>
</div>
</motion.div>
</div>
);
}
function ScoreRing({ score }: { score: number }) {
const pct = (score+100)/2;
const color = score>=20?'#E53935':score<=-20?'#78909C':'#FB8C00';
const r=20; const c=2*Math.PI*r;
return (
<div className="relative w-16 h-16">
<svg className="w-16 h-16 -rotate-90" viewBox="0 0 48 48">
<circle cx="24" cy="24" r={r} fill="none" stroke="currentColor" className="text-border" strokeWidth="4"/>
<circle cx="24" cy="24" r={r} fill="none" stroke={color} strokeWidth="4" strokeLinecap="round"
strokeDasharray={c} strokeDashoffset={c*(1-pct/100)} className="transition-all duration-700"/>
</svg>
<span className="absolute inset-0 flex items-center justify-center text-sm font-bold">{score}</span>
</div>
);
}
function InfoCard({ label, value, sub, highlight }: { label: string; value: string; sub?: string; highlight?: boolean }) {
return (
<div className={`bg-card rounded-xl border p-2.5 text-center ${highlight?'border-primary/30':''}`}>
<p className="text-[10px] text-muted">{label}</p>
<p className={`text-sm font-bold font-chinese ${highlight?'text-primary':''}`}>{value}</p>
{sub && <p className="text-[10px] text-muted mt-0.5">{sub}</p>}
</div>
);
}
function QuickBtn({ icon, label, onClick }: { icon: React.ReactNode; label: string; onClick: () => void }) {
return (
<button onClick={onClick} className="flex flex-col items-center gap-1 py-3 rounded-xl bg-card border border-border hover:bg-foreground/5 transition-colors">
<span className="text-secondary">{icon}</span>
<span className="text-[10px] font-medium">{label}</span>
</button>
);
}
-145
View File
@@ -1,145 +0,0 @@
import { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useSettingsStore } from '../stores/settings';
import { useUserStore } from '../stores/user';
import { Button } from '../components/ui/Button';
import { getTodayInfo, getMonthCalendar } from '@lunar/core';
import { Sun, Moon, Monitor, Stars, Search, Trash2 } from 'lucide-react';
export default function SettingsPage() {
const navigate = useNavigate();
const { theme, weekStartDay, ziHourSect, solarTime, setTheme, setWeekStartDay, setZiHourSect, setSolarTime, resetDefaults } = useSettingsStore();
const { activeProfile: profile, activeBazi: baziResult, clearAll } = useUserStore();
const [lunarSearch, setLunarSearch] = useState({ month: 1, day: 1 });
// Find next occurrence of a lunar date
const lunarResult = useMemo(() => {
try {
const now = new Date();
const curYear = now.getFullYear();
// Search from current year forward
for (let y = curYear; y <= curYear + 3; y++) {
for (let m = 1; m <= 12; m++) {
const cal = getMonthCalendar(y, m);
for (const week of cal) {
for (const d of week) {
if (d.lunarMonth === lunarSearch.month && d.lunarDay === lunarSearch.day && !d.isLeapMonth && d.solarYear >= curYear) {
return { solarDate: d.solarDate, lunarName: `${d.lunarMonthName}${d.lunarDayName}`, ganzhi: d.lunarDayGanzhi };
}
}
}
}
}
return null;
} catch { return null; }
}, [lunarSearch]);
// Today's moon info
const moonInfo = useMemo(() => {
const di = getTodayInfo();
return { phase: di.moonPhase, solarTerm: di.solarTerm, phenology: di.phenology };
}, []);
const monthNames = ['正月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'];
const dayNames = ['初一','初二','初三','初四','初五','初六','初七','初八','初九','初十','十一','十二','十三','十四','十五','十六','十七','十八','十九','二十','廿一','廿二','廿三','廿四','廿五','廿六','廿七','廿八','廿九','三十'];
return (
<div className="py-1 space-y-2 max-w-lg mx-auto">
<h1 className="text-base font-bold font-chinese"></h1>
{/* Profile */}
<div className="bg-card rounded-xl border border-border p-2.5">
<p className="text-xs font-medium mb-2"></p>
{profile ? (
<div className="space-y-2">
<div className="flex items-center justify-between">
<div>
<p className="text-xs font-medium">{profile.gender==='male'?'♂':'♀'} {profile.birthYear}/{profile.birthMonth}/{profile.birthDay}</p>
{baziResult?.eightChar && <p className="text-[10px] text-muted"> <span className="text-primary font-medium">{baziResult.eightChar.dayMaster}</span></p>}
</div>
<div className="flex gap-1">
<button onClick={() => navigate('/bazi')} className="p-1.5 rounded-lg bg-background hover:bg-border/20"><Stars size={14} className="text-primary" /></button>
<button onClick={clearAll} className="p-1.5 rounded-lg bg-background hover:bg-border/20"><Trash2 size={14} className="text-muted" /></button>
</div>
</div>
<div className="flex gap-1.5">
<button onClick={() => navigate('/bazi')} className="flex-1 py-1.5 text-[10px] rounded-lg bg-background hover:bg-border/20"></button>
<button onClick={() => navigate('/daily-fortune')} className="flex-1 py-1.5 text-[10px] rounded-lg bg-background hover:bg-border/20"></button>
<button onClick={() => navigate('/divination')} className="flex-1 py-1.5 text-[10px] rounded-lg bg-background hover:bg-border/20"></button>
</div>
</div>
) : (
<div className="text-center py-2">
<p className="text-xs text-muted mb-1.5"></p>
<Button variant="primary" size="sm" onClick={() => navigate('/bazi')}></Button>
</div>
)}
</div>
{/* Lunar date finder */}
<div className="bg-card rounded-xl border border-border p-2.5">
<p className="text-xs font-medium mb-2 flex items-center gap-1"><Search size={12}/></p>
<div className="flex items-center gap-1.5 mb-2">
<select value={lunarSearch.month} onChange={e => setLunarSearch(p => ({...p, month: parseInt(e.target.value)}))}
className="px-2 py-1.5 rounded border border-border bg-background text-xs">
{monthNames.map((n,i) => <option key={i+1} value={i+1}>{n}</option>)}
</select>
<select value={lunarSearch.day} onChange={e => setLunarSearch(p => ({...p, day: parseInt(e.target.value)}))}
className="px-2 py-1.5 rounded border border-border bg-background text-xs">
{dayNames.map((n,i) => <option key={i+1} value={i+1}>{n}</option>)}
</select>
</div>
{lunarResult ? (
<button onClick={() => navigate(`/calendar/${lunarResult.solarDate}`)} className="w-full p-2 rounded-lg bg-background hover:bg-border/20 text-left">
<p className="text-xs font-medium">{lunarResult.lunarName}</p>
<p className="text-[10px] text-muted">{lunarResult.solarDate} · {lunarResult.ganzhi}</p>
</button>
) : (
<p className="text-[10px] text-muted text-center py-1"></p>
)}
</div>
{/* Moon & Phenology */}
<div className="bg-card rounded-xl border border-border p-2.5">
<p className="text-xs font-medium mb-1"></p>
<div className="flex items-center gap-3 text-xs">
<span>🌙 {moonInfo.phase || '-'}</span>
{moonInfo.solarTerm && <span>🌿 {moonInfo.solarTerm}</span>}
</div>
{moonInfo.phenology && <p className="text-[10px] text-muted mt-1">{moonInfo.phenology}</p>}
</div>
{/* Display */}
<div className="bg-card rounded-xl border border-border p-2.5">
<p className="text-xs font-medium mb-2"></p>
<div className="flex gap-1.5 mb-2">
<button onClick={()=>setTheme('light')} className={`flex-1 flex flex-col items-center gap-1 py-2 rounded-lg border text-[10px] ${theme==='light'?'border-primary bg-primary/5 text-primary':'border-border text-secondary'}`}><Sun size={14}/></button>
<button onClick={()=>setTheme('dark')} className={`flex-1 flex flex-col items-center gap-1 py-2 rounded-lg border text-[10px] ${theme==='dark'?'border-primary bg-primary/5 text-primary':'border-border text-secondary'}`}><Moon size={14}/></button>
<button onClick={()=>setTheme('system')} className={`flex-1 flex flex-col items-center gap-1 py-2 rounded-lg border text-[10px] ${theme==='system'?'border-primary bg-primary/5 text-primary':'border-border text-secondary'}`}><Monitor size={14}/></button>
</div>
<div className="flex gap-1.5">
<button onClick={()=>setWeekStartDay(0)} className={`flex-1 py-1.5 rounded-lg border text-[10px] ${weekStartDay===0?'border-primary bg-primary/5 text-primary':'border-border text-secondary'}`}></button>
<button onClick={()=>setWeekStartDay(1)} className={`flex-1 py-1.5 rounded-lg border text-[10px] ${weekStartDay===1?'border-primary bg-primary/5 text-primary':'border-border text-secondary'}`}></button>
</div>
<p className="text-xs font-medium mt-3 mb-1.5"></p>
<div className="flex gap-1.5">
<button onClick={()=>setZiHourSect('lateZiNextDay')} className={`flex-1 py-1.5 rounded-lg border text-[10px] ${ziHourSect==='lateZiNextDay'?'border-primary bg-primary/5 text-primary':'border-border text-secondary'}`}><br/>23</button>
<button onClick={()=>setZiHourSect('earlyZiSameDay')} className={`flex-1 py-1.5 rounded-lg border text-[10px] ${ziHourSect==='earlyZiSameDay'?'border-primary bg-primary/5 text-primary':'border-border text-secondary'}`}><br/>0</button>
</div>
<p className="text-[9px] text-muted mt-1">23:00 </p>
<p className="text-xs font-medium mt-3 mb-1.5"></p>
<div className="flex gap-1.5">
<button onClick={()=>setSolarTime(true)} className={`flex-1 py-1.5 rounded-lg border text-[10px] ${solarTime?'border-primary bg-primary/5 text-primary':'border-border text-secondary'}`}></button>
<button onClick={()=>setSolarTime(false)} className={`flex-1 py-1.5 rounded-lg border text-[10px] ${!solarTime?'border-primary bg-primary/5 text-primary':'border-border text-secondary'}`}></button>
</div>
<p className="text-[9px] text-muted mt-1"></p>
</div>
{/* About */}
<div className="text-center space-y-1">
<p className="text-[10px] text-muted"> v0.1.0 · tyme4ts · 64 · </p>
<button onClick={resetDefaults} className="text-[10px] text-muted hover:text-primary"></button>
</div>
</div>
);
}
@@ -1,71 +0,0 @@
import { useMemo, useState } from 'react';
import { motion } from 'framer-motion';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { getDayInfo } from '@lunar/core';
export default function SolarTermsPage() {
const [year, setYear] = useState(new Date().getFullYear());
const terms = useMemo(() => {
const result: { name: string; date: string; time: string; isJie: boolean; desc: string }[] = [];
const seen = new Set<string>();
// Scan through the year to find term days
for (let month = 1; month <= 12; month++) {
for (let day = 1; day <= 31; day++) {
try {
const di = getDayInfo(year, month, day);
if (di.isTermDay && di.solarTerm && !seen.has(di.solarTerm)) {
seen.add(di.solarTerm);
const isJie = ['立春','惊蛰','清明','立夏','芒种','小暑','立秋','白露','寒露','立冬','大雪','小寒'].includes(di.solarTerm);
result.push({
name: di.solarTerm,
date: di.solarDate,
time: di.solarTermTime || '',
isJie,
desc: di.phenology || '',
});
}
} catch { /* date invalid */ }
}
}
return result;
}, [year]);
return (
<div className="py-1 space-y-2 max-w-lg mx-auto">
{/* Year picker */}
<div className="flex items-center justify-between">
<button onClick={()=>setYear(y=>y-1)} className="p-1.5 rounded-lg hover:bg-foreground/5"><ChevronLeft size={18}/></button>
<h1 className="text-base font-bold font-chinese">{year} </h1>
<button onClick={()=>setYear(y=>y+1)} className="p-1.5 rounded-lg hover:bg-foreground/5"><ChevronRight size={18}/></button>
</div>
{/* Terms list */}
<motion.div className="bg-card rounded-xl border border-border overflow-hidden" initial={{opacity:0}} animate={{opacity:1}}>
{terms.map((term, idx) => (
<motion.div
key={term.name}
initial={{opacity:0,x:-8}}
animate={{opacity:1,x:0}}
transition={{delay:idx*0.02}}
className={`flex items-center justify-between px-3 py-2.5 border-b border-border/50 last:border-0 ${
term.isJie ? 'bg-primary/[0.02]' : ''
}`}
>
<div className="flex items-center gap-2">
<span className={`text-xs font-medium w-10 ${term.isJie?'text-primary':'text-green-600'}`}>
{term.isJie ? '节' : '气'}
</span>
<span className="text-sm font-chinese font-medium">{term.name}</span>
</div>
<div className="text-right">
<p className="text-xs text-secondary">{term.date}</p>
<p className="text-[10px] text-muted">{term.time}</p>
{term.desc && <p className="text-[9px] text-muted">{term.desc}</p>}
</div>
</motion.div>
))}
</motion.div>
</div>
);
}
-33
View File
@@ -1,33 +0,0 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
export interface Bookmark {
id: string;
solarDate: string; // YYYY-MM-DD
label: string; // 名称
lunarMonth?: number;
lunarDay?: number;
isLunar: boolean; // true = lunar recurring, false = solar fixed
color: string; // #C41E3A, #4CAF50, etc.
}
interface BookmarksState {
items: Bookmark[];
add: (b: Omit<Bookmark, 'id'>) => void;
remove: (id: string) => void;
getByDate: (solarDate: string) => Bookmark[];
getByLunarDate: (month: number, day: number) => Bookmark[];
}
export const useBookmarkStore = create<BookmarksState>()(
persist(
(set, get) => ({
items: [],
add: (b) => set(s => ({ items: [...s.items, { ...b, id: Date.now().toString(36)}] })),
remove: (id) => set(s => ({ items: s.items.filter(i => i.id !== id) })),
getByDate: (solarDate) => get().items.filter(i => !i.isLunar && i.solarDate === solarDate),
getByLunarDate: (month, day) => get().items.filter(i => i.isLunar && i.lunarMonth === month && i.lunarDay === day),
}),
{ name: 'lunar-bookmarks' },
),
);
-58
View File
@@ -1,58 +0,0 @@
import { create } from 'zustand';
interface CalendarState {
viewDate: Date;
selectedDate: Date | null;
weekStart: 0 | 1;
setViewDate: (d: Date) => void;
goToToday: () => void;
goToNextMonth: () => void;
goToPrevMonth: () => void;
goToNextYear: () => void;
goToPrevYear: () => void;
selectDate: (d: Date) => void;
clearSelection: () => void;
setWeekStart: (ws: 0 | 1) => void;
}
function getToday(): Date {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate());
}
export const useCalendarStore = create<CalendarState>((set, get) => ({
viewDate: getToday(),
selectedDate: getToday(),
weekStart: 0,
setViewDate: (d) => set({ viewDate: d }),
goToToday: () => set({ viewDate: getToday(), selectedDate: getToday() }),
goToNextMonth: () => {
const { viewDate } = get();
const d = new Date(viewDate);
d.setMonth(d.getMonth() + 1);
set({ viewDate: d });
},
goToPrevMonth: () => {
const { viewDate } = get();
const d = new Date(viewDate);
d.setMonth(d.getMonth() - 1);
set({ viewDate: d });
},
goToNextYear: () => {
const { viewDate } = get();
const d = new Date(viewDate);
d.setFullYear(d.getFullYear() + 1);
set({ viewDate: d });
},
goToPrevYear: () => {
const { viewDate } = get();
const d = new Date(viewDate);
d.setFullYear(d.getFullYear() - 1);
set({ viewDate: d });
},
selectDate: (d) => set({ selectedDate: d }),
clearSelection: () => set({ selectedDate: null }),
setWeekStart: (ws) => set({ weekStart: ws }),
}));
-92
View File
@@ -1,92 +0,0 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
type Theme = 'light' | 'dark' | 'system';
type ZiHourSect = 'earlyZiSameDay' | 'lateZiNextDay';
interface SettingsState {
theme: Theme;
weekStartDay: 0 | 1;
showLunar: boolean;
showSolarTerm: boolean;
showHoliday: boolean;
ziHourSect: ZiHourSect;
solarTime: boolean;
setTheme: (t: Theme) => void;
setWeekStartDay: (ws: 0 | 1) => void;
toggleShowLunar: () => void;
toggleShowSolarTerm: () => void;
toggleShowHoliday: () => void;
setZiHourSect: (s: ZiHourSect) => void;
setSolarTime: (v: boolean) => void;
resetDefaults: () => void;
}
function applyTheme(theme: Theme) {
const root = document.documentElement;
if (theme === 'dark') {
root.classList.add('dark');
} else if (theme === 'light') {
root.classList.remove('dark');
} else {
// system
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
root.classList.add('dark');
} else {
root.classList.remove('dark');
}
}
}
export const useSettingsStore = create<SettingsState>()(
persist(
(set, get) => ({
theme: 'system',
weekStartDay: 0,
showLunar: true,
showSolarTerm: true,
showHoliday: true,
ziHourSect: 'lateZiNextDay',
solarTime: true,
setTheme: (theme) => {
applyTheme(theme);
set({ theme });
},
setWeekStartDay: (ws) => set({ weekStartDay: ws }),
toggleShowLunar: () => set({ showLunar: !get().showLunar }),
toggleShowSolarTerm: () => set({ showSolarTerm: !get().showSolarTerm }),
toggleShowHoliday: () => set({ showHoliday: !get().showHoliday }),
setZiHourSect: (ziHourSect) => set({ ziHourSect }),
setSolarTime: (solarTime) => set({ solarTime }),
resetDefaults: () => {
applyTheme('system');
set({
theme: 'system',
weekStartDay: 0,
showLunar: true,
showSolarTerm: true,
showHoliday: true,
ziHourSect: 'lateZiNextDay',
solarTime: true,
});
},
}),
{
name: 'lunar-settings',
onRehydrateStorage: () => (state) => {
if (state) applyTheme(state.theme);
},
},
),
);
// Listen for system theme changes
if (typeof window !== 'undefined') {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
const { theme } = useSettingsStore.getState();
if (theme === 'system') applyTheme('system');
});
}
-37
View File
@@ -1,37 +0,0 @@
import { create } from 'zustand';
interface UIState {
isSideNavOpen: boolean;
isMobile: boolean;
activeTab: string;
showDayDetail: boolean;
toggleSideNav: () => void;
closeSideNav: () => void;
setMobile: (v: boolean) => void;
setActiveTab: (t: string) => void;
openDayDetail: () => void;
closeDayDetail: () => void;
}
export const useUIStore = create<UIState>((set) => ({
isSideNavOpen: false,
isMobile: typeof window !== 'undefined' ? window.innerWidth < 768 : false,
activeTab: 'calendar',
showDayDetail: false,
toggleSideNav: () => set((s) => ({ isSideNavOpen: !s.isSideNavOpen })),
closeSideNav: () => set({ isSideNavOpen: false }),
setMobile: (v) => set({ isMobile: v }),
setActiveTab: (t) => set({ activeTab: t }),
openDayDetail: () => set({ showDayDetail: true }),
closeDayDetail: () => set({ showDayDetail: false }),
}));
// Listen for resize to update mobile state
if (typeof window !== 'undefined') {
window.addEventListener('resize', () => {
const isMobile = window.innerWidth < 768;
useUIStore.getState().setMobile(isMobile);
});
}
-120
View File
@@ -1,120 +0,0 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { EightCharInfo, BaziFullResult } from '@lunar/core';
export interface UserProfile {
name: string;
birthYear: number;
birthMonth: number;
birthDay: number;
birthHour: number;
birthMinute: number;
gender: 'male' | 'female';
longitude?: number;
/** UTC 时区偏移(小时),海外出生时填写;缺省按北京时间 UTC+8 排盘 */
tzOffset?: number;
}
export interface SavedProfile {
profile: UserProfile;
baziResult: BaziFullResult | null;
}
interface UserState {
profiles: SavedProfile[];
activeIndex: number;
isLoading: boolean;
error: string | null;
// Current active profile convenience
activeProfile: UserProfile | null;
activeBazi: BaziFullResult | null;
eightChar: EightCharInfo | null;
// Actions
addProfile: (profile: UserProfile) => void;
updateProfile: (index: number, profile: UserProfile) => void;
removeProfile: (index: number) => void;
setActiveIndex: (index: number) => void;
setBaziResult: (index: number, result: BaziFullResult) => void;
setLoading: (loading: boolean) => void;
setError: (error: string | null) => void;
clearAll: () => void;
}
function deriveActive(state: Pick<UserState, 'profiles' | 'activeIndex'>) {
const p = state.profiles[state.activeIndex];
return {
activeProfile: p?.profile || null,
activeBazi: p?.baziResult || null,
eightChar: p?.baziResult?.eightChar || null,
};
}
export const useUserStore = create<UserState>()(
persist(
(set, get) => ({
profiles: [],
activeIndex: 0,
isLoading: false,
error: null,
activeProfile: null,
activeBazi: null,
eightChar: null,
addProfile: (profile) => {
const { profiles } = get();
if (profiles.length >= 3) return; // max 3
const newProfiles = [...profiles, { profile, baziResult: null }];
const activeIndex = newProfiles.length - 1;
set({ profiles: newProfiles, activeIndex, ...deriveActive({ profiles: newProfiles, activeIndex }) });
},
updateProfile: (index, profile) => {
const { profiles } = get();
const newProfiles = [...profiles];
newProfiles[index] = { ...newProfiles[index], profile };
const activeIndex = get().activeIndex;
set({ profiles: newProfiles, ...deriveActive({ profiles: newProfiles, activeIndex }) });
},
removeProfile: (index) => {
const { profiles, activeIndex } = get();
const newProfiles = profiles.filter((_, i) => i !== index);
const newActive = activeIndex >= newProfiles.length ? Math.max(0, newProfiles.length - 1) : activeIndex;
set({ profiles: newProfiles, activeIndex: newActive, ...deriveActive({ profiles: newProfiles, activeIndex: newActive }) });
},
setActiveIndex: (index) => {
const { profiles } = get();
set({ activeIndex: index, ...deriveActive({ profiles, activeIndex: index }) });
},
setBaziResult: (index, result) => {
const { profiles, activeIndex } = get();
const newProfiles = [...profiles];
newProfiles[index] = { ...newProfiles[index], baziResult: result };
set({ profiles: newProfiles, isLoading: false, ...deriveActive({ profiles: newProfiles, activeIndex }) });
},
setLoading: (loading) => set({ isLoading: loading }),
setError: (error) => set({ error, isLoading: false }),
clearAll: () => set({ profiles: [], activeIndex: 0, isLoading: false, error: null, activeProfile: null, activeBazi: null, eightChar: null }),
}),
{
name: 'lunar-user-profiles',
partialize: (state) => ({
profiles: state.profiles,
activeIndex: state.activeIndex,
}),
onRehydrateStorage: () => (state) => {
if (state) {
const derived = deriveActive({ profiles: state.profiles, activeIndex: state.activeIndex });
state.activeProfile = derived.activeProfile;
state.activeBazi = derived.activeBazi;
state.eightChar = derived.eightChar;
}
},
},
),
);
-144
View File
@@ -1,144 +0,0 @@
@import "tailwindcss";
/* ===== Design Tokens ===== */
:root {
/* Primary palette: cinnabar red / gold */
--color-primary: #C41E3A;
--color-primary-light: #E85D75;
--color-primary-dark: #8B1A2B;
--color-accent: #D4A853;
--color-accent-light: #F0D68A;
/* Five Element colors */
--color-wood: #4CAF50;
--color-fire: #E53935;
--color-earth: #8D6E3F;
--color-metal: #B0BEC5;
--color-water: #1E88E5;
/* Semantic */
--color-lucky: #C41E3A;
--color-unlucky: #546E7A;
/* Surfaces */
--color-bg: #FFFBF5;
--color-bg-card: #FFFFFF;
--color-bg-elevated: #FFF8F0;
--color-border: #E8D5C4;
--color-text: #1A1A1A;
--color-text-secondary: #6B5E53;
--color-text-muted: #9E8E7E;
/* Fonts */
--font-sans: 'PingFang SC', 'Noto Sans SC', 'Hiragino Sans GB', system-ui, -apple-system, sans-serif;
--font-serif: 'Noto Serif SC', 'STSong', 'SimSun', 'Songti SC', serif;
--font-mono: 'SF Mono', 'JetBrains Mono', 'Fira Code', monospace;
/* Radii */
--radius-sm: 0.375rem;
--radius-md: 0.5rem;
--radius-lg: 0.75rem;
--radius-xl: 1rem;
}
.dark {
--color-primary: #E85D75;
--color-primary-light: #F48F9F;
--color-primary-dark: #B71C32;
--color-accent: #F0D68A;
--color-accent-light: #F5E6B8;
--color-bg: #1A1410;
--color-bg-card: #2A2218;
--color-bg-elevated: #3A2E20;
--color-border: #4A3A2A;
--color-text: #F5F0E8;
--color-text-secondary: #A09888;
--color-text-muted: #6B6058;
--color-lucky: #E85D75;
--color-unlucky: #78909C;
}
/* ===== Base Styles ===== */
@theme inline {
--color-background: var(--color-bg);
--color-foreground: var(--color-text);
--color-primary: var(--color-primary);
--color-primary-light: var(--color-primary-light);
--color-accent: var(--color-accent);
--color-card: var(--color-bg-card);
--color-border: var(--color-border);
--color-muted: var(--color-text-muted);
--color-secondary: var(--color-text-secondary);
--font-sans: var(--font-sans);
--font-serif: var(--font-serif);
--font-mono: var(--font-mono);
}
body {
font-family: var(--font-sans);
background-color: var(--color-bg);
color: var(--color-text);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
overflow-x: hidden;
}
/* Chinese pattern background for cards */
.chinese-pattern {
background-image:
radial-gradient(circle at 20% 20%, rgba(212, 168, 83, 0.04) 1px, transparent 1px),
radial-gradient(circle at 80% 80%, rgba(212, 168, 83, 0.04) 1px, transparent 1px);
background-size: 24px 24px, 24px 24px;
}
/* Serif font for Chinese titles */
.font-chinese {
font-family: var(--font-serif);
}
/* Calendar grid cell transition */
.calendar-cell {
transition: background-color 0.15s ease, transform 0.1s ease;
}
.calendar-cell:active {
transform: scale(0.95);
}
/* Scrollbar styling */
::-webkit-scrollbar {
width: 4px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: var(--color-border);
border-radius: 2px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--color-text-muted);
}
/* ===== Utility Classes ===== */
@utility container-page {
max-width: 480px;
margin-left: auto;
margin-right: auto;
padding-left: 1rem;
padding-right: 1rem;
}
@media (min-width: 768px) {
.container-page {
max-width: 768px;
}
}
@media (min-width: 1024px) {
.container-page {
max-width: 1024px;
padding-left: 2rem;
padding-right: 2rem;
}
}
-11
View File
@@ -1,11 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"jsx": "react-jsx",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"outDir": "./dist",
"rootDir": "./src",
"noEmit": true
},
"include": ["src"]
}
-62
View File
@@ -1,62 +0,0 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';
import { VitePWA } from 'vite-plugin-pwa';
import { resolve } from 'path';
export default defineConfig({
plugins: [
tailwindcss(),
react(),
VitePWA({
registerType: 'autoUpdate',
includeAssets: ['favicon.svg'],
manifest: {
name: '万年历 - 农历黄历八字运势',
short_name: '万年历',
description: '农历黄历、八字排盘、每日运势',
lang: 'zh-CN',
theme_color: '#FFFBF5',
background_color: '#FFFBF5',
display: 'standalone',
orientation: 'portrait',
start_url: '/',
icons: [
{
src: 'favicon.svg',
sizes: '64x64',
type: 'image/svg+xml',
},
],
},
workbox: {
globPatterns: ['**/*.{js,css,html,svg,png,woff2}'],
runtimeCaching: [
{
urlPattern: /^https:\/\/fonts\.googleapis\.com\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'google-fonts-cache',
expiration: { maxEntries: 10, maxAgeSeconds: 60 * 60 * 24 * 365 },
},
},
],
},
}),
],
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
},
conditions: ['development', 'browser'],
},
server: {
port: 4258,
strictPort: true,
open: true,
},
build: {
target: 'es2022',
sourcemap: true,
},
});
-5928
View File
File diff suppressed because it is too large Load Diff
-4
View File
@@ -1,4 +0,0 @@
packages:
- 'packages/*'
allowBuilds:
esbuild: true
-21
View File
@@ -1,21 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"isolatedModules": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true,
"useDefineForClassFields": true
}
}