chahinebrini f4da81f551 feat(native/blocker): two collapsible sections + new AddDomainSheet layout
The Seiten/Mails top-tabs added in 5c6fa3d are gone. Per the user's
revised vision, web-domains and mail-patterns live side by side as two
collapsible <DomainSection>s with their own header, slot pill, progress
bar, and add-button — closer to the original Eigene-Domains affordance
plus a sibling Eigene-Mails section. Both default open; chevron-up/down
per the existing icon convention.

AddDomainSheet was rewritten from scratch to fix the layout-bug
visible in the screenshot — SheetFieldStack's two-ScrollView intro/
fields split was wrong for a single-input use case and was rendering
the chip at the bottom of the scroll area with a huge gap under the
TypePicker. The new sheet is a plain ScrollView with TypePicker, label,
TextInput, help-card, preview-card, warning-card, confirm-row, and the
Cancel + Hinzufügen buttons stacked top-to-bottom with `gap: 12`. No
Pressable anywhere — TouchableOpacity only, per the hard rule.

DomainGrid is now a pure tile renderer: the header / slot pill / add
affordance live on the section component above it. Its `kind` prop
(renamed from `activeTab`) drives the type filter — for v1.0, mail
means strictly `mail_domain` (display-name is gone).

i18n: new keys section_domains / section_mails / add_sheet_cta. mail-
related copy (label, placeholder, help, empty) had every "Display-Name"
mention stripped so the user can't read about an option that doesn't
ship.

Progressbar inline in DomainSection with the same Animated.timing
pattern DeviceProgressBar uses, with a 3-step color threshold
(green / brandOrange / error) keyed on the bucket fill ratio.
2026-05-16 02:19:27 +02:00

208 lines
6.4 KiB
TypeScript

import { useCallback, useEffect, useState } from 'react';
import { apiFetch } from '../lib/api';
export type DomainStatus = 'active' | 'submitted' | 'approved' | 'rejected';
export type EntryKind = 'web' | 'mail_domain' | 'mail_display_name';
export type CustomDomain = {
id: string;
domain: string;
type?: EntryKind;
status: DomainStatus;
addedAt?: string;
postId?: string | null;
submission?: { id: string; yesVotes: number; noVotes: number; status: string } | null;
};
export type Plan = 'free' | 'pro' | 'legend';
export type Tier = {
plan: Plan;
domainLimit: number; // free=5, pro=5, legend=10
refillEnabled: boolean; // free=false, pro/legend=true
globalBlocklist: boolean; // free=false, pro/legend=true
canSubmit: boolean; // free=false, pro/legend=true
usedSlots: number; // active+submitted (NICHT approved/rejected)
atLimit: boolean;
};
function deriveTier(plan: Plan, domains: CustomDomain[]): Tier {
const limit = plan === 'legend' ? 10 : 5;
const refill = plan !== 'free';
const usedSlots = domains.filter((d) => d.status === 'active' || d.status === 'submitted').length;
return {
plan,
domainLimit: limit,
refillEnabled: refill,
globalBlocklist: refill,
canSubmit: refill,
usedSlots,
atLimit: usedSlots >= limit,
};
}
export type CountsByType = {
web: number;
mail: number;
};
export type LimitsByType = {
web: number;
mail: number;
};
export type UseCustomDomainsReturn = {
domains: CustomDomain[];
tier: Tier;
countsByType: CountsByType;
limits: LimitsByType;
loading: boolean;
error: string | null;
refresh: () => Promise<void>;
addDomain: (domain: string, kind?: 'web' | 'mail') => Promise<{ ok: boolean; error?: string; alreadyGlobal?: boolean }>;
submitDomain: (id: string) => Promise<{ ok: boolean; error?: string }>;
removeDomain: (id: string) => Promise<{ ok: boolean; error?: string }>;
/** Live-Validate (regex) ob string gültiger Domain-Name ist. */
isValidDomain: (s: string) => boolean;
/** Normalize: lowercase, http(s)://, /path stripping, www. weg. */
normalizeDomain: (s: string) => string;
};
const DOMAIN_REGEX = /^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i;
export function normalizeDomain(input: string): string {
let s = input.trim().toLowerCase();
if (s.startsWith('https://')) s = s.slice(8);
else if (s.startsWith('http://')) s = s.slice(7);
const slash = s.indexOf('/');
if (slash >= 0) s = s.slice(0, slash);
if (s.startsWith('www.')) s = s.slice(4);
return s;
}
export function isValidDomain(input: string): boolean {
const n = normalizeDomain(input);
if (!n || n.length > 253) return false;
return DOMAIN_REGEX.test(n);
}
/**
* Custom-Domain CRUD gegen `/api/custom-domains/*` mit Tier-aware Limits.
*
* Tier-Logik (Single-Source-of-Truth: User.plan):
* Free → 5 Slots, kein Refill, keine Submit
* Pro → 5 Slots, Refill bei approved/rejected, Submit erlaubt
* Legend → 10 Slots, Refill, Submit
*/
export function useCustomDomains(plan: Plan): UseCustomDomainsReturn {
const [domains, setDomains] = useState<CustomDomain[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchDomains = useCallback(async () => {
try {
// Backend (`server/api/custom-domains/index.get.ts`) gibt Array DIREKT zurück,
// kein { domains: [...] }-Wrapper.
const res = await apiFetch<CustomDomain[] | { domains?: CustomDomain[] }>(
'/api/custom-domains',
);
const arr = Array.isArray(res) ? res : (res?.domains ?? []);
console.log('[useCustomDomains] fetched:', arr.length, 'domains', arr.slice(0, 3));
setDomains(arr);
setError(null);
} catch (e: any) {
console.error('[useCustomDomains] fetch failed:', e?.message ?? e);
setError(e?.message ?? 'unknown');
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchDomains();
}, [fetchDomains]);
const addDomain = useCallback(
async (input: string, kind: 'web' | 'mail' = 'web') => {
if (kind === 'web' && !isValidDomain(input)) return { ok: false, error: 'invalid_domain' };
if (kind === 'mail' && !input.trim()) return { ok: false, error: 'invalid_pattern' };
const tier = deriveTier(plan, domains);
if (tier.atLimit) return { ok: false, error: 'limit_reached' };
const pattern = kind === 'web' ? normalizeDomain(input) : input.trim();
try {
const res = await apiFetch<any>('/api/custom-domains', {
method: 'POST',
body: { pattern, kind },
});
if (res?.alreadyGlobal) {
return { ok: false, alreadyGlobal: true };
}
await fetchDomains();
return { ok: true };
} catch (e: any) {
return { ok: false, error: e?.message ?? 'add_failed' };
}
},
[plan, domains, fetchDomains],
);
const submitDomain = useCallback(
async (id: string) => {
const tier = deriveTier(plan, domains);
if (!tier.canSubmit) return { ok: false, error: 'plan_does_not_support_submit' };
try {
await apiFetch(`/api/custom-domains/${id}/submit`, { method: 'POST', body: {} });
await fetchDomains();
return { ok: true };
} catch (e: any) {
return { ok: false, error: e?.message ?? 'submit_failed' };
}
},
[plan, domains, fetchDomains],
);
const removeDomain = useCallback(
async (id: string) => {
try {
await apiFetch(`/api/custom-domains/${id}`, { method: 'DELETE' });
await fetchDomains();
return { ok: true };
} catch (e: any) {
return { ok: false, error: e?.message ?? 'remove_failed' };
}
},
[fetchDomains],
);
const tier = deriveTier(plan, domains);
const countsByType: CountsByType = {
web: domains.filter(
(d) => d.status !== 'approved' && (d.type === 'web' || !d.type),
).length,
mail: domains.filter(
(d) => d.status !== 'approved' && d.type === 'mail_domain',
).length,
};
const webLimit = plan === 'legend' ? 8 : 4;
const mailLimit = plan === 'legend' ? 2 : 1;
const limits: LimitsByType = { web: webLimit, mail: mailLimit };
return {
domains,
tier,
countsByType,
limits,
loading,
error,
refresh: fetchDomains,
addDomain,
submitDomain,
removeDomain,
isValidDomain,
normalizeDomain,
};
}