88 lines
11 KiB
TypeScript
88 lines
11 KiB
TypeScript
import { api, type Color, type RealIdentity } from '../adapters/real';
|
||
import { newId } from '../domain/id';
|
||
import { useEffect, useRef, useState } from 'react';
|
||
import { validateCreation, type Identity } from '../domain/model';
|
||
import { freshState } from '../demo/fixtures';
|
||
import { delay } from '../adapters/demo';
|
||
import { BaseColor, Button, Field, Icon, Status } from '../shared/ui';
|
||
import type { DemoState } from '../domain/model';
|
||
const HOURS = ['子时', '丑时', '寅时', '卯时', '辰时', '巳时', '午时', '未时', '申时', '酉时', '戌时', '亥时'];
|
||
// A random birthday she could have: an adult of 19–35, any month, a day every month has, any hour.
|
||
function randomBirth(now = new Date()) {
|
||
const pick = (n: number) => Math.floor(Math.random() * n);
|
||
return { birth: `${now.getFullYear() - 19 - pick(17)}-${String(1 + pick(12)).padStart(2, '0')}-${String(1 + pick(28)).padStart(2, '0')}`, hour: HOURS[pick(12)] };
|
||
}
|
||
// What the left-hand story says at each moment of the first meeting (HEL-815).
|
||
const STORY: Record<string, [string, string]> = {
|
||
0: ['先给她一个名字,和一个属于她的生日。', '名字由你来起。生日可以随机,也可以由你指定。'],
|
||
1: ['这是她出生时带来的底色。', '底色只读。她以后的样子,由你们的相处慢慢长出来。'],
|
||
2: ['你们从什么关系开始?', '不替你选。以后也可以在设置里调整。'],
|
||
3: ['确认之后,她就住进来了。', '这件事只会发生一次。'],
|
||
run: ['她在收拾东西,马上就好。', '窗外的灯一直亮着。'],
|
||
fail: ['差一点就好了。', '你填的都还在。'],
|
||
4: ['她住进来了。', '去看看她吧。']
|
||
};
|
||
const RELATIONS: [string, string][] = [['朋友', '像朋友一样相处,慢慢熟起来。'], ['恋人', '从恋人开始,彼此更亲近一些。']];
|
||
export function CreationWizard({ onCreate, onEnter, fail, real = false }: {
|
||
real?: boolean;
|
||
onCreate: (s: DemoState) => void;
|
||
onEnter: () => void;
|
||
fail: boolean;
|
||
}) {
|
||
const [initial] = useState(randomBirth);
|
||
const [step, setStep] = useState(0), [name, setName] = useState(''), [birth, setBirth] = useState(initial.birth), [hour, setHour] = useState(initial.hour), [how, setHow] = useState<'random' | 'pick'>('random'), [relation, setRelation] = useState(''), [nickname, setNickname] = useState(''), [boundary, setBoundary] = useState(''), [agreed, setAgreed] = useState(false), [error, setError] = useState(''), [phase, setPhase] = useState(-1), [busy, setBusy] = useState(false), [back, setBack] = useState(false);
|
||
const [color, setColor] = useState<Color>();
|
||
const nameField = useRef<HTMLInputElement>(null), birthField = useRef<HTMLInputElement>(null), relationGroup = useRef<HTMLDivElement>(null);
|
||
const labels = ['出生资料', '她的底色', '你们的关系', '最终确认'];
|
||
const field = error.includes('名字') ? 'name' : error.includes('出生') ? 'birth' : error.includes('关系') ? 'relation' : '';
|
||
// A rejected step puts the cursor where the problem is, so the next key fixes it.
|
||
useEffect(() => { if (field === 'name') nameField.current?.focus(); else if (field === 'birth') birthField.current?.focus(); else if (field === 'relation') relationGroup.current?.querySelector('button')?.focus(); }, [field, error]);
|
||
const go = (to: number) => { setBack(to < step); setStep(to); };
|
||
async function next() { const err = validateCreation(name, birth, step === 2 ? relation : '朋友'); if (err) {
|
||
setError(err);
|
||
return;
|
||
} setError(''); if (real && step === 0) { setBusy(true); try { setColor(await api<Color>('companion/preview', { method: 'POST', body: JSON.stringify({ name, birth, hour }) })); } catch (e) { setError((e as Error).message); return; } finally { setBusy(false); } } go(step + 1); }
|
||
async function create() { const err = validateCreation(name, birth, relation); if (err || !agreed) {
|
||
setError(err || '请先确认你已了解。');
|
||
return;
|
||
} setBusy(true); setError(''); try {
|
||
if (real) {
|
||
setPhase(0);
|
||
const identity = await api<RealIdentity>('companion', { method: 'POST', body: JSON.stringify({ name, birth, hour, relation, nickname, ...(boundary.trim() ? { boundary: boundary.trim() } : {}) }) });
|
||
setPhase(2); onCreate({ ...freshState(identity), messages: [], events: [], memories: [] }); go(4); return;
|
||
}
|
||
const c = new AbortController();
|
||
for (let p = 0; p < 3; p++) {
|
||
setPhase(p);
|
||
await delay(280, c.signal);
|
||
if (fail && p === 1)
|
||
throw new Error('这一步没完成,资料都还在。可以重试,或返回修改。');
|
||
}
|
||
const identity: Identity = { id: newId(), name: name.trim(), birth, hour, relation: relation as Identity['relation'], nickname: nickname.trim(), boundary: boundary.trim() || '尊重彼此的节奏' };
|
||
onCreate(freshState(identity));
|
||
go(4);
|
||
}
|
||
catch (e) {
|
||
setError((e as Error).message);
|
||
}
|
||
finally {
|
||
setBusy(false);
|
||
} }
|
||
const reroll = () => { const r = randomBirth(); setBirth(r.birth); setHour(r.hour); setHow('random'); setError(''); };
|
||
const [y, m, d] = birth.split('-');
|
||
const story = STORY[step === 4 ? 4 : step === 3 && phase >= 0 ? (error ? 'fail' : busy ? 'run' : 3) : step];
|
||
// One companion only: the server refuses a second (409). Reopening restores the one that exists; nothing is overwritten.
|
||
const exists = real && error.includes('已经有一位她');
|
||
return <main className="create"><div className="story"><div className="eyebrow">初次见面{step < 4 ? ` · 第 ${step + 1} 步,共 4 步` : ' · 第一晚'}</div><h1>{story[0]}</h1><p className="quiet">{story[1]}</p><p>{real ? '资料与对话保存在服务器,重开或换设备都能恢复同一位她。最终确认前不会建档。' : '这是本机演示。你的选择只保存在这个浏览器,没有创建服务器上的真实伴侣。'}</p><div className="single"><Icon name="lock"/>首版只有一位。创建后不提供切换或清空重建。</div></div><section className="wiz glass read"><div className="steps">{labels.map((l, i) => <span className={i <= step ? 'on' : ''} key={l}/>)}</div><div className="steplabel">{step < 4 ? `${step + 1} / 4 · ${labels[step]}` : '创建完成'}</div><div className="wbody"><div className={`wstep on ${back ? 'back-in' : ''}`} key={step}>
|
||
{step === 0 && <><h2>先认识她的开始</h2><p className="lead">名字由你起,生辰也可以在确认前修改。</p><Field label="她的名字"><input className="input" ref={nameField} value={name} maxLength={20} placeholder="由你来起 · 1–20 个字" aria-invalid={field === 'name'} onChange={e => setName(e.target.value)} autoComplete="off"/></Field>
|
||
<div className="field"><span>她的生日</span><div className="seg" role="group" aria-label="她的生日怎么来">{([['random', '随机生成'], ['pick', '我来指定']] as const).map(([k, l]) => <button key={k} aria-pressed={how === k} onClick={() => k === 'random' ? reroll() : setHow('pick')}>{l}</button>)}</div></div>
|
||
<div className="birth-pick"><Field label="出生日期(公历)" hint="需已满 18 岁。"><input className="input" ref={birthField} type="date" value={birth} aria-invalid={field === 'birth'} onChange={e => { setBirth(e.target.value); setHow('pick'); }}/></Field><Field label="出生时辰" hint="北京时间;子时23:00–00:59,丑时01:00–02:59,之后每两小时一段。排盘取时辰内偶数整点,子时取本日00:00。"><select className="select" value={hour} onChange={e => { setHour(e.target.value); setHow('pick'); }}>{HOURS.map(h => <option key={h}>{h}</option>)}</select></Field></div>
|
||
<div className="derived"><p><small>公历</small>{y || '—'} 年 {Number(m) || '—'} 月 {Number(d) || '—'} 日 · {hour}</p><p><small>农历与四柱</small>{real ? '下一步由排盘计算' : '演示不排盘'}</p></div>
|
||
<p className="d-dim">{how === 'random' ? '已随机生成。可以再随机一次,或换成「我来指定」。' : '确认前都可以改。'}</p></>}
|
||
{step === 1 && <><h2>{name.trim()}的底色</h2><p className="lead">这是倾向,不是台词。她会怎样理解自己、长成什么样,由她在相处和生活里慢慢形成,不按固定模板。</p><BaseColor color={real ? color : undefined}/></>}
|
||
{step === 2 && <><h2>由你选择关系</h2><p className="lead">没有预选答案。以后可以在设置中确认修改,记忆会保留。</p><div className="rel-cards" role="group" aria-label="你们的关系" ref={relationGroup}>{RELATIONS.map(([r, text]) => <button aria-pressed={relation === r} aria-label={r} aria-describedby={`rel-${r}`} key={r} onClick={() => { setRelation(r); if (field === 'relation') setError(''); }}><b>{r}</b><small id={`rel-${r}`}>{text}</small></button>)}</div><Field label="她怎么称呼你(可选)"><input className="input" maxLength={40} value={nickname} placeholder="比如:你的名字或昵称" onChange={e => setNickname(e.target.value)}/></Field><Field label="相处边界(可选)"><textarea className="textarea" maxLength={2000} value={boundary} placeholder="比如:彼此保留自己的时间" onChange={e => setBoundary(e.target.value)}/></Field></>}
|
||
{step === 3 && <><h2>让这次相识,有一个开始</h2><div className="sum">{[['名字', name], ['生辰', `${birth} · ${hour}`], ['关系', relation], ['称呼', nickname || '暂时不设'], ...(boundary.trim() ? [['相处边界', boundary.trim()]] : [])].map(([k, v]) => <div className="r" key={k}><span>{k}</span><b>{v}</b></div>)}</div><BaseColor color={real ? color : undefined}/><label className="check"><input type="checkbox" checked={agreed} disabled={busy || phase === 2} onChange={e => setAgreed(e.target.checked)}/>{real ? '我明白:这将创建服务器上的真实档案;创建后底色只读,只保留一位伴侣。关系以后可以调整。' : '我明白:这是本机演示;创建后底色只读,只保留一位伴侣。关系以后可以调整。'}</label>{phase >= 0 && <ul className="phases">{(real ? ['核对真实排盘', '保存唯一档案', '档案已保存'] : ['排好底色(示例)', '形成最初的小习惯(示例)', '布置房间(示例)']).map((p, i) => <li key={p} className={i < phase ? 'ok' : i === phase ? (error ? 'fail' : 'run') : ''}><i>{i < phase ? '✓' : ''}</i>{p}</li>)}</ul>}{busy && <p className="d-dim">通常不到一分钟。可以先看看窗外。</p>}</>}
|
||
{step === 4 && <div className="born"><div className="halo"><i/></div><div className="eyebrow">第一晚</div><h2>{name.trim()}住进来了</h2><p className="lead">刚开始,还没有共同的日子。日子和回忆会从今晚开始,慢慢留下。</p></div>}
|
||
<Status text={error} error/>{exists && <Button onClick={() => location.reload()}>重新打开,恢复已有的她</Button>}</div></div><footer className="wfoot">{step > 0 && step < 4 && <Button disabled={busy} onClick={() => { const fix = error && phase >= 0; setError(''); setPhase(-1); go(fix ? 0 : step - 1); }}>{error && phase >= 0 ? '返回修改' : '上一步'}</Button>}<span className="grow"/>{step < 3 ? <Button primary disabled={busy} onClick={() => void next()}>{busy ? '正在排盘…' : '下一步'}</Button> : step === 3 ? <Button primary disabled={!agreed || busy || exists} onClick={() => void create()}>{busy ? '正在创建…' : error && phase >= 0 ? '再试一次' : '确认创建'}</Button> : <Button primary onClick={onEnter}>去看看她</Button>}</footer></section></main>;
|
||
}
|