rebreak-monorepo/apps/rebreak-native/components/mail/MailDistributionChart.tsx
chahinebrini 432d9d27a3 feat(mail-page): hero-donut + FAB + collapsible bar-chart + legend truncation
UX-Welle nach User-Feedback aus dem ersten Live-Test der Mail-Page:

Page-Hierarchie neu (top → bottom):

1. HALF-DONUT als HERO-Karte — bisherige "BLOCKIERT XX über N Postfächer Live"-
   Banner-Card weg, Inhalt ist jetzt Title-Zeile innerhalb der Donut-Karte
   (rendert nur ab ≥2 Connections; Fallback-Stats-Row für 0-1 Connections)
2. Postfach-Liste (Account-Cards aus letztem Refactor — schlanker Header)
3. NEU: "Mehr Infos"-Collapsible — Bar-Chart "Blockiert letzte 30 Tage"
   liegt jetzt versteckt drin (default collapsed)
4. Activity-Log "Kürzlich blockiert" (unverändert)
5. NEU: FAB unten rechts — 56pt brandOrange Kreis mit "+"-Icon,
   öffnet ConnectMailSheet. Section-Header-Plus-Button entfällt.

Half-Donut Legend-Truncation:
- ≤3 Connections → alle anzeigen
- =4 Connections → alle anzeigen
- ≥5 Connections → Top-3 by blocked-count + "Sonstige"-Bucket
  · Donut: 4 Segmente (Top-3 + OTHER_COLOR grau)
  · Legend: 4 Zeilen (Top-3 fett, "weitere"-Zeile in regular grau)

Backend: GET /api/mail/stats/blocked-by-day?connectionId=<uuid> als
optionaler Filter (für per-Connection-Bar-Chart in expanded Account-Card,
in dieser Welle noch nicht im UI verdrahtet — Erweiterung kommt wenn
gewünscht).

FAB-Details (iOS-diskreter Shadow statt Material-Glow):
- position absolute, right 24, bottom = tabBarHeight + insets.bottom + 16
- 56pt, borderRadius 28, brandOrange BG, weißes Plus-Icon
- ScrollView paddingBottom angehoben damit kein Content unter dem FAB clipped

Edge-Cases:
- 0 Accounts → FAB sichtbar, Donut/Stats/Charts/Log versteckt + EmptyState
- 1 Account → Donut hidden (nur mit ≥2 Connections sinnvoll), Fallback-Stats-Row
- limitReached + FAB-Tap → bestehender Plan-Alert (FAB ist visuell nicht disabled)

Memory: Pull-to-refresh + bestehendes 30s-Status-Polling reichen für "wartet
auf erste verbindung"→"aktiv"-Übergang nach OAuth-Connect (Daemon-Heartbeat
braucht initial 2-9min, mo-Befund). UX-Polish-Option für später: in der
Initial-Phase einen freundlicheren "Verbinde gerade…"-Status anzeigen.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 22:39:45 +02:00

323 lines
8.8 KiB
TypeScript

import { useMemo } from 'react';
import { Text, View } from 'react-native';
import Svg, { Path, Circle } from 'react-native-svg';
import { useTranslation } from 'react-i18next';
import { useColors } from '../../lib/theme';
import type { BlockedByConnectionEntry } from '../../hooks/useMailStats';
type Props = {
data: BlockedByConnectionEntry[];
/** When true: renders as full-width hero card with integrated title row */
hero?: boolean;
totalBlocked?: number;
accountCount?: number;
isLegend?: boolean;
};
const SLICE_COLORS = ['#ef4444', '#3b82f6', '#f59e0b', '#8b5cf6'];
const OTHER_COLOR = '#a3a3a3';
// Legend cap: show max 3 named entries + optional "others" row
const MAX_LEGEND_ENTRIES = 3;
const R_OUTER = 54;
const R_INNER = 34;
const CX = 64;
const CY = 64;
// Half-donut: upper semicircle, flat edge at bottom.
// Slices sweep from -90° (left) to +90° (right) = 180° total.
const HALF_DONUT_START_DEG = -90;
function domainFromEmail(email: string): string {
return email.split('@')[1] ?? email;
}
function displayLabel(entry: BlockedByConnectionEntry): string {
return entry.title ?? domainFromEmail(entry.email);
}
function polarToXY(cx: number, cy: number, r: number, angleDeg: number) {
const rad = ((angleDeg - 90) * Math.PI) / 180;
return {
x: cx + r * Math.cos(rad),
y: cy + r * Math.sin(rad),
};
}
function arcPath(
cx: number,
cy: number,
rOuter: number,
rInner: number,
startDeg: number,
endDeg: number,
): string {
const outerStart = polarToXY(cx, cy, rOuter, startDeg);
const outerEnd = polarToXY(cx, cy, rOuter, endDeg);
const innerEnd = polarToXY(cx, cy, rInner, endDeg);
const innerStart = polarToXY(cx, cy, rInner, startDeg);
const large = endDeg - startDeg > 180 ? 1 : 0;
return [
`M ${outerStart.x} ${outerStart.y}`,
`A ${rOuter} ${rOuter} 0 ${large} 1 ${outerEnd.x} ${outerEnd.y}`,
`L ${innerEnd.x} ${innerEnd.y}`,
`A ${rInner} ${rInner} 0 ${large} 0 ${innerStart.x} ${innerStart.y}`,
'Z',
].join(' ');
}
export function MailDistributionChart({ data, hero, totalBlocked, accountCount, isLegend }: Props) {
const { t } = useTranslation();
const colors = useColors();
const total = data.reduce((s, d) => s + d.count, 0);
// Build donut slices: always cap at 4 visible segments (Top-3 + Sonstige).
// Edge-case: ≤3 → no grouping. Exactly 4 → show all 4 (no grouping).
// 5+ → Top-3 + Sonstige.
const slices = useMemo(() => {
if (data.length === 0 || total === 0) return [];
const sorted = [...data].sort((a, b) => b.count - a.count);
if (sorted.length <= 4) {
return sorted.map((e, i) => ({
label: displayLabel(e),
count: e.count,
color: SLICE_COLORS[i] ?? OTHER_COLOR,
isOther: false,
hiddenCount: 0,
}));
}
// 5+ connections: Top-3 + Sonstige bucket
const top3 = sorted.slice(0, MAX_LEGEND_ENTRIES);
const rest = sorted.slice(MAX_LEGEND_ENTRIES);
const restCount = rest.reduce((s, e) => s + e.count, 0);
const restConnectionCount = rest.length;
const items = top3.map((e, i) => ({
label: displayLabel(e),
count: e.count,
color: SLICE_COLORS[i],
isOther: false,
hiddenCount: 0,
}));
items.push({
label: t('mail.stats.distribution_other_n', { n: restConnectionCount }),
count: restCount,
color: OTHER_COLOR,
isOther: true,
hiddenCount: restConnectionCount,
});
return items;
}, [data, total, t]);
if (data.length <= 1 || total === 0) return null;
let cursor = HALF_DONUT_START_DEG;
const displayTotal = totalBlocked ?? total;
if (hero) {
return (
<View
style={{
backgroundColor: colors.surface,
borderRadius: 16,
borderWidth: 1,
borderColor: colors.border,
paddingHorizontal: 16,
paddingTop: 16,
paddingBottom: 16,
}}
>
{/* Integrated title row */}
<View
style={{
flexDirection: 'row',
alignItems: 'center',
marginBottom: 14,
}}
>
<View style={{ flex: 1 }}>
<Text
style={{
fontSize: 22,
fontFamily: 'Nunito_800ExtraBold',
color: colors.error,
lineHeight: 26,
}}
>
{displayTotal.toLocaleString()}
</Text>
<Text
style={{
fontSize: 12,
fontFamily: 'Nunito_400Regular',
color: colors.textMuted,
marginTop: 2,
}}
>
{t('mail.stats_account_summary', { count: accountCount ?? data.length })}
</Text>
</View>
{/* Live / Scheduled pill */}
<View
style={{
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 10,
paddingVertical: 5,
borderRadius: 999,
backgroundColor: isLegend ? '#f0fdf4' : '#eff6ff',
}}
>
<View
style={{
width: 6,
height: 6,
borderRadius: 3,
backgroundColor: isLegend ? '#16a34a' : '#2563eb',
marginRight: 6,
}}
/>
<Text
style={{
fontSize: 12,
fontFamily: 'Nunito_700Bold',
color: isLegend ? '#16a34a' : '#2563eb',
}}
>
{isLegend ? t('mail.live') : t('mail.scheduled')}
</Text>
</View>
</View>
{/* Donut + Legend */}
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 16 }}>
<Svg width={128} height={68} viewBox="0 0 128 68">
{slices.map((slice) => {
const sweep = (slice.count / total) * 180;
const startDeg = cursor;
cursor += sweep;
return (
<Path
key={slice.label}
d={arcPath(CX, CY, R_OUTER, R_INNER, startDeg, startDeg + sweep)}
fill={slice.color}
/>
);
})}
<Circle cx={CX} cy={CY} r={R_INNER - 1} fill={colors.surface} />
</Svg>
<View style={{ flex: 1, gap: 5 }}>
{slices.map((slice) => (
<LegendRow key={slice.label} slice={slice} colors={colors} />
))}
</View>
</View>
</View>
);
}
// Standard (non-hero) card — kept for potential reuse
return (
<View
style={{
backgroundColor: colors.surface,
borderRadius: 16,
borderWidth: 1,
borderColor: colors.border,
paddingHorizontal: 16,
paddingTop: 14,
paddingBottom: 14,
}}
>
<Text
style={{
fontSize: 11,
fontFamily: 'Nunito_700Bold',
color: colors.textMuted,
textTransform: 'uppercase',
letterSpacing: 0.7,
marginBottom: 12,
}}
>
{t('mail.stats.distribution_heading')}
</Text>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 16 }}>
<Svg width={128} height={68} viewBox="0 0 128 68">
{slices.map((slice) => {
const sweep = (slice.count / total) * 180;
const startDeg = cursor;
cursor += sweep;
return (
<Path
key={slice.label}
d={arcPath(CX, CY, R_OUTER, R_INNER, startDeg, startDeg + sweep)}
fill={slice.color}
/>
);
})}
<Circle cx={CX} cy={CY} r={R_INNER - 1} fill={colors.surface} />
</Svg>
<View style={{ flex: 1, gap: 6 }}>
{slices.map((slice) => (
<LegendRow key={slice.label} slice={slice} colors={colors} />
))}
</View>
</View>
</View>
);
}
function LegendRow({
slice,
colors,
}: {
slice: { label: string; count: number; color: string; isOther: boolean };
colors: ReturnType<typeof useColors>;
}) {
return (
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}>
<View
style={{
width: 8,
height: 8,
borderRadius: 4,
backgroundColor: slice.color,
}}
/>
<Text
style={{
flex: 1,
fontSize: 12,
fontFamily: slice.isOther ? 'Nunito_400Regular' : 'Nunito_600SemiBold',
color: slice.isOther ? colors.textMuted : colors.text,
}}
numberOfLines={1}
>
{slice.label}
</Text>
<Text
style={{
fontSize: 12,
fontFamily: 'Nunito_700Bold',
color: colors.textMuted,
}}
>
{slice.count}
</Text>
</View>
);
}