Files
Jyotisha/frontend/src/components/chat-answer-shape.tsx
T
ClaudeandClaude Opus 5.5 9133e58e57
Independent Staging Quality Gate / validate-frontend (push) Successful in 5m56s
Independent Staging Quality Gate / validate-python (push) Successful in 7m56s
Independent Staging Quality Gate / publish (push) Successful in 3m40s
fix(chat): tidy answer layout — strip in one fixed slot reserved from the first frame, dates only in the strip, one footer line, legend on the heading row, round jump button, title checks, dark strip tones (BUG-2320)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq
2026-11-24 16:00:23 +08:00

295 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { ChevronRight } from "lucide-react";
import { useEffect, useState, type ReactNode } from "react";
import { ConversationFollowUps } from "@/components/conversation-follow-ups";
import { Button } from "@/components/ui/button";
import type { ChartBoardStyle } from "@/lib/chart-board-style";
import { chartAreaHouses, chartAreaNames } from "@/lib/chat-chart-areas";
import {
ANSWER_TONE_LABELS,
currentMonthIndex,
FOLLOW_UP_HEADING,
stripFooterLine,
type AnswerShape,
type AnswerTone,
type TimelineSegment,
} from "@/lib/chat-answer-shape";
import { CHART_SIZE, HOUSE_POLYGONS, polygonPoints } from "@/lib/north-indian-chart-geometry";
import { useUiStore } from "@/stores/ui-store";
/**
* BUG-2281: the parts of an answer in the owner-approved prototype's shape (verdict card, the chart row, the one-year
* strip, 接着问). The body and 「判断依据」 stay the existing markdown and fold (chat-message-content.tsx).
*/
export function AnswerVerdict({ verdict }: Readonly<{ verdict: AnswerShape["verdict"] }>) {
if (!verdict.sentence && !verdict.facts.length) return null;
return (
<section className="chat-answer-verdict" aria-label="结论">
{verdict.sentence ? <p className="chat-answer-verdict-sentence">{verdict.sentence}</p> : null}
{verdict.facts.length ? (
<dl className="chat-answer-verdict-facts">
{verdict.facts.map((fact) => (
<div key={fact.label} className="chat-answer-verdict-fact">
<dt>{fact.label}</dt>
<dd>{fact.value}</dd>
</div>
))}
</dl>
) : null}
</section>
);
}
const SIGNS = ["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"] as const;
/** South Indian fixed sign cells (row, column) by sign index, 0 = Aries (as in mini-varga-chart.tsx). */
const SOUTH_CELL: Readonly<Record<number, readonly [number, number]>> = {
11: [0, 0], 0: [0, 1], 1: [0, 2], 2: [0, 3], 10: [1, 0], 3: [1, 3], 9: [2, 0], 4: [2, 3], 8: [3, 0], 7: [3, 1], 6: [3, 2], 5: [3, 3],
};
/** The chart outline in the reader's board style with the answer's areas lit. Areas only, never planets (owner). */
export function AnswerAreasChart({ houses, ascendantSign, style }: Readonly<{ houses: readonly number[]; ascendantSign?: string; style: ChartBoardStyle }>) {
const lit = new Set(houses);
const ascendant = SIGNS.indexOf((ascendantSign ?? "") as (typeof SIGNS)[number]);
if (style === "south" && ascendant >= 0) {
const size = CHART_SIZE / 4;
return (
<svg className="chat-answer-areas-chart" data-chart-style="south" viewBox={`-4 -4 ${CHART_SIZE + 8} ${CHART_SIZE + 8}`} aria-hidden="true">
{Object.entries(SOUTH_CELL).map(([sign, [row, column]]) => {
const house = ((Number(sign) - ascendant + 12) % 12) + 1;
return <rect key={sign} x={column * size + 6} y={row * size + 6} width={size - 12} height={size - 12} rx={12} className={lit.has(house) ? "is-lit" : undefined} />;
})}
</svg>
);
}
return (
<svg className="chat-answer-areas-chart" data-chart-style="north" viewBox={`-4 -4 ${CHART_SIZE + 8} ${CHART_SIZE + 8}`} aria-hidden="true">
{Object.entries(HOUSE_POLYGONS).map(([house, points]) => (
<polygon key={house} points={polygonPoints(points)} className={lit.has(Number(house)) ? "is-lit" : undefined} />
))}
</svg>
);
}
function useBoardStyle(): ChartBoardStyle {
const style = useUiStore((state) => state.chartBoardStyle);
const hydrated = useUiStore((state) => state.chartBoardStyleHydrated);
const hydrate = useUiStore((state) => state.hydrateChartBoardStyle);
useEffect(() => {
if (!hydrated) hydrate();
}, [hydrate, hydrated]);
return style;
}
/** 「这是从你的星盘里看出来的」: the lit areas and their plain names; tapping opens 「判断依据」. */
export function AnswerAreas({ houses, ascendantSign, onOpen }: Readonly<{ houses: readonly number[]; ascendantSign?: string; onOpen: () => void }>) {
const style = useBoardStyle();
const list = chartAreaHouses(houses);
if (!list.length) return null;
const names = chartAreaNames(list);
return (
<Button type="button" variant="ghost" className="chat-answer-areas" onClick={onOpen}>
<AnswerAreasChart houses={list} ascendantSign={ascendantSign} style={style} />
<span className="chat-answer-areas-text">
<span className="chat-answer-areas-title">这是从你的星盘里看出来的</span>
<span className="chat-answer-areas-names">这次看了 {names.length} 个地方:{names.join("、")}</span>
</span>
<ChevronRight aria-hidden="true" className="chat-answer-areas-chevron" />
</Button>
);
}
/** 「12 月」「明年 5 月」「2029 年 1 月」 relative to this month's year. */
export function monthLabel(index: number, now = currentMonthIndex()): string {
const year = Math.floor(index / 12);
const month = (index % 12) + 1;
const diff = year - Math.floor(now / 12);
if (diff === 0) return `${month} 月`;
if (diff === 1) return `明年 ${month} 月`;
if (diff === 2) return `后年 ${month} 月`;
return `${year} 年 ${month} 月`;
}
/**
* The month under each segment's start: 「现在」 for a first stretch that starts now, the year only where it changes
* (「明年 2 月」 then 「5 月」), nothing under a segment shorter than two months (no room for the label).
*/
export function stripTicks(segments: readonly TimelineSegment[], weights: readonly number[], now = currentMonthIndex()): string[] {
let year = Math.floor(now / 12);
return segments.map((segment, index) => {
if (!segment.months || weights[index]! < 2) return "";
if (index === 0 && /^(?:现在|眼下|目前)/u.test(segment.range)) return "现在";
const start = segment.months[0];
const label = Math.floor(start / 12) === year ? `${(start % 12) + 1} 月` : monthLabel(start, now);
year = Math.floor(start / 12);
return label;
});
}
/** Segment widths in months (at least one each); equal widths when any range could not be read. */
/** BUG-2319: the colour token of one stretch's tone; anything unknown (an older or newer receipt) is the neutral fill. */
const STRIP_TONE_COLOR: Readonly<Record<string, string>> = {
chance: "var(--strip-chance)",
chance_costly: "var(--strip-chance-costly)",
strain: "var(--strip-strain)",
};
export function stripToneColor(tone: string | undefined): string {
return (tone && STRIP_TONE_COLOR[tone]) || "var(--strip-none)";
}
/**
* BUG-2319: one gradient runs across the whole bar — each stretch's colour sits at its middle and blends into its
* neighbours' — and every block shows its own slice of it (background sized to the whole bar, shifted to the block's
* place), so the blocks read as one continuous axis instead of each carrying its own small gradient.
*/
export function stripSliceStyles(weights: readonly number[], tones: readonly (string | undefined)[] | null): Array<React.CSSProperties | undefined> {
if (!tones) return weights.map(() => undefined);
const total = weights.reduce((sum, weight) => sum + weight, 0) || 1;
const starts: number[] = [];
let at = 0;
for (const weight of weights) { starts.push(at / total); at += weight; }
const stops = weights.map((weight, index) => `${stripToneColor(tones[index])} ${((starts[index]! + weight / total / 2) * 100).toFixed(2)}%`);
const image = weights.length === 1 ? stripToneColor(tones[0]) : `linear-gradient(90deg, ${stops.join(", ")})`;
return weights.map((weight, index) => {
const width = weight / total;
if (weights.length === 1 || width >= 1) return { background: image };
return {
backgroundImage: image,
backgroundSize: `${(100 / width).toFixed(3)}% 100%`,
backgroundPosition: `${((starts[index]! / (1 - width)) * 100).toFixed(3)}% 0`,
backgroundRepeat: "no-repeat",
};
});
}
export function segmentWeights(segments: readonly TimelineSegment[]): number[] {
if (segments.some((segment) => !segment.months)) return segments.map(() => 1);
return segments.map((segment) => Math.max(1, segment.months![1] - segment.months![0] + 1));
}
/**
* The one-year strip: one segment per timeline entry, widths by duration, colour and label together. Tapping a segment
* shows its range, sentence, 该做 and 别做 in the panel below; every panel sits in the same grid cell, so the panel is as
* tall as the longest one and does not change height with the selection. Tones come from the receipt (program-derived);
* without them (still streaming, or an answer without evidence keys) the segments are neutral and no legend shows.
*/
/*
* BUG-2305 `reserve` (the answer streamed in this row): the legend line and the footer line keep their slots while
* streaming and after, filled at completion, so the body under the strip does not move when they appear.
* BUG-2320 (owner-approved tidy prototype): the legend sits on the heading's row, right-aligned (only the labels in use;
* it wraps under the heading on very narrow widths); the turning-point sentence and the birth-time note are ONE small
* muted footer line under the panel (`stripFooterLine`).
*/
export function AnswerYearStrip({ timeline, tones, timeSensitive = false, reserve = false }: Readonly<{ timeline: NonNullable<AnswerShape["timeline"]>; tones?: readonly AnswerTone[]; timeSensitive?: boolean; reserve?: boolean }>) {
const [picked, setPicked] = useState(0);
const segments = timeline.segments;
if (!segments.length) return null;
const selected = Math.min(picked, segments.length - 1);
const known = tones && tones.length === segments.length ? tones : null;
const weights = segmentWeights(segments);
const columns = weights.map((weight) => `minmax(40px, ${weight}fr)`).join(" ");
// BUG-2310: the legend lists only the labels present; a stretch with no tag has a neutral fill and no words.
const used = known ? (["chance", "chance_costly", "strain"] as const).filter((tone) => known.includes(tone)) : [];
// #359: a tone this page does not know (a receipt written by a newer or older release) shows no words, never "undefined".
const toneWords = (index: number) => {
const label = known ? (ANSWER_TONE_LABELS as Readonly<Record<string, string | undefined>>)[known[index] as string] : undefined;
return typeof label === "string" && label ? `,${label}` : "";
};
const slices = stripSliceStyles(weights, known);
const footer = stripFooterLine(timeline.note, timeSensitive);
return (
// BUG-2308: a strip that arrives in a live row (`reserve`) enters once, as a whole (opacity and transform only).
<section className={`chat-answer-strip${reserve ? " is-arriving" : ""}`} aria-label={timeline.heading}>
<div className="chat-answer-strip-head">
<p className="chat-answer-label">{timeline.heading}</p>
{used.length || reserve ? (
<div className="chat-answer-strip-legend" aria-hidden="true">
{used.map((tone) => <span key={tone}><i style={{ background: stripToneColor(tone) }} />{ANSWER_TONE_LABELS[tone]}</span>)}
</div>
) : null}
</div>
<div className="chat-answer-strip-bar" style={{ gridTemplateColumns: columns }}>
{segments.map((segment, index) => (
<Button
key={`${index}-${segment.title}`}
type="button"
variant="ghost"
className={`chat-answer-strip-segment${known ? " is-toned" : " is-pending"}`}
style={slices[index]}
aria-pressed={index === selected}
aria-label={`${segment.title},${segment.range}${toneWords(index)}`}
onClick={() => setPicked(index)}
>
{segment.title}
</Button>
))}
</div>
<div className="chat-answer-strip-ticks" style={{ gridTemplateColumns: columns }} aria-hidden="true">
{stripTicks(segments, weights).map((tick, index) => <span key={index}>{tick}</span>)}
</div>
<div className="chat-answer-strip-detail" aria-live="polite">
{segments.map((segment, index) => (
<div key={index} className="chat-answer-strip-panel" data-active={index === selected ? "" : undefined} aria-hidden={index !== selected}>
<span className="chat-answer-strip-when">{segment.range}{toneWords(index)}</span>
{segment.sentence ? <b className="chat-answer-strip-sentence">{segment.sentence}</b> : null}
{segment.doThis || segment.avoid ? (
<dl>
{segment.doThis ? <div><dt>该做</dt><dd>{segment.doThis}</dd></div> : null}
{segment.avoid ? <div><dt>别做</dt><dd>{segment.avoid}</dd></div> : null}
</dl>
) : null}
</div>
))}
</div>
{/* BUG-2320: one quiet line — the next turning point, then (only when the card marks the boundaries as moving with
the birth time) the birth-time note. */}
{footer || reserve ? <p className="chat-answer-strip-caveat" aria-hidden={footer ? undefined : true}>{footer}</p> : null}
</section>
);
}
/**
* BUG-2320: the strip's fixed place — under the chart row, above the year sentence and the body — whatever order the
* writer used (the parser lifts the time section). In a row that streams here (`reserved`) the slot has the final strip's
* fixed height from the first frame (the label and a neutral bar stand in until the section is complete), so nothing
* moves when the strip is drawn into it. Rows read from history use the wrapper without a reserved height.
*/
export function AnswerStripSlot({ reserved, heading, children }: Readonly<{ reserved: boolean; heading: string; children: ReactNode }>) {
return (
<div className={`chat-answer-strip-slot${reserved ? " is-reserved" : ""}`}>
{children ?? (
<div className="chat-answer-strip-placeholder" aria-hidden="true">
<p className="chat-answer-label">{heading}</p>
<span className="chat-answer-strip-placeholder-bar" />
</div>
)}
</div>
);
}
/**
* 「接着问」: the answer's own three questions, each sends itself (the existing follow-up buttons). BUG-2305 (owner
* 2026-11-24): no visible 「接着问」 label; the group keeps it as its accessible name. The transcript places it after the
* answer's action icons, the last thing above the composer.
*/
export function AnswerFollowUps({ questions, disabled, onSelect }: Readonly<{ questions: readonly string[]; disabled?: boolean; onSelect: (question: string) => void }>) {
if (!questions.length) return null;
return (
<section className="chat-answer-next" aria-label={FOLLOW_UP_HEADING}>
<ConversationFollowUps questions={questions} disabled={disabled} onSelect={onSelect} />
</section>
);
}
/**
* BUG-2305 (owner picked prototype style 3, 2026-11-24): 判断依据 and 盘面数据 together in one muted rounded box, a
* hairline between the rows; each row is the existing fold (details/summary, count, chevron), opening inside the box.
* Only the wrapper and its class are new, so another look is a CSS change. Unboxed (report chats): no wrapper at all.
*/
export function AnswerEvidenceGroup({ boxed, children }: Readonly<{ boxed: boolean; children: ReactNode }>) {
if (!boxed) return <>{children}</>;
return <div className="chat-answer-evidence">{children}</div>;
}