index.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. import React, { useState, useRef } from 'react';
  2. import Head from 'next/head';
  3. import { snapdom } from '@zumer/snapdom';
  4. // TODO: 从这里引入怪怪的,但是先这样吧!
  5. import { type AIGeneratedMagicalGirl } from './api/generate-magical-girl';
  6. import { MainColor } from '../lib/main-color';
  7. import Link from 'next/link';
  8. import { useCooldown } from '../lib/cooldown';
  9. import { quickCheck } from '@/lib/sensitive-word-filter';
  10. import { useRouter } from 'next/router';
  11. interface MagicalGirl {
  12. realName: string;
  13. name: string;
  14. flowerDescription: string;
  15. appearance: {
  16. height: string;
  17. weight: string;
  18. hairColor: string;
  19. hairStyle: string;
  20. eyeColor: string;
  21. skinTone: string;
  22. wearing: string;
  23. specialFeature: string;
  24. mainColor: string; // 写法有点诡异,但是能用就行.jpg
  25. firstPageColor: string;
  26. secondPageColor: string;
  27. };
  28. spell: string;
  29. level: string;
  30. levelEmoji: string;
  31. }
  32. // 保留原有的 levels 数组和相关函数
  33. const levels = [
  34. { name: '种', emoji: '🌱' },
  35. { name: '芽', emoji: '🍃' },
  36. { name: '叶', emoji: '🌿' },
  37. { name: '蕾', emoji: '🌸' },
  38. { name: '花', emoji: '🌺' },
  39. { name: '宝石权杖', emoji: '💎' }
  40. ];
  41. // 定义8套渐变配色方案,与 MainColor 枚举顺序对应
  42. const gradientColors: Record<string, { first: string; second: string }> = {
  43. [MainColor.Red]: { first: '#ff6b6b', second: '#ee5a6f' },
  44. [MainColor.Orange]: { first: '#ff922b', second: '#ffa94d' },
  45. [MainColor.Cyan]: { first: '#22b8cf', second: '#66d9e8' },
  46. [MainColor.Blue]: { first: '#5c7cfa', second: '#748ffc' },
  47. [MainColor.Purple]: { first: '#9775fa', second: '#b197fc' },
  48. [MainColor.Pink]: { first: '#ff9a9e', second: '#fecfef' },
  49. [MainColor.Yellow]: { first: '#f59f00', second: '#fcc419' },
  50. [MainColor.Green]: { first: '#51cf66', second: '#8ce99a' }
  51. };
  52. function seedRandom(str: string): number {
  53. let hash = 0;
  54. for (let i = 0; i < str.length; i++) {
  55. const char = str.charCodeAt(i);
  56. hash = ((hash << 5) - hash) + char;
  57. hash = hash & hash;
  58. }
  59. return Math.abs(hash);
  60. }
  61. function getWeightedRandomFromSeed<T>(array: T[], weights: number[], seed: number, offset: number = 0): T {
  62. // 使用种子生成 0-1 之间的伪随机数
  63. const pseudoRandom = ((seed + offset) * 9301 + 49297) % 233280 / 233280.0;
  64. // 累计权重
  65. let cumulativeWeight = 0;
  66. const cumulativeWeights = weights.map(weight => cumulativeWeight += weight);
  67. const totalWeight = cumulativeWeights[cumulativeWeights.length - 1];
  68. // 找到对应的索引
  69. const randomValue = pseudoRandom * totalWeight;
  70. const index = cumulativeWeights.findIndex(weight => randomValue <= weight);
  71. return array[index >= 0 ? index : 0];
  72. }
  73. function checkNameLength(name: string): boolean {
  74. return name.length <= 300;
  75. }
  76. // 使用 API 路由生成魔法少女
  77. async function generateMagicalGirl(inputName: string): Promise<MagicalGirl> {
  78. try {
  79. const response = await fetch('/api/generate-magical-girl', {
  80. method: 'POST',
  81. headers: {
  82. 'Content-Type': 'application/json',
  83. },
  84. body: JSON.stringify({ name: inputName }),
  85. });
  86. if (!response.ok) {
  87. const error = await response.json();
  88. // 处理不同的 HTTP 状态码
  89. if (response.status === 429) {
  90. const retryAfter = error.retryAfter || 60;
  91. throw new Error(`请求过于频繁!请等待 ${retryAfter} 秒后再试。`);
  92. } else if (response.status >= 500) {
  93. throw new Error('服务器内部错误,请稍后重试');
  94. } else {
  95. throw new Error(error.message || error.error || '生成失败');
  96. }
  97. }
  98. const aiGenerated: AIGeneratedMagicalGirl = await response.json();
  99. // 等级概率配置: [种, 芽, 叶, 蕾, 花, 宝石权杖]
  100. const levelProbabilities = [0.1, 0.2, 0.3, 0.3, 0.07, 0.03];
  101. // 使用加权随机选择生成 level
  102. const seed = seedRandom(aiGenerated.flowerName + inputName);
  103. const level = getWeightedRandomFromSeed(levels, levelProbabilities, seed, 6);
  104. return {
  105. realName: inputName,
  106. name: aiGenerated.flowerName,
  107. flowerDescription: aiGenerated.flowerDescription,
  108. appearance: aiGenerated.appearance,
  109. spell: aiGenerated.spell,
  110. level: level.name,
  111. levelEmoji: level.emoji
  112. };
  113. } catch (error) {
  114. // 处理网络错误和其他异常
  115. if (error instanceof Error) {
  116. // 如果已经是我们抛出的错误,直接重新抛出
  117. if (error.message.includes('请求过于频繁') ||
  118. error.message.includes('服务器内部错误') ||
  119. error.message.includes('生成失败')) {
  120. throw error;
  121. }
  122. }
  123. // 处理网络连接错误
  124. if (error instanceof TypeError && error.message.includes('fetch')) {
  125. throw new Error('网络连接失败,请检查网络后重试');
  126. }
  127. // 其他未知错误
  128. throw new Error('生成魔法少女时发生未知错误,请重试');
  129. }
  130. }
  131. export default function Home() {
  132. const [inputName, setInputName] = useState('');
  133. const [magicalGirl, setMagicalGirl] = useState<MagicalGirl | null>(null);
  134. const [isGenerating, setIsGenerating] = useState(false);
  135. const [showImageModal, setShowImageModal] = useState(false);
  136. const [savedImageUrl, setSavedImageUrl] = useState<string | null>(null);
  137. const [error, setError] = useState<string | null>(null);
  138. const resultRef = useRef<HTMLDivElement>(null);
  139. const { isCooldown, startCooldown, remainingTime } = useCooldown('generateMagicalGirlCooldown', 60000);
  140. const router = useRouter();
  141. const handleGenerate = async () => {
  142. if (isCooldown) {
  143. setError(`请等待 ${remainingTime} 秒后再生成`);
  144. return;
  145. }
  146. if (!inputName.trim()) return;
  147. if (!checkNameLength(inputName)) {
  148. setError('名字太长啦,你怎么回事!');
  149. return;
  150. }
  151. // 检查敏感词
  152. const result = await quickCheck(inputName.trim());
  153. if (result.hasSensitiveWords) {
  154. router.push('/arrested');
  155. return;
  156. }
  157. setIsGenerating(true);
  158. setError(null); // 清除之前的错误
  159. try {
  160. const result = await generateMagicalGirl(inputName.trim());
  161. setMagicalGirl(result);
  162. setError(null); // 成功时清除错误
  163. } catch (error) {
  164. // 处理不同类型的错误
  165. if (error instanceof Error) {
  166. const errorMessage = error.message;
  167. // 检查是否是 rate limit 错误
  168. if (errorMessage.includes('请求过于频繁')) {
  169. setError('🚫 请求太频繁了!每2分钟只能生成一次魔法少女哦~请稍后再试吧!');
  170. } else if (errorMessage.includes('网络')) {
  171. setError('🌐 网络连接有问题!请检查网络后重试~');
  172. } else {
  173. setError(`✨ 魔法失效了!${errorMessage}`);
  174. }
  175. } else {
  176. setError('✨ 魔法失效了!可能是用的人太多狸!请再生成一次试试吧~');
  177. }
  178. } finally {
  179. setIsGenerating(false);
  180. startCooldown();
  181. }
  182. };
  183. const handleSaveImage = async () => {
  184. if (!resultRef.current) return;
  185. try {
  186. // 临时隐藏保存按钮和说明文字
  187. const saveButton = resultRef.current.querySelector('.save-button') as HTMLElement;
  188. const logoPlaceholder = resultRef.current.querySelector('.logo-placeholder') as HTMLElement;
  189. if (saveButton) saveButton.style.display = 'none';
  190. if (logoPlaceholder) logoPlaceholder.style.display = 'flex';
  191. const result = await snapdom(resultRef.current, {
  192. scale: 1,
  193. });
  194. // 恢复按钮显示
  195. if (saveButton) saveButton.style.display = 'block';
  196. if (logoPlaceholder) logoPlaceholder.style.display = 'none';
  197. // 获取 result.toPng() 生成的 HTMLImageElement 的图片 URL
  198. // toPng() 返回 Promise<HTMLImageElement>,可通过 .src 获取图片的 base64 url
  199. const imgElement = await result.toPng();
  200. const imageUrl = imgElement.src;
  201. setSavedImageUrl(imageUrl);
  202. setShowImageModal(true);
  203. } catch {
  204. alert('生成图片失败,请重试');
  205. // 确保在失败时也恢复按钮显示
  206. const saveButton = resultRef.current?.querySelector('.save-button') as HTMLElement;
  207. const logoPlaceholder = resultRef.current?.querySelector('.logo-placeholder') as HTMLElement;
  208. if (saveButton) saveButton.style.display = 'block';
  209. if (logoPlaceholder) logoPlaceholder.style.display = 'none';
  210. }
  211. };
  212. return (
  213. <>
  214. <Head>
  215. <link rel="preload" href="/logo.svg" as="image" type="image/svg+xml" />
  216. <link rel="preload" href="/logo-white.svg" as="image" type="image/svg+xml" />
  217. </Head>
  218. <div className="magic-background">
  219. <div className="container">
  220. <div className="card">
  221. <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', marginBottom: '1rem' }}>
  222. <img src="/logo.svg" width={250} height={160} alt="Logo" />
  223. </div>
  224. <p className="subtitle text-center">你是什么魔法少女呢!</p>
  225. <p className="subtitle text-center">
  226. 或者要不要来试试 <Link href="/details" className="footer-link">奇妙妖精大调查</Link>或 <Link href="/acg" className="footer-link">二次元魔法少女生成器</Link>?
  227. </p>
  228. <div style={{ marginTop: '1rem', marginBottom: '2rem', textAlign: 'center' }}>
  229. <p style={{ fontSize: '0.8rem', marginTop: '1rem', color: '#999', fontStyle: 'italic' }}>本测试设定来源于小说《下班,然后变成魔法少女》</p>
  230. <p style={{ fontSize: '0.8rem', marginTop: '0.2rem', color: '#999', fontStyle: '' }}><del>以及广告位募集中</del></p>
  231. <p style={{ fontSize: '0.8rem', marginTop: '0.2rem', color: '#999', fontStyle: '' }}><del>如有意向请联系魔法国度研究院院长 @祖母绿:1********</del></p>
  232. </div>
  233. <div className="input-group">
  234. <label htmlFor="name" className="input-label">
  235. 请输入你的名字:
  236. </label>
  237. <input
  238. id="name"
  239. type="text"
  240. value={inputName}
  241. onChange={(e) => setInputName(e.target.value)}
  242. className="input-field"
  243. placeholder="例如:鹿目圆香"
  244. onKeyDown={(e) => e.key === 'Enter' && handleGenerate()}
  245. />
  246. </div>
  247. <button
  248. onClick={handleGenerate}
  249. disabled={!inputName.trim() || isGenerating || isCooldown}
  250. className="generate-button"
  251. >
  252. {isCooldown
  253. ? `请等待 ${remainingTime} 秒`
  254. : isGenerating
  255. ? '少女创造中,请稍后捏 (≖ᴗ≖)✧✨'
  256. : 'へんしん(ノ゚▽゚)ノ! '}
  257. </button>
  258. {error && (
  259. <div className="error-message">
  260. {error}
  261. </div>
  262. )}
  263. {magicalGirl && (
  264. <div
  265. ref={resultRef}
  266. className="result-card"
  267. style={{
  268. background: (() => {
  269. const colors = gradientColors[magicalGirl.appearance.mainColor] || gradientColors[MainColor.Pink];
  270. return `linear-gradient(135deg, ${colors.first} 0%, ${colors.second} 100%)`;
  271. })()
  272. }}
  273. >
  274. <div className="result-content">
  275. <div className="flex justify-center items-center" style={{ marginBottom: '1rem', background: 'transparent' }}>
  276. <img src="/mahou-title.svg" width={300} height={70} alt="Logo" style={{ display: 'block', background: 'transparent' }} />
  277. </div>
  278. <div className="result-item">
  279. <div className="result-label">✨ 真名解放</div>
  280. <div className="result-value">{magicalGirl.realName}</div>
  281. </div>
  282. <div className="result-item">
  283. <div className="result-label">💝 魔法少女名</div>
  284. <div className="result-value">
  285. {magicalGirl.name}
  286. <div style={{ fontStyle: 'italic', marginTop: '8px', fontSize: '14px', opacity: 0.9 }}>
  287. 「{magicalGirl.flowerDescription}」
  288. </div>
  289. </div>
  290. </div>
  291. <div className="result-item">
  292. <div className="result-label">👗 外貌</div>
  293. <div className="result-value">
  294. 身高:{magicalGirl.appearance.height}<br />
  295. 体重:{magicalGirl.appearance.weight}<br />
  296. 发色:{magicalGirl.appearance.hairColor}<br />
  297. 发型:{magicalGirl.appearance.hairStyle}<br />
  298. 瞳色:{magicalGirl.appearance.eyeColor}<br />
  299. 肤色:{magicalGirl.appearance.skinTone}<br />
  300. 穿着:{magicalGirl.appearance.wearing}<br />
  301. 特征:{magicalGirl.appearance.specialFeature}
  302. </div>
  303. </div>
  304. <div className="result-item">
  305. <div className="result-label">✨ 变身咒语</div>
  306. <div className="result-value">
  307. <div style={{ whiteSpace: 'pre-line' }}>{magicalGirl.spell}</div>
  308. </div>
  309. </div>
  310. <div className="result-item">
  311. <div className="result-label">⭐ 魔法等级</div>
  312. <div className="result-value">
  313. <span className="level-badge">
  314. {magicalGirl.levelEmoji} {magicalGirl.level}
  315. </span>
  316. </div>
  317. </div>
  318. <button onClick={handleSaveImage} className="save-button">
  319. 📱 保存为图片
  320. </button>
  321. {/* Logo placeholder for saved images */}
  322. <div className="logo-placeholder" style={{ display: 'none', justifyContent: 'center', marginTop: '1rem' }}>
  323. <img
  324. src="/logo-white-qrcode.svg"
  325. width={320}
  326. height={80}
  327. alt="Logo"
  328. style={{
  329. display: 'block',
  330. maxWidth: '100%',
  331. height: 'auto'
  332. }}
  333. />
  334. </div>
  335. </div>
  336. </div>
  337. )}
  338. <div className="text-center w-full text-sm text-gray-500" style={{ marginTop: '8px' }}> 立绘生成功能开发中(大概)... </div>
  339. </div>
  340. <footer className="footer">
  341. <p>
  342. <a href="https://github.com/colasama" target="_blank" rel="noopener noreferrer" className="footer-link">@Colanns</a> 急速出品
  343. </p>
  344. <p>
  345. 本项目 AI 能力由&nbsp;
  346. <a href="https://github.com/KouriChat/KouriChat" target="_blank" rel="noopener noreferrer" className="footer-link">KouriChat</a> &&nbsp;
  347. <a href="https://api.kourichat.com/" target="_blank" rel="noopener noreferrer" className="footer-link">Kouri API</a>
  348. &nbsp;强力支持
  349. </p>
  350. <p>
  351. <a href="https://github.com/colasama/MahoShojo-Generator" target="_blank" rel="noopener noreferrer" className="footer-link">colasama/MahoShojo-Generator</a>
  352. </p>
  353. </footer>
  354. </div>
  355. {/* Image Modal */}
  356. {showImageModal && savedImageUrl && (
  357. <div className="fixed inset-0 bg-black flex items-center justify-center z-50"
  358. style={{ backgroundColor: 'rgba(0, 0, 0, 0.7)', paddingLeft: '2rem', paddingRight: '2rem' }}
  359. >
  360. <div className="bg-white rounded-lg max-w-lg w-full max-h-[80vh] overflow-auto relative">
  361. <div className="flex justify-between items-center m-0">
  362. <div></div>
  363. <button
  364. onClick={() => setShowImageModal(false)}
  365. className="text-gray-500 hover:text-gray-700 text-3xl leading-none"
  366. style={{ marginRight: '0.5rem' }}
  367. >
  368. ×
  369. </button>
  370. </div>
  371. <p className="text-center text-sm text-gray-600" style={{ marginTop: '0.5rem' }}>
  372. 💫 长按图片保存到相册
  373. </p>
  374. <div className="items-center flex flex-col" style={{ padding: '0.5rem' }}>
  375. <img
  376. src={savedImageUrl}
  377. alt="魔法少女登记表"
  378. className="w-1/2 h-auto rounded-lg mx-auto"
  379. />
  380. </div>
  381. </div>
  382. </div>
  383. )}
  384. </div>
  385. </>
  386. );
  387. }