@devbie/fewbie-cli 1.13.2 → 1.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/template-ownership.js +1 -1
- package/dist/lib/template-ownership.js.map +1 -1
- package/dist/registry/copilot/contract.json +87 -0
- package/dist/registry/copilot/fewbie.module.json +144 -0
- package/dist/registry/forgot-password/contract.json +1 -1
- package/dist/registry/forgot-password/fewbie.module.json +5 -5
- package/dist/registry/login-form/contract.json +1 -1
- package/dist/registry/login-form/fewbie.module.json +4 -4
- package/dist/registry/login-page/contract.json +1 -1
- package/dist/registry/login-page/fewbie.module.json +4 -4
- package/dist/registry/notification-center/contract.json +67 -0
- package/dist/registry/notification-center/fewbie.module.json +109 -0
- package/dist/registry/password-checklist/contract.json +1 -1
- package/dist/registry/password-checklist/fewbie.module.json +4 -4
- package/dist/registry/preferences-settings/contract.json +1 -1
- package/dist/registry/preferences-settings/fewbie.module.json +4 -4
- package/dist/registry/profile-settings/contract.json +1 -1
- package/dist/registry/profile-settings/fewbie.module.json +4 -4
- package/dist/registry/security-settings/contract.json +1 -1
- package/dist/registry/security-settings/fewbie.module.json +4 -4
- package/dist/registry/settings-required-state/contract.json +1 -1
- package/dist/registry/settings-required-state/fewbie.module.json +4 -4
- package/package.json +1 -1
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"x-fewbie.contract": {
|
|
9
9
|
"version": "1.0.0",
|
|
10
10
|
"framework": "^1.7.0",
|
|
11
|
-
"entry": "src/
|
|
11
|
+
"entry": "src/features/login-page/index.ts",
|
|
12
12
|
"labels": [
|
|
13
13
|
"title",
|
|
14
14
|
"description",
|
|
@@ -57,17 +57,17 @@
|
|
|
57
57
|
},
|
|
58
58
|
"files": [
|
|
59
59
|
{
|
|
60
|
-
"path": "src/
|
|
60
|
+
"path": "src/features/login-page/index.ts",
|
|
61
61
|
"content": "export { LoginPage } from \"./login-page\";\nexport type {\n LoginCredentials,\n LoginLabels,\n LoginOAuthProvider,\n LoginPageProps,\n LoginPort,\n LoginResult,\n LoginTotpChallenge,\n LoginVerificationCode,\n VerificationCodeResult,\n} from \"./types\";\n",
|
|
62
62
|
"type": "registry:block"
|
|
63
63
|
},
|
|
64
64
|
{
|
|
65
|
-
"path": "src/
|
|
65
|
+
"path": "src/features/login-page/types.ts",
|
|
66
66
|
"content": "import type { ReactNode } from \"react\";\n\n/**\n * Every string the page renders. The host supplies translated copy; the module\n * owns no user-facing text of its own, so a host that follows the fewbie\n * i18n rule (display copy lives in the host message files) stays compliant.\n */\nexport interface LoginLabels {\n title: string;\n description: string;\n tabPassword: string;\n tabVerificationCode: string;\n email: string;\n password: string;\n submit: string;\n verificationCode: string;\n getCode: string;\n orContinueWith: string;\n back: string;\n clearEmail: string;\n clearPassword: string;\n hidePassword: string;\n showPassword: string;\n clearCode: string;\n invalidEmail: string;\n emailRequired: string;\n passwordMin: string;\n passwordRequired: string;\n codeDigits: string;\n codeRequired: string;\n invalidCredentials: string;\n loginFailed: string;\n totpLabel: string;\n totpHint: string;\n totpSubmit: string;\n}\n\n/** One third-party sign-in entry; the host owns the URL and the brand mark. */\nexport interface LoginOAuthProvider {\n /** Stable key for React, e.g. \"google\". */\n id: string;\n label: string;\n /** Absolute URL of the provider's backend entry point. */\n href: string;\n icon?: ReactNode;\n}\n\nexport interface LoginCredentials {\n account: string;\n password: string;\n}\n\nexport interface LoginVerificationCode {\n account: string;\n verificationCode: string;\n}\n\n/** Second factor for a sign-in the backend already accepted. */\nexport interface LoginTotpChallenge {\n totpToken: string;\n code: string;\n}\n\nexport interface LoginResult {\n /** True only when a session was established. */\n ok: boolean;\n /** The backend rejected the credentials (as opposed to a transport error). */\n invalidCredentials?: boolean;\n /** A second factor is still required; the page renders the authenticator form. */\n multiFactorRequired?: boolean;\n totpToken?: string;\n}\n\nexport interface VerificationCodeResult {\n ok: boolean;\n /** Resend cooldown reported by the backend; defaults to 60 seconds. */\n secondsOfCountdown?: number;\n}\n\n/**\n * Host-owned transport and side effects. The module never calls fetch or the\n * router: the host decides how to reach its backend and where to navigate.\n */\nexport interface LoginPort {\n signIn(input: LoginCredentials | LoginVerificationCode | LoginTotpChallenge): Promise<LoginResult>;\n sendVerificationCode(email: string): Promise<VerificationCodeResult>;\n}\n\nexport interface LoginPageProps {\n labels: LoginLabels;\n port: LoginPort;\n /** Persistent banners (pending approval, disabled account, ...), host-styled. */\n notices?: ReactNode;\n /** Third-party providers; the divider is hidden when empty. */\n oauthProviders?: LoginOAuthProvider[];\n /** Called after a successful sign-in; the host navigates. */\n onSignedIn?: () => void;\n /** Called after a verification code was sent; the host may toast. */\n onCodeSent?: () => void;\n}\n",
|
|
67
67
|
"type": "registry:block"
|
|
68
68
|
},
|
|
69
69
|
{
|
|
70
|
-
"path": "src/
|
|
70
|
+
"path": "src/features/login-page/login-page.tsx",
|
|
71
71
|
"content": "\"use client\";\n\nimport { useEffect, useState, type FormEvent } from \"react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent, CardDescription, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Tabs, TabsList, TabsTrigger } from \"@/components/ui/tabs\";\nimport type { LoginLabels, LoginPageProps, LoginResult } from \"./types\";\n\ntype LoginMode = \"password\" | \"code\";\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst CODE_LENGTH = 6;\nconst DEFAULT_RESEND_SECONDS = 60;\n\nfunction Spinner() {\n return (\n <span\n aria-hidden=\"true\"\n className=\"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent\"\n />\n );\n}\n\nfunction ClearIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M18 6 6 18M6 6l12 12\" />\n </svg>\n );\n}\n\nfunction EyeIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z\" />\n <circle cx=\"12\" cy=\"12\" r=\"3\" />\n </svg>\n );\n}\n\nfunction EyeOffIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M3 3l18 18\" />\n <path d=\"M10.6 10.6a3 3 0 0 0 4.2 4.2\" />\n <path d=\"M9.9 5.2A10.9 10.9 0 0 1 12 5c6.5 0 10 7 10 7a17.6 17.6 0 0 1-3.2 4.1\" />\n <path d=\"M6.2 6.2A17.4 17.4 0 0 0 2 12s3.5 7 10 7a10.6 10.6 0 0 0 4.2-.9\" />\n </svg>\n );\n}\n\n/**\n * Page-level login module: password and verification-code tabs, an inline TOTP\n * challenge, and third-party entries. Transport, navigation, toasts and brand\n * shell belong to the host and enter through `port`, `oauthProviders` and the\n * `onSignedIn`/`onCodeSent` callbacks.\n */\nexport function LoginPage({ labels, port, notices, oauthProviders, onSignedIn, onCodeSent }: LoginPageProps) {\n const [mode, setMode] = useState<LoginMode>(\"password\");\n const [showPassword, setShowPassword] = useState(false);\n // Seconds left before the user can request another verification code.\n const [secondsLeft, setSecondsLeft] = useState(0);\n // When set, the primary factor was accepted and the user must finish login\n // with a TOTP code from their authenticator app.\n const [mfaToken, setMfaToken] = useState<string | null>(null);\n const [error, setError] = useState<string | null>(null);\n\n const [passwordEmail, setPasswordEmail] = useState(\"\");\n const [password, setPasswordValue] = useState(\"\");\n const [passwordErrors, setPasswordErrors] = useState<{ email?: string; password?: string }>({});\n\n const [codeEmail, setCodeEmail] = useState(\"\");\n const [code, setCode] = useState(\"\");\n const [codeErrors, setCodeErrors] = useState<{ email?: string; code?: string }>({});\n\n const [pending, setPending] = useState(false);\n const [sendPending, setSendPending] = useState(false);\n\n const isCountingDown = secondsLeft > 0;\n\n // Countdown timer for resending the verification code.\n useEffect(() => {\n if (!isCountingDown) return;\n const timer = setInterval(() => setSecondsLeft((prev) => Math.max(0, prev - 1)), 1000);\n return () => clearInterval(timer);\n }, [isCountingDown]);\n\n function complete(result: LoginResult): void {\n if (result.multiFactorRequired && result.totpToken) {\n setMfaToken(result.totpToken);\n return;\n }\n if (!result.ok) {\n setError(result.invalidCredentials ? labels.invalidCredentials : labels.loginFailed);\n return;\n }\n onSignedIn?.();\n }\n\n async function submit(input: Parameters<LoginPageProps[\"port\"][\"signIn\"]>[0]): Promise<void> {\n setPending(true);\n setError(null);\n try {\n complete(await port.signIn(input));\n } catch {\n setError(labels.loginFailed);\n } finally {\n setPending(false);\n }\n }\n\n function validateEmail(value: string): string | undefined {\n if (!value.trim()) return labels.emailRequired;\n if (!EMAIL_PATTERN.test(value)) return labels.invalidEmail;\n return undefined;\n }\n\n function onPasswordSubmit(event: FormEvent<HTMLFormElement>): void {\n event.preventDefault();\n const nextErrors = {\n email: validateEmail(passwordEmail),\n password: !password ? labels.passwordRequired : password.length < 8 ? labels.passwordMin : undefined,\n };\n setPasswordErrors(nextErrors);\n if (nextErrors.email || nextErrors.password) return;\n void submit({ account: passwordEmail, password });\n }\n\n function onCodeSubmit(event: FormEvent<HTMLFormElement>): void {\n event.preventDefault();\n const nextErrors = {\n email: validateEmail(codeEmail),\n code: !code ? labels.codeRequired : code.length !== CODE_LENGTH ? labels.codeDigits : undefined,\n };\n setCodeErrors(nextErrors);\n if (nextErrors.email || nextErrors.code) return;\n void submit({ account: codeEmail, verificationCode: code });\n }\n\n async function handleSendCode(): Promise<void> {\n if (secondsLeft > 0 || sendPending) return;\n const emailError = validateEmail(codeEmail);\n setCodeErrors((prev) => ({ ...prev, email: emailError }));\n if (emailError) return;\n\n setSendPending(true);\n try {\n const result = await port.sendVerificationCode(codeEmail);\n if (!result.ok) {\n setError(labels.loginFailed);\n return;\n }\n // Follow the resend cooldown returned by the backend.\n setSecondsLeft(result.secondsOfCountdown ?? DEFAULT_RESEND_SECONDS);\n onCodeSent?.();\n } catch {\n setError(labels.loginFailed);\n } finally {\n setSendPending(false);\n }\n }\n\n // Switch login mode while carrying the typed email between the two forms.\n function handleModeChange(value: LoginMode): void {\n if (value === \"code\") {\n if (passwordEmail) setCodeEmail(passwordEmail);\n } else if (codeEmail) {\n setPasswordEmail(codeEmail);\n }\n setError(null);\n setMode(value);\n }\n\n const showOAuth = (oauthProviders?.length ?? 0) > 0;\n\n return (\n <Card className=\"w-full shadow-sm\">\n <CardHeader>\n <CardTitle className=\"text-xl\">{labels.title}</CardTitle>\n <CardDescription>{labels.description}</CardDescription>\n </CardHeader>\n <CardContent>\n {notices}\n\n <Tabs value={mode} onValueChange={(value) => handleModeChange(value as LoginMode)} className=\"mb-6\">\n <TabsList className=\"w-full\">\n <TabsTrigger value=\"password\">{labels.tabPassword}</TabsTrigger>\n <TabsTrigger value=\"code\">{labels.tabVerificationCode}</TabsTrigger>\n </TabsList>\n </Tabs>\n\n {/* MFA challenge — primary factor accepted, TOTP code still required */}\n {mfaToken && (\n <TotpChallenge\n labels={labels}\n isPending={pending}\n onSubmit={(totpCode) => void submit({ totpToken: mfaToken, code: totpCode })}\n onBack={() => {\n setError(null);\n setMfaToken(null);\n }}\n />\n )}\n\n {/* Password login form. method=\"post\" keeps a native submit (before\n hydration) from serializing credentials into the query string. */}\n {mode === \"password\" && !mfaToken && (\n <form method=\"post\" onSubmit={onPasswordSubmit} noValidate className=\"space-y-5\">\n <div className=\"space-y-2\">\n <Label htmlFor=\"login-page-email\">{labels.email}</Label>\n <div className=\"relative\">\n <Input\n id=\"login-page-email\"\n autoComplete=\"email\"\n value={passwordEmail}\n onChange={(event) => setPasswordEmail(event.target.value)}\n className=\"pr-10\"\n />\n {passwordEmail && (\n <button\n type=\"button\"\n onClick={() => setPasswordEmail(\"\")}\n className=\"absolute top-1/2 right-2 -translate-y-1/2 text-muted-foreground hover:text-foreground\"\n aria-label={labels.clearEmail}\n >\n <ClearIcon />\n </button>\n )}\n </div>\n {passwordErrors.email && <p className=\"text-sm text-destructive\">{passwordErrors.email}</p>}\n </div>\n\n <div className=\"space-y-2\">\n <Label htmlFor=\"login-page-password\">{labels.password}</Label>\n <div className=\"relative\">\n <Input\n id=\"login-page-password\"\n type={showPassword ? \"text\" : \"password\"}\n autoComplete=\"current-password\"\n value={password}\n onChange={(event) => setPasswordValue(event.target.value)}\n className=\"pr-20\"\n />\n <div className=\"absolute top-1/2 right-2 flex -translate-y-1/2 items-center gap-1\">\n {password && (\n <button\n type=\"button\"\n onClick={() => setPasswordValue(\"\")}\n className=\"text-muted-foreground hover:text-foreground\"\n aria-label={labels.clearPassword}\n >\n <ClearIcon />\n </button>\n )}\n <button\n type=\"button\"\n onClick={() => setShowPassword((prev) => !prev)}\n className=\"text-muted-foreground hover:text-foreground\"\n aria-label={showPassword ? labels.hidePassword : labels.showPassword}\n >\n {showPassword ? <EyeOffIcon /> : <EyeIcon />}\n </button>\n </div>\n </div>\n {passwordErrors.password && <p className=\"text-sm text-destructive\">{passwordErrors.password}</p>}\n </div>\n\n {error && <p className=\"text-sm text-destructive\">{error}</p>}\n\n <Button type=\"submit\" className=\"w-full\" disabled={pending}>\n {pending ? <Spinner /> : labels.submit}\n </Button>\n </form>\n )}\n\n {/* Verification code login form */}\n {mode === \"code\" && !mfaToken && (\n <form method=\"post\" onSubmit={onCodeSubmit} noValidate className=\"space-y-5\">\n <div className=\"space-y-2\">\n <Label htmlFor=\"login-page-code-email\">{labels.email}</Label>\n <div className=\"relative\">\n <Input\n id=\"login-page-code-email\"\n autoComplete=\"email\"\n value={codeEmail}\n onChange={(event) => setCodeEmail(event.target.value)}\n className=\"pr-10\"\n />\n {codeEmail && (\n <button\n type=\"button\"\n onClick={() => setCodeEmail(\"\")}\n className=\"absolute top-1/2 right-2 -translate-y-1/2 text-muted-foreground hover:text-foreground\"\n aria-label={labels.clearEmail}\n >\n <ClearIcon />\n </button>\n )}\n </div>\n {codeErrors.email && <p className=\"text-sm text-destructive\">{codeErrors.email}</p>}\n </div>\n\n <div className=\"space-y-2\">\n <Label htmlFor=\"login-page-code\">{labels.verificationCode}</Label>\n <div className=\"relative\">\n <Input\n id=\"login-page-code\"\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n value={code}\n onChange={(event) => setCode(event.target.value.replace(/\\D/g, \"\").slice(0, CODE_LENGTH))}\n className=\"pr-32\"\n />\n <div className=\"absolute top-1/2 right-2 flex -translate-y-1/2 items-center gap-2\">\n {code && (\n <button\n type=\"button\"\n onClick={() => setCode(\"\")}\n className=\"text-muted-foreground hover:text-foreground\"\n aria-label={labels.clearCode}\n >\n <ClearIcon />\n </button>\n )}\n <Button\n type=\"button\"\n variant=\"link\"\n size=\"sm\"\n className=\"h-auto p-0 text-xs font-normal\"\n onClick={() => void handleSendCode()}\n disabled={secondsLeft > 0 || sendPending}\n >\n {sendPending ? <Spinner /> : secondsLeft > 0 ? `${secondsLeft}s` : labels.getCode}\n </Button>\n </div>\n </div>\n {codeErrors.code && <p className=\"text-sm text-destructive\">{codeErrors.code}</p>}\n </div>\n\n {error && <p className=\"text-sm text-destructive\">{error}</p>}\n\n <Button type=\"submit\" className=\"w-full\" disabled={pending}>\n {pending ? <Spinner /> : labels.submit}\n </Button>\n </form>\n )}\n\n {/* Third-party entries */}\n {showOAuth && (\n <div className=\"mt-6\">\n <div className=\"relative mb-4\">\n <div className=\"absolute inset-0 flex items-center\">\n <span className=\"w-full border-t\" />\n </div>\n <div className=\"relative flex justify-center text-xs uppercase\">\n <span className=\"bg-card px-2 text-muted-foreground\">{labels.orContinueWith}</span>\n </div>\n </div>\n {oauthProviders?.map((provider, index) => (\n <Button key={provider.id} asChild variant=\"outline\" className={index === 0 ? \"w-full\" : \"mt-3 w-full\"}>\n <a href={provider.href}>\n {provider.icon && <span className=\"mr-2 inline-flex items-center\">{provider.icon}</span>}\n {provider.label}\n </a>\n </Button>\n ))}\n </div>\n )}\n </CardContent>\n </Card>\n );\n}\n\ninterface TotpChallengeProps {\n labels: LoginLabels;\n isPending: boolean;\n onSubmit: (code: string) => void;\n onBack: () => void;\n}\n\nfunction TotpChallenge({ labels, isPending, onSubmit, onBack }: TotpChallengeProps) {\n const [totpCode, setTotpCode] = useState(\"\");\n\n return (\n <form\n method=\"post\"\n onSubmit={(event) => {\n event.preventDefault();\n if (totpCode.length === CODE_LENGTH) onSubmit(totpCode);\n }}\n noValidate\n className=\"space-y-5\"\n >\n <div className=\"space-y-2\">\n <Label htmlFor=\"login-page-totp\">{labels.totpLabel}</Label>\n <Input\n id=\"login-page-totp\"\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n value={totpCode}\n onChange={(event) => setTotpCode(event.target.value.replace(/\\D/g, \"\").slice(0, CODE_LENGTH))}\n placeholder=\"123456\"\n autoFocus\n />\n <p className=\"text-xs text-muted-foreground\">{labels.totpHint}</p>\n </div>\n\n <Button type=\"submit\" className=\"w-full\" disabled={isPending || totpCode.length !== CODE_LENGTH}>\n {isPending ? <Spinner /> : labels.totpSubmit}\n </Button>\n <Button type=\"button\" variant=\"link\" size=\"sm\" className=\"w-full\" onClick={onBack}>\n {labels.back}\n </Button>\n </form>\n );\n}\n",
|
|
72
72
|
"type": "registry:block"
|
|
73
73
|
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": "1.0.0",
|
|
3
|
+
"framework": "^1.7.0",
|
|
4
|
+
"entry": "src/components/notification-center/index.ts",
|
|
5
|
+
"labels": [
|
|
6
|
+
"ariaLatestNotification",
|
|
7
|
+
"ariaRead",
|
|
8
|
+
"ariaUnread",
|
|
9
|
+
"badgeAlertRecovered",
|
|
10
|
+
"bellLabel",
|
|
11
|
+
"contextLabel",
|
|
12
|
+
"deliveryReasonDeliver",
|
|
13
|
+
"deliveryReasonLabel",
|
|
14
|
+
"deliveryReasonMissing",
|
|
15
|
+
"deliveryReasonNoMatch",
|
|
16
|
+
"deliveryReasonRule",
|
|
17
|
+
"deliveryReasonSuppress",
|
|
18
|
+
"detailLabel",
|
|
19
|
+
"detailsLabel",
|
|
20
|
+
"empty",
|
|
21
|
+
"greetingAllQuiet",
|
|
22
|
+
"greetingCaughtUp",
|
|
23
|
+
"greetingInboxZero",
|
|
24
|
+
"greetingNoAlerts",
|
|
25
|
+
"greetingNothingToDo",
|
|
26
|
+
"loading",
|
|
27
|
+
"markAllRead",
|
|
28
|
+
"occurrencesCount",
|
|
29
|
+
"occurrencesLabel",
|
|
30
|
+
"openAlertCenter",
|
|
31
|
+
"openLinkedPage",
|
|
32
|
+
"pushFailedMany",
|
|
33
|
+
"pushFailedOne",
|
|
34
|
+
"read",
|
|
35
|
+
"selectPrompt",
|
|
36
|
+
"severityCritical",
|
|
37
|
+
"severityHigh",
|
|
38
|
+
"severityLow",
|
|
39
|
+
"severityMedium",
|
|
40
|
+
"severityUnknown",
|
|
41
|
+
"sourceLabel",
|
|
42
|
+
"unread",
|
|
43
|
+
"viewAll"
|
|
44
|
+
],
|
|
45
|
+
"ports": [
|
|
46
|
+
"fetchDeliveryAttempt",
|
|
47
|
+
"fetchPushFailures",
|
|
48
|
+
"fetchRecent",
|
|
49
|
+
"fetchUnread",
|
|
50
|
+
"fetchUnreadCount",
|
|
51
|
+
"markAllRead",
|
|
52
|
+
"markRead"
|
|
53
|
+
],
|
|
54
|
+
"ui": [
|
|
55
|
+
"badge",
|
|
56
|
+
"button",
|
|
57
|
+
"popover",
|
|
58
|
+
"separator",
|
|
59
|
+
"sheet",
|
|
60
|
+
"tooltip"
|
|
61
|
+
],
|
|
62
|
+
"states": [
|
|
63
|
+
"loading",
|
|
64
|
+
"empty",
|
|
65
|
+
"ready"
|
|
66
|
+
]
|
|
67
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/r/registry-item.json",
|
|
3
|
+
"name": "notification-center",
|
|
4
|
+
"type": "registry:component",
|
|
5
|
+
"x-fewbie.contract": {
|
|
6
|
+
"version": "1.0.0",
|
|
7
|
+
"framework": "^1.7.0",
|
|
8
|
+
"entry": "src/components/notification-center/index.ts",
|
|
9
|
+
"labels": [
|
|
10
|
+
"ariaLatestNotification",
|
|
11
|
+
"ariaRead",
|
|
12
|
+
"ariaUnread",
|
|
13
|
+
"badgeAlertRecovered",
|
|
14
|
+
"bellLabel",
|
|
15
|
+
"contextLabel",
|
|
16
|
+
"deliveryReasonDeliver",
|
|
17
|
+
"deliveryReasonLabel",
|
|
18
|
+
"deliveryReasonMissing",
|
|
19
|
+
"deliveryReasonNoMatch",
|
|
20
|
+
"deliveryReasonRule",
|
|
21
|
+
"deliveryReasonSuppress",
|
|
22
|
+
"detailLabel",
|
|
23
|
+
"detailsLabel",
|
|
24
|
+
"empty",
|
|
25
|
+
"greetingAllQuiet",
|
|
26
|
+
"greetingCaughtUp",
|
|
27
|
+
"greetingInboxZero",
|
|
28
|
+
"greetingNoAlerts",
|
|
29
|
+
"greetingNothingToDo",
|
|
30
|
+
"loading",
|
|
31
|
+
"markAllRead",
|
|
32
|
+
"occurrencesCount",
|
|
33
|
+
"occurrencesLabel",
|
|
34
|
+
"openAlertCenter",
|
|
35
|
+
"openLinkedPage",
|
|
36
|
+
"pushFailedMany",
|
|
37
|
+
"pushFailedOne",
|
|
38
|
+
"read",
|
|
39
|
+
"selectPrompt",
|
|
40
|
+
"severityCritical",
|
|
41
|
+
"severityHigh",
|
|
42
|
+
"severityLow",
|
|
43
|
+
"severityMedium",
|
|
44
|
+
"severityUnknown",
|
|
45
|
+
"sourceLabel",
|
|
46
|
+
"unread",
|
|
47
|
+
"viewAll"
|
|
48
|
+
],
|
|
49
|
+
"ports": [
|
|
50
|
+
"fetchDeliveryAttempt",
|
|
51
|
+
"fetchPushFailures",
|
|
52
|
+
"fetchRecent",
|
|
53
|
+
"fetchUnread",
|
|
54
|
+
"fetchUnreadCount",
|
|
55
|
+
"markAllRead",
|
|
56
|
+
"markRead"
|
|
57
|
+
],
|
|
58
|
+
"ui": [
|
|
59
|
+
"badge",
|
|
60
|
+
"button",
|
|
61
|
+
"popover",
|
|
62
|
+
"separator",
|
|
63
|
+
"sheet",
|
|
64
|
+
"tooltip"
|
|
65
|
+
],
|
|
66
|
+
"states": [
|
|
67
|
+
"loading",
|
|
68
|
+
"empty",
|
|
69
|
+
"ready"
|
|
70
|
+
]
|
|
71
|
+
},
|
|
72
|
+
"files": [
|
|
73
|
+
{
|
|
74
|
+
"path": "src/components/notification-center/types.ts",
|
|
75
|
+
"content": "import type { LucideIcon } from \"lucide-react\";\n\n/**\n * Every string the surfaces render. The host supplies translated copy, so the\n * item carries no vocabulary of its own. `{count}` / `{id}` / `{title}` are\n * replaced by `interpolate` from `format.ts`.\n */\nexport interface NotificationCenterLabels {\n bellLabel: string;\n markAllRead: string;\n loading: string;\n empty: string;\n viewAll: string;\n ariaRead: string;\n ariaUnread: string;\n ariaLatestNotification: string;\n detailsLabel: string;\n selectPrompt: string;\n occurrencesCount: string;\n sourceLabel: string;\n detailLabel: string;\n openAlertCenter: string;\n openLinkedPage: string;\n occurrencesLabel: string;\n deliveryReasonLabel: string;\n deliveryReasonMissing: string;\n deliveryReasonSuppress: string;\n deliveryReasonDeliver: string;\n deliveryReasonRule: string;\n deliveryReasonNoMatch: string;\n contextLabel: string;\n severityCritical: string;\n severityHigh: string;\n severityMedium: string;\n severityLow: string;\n severityUnknown: string;\n badgeAlertRecovered: string;\n read: string;\n unread: string;\n pushFailedOne: string;\n pushFailedMany: string;\n greetingAllQuiet: string;\n greetingNothingToDo: string;\n greetingCaughtUp: string;\n greetingNoAlerts: string;\n greetingInboxZero: string;\n}\n\n/** One record as the host's API returns it, trimmed to what the surfaces read. */\nexport interface NotificationRecord {\n id: string;\n notificationKey: string;\n title: string;\n detail?: string | null;\n severity: string;\n /** Lifecycle status; `resolved` renders the recovered badge instead of severity. */\n status: string;\n read: boolean;\n link?: string | null;\n sourceType?: string | null;\n payload?: unknown;\n createdAt: string;\n}\n\n/** Host-owned mapping from a notification key to its copy and category. */\nexport interface NotificationMetaEntry {\n label: string;\n category?: string;\n}\n\n/** Icon and tint per host category; unknown categories fall back. */\nexport interface NotificationCategoryVisual {\n icon: LucideIcon;\n className: string;\n}\n\n/** Delivery decision recorded for one notification, fetched on expand. */\nexport interface NotificationDeliveryAttempt {\n decision: string;\n reason?: string | null;\n ruleId?: string | null;\n createdAt: string;\n /** Already-localized runtime interception reason, if the host resolves one. */\n runtimeReasonLabel?: string | null;\n}\n\n/** One unresolved push failure row. */\nexport interface NotificationPushFailure {\n id: string;\n recipientKey: string;\n notificationTitle?: string | null;\n error: string;\n createdAt: string;\n}\n\n/**\n * Host-owned transport. The item never imports `fetch`, a router, a query\n * library or a toast library; polling, loading and error handling stay here.\n */\nexport interface NotificationCenterPort {\n fetchUnreadCount(): Promise<number>;\n fetchRecent(limit: number): Promise<NotificationRecord[]>;\n fetchUnread(limit: number): Promise<NotificationRecord[]>;\n markAllRead(): Promise<number>;\n markRead(id: string): Promise<void>;\n fetchDeliveryAttempt?(id: string): Promise<NotificationDeliveryAttempt | null>;\n fetchPushFailures?(): Promise<NotificationPushFailure[]>;\n}\n\nexport interface NotificationCenterProps {\n labels: NotificationCenterLabels;\n port: NotificationCenterPort;\n /** Domain mapping: notification key -> translated label + host category. */\n resolveMeta: (notificationKey: string) => NotificationMetaEntry;\n categoryVisuals: Record<string, NotificationCategoryVisual>;\n fallbackVisual: NotificationCategoryVisual;\n /** Best-effort attribution line; the host owns which payload fields matter. */\n resolveSource?: (notification: NotificationRecord) => string | null;\n /** Host-owned navigation; the item never imports a router. */\n onNavigate: (path: string) => void;\n onOpenLink: (link: string) => void;\n /** Locale for relative time and timestamps; defaults to the browser locale. */\n locale?: string;\n notificationsPath?: string;\n alertCenterPath?: string;\n pollIntervalMs?: number;\n /** Called after a successful mark-all-read so the host can toast. */\n onMarkedRead?: (count: number) => void;\n /** Called when a transport call fails so the host can toast or log it. */\n onError?: (error: unknown) => void;\n className?: string;\n}\n",
|
|
76
|
+
"type": "registry:component"
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
"path": "src/components/notification-center/format.ts",
|
|
80
|
+
"content": "/**\n * Locale formatting, title normalization and grouping helpers. These are\n * generic presentation concerns, so they stay in the item; anything that names\n * a host's notification keys lives in the host and enters through `resolveMeta`\n * and `resolveSource`.\n */\nimport type { NotificationRecord } from \"./types\";\n\nconst STATUS_MARKERS = [\"\\u{1F534}\", \"\\u{1F7E0}\", \"\\u{1F7E2}\", \"\\u{1F518}\"] as const;\n\n/** Replace `{name}` placeholders; missing values are left untouched. */\nexport function interpolate(template: string, values: Record<string, string | number>): string {\n return template.replace(/\\{(\\w+)\\}/g, (match, name: string) => (name in values ? String(values[name]) : match));\n}\n\n/** Drop a leading status emoji so in-app surfaces can show their own indicator. */\nexport function stripTitleMarker(title: string): string {\n const marker = STATUS_MARKERS.find((candidate) => title.startsWith(candidate));\n return marker ? title.slice(marker.length).trimStart() : title;\n}\n\nexport function resolveLocale(locale?: string): string {\n return locale ?? (typeof navigator === \"undefined\" ? \"en\" : navigator.language);\n}\n\nconst RELATIVE_DIVISIONS: Array<{ amount: number; unit: Intl.RelativeTimeFormatUnit }> = [\n { amount: 60, unit: \"second\" },\n { amount: 60, unit: \"minute\" },\n { amount: 24, unit: \"hour\" },\n { amount: 7, unit: \"day\" },\n { amount: 4.34524, unit: \"week\" },\n { amount: 12, unit: \"month\" },\n { amount: Number.POSITIVE_INFINITY, unit: \"year\" },\n];\n\n/** Localized \"3 minutes ago\" using only `Intl`, with no date library. */\nexport function formatRelativeTime(value: string, locale: string, now: Date = new Date()): string {\n const formatter = new Intl.RelativeTimeFormat(locale, { numeric: \"auto\" });\n let duration = (new Date(value).getTime() - now.getTime()) / 1000;\n for (const division of RELATIVE_DIVISIONS) {\n if (Math.abs(duration) < division.amount) {\n return formatter.format(Math.round(duration), division.unit);\n }\n duration /= division.amount;\n }\n return formatter.format(Math.round(duration), \"year\");\n}\n\n/** Absolute timestamp; `timeStyle` covers the long hover form and the seconds column. */\nexport function formatTimestamp(value: string, locale: string, timeStyle: \"short\" | \"medium\" = \"short\"): string {\n return new Intl.DateTimeFormat(locale, { dateStyle: \"short\", timeStyle }).format(new Date(value));\n}\n\n/** Day bucket key: `today`/`yesterday` sentinels, otherwise an ISO date. */\nexport function dayBucket(value: string, now: Date = new Date()): \"today\" | \"yesterday\" | string {\n const target = new Date(value);\n const sameDay = (left: Date, right: Date) =>\n left.getFullYear() === right.getFullYear() &&\n left.getMonth() === right.getMonth() &&\n left.getDate() === right.getDate();\n if (sameDay(target, now)) return \"today\";\n const yesterday = new Date(now);\n yesterday.setDate(now.getDate() - 1);\n if (sameDay(target, yesterday)) return \"yesterday\";\n return `${target.getFullYear()}-${String(target.getMonth() + 1).padStart(2, \"0\")}-${String(target.getDate()).padStart(2, \"0\")}`;\n}\n\nconst SEVERITY_DOT: Record<string, string> = {\n critical: \"bg-destructive\",\n high: \"bg-destructive/70\",\n medium: \"bg-warning\",\n low: \"bg-primary\",\n unknown: \"bg-muted-foreground/50\",\n};\n\n/** Recovery is a lifecycle state, not an alert level, so it reads green. */\nexport function notificationDotClass(status: string, severity: string): string {\n if (status === \"resolved\") return \"bg-success\";\n return SEVERITY_DOT[severity] ?? SEVERITY_DOT.unknown;\n}\n\nconst SEVERITY_BADGE: Record<string, string> = {\n critical: \"border-destructive/30 bg-destructive/10 text-destructive\",\n high: \"border-destructive/30 bg-destructive/10 text-destructive\",\n medium: \"border-warning/30 bg-warning/10 text-warning\",\n low: \"border-primary/30 bg-primary/10 text-primary\",\n unknown: \"border-border bg-muted text-muted-foreground\",\n};\n\nexport function severityBadgeClass(severity: string): string {\n return SEVERITY_BADGE[severity] ?? SEVERITY_BADGE.unknown;\n}\n\nexport function severityLabelKey(\n severity: string,\n): \"severityCritical\" | \"severityHigh\" | \"severityMedium\" | \"severityLow\" | \"severityUnknown\" {\n switch (severity) {\n case \"critical\":\n return \"severityCritical\";\n case \"high\":\n return \"severityHigh\";\n case \"medium\":\n return \"severityMedium\";\n case \"low\":\n return \"severityLow\";\n default:\n return \"severityUnknown\";\n }\n}\n\n/** Repeated alerts (same key, title and source on the same day) collapse into one row. */\nexport interface NotificationGroup {\n key: string;\n latest: NotificationRecord;\n records: NotificationRecord[];\n unreadIds: string[];\n}\n\nexport interface NotificationDayGroup {\n label: \"today\" | \"yesterday\" | string;\n groups: NotificationGroup[];\n}\n\nexport function groupNotifications(\n records: NotificationRecord[],\n resolveSource?: (notification: NotificationRecord) => string | null,\n): NotificationDayGroup[] {\n const days = new Map<string, Map<string, NotificationGroup>>();\n\n for (const record of records) {\n const day = dayBucket(record.createdAt);\n const groupKey = [day, record.notificationKey, record.title, resolveSource?.(record) ?? \"\"].join(\"|\");\n let groups = days.get(day);\n if (!groups) {\n groups = new Map();\n days.set(day, groups);\n }\n const existing = groups.get(groupKey);\n if (existing) {\n existing.records.push(record);\n if (!record.read) existing.unreadIds.push(record.id);\n continue;\n }\n groups.set(groupKey, {\n key: groupKey,\n latest: record,\n records: [record],\n unreadIds: record.read ? [] : [record.id],\n });\n }\n\n return Array.from(days.values()).map((groups) => {\n const list = Array.from(groups.values());\n return { label: dayBucket(list[0].latest.createdAt), groups: list };\n });\n}\n",
|
|
81
|
+
"type": "registry:component"
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
"path": "src/components/notification-center/notification-center.tsx",
|
|
85
|
+
"content": "\"use client\";\n\nimport { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from \"react\";\nimport type { NotificationCenterProps } from \"./types\";\n\nconst NotificationCenterContext = createContext<NotificationCenterProps | null>(null);\n\n/**\n * Supplies copy, transport and host callbacks to every surface in this item.\n * The provider is required: labels and ports are never hard-coded here.\n */\nexport function NotificationCenterProvider({ children, ...props }: NotificationCenterProps & { children: ReactNode }) {\n return <NotificationCenterContext.Provider value={props}>{children}</NotificationCenterContext.Provider>;\n}\n\nexport function useNotificationCenter(): NotificationCenterProps {\n const value = useContext(NotificationCenterContext);\n if (!value) {\n throw new Error(\"NotificationCenter surfaces must render inside <NotificationCenterProvider>.\");\n }\n return value;\n}\n\nexport interface PolledResult<T> {\n data: T | undefined;\n loading: boolean;\n error: unknown;\n reload: () => void;\n}\n\n/**\n * Minimal polling loader: no query library, so the item installs into any host\n * without a `QueryClientProvider`. The first load owns the loading state; later\n * polls refresh silently.\n */\nexport function usePolled<T>(load: () => Promise<T>, intervalMs: number, enabled = true): PolledResult<T> {\n const [data, setData] = useState<T | undefined>(undefined);\n const [loading, setLoading] = useState(enabled);\n const [error, setError] = useState<unknown>(undefined);\n const [nonce, setNonce] = useState(0);\n const loaded = useRef(false);\n const loadRef = useRef(load);\n\n useEffect(() => {\n loadRef.current = load;\n });\n\n useEffect(() => {\n if (!enabled) return;\n let alive = true;\n const run = async () => {\n if (!loaded.current) setLoading(true);\n try {\n const next = await loadRef.current();\n if (!alive) return;\n loaded.current = true;\n setData(next);\n setError(undefined);\n } catch (caught) {\n if (alive) setError(caught);\n } finally {\n if (alive) setLoading(false);\n }\n };\n void run();\n const timer = intervalMs > 0 ? window.setInterval(() => void run(), intervalMs) : undefined;\n return () => {\n alive = false;\n if (timer !== undefined) window.clearInterval(timer);\n };\n }, [enabled, intervalMs, nonce]);\n\n const reload = useCallback(() => setNonce((value) => value + 1), []);\n return { data, loading, error, reload };\n}\n",
|
|
86
|
+
"type": "registry:component"
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
"path": "src/components/notification-center/notification-detail.tsx",
|
|
90
|
+
"content": "\"use client\";\n\nimport { createElement, useCallback, useEffect, useState } from \"react\";\nimport { AlertTriangle, ExternalLink, Inbox, LoaderCircle } from \"lucide-react\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { Button } from \"@/components/ui/button\";\nimport { Separator } from \"@/components/ui/separator\";\nimport { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from \"@/components/ui/sheet\";\nimport { useNotificationCenter } from \"./notification-center\";\nimport {\n formatRelativeTime,\n formatTimestamp,\n interpolate,\n resolveLocale,\n severityBadgeClass,\n severityLabelKey,\n stripTitleMarker,\n type NotificationGroup,\n} from \"./format\";\nimport type { NotificationDeliveryAttempt, NotificationRecord } from \"./types\";\n\n/** Current time, refreshed periodically so relative labels do not go stale. */\nexport function useNow(intervalMs = 60_000): Date {\n const [now, setNow] = useState(() => new Date());\n useEffect(() => {\n const timer = window.setInterval(() => setNow(new Date()), intervalMs);\n return () => window.clearInterval(timer);\n }, [intervalMs]);\n return now;\n}\n\nexport function RelativeTime({ value, className }: { value: string; className?: string }) {\n const { locale } = useNotificationCenter();\n const resolved = resolveLocale(locale);\n const now = useNow(60_000);\n return (\n <time dateTime={value} title={formatTimestamp(value, resolved, \"medium\")} className={className}>\n {formatRelativeTime(value, resolved, now)}\n </time>\n );\n}\n\nexport function SeverityBadge({ severity, className }: { severity: string; className?: string }) {\n const { labels } = useNotificationCenter();\n return (\n <Badge variant=\"outline\" className={`${severityBadgeClass(severity)} ${className ?? \"\"}`}>\n {labels[severityLabelKey(severity)]}\n </Badge>\n );\n}\n\nexport function RecoveredBadge({ className }: { className?: string }) {\n const { labels } = useNotificationCenter();\n return (\n <Badge variant=\"outline\" className={`border-success/30 bg-success/10 text-success ${className ?? \"\"}`}>\n {labels.badgeAlertRecovered}\n </Badge>\n );\n}\n\n/** camelCase payload keys become readable labels, e.g. \"projectName\" -> \"Project Name\". */\nfunction humanizeKey(key: string): string {\n const spaced = key.replace(/([A-Z])/g, \" $1\").replace(/[_-]+/g, \" \");\n return spaced.charAt(0).toUpperCase() + spaced.slice(1);\n}\n\nfunction formatPayloadValue(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n if (typeof value === \"object\") return JSON.stringify(value, null, 2);\n return String(value);\n}\n\n/** Key/value table of the notification context payload, shared by sheet and panel. */\nexport function NotificationContextTable({ payload }: { payload: unknown }) {\n const { labels } = useNotificationCenter();\n const entries = Object.entries((payload as Record<string, unknown> | null | undefined) ?? {}).filter(\n ([, value]) => value !== null && value !== undefined && value !== \"\",\n );\n if (entries.length === 0) return null;\n\n return (\n <div className=\"space-y-2\">\n <span className=\"text-xs font-medium text-muted-foreground\">{labels.contextLabel}</span>\n <dl className=\"divide-y rounded-lg border\">\n {entries.map(([key, value]) => (\n <div key={key} className=\"grid grid-cols-3 gap-2 px-3 py-2 text-sm\">\n <dt className=\"col-span-1 text-xs leading-5 text-muted-foreground\">{humanizeKey(key)}</dt>\n <dd\n className={`col-span-2 break-words text-foreground ${\n typeof value === \"object\" ? \"font-mono text-xs whitespace-pre-wrap\" : \"whitespace-pre-line\"\n }`}\n >\n {formatPayloadValue(value)}\n </dd>\n </div>\n ))}\n </dl>\n </div>\n );\n}\n\ninterface OpenNotificationOptions {\n /** Open the detail sheet even when the notification carries a link. */\n forceSheet?: boolean;\n}\n\n/**\n * Shared \"open a notification\" behavior: mark it read, then either hand the\n * link to the host or fall back to the detail sheet. Navigation safety and\n * routing belong to the host, so this hook only calls `onOpenLink`.\n */\nexport function useOpenNotification() {\n const host = useNotificationCenter();\n const [selected, setSelected] = useState<NotificationRecord | null>(null);\n const [sheetOpen, setSheetOpen] = useState(false);\n const { onError } = host;\n\n const openNotification = useCallback(\n async (notification: NotificationRecord, options: OpenNotificationOptions = {}) => {\n try {\n if (!notification.read) await host.port.markRead(notification.id);\n } catch (caught) {\n onError?.(caught);\n return;\n }\n if (notification.link && !options.forceSheet) {\n host.onOpenLink(notification.link);\n return;\n }\n setSelected(notification);\n setSheetOpen(true);\n },\n [host, onError],\n );\n\n const sheetProps = {\n notification: selected,\n open: sheetOpen,\n onOpenChange: setSheetOpen,\n onOpenLink: (notification: NotificationRecord) => {\n setSheetOpen(false);\n if (notification.link) host.onOpenLink(notification.link);\n },\n };\n\n return { openNotification, sheetProps };\n}\n\nfunction DetailHeader({ notification }: { notification: NotificationRecord }) {\n const { labels, resolveMeta, categoryVisuals, fallbackVisual } = useNotificationCenter();\n const meta = resolveMeta(notification.notificationKey);\n const visual = (meta.category ? categoryVisuals[meta.category] : undefined) ?? fallbackVisual;\n return (\n <div className=\"flex items-center gap-3\">\n <span className={`flex size-10 shrink-0 items-center justify-center rounded-lg ${visual.className}`}>\n {createElement(visual.icon, { className: \"size-5\" })}\n </span>\n <div className=\"flex min-w-0 flex-col gap-1.5\">\n <SheetTitle className=\"text-base leading-snug\">{stripTitleMarker(notification.title)}</SheetTitle>\n <div className=\"flex flex-wrap items-center gap-2\">\n {notification.status === \"resolved\" ? <RecoveredBadge /> : <SeverityBadge severity={notification.severity} />}\n <Badge variant=\"secondary\">{meta.label}</Badge>\n {notification.read ? <Badge variant=\"outline\">{labels.read}</Badge> : <Badge>{labels.unread}</Badge>}\n </div>\n </div>\n </div>\n );\n}\n\nexport function NotificationDetailSheet({\n notification,\n open,\n onOpenChange,\n onOpenLink,\n}: {\n notification: NotificationRecord | null;\n open: boolean;\n onOpenChange: (open: boolean) => void;\n onOpenLink: (notification: NotificationRecord) => void;\n}) {\n const { labels, resolveSource, onNavigate, alertCenterPath } = useNotificationCenter();\n const locale = resolveLocale(useNotificationCenter().locale);\n\n if (!notification) {\n return (\n <Sheet open={open} onOpenChange={onOpenChange}>\n <SheetContent />\n </Sheet>\n );\n }\n\n const source = resolveSource?.(notification) ?? null;\n\n return (\n <Sheet open={open} onOpenChange={onOpenChange}>\n <SheetContent className=\"flex w-full flex-col gap-0 sm:max-w-md\">\n <SheetHeader>\n <DetailHeader notification={notification} />\n <SheetDescription className=\"space-y-1\">\n <span className=\"block\">{formatTimestamp(notification.createdAt, locale)}</span>\n <span className=\"block font-mono text-xs\">{notification.notificationKey}</span>\n </SheetDescription>\n </SheetHeader>\n\n <div className=\"flex-1 space-y-5 overflow-y-auto px-4 pb-4\">\n {source ? (\n <div className=\"space-y-1\">\n <span className=\"text-xs font-medium text-muted-foreground\">{labels.sourceLabel}</span>\n <p className=\"text-sm text-foreground\">{source}</p>\n </div>\n ) : null}\n\n {notification.detail ? (\n <div className=\"space-y-1\">\n <span className=\"text-xs font-medium text-muted-foreground\">{labels.detailLabel}</span>\n <p className=\"whitespace-pre-line rounded-lg border bg-muted/40 p-3 text-sm text-foreground\">\n {notification.detail}\n </p>\n </div>\n ) : null}\n\n <NotificationContextTable payload={notification.payload} />\n </div>\n\n <Separator />\n <SheetFooter>\n {notification.sourceType === \"alert\" ? (\n <Button className=\"w-full\" variant=\"outline\" onClick={() => onNavigate(alertCenterPath ?? \"/alert-center\")}>\n <AlertTriangle className=\"size-4\" />\n {labels.openAlertCenter}\n </Button>\n ) : null}\n {notification.link ? (\n <Button className=\"w-full\" onClick={() => onOpenLink(notification)}>\n <ExternalLink className=\"size-4\" />\n {labels.openLinkedPage}\n </Button>\n ) : null}\n </SheetFooter>\n </SheetContent>\n </Sheet>\n );\n}\n\nfunction DeliveryReasonBlock({ notificationId }: { notificationId: string }) {\n const { labels, port, locale } = useNotificationCenter();\n const [open, setOpen] = useState(false);\n const [attempt, setAttempt] = useState<NotificationDeliveryAttempt | null>(null);\n const [busy, setBusy] = useState(false);\n const load = port.fetchDeliveryAttempt;\n\n if (!load) return null;\n\n const toggle = () => {\n const next = !open;\n setOpen(next);\n if (!next) return;\n setBusy(true);\n load(notificationId)\n .then((result) => setAttempt(result))\n .catch(() => setAttempt(null))\n .finally(() => setBusy(false));\n };\n\n return (\n <div className=\"space-y-2\">\n <button type=\"button\" aria-expanded={open} onClick={toggle} className=\"text-xs font-medium text-muted-foreground\">\n {labels.deliveryReasonLabel}\n </button>\n {open ? (\n busy ? (\n <div className=\"flex justify-center py-2\">\n <LoaderCircle className=\"size-4 animate-spin text-muted-foreground\" />\n </div>\n ) : !attempt ? (\n <p className=\"text-sm text-muted-foreground\">{labels.deliveryReasonMissing}</p>\n ) : (\n <div className=\"flex flex-wrap items-center gap-2 text-sm\">\n <Badge variant={attempt.decision === \"suppress\" ? \"destructive\" : \"default\"}>\n {attempt.decision === \"suppress\" ? labels.deliveryReasonSuppress : labels.deliveryReasonDeliver}\n </Badge>\n <span className=\"text-muted-foreground\">\n {attempt.reason === \"rule\" ? labels.deliveryReasonRule : labels.deliveryReasonNoMatch}\n </span>\n {attempt.ruleId ? (\n <span className=\"font-mono text-xs text-muted-foreground\">{attempt.ruleId.slice(0, 8)}</span>\n ) : null}\n {attempt.runtimeReasonLabel ? <Badge variant=\"secondary\">{attempt.runtimeReasonLabel}</Badge> : null}\n <span className=\"text-xs text-muted-foreground\">\n {formatTimestamp(attempt.createdAt, resolveLocale(locale))}\n </span>\n </div>\n )\n ) : null}\n </div>\n );\n}\n\n/** Persistent right-hand pane of an inbox view; the host owns the page and list. */\nexport function NotificationDetailPanel({\n group,\n onOpenLink,\n}: {\n group: NotificationGroup | null;\n onOpenLink: (notification: NotificationRecord) => void;\n}) {\n const { labels, resolveMeta, categoryVisuals, fallbackVisual, resolveSource, onNavigate, alertCenterPath } =\n useNotificationCenter();\n const locale = resolveLocale(useNotificationCenter().locale);\n\n if (!group) {\n return (\n <div className=\"flex min-h-0 flex-1 flex-col items-center justify-center gap-2 text-muted-foreground\">\n <Inbox className=\"size-8\" />\n <span className=\"text-sm\">{labels.selectPrompt}</span>\n </div>\n );\n }\n\n const notification = group.latest;\n const meta = resolveMeta(notification.notificationKey);\n const visual = (meta.category ? categoryVisuals[meta.category] : undefined) ?? fallbackVisual;\n const source = resolveSource?.(notification) ?? null;\n\n return (\n <section aria-label={labels.detailsLabel} className=\"flex min-h-0 flex-1 flex-col\">\n <header className=\"flex items-start gap-3 border-b px-6 py-4\">\n <span className={`flex size-10 shrink-0 items-center justify-center rounded-lg ${visual.className}`}>\n {createElement(visual.icon, { className: \"size-5\" })}\n </span>\n <div className=\"min-w-0 flex-1\">\n <h2 className=\"text-base leading-snug font-semibold text-balance\">{stripTitleMarker(notification.title)}</h2>\n <div className=\"mt-1.5 flex flex-wrap items-center gap-2\">\n {notification.status === \"resolved\" ? (\n <RecoveredBadge />\n ) : (\n <SeverityBadge severity={notification.severity} />\n )}\n <Badge variant=\"secondary\">{meta.label}</Badge>\n {group.records.length > 1 ? (\n <Badge variant=\"outline\">{interpolate(labels.occurrencesCount, { count: group.records.length })}</Badge>\n ) : null}\n </div>\n <p className=\"mt-1.5 flex flex-wrap items-center gap-x-3 text-xs text-muted-foreground\">\n <span>{formatTimestamp(notification.createdAt, locale)}</span>\n <span className=\"font-mono\">{notification.notificationKey}</span>\n </p>\n </div>\n {notification.link || notification.sourceType === \"alert\" ? (\n <div className=\"flex items-center gap-2\">\n {notification.sourceType === \"alert\" ? (\n <Button size=\"sm\" variant=\"outline\" onClick={() => onNavigate(alertCenterPath ?? \"/alert-center\")}>\n <AlertTriangle className=\"size-4\" />\n {labels.openAlertCenter}\n </Button>\n ) : null}\n {notification.link ? (\n <Button size=\"sm\" onClick={() => onOpenLink(notification)}>\n <ExternalLink className=\"size-4\" />\n {labels.openLinkedPage}\n </Button>\n ) : null}\n </div>\n ) : null}\n </header>\n\n <div className=\"flex min-h-0 flex-1 flex-col gap-5 overflow-y-auto px-6 py-5\">\n {source ? (\n <div className=\"space-y-1\">\n <span className=\"text-xs font-medium text-muted-foreground\">{labels.sourceLabel}</span>\n <p className=\"text-sm text-foreground\">{source}</p>\n </div>\n ) : null}\n\n {notification.detail ? (\n <div className=\"space-y-1\">\n <span className=\"text-xs font-medium text-muted-foreground\">{labels.detailLabel}</span>\n <p className=\"rounded-lg border bg-muted/40 p-3 text-sm whitespace-pre-line text-foreground\">\n {notification.detail}\n </p>\n </div>\n ) : null}\n\n <NotificationContextTable payload={notification.payload} />\n <DeliveryReasonBlock notificationId={notification.id} />\n\n {group.records.length > 1 ? (\n <div className=\"space-y-2\">\n <span className=\"text-xs font-medium text-muted-foreground\">{labels.occurrencesLabel}</span>\n <ol className=\"divide-y rounded-lg border\">\n {group.records.map((record) => (\n <li key={record.id} className=\"flex items-center justify-between gap-3 px-3 py-2 text-sm\">\n <span className=\"tabular-nums text-foreground\">\n {formatTimestamp(record.createdAt, locale, \"medium\")}\n </span>\n <RelativeTime value={record.createdAt} className=\"text-xs text-muted-foreground\" />\n </li>\n ))}\n </ol>\n </div>\n ) : null}\n </div>\n </section>\n );\n}\n",
|
|
91
|
+
"type": "registry:component"
|
|
92
|
+
},
|
|
93
|
+
{
|
|
94
|
+
"path": "src/components/notification-center/notification-bell.tsx",
|
|
95
|
+
"content": "\"use client\";\n\nimport { useState } from \"react\";\nimport { Bell, Check } from \"lucide-react\";\nimport { Button } from \"@/components/ui/button\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"@/components/ui/popover\";\nimport { Tooltip, TooltipContent, TooltipTrigger } from \"@/components/ui/tooltip\";\nimport { useNotificationCenter, usePolled } from \"./notification-center\";\nimport { notificationDotClass, stripTitleMarker } from \"./format\";\nimport { NotificationDetailSheet, RelativeTime, SeverityBadge, useOpenNotification } from \"./notification-detail\";\n\nconst RECENT_LIMIT = 6;\n\n/**\n * Header bell: unread count plus a recent-unread popover. All data comes from\n * the host port; the item owns polling and local interactions.\n */\nexport function NotificationBell({ className }: { className?: string }) {\n const host = useNotificationCenter();\n const { labels, port, pollIntervalMs, notificationsPath, onNavigate, onMarkedRead } = host;\n const interval = pollIntervalMs ?? 60_000;\n const [open, setOpen] = useState(false);\n\n const unread = usePolled(() => port.fetchUnreadCount(), interval);\n const recent = usePolled(() => port.fetchRecent(RECENT_LIMIT), interval);\n const { openNotification, sheetProps } = useOpenNotification();\n\n const unreadCount = unread.data ?? 0;\n const records = recent.data ?? [];\n\n const markAllRead = async () => {\n try {\n const count = await port.markAllRead();\n if (count > 0) onMarkedRead?.(count);\n unread.reload();\n recent.reload();\n } catch (caught) {\n host.onError?.(caught);\n }\n };\n\n return (\n <>\n <Popover open={open} onOpenChange={setOpen}>\n <Tooltip>\n <TooltipTrigger asChild>\n <PopoverTrigger asChild>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon\"\n className={`relative ${className ?? \"\"}`}\n aria-label={labels.bellLabel}\n >\n <Bell className=\"size-5\" />\n {unreadCount > 0 ? (\n <span className=\"absolute -end-0.5 -top-0.5 flex min-w-4 items-center justify-center rounded-full bg-destructive px-1 text-[10px] leading-4 font-semibold text-destructive-foreground tabular-nums\">\n {unreadCount > 99 ? \"99+\" : unreadCount}\n </span>\n ) : null}\n </Button>\n </PopoverTrigger>\n </TooltipTrigger>\n <TooltipContent side=\"bottom\">\n {labels.bellLabel}\n {unreadCount > 0 ? ` (${unreadCount})` : \"\"}\n </TooltipContent>\n </Tooltip>\n\n <PopoverContent align=\"end\" className=\"w-80 p-0\">\n <div className=\"flex items-center justify-between border-b px-3 py-2\">\n <span className=\"text-sm font-medium\">{labels.bellLabel}</span>\n {unreadCount > 0 ? (\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"ghost\"\n className=\"h-7 gap-1 px-2 text-xs\"\n onClick={() => void markAllRead()}\n >\n <Check className=\"size-3.5\" />\n {labels.markAllRead}\n </Button>\n ) : null}\n </div>\n\n <div className=\"max-h-80 overflow-y-auto\">\n {recent.loading ? (\n <p className=\"px-3 py-6 text-center text-sm text-muted-foreground\">{labels.loading}</p>\n ) : records.length === 0 ? (\n <p className=\"px-3 py-6 text-center text-sm text-muted-foreground\">{labels.empty}</p>\n ) : (\n <ul className=\"divide-y\">\n {records.map((record) => (\n <li key={record.id}>\n <button\n type=\"button\"\n className=\"flex w-full items-start gap-2 px-3 py-2.5 text-start transition-colors hover:bg-muted/60\"\n onClick={() => {\n setOpen(false);\n void openNotification(record);\n }}\n >\n <span\n className={`mt-1.5 size-2 shrink-0 rounded-full ${notificationDotClass(record.status, record.severity)}`}\n aria-label={record.read ? labels.read : labels.unread}\n />\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate text-sm font-medium text-foreground\">\n {stripTitleMarker(record.title)}\n </span>\n <span className=\"mt-0.5 flex items-center gap-2 text-xs text-muted-foreground\">\n <RelativeTime value={record.createdAt} />\n <SeverityBadge severity={record.severity} className=\"px-1.5 py-0 text-[10px]\" />\n </span>\n </span>\n </button>\n </li>\n ))}\n </ul>\n )}\n </div>\n\n <div className=\"border-t px-3 py-2\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n className=\"h-8 w-full text-xs\"\n onClick={() => {\n setOpen(false);\n onNavigate(notificationsPath ?? \"/notifications\");\n }}\n >\n {labels.viewAll}\n </Button>\n </div>\n </PopoverContent>\n </Popover>\n\n <NotificationDetailSheet {...sheetProps} />\n </>\n );\n}\n",
|
|
96
|
+
"type": "registry:component"
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
"path": "src/components/notification-center/notification-ticker.tsx",
|
|
100
|
+
"content": "\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport { Activity, RadioTower } from \"lucide-react\";\nimport { interpolate } from \"./format\";\nimport { useNotificationCenter, usePolled } from \"./notification-center\";\nimport { NotificationDetailSheet, RelativeTime, useOpenNotification } from \"./notification-detail\";\n\nconst TICKER_LIMIT = 8;\nconst ROTATE_MS = 6_000;\n\nconst GREETING_KEYS = [\n \"greetingAllQuiet\",\n \"greetingNothingToDo\",\n \"greetingCaughtUp\",\n \"greetingNoAlerts\",\n \"greetingInboxZero\",\n] as const;\n\n/**\n * Shell-level ticker: the latest unread notification, a quiet-day greeting when\n * there is none, and a push-delivery failure strip. Mount next to the bell.\n */\nexport function NotificationTicker({ className }: { className?: string }) {\n const host = useNotificationCenter();\n const { labels, port, pollIntervalMs } = host;\n const interval = pollIntervalMs ?? 60_000;\n const unread = usePolled(() => port.fetchUnread(TICKER_LIMIT), interval);\n const { openNotification, sheetProps } = useOpenNotification();\n const [cursor, setCursor] = useState(0);\n\n const records = unread.data ?? [];\n const current = records.length > 0 ? records[cursor % records.length] : null;\n const greeting = labels[GREETING_KEYS[cursor % GREETING_KEYS.length]];\n\n useEffect(() => {\n if (records.length <= 1) return;\n const timer = window.setInterval(() => setCursor((value) => value + 1), ROTATE_MS);\n return () => window.clearInterval(timer);\n }, [records.length]);\n\n return (\n <div className={`flex min-w-0 items-center gap-3 ${className ?? \"\"}`}>\n <div\n aria-live=\"polite\"\n className=\"flex min-w-0 flex-1 items-center gap-2 rounded-full border bg-muted/40 px-3 py-1\"\n >\n <Activity className=\"size-3.5 shrink-0 text-primary\" />\n {current ? (\n <button\n type=\"button\"\n className=\"flex min-w-0 flex-1 items-center gap-2 text-start text-xs text-foreground\"\n aria-label={interpolate(labels.ariaLatestNotification, { title: current.title })}\n onClick={() => void openNotification(current)}\n >\n <span\n className=\"truncate\"\n // The title already carries the host's status marker; keep it in the ticker.\n >\n {current.title}\n </span>\n <RelativeTime value={current.createdAt} className=\"shrink-0 text-muted-foreground\" />\n </button>\n ) : (\n <span className=\"truncate text-xs text-muted-foreground\">{greeting}</span>\n )}\n </div>\n <PushFailureStrip />\n <NotificationDetailSheet {...sheetProps} />\n </div>\n );\n}\n\n/**\n * Push delivery failures are transport-level and read-only; they render as a\n * compact strip so operators notice a broken adapter without opening a page.\n */\nfunction PushFailureStrip() {\n const { labels, port, pollIntervalMs } = useNotificationCenter();\n const failures = usePolled(\n () => (port.fetchPushFailures ? port.fetchPushFailures() : Promise.resolve([])),\n pollIntervalMs ?? 60_000,\n );\n const rows = failures.data ?? [];\n if (!port.fetchPushFailures || rows.length === 0) return null;\n\n const summary = rows.length === 1 ? labels.pushFailedOne : interpolate(labels.pushFailedMany, { count: rows.length });\n\n return (\n <div\n role=\"status\"\n className=\"flex min-w-0 items-center gap-2 rounded-full border border-destructive/30 bg-destructive/10 px-3 py-1 text-xs text-destructive\"\n title={rows[0].error}\n >\n <RadioTower className=\"size-3.5 shrink-0\" />\n <span className=\"truncate\">{summary}</span>\n <span className=\"truncate font-mono text-[10px] opacity-80\">\n {rows[0].notificationTitle ?? rows[0].recipientKey}\n </span>\n </div>\n );\n}\n",
|
|
101
|
+
"type": "registry:component"
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
"path": "src/components/notification-center/index.ts",
|
|
105
|
+
"content": "export { NotificationCenterProvider, useNotificationCenter, usePolled } from \"./notification-center\";\nexport type { PolledResult } from \"./notification-center\";\nexport { NotificationBell } from \"./notification-bell\";\nexport { NotificationTicker } from \"./notification-ticker\";\nexport {\n NotificationContextTable,\n NotificationDetailPanel,\n NotificationDetailSheet,\n RecoveredBadge,\n RelativeTime,\n SeverityBadge,\n useOpenNotification,\n} from \"./notification-detail\";\nexport {\n formatRelativeTime,\n formatTimestamp,\n groupNotifications,\n interpolate,\n notificationDotClass,\n severityBadgeClass,\n stripTitleMarker,\n} from \"./format\";\nexport type { NotificationDayGroup, NotificationGroup } from \"./format\";\nexport type {\n NotificationCategoryVisual,\n NotificationCenterLabels,\n NotificationCenterPort,\n NotificationCenterProps,\n NotificationDeliveryAttempt,\n NotificationMetaEntry,\n NotificationPushFailure,\n NotificationRecord,\n} from \"./types\";\n",
|
|
106
|
+
"type": "registry:component"
|
|
107
|
+
}
|
|
108
|
+
]
|
|
109
|
+
}
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"x-fewbie.contract": {
|
|
9
9
|
"version": "1.0.0",
|
|
10
10
|
"framework": "^1.7.0",
|
|
11
|
-
"entry": "src/
|
|
11
|
+
"entry": "src/features/password-checklist/index.ts",
|
|
12
12
|
"labels": [
|
|
13
13
|
"requirements",
|
|
14
14
|
"ruleLength",
|
|
@@ -25,17 +25,17 @@
|
|
|
25
25
|
},
|
|
26
26
|
"files": [
|
|
27
27
|
{
|
|
28
|
-
"path": "src/
|
|
28
|
+
"path": "src/features/password-checklist/index.ts",
|
|
29
29
|
"content": "export { PasswordChecklist, checkPasswordPolicy, isStrongPassword } from \"./password-checklist\";\nexport type { PasswordPolicyChecks, PasswordRuleKey } from \"./password-checklist\";\nexport type { PasswordChecklistLabels, PasswordChecklistProps } from \"./types\";\n",
|
|
30
30
|
"type": "registry:block"
|
|
31
31
|
},
|
|
32
32
|
{
|
|
33
|
-
"path": "src/
|
|
33
|
+
"path": "src/features/password-checklist/types.ts",
|
|
34
34
|
"content": "/**\n * Every string the checklist renders. The host supplies translated copy; the\n * module owns no user-facing text of its own.\n */\nexport interface PasswordChecklistLabels {\n /** Accessible name of the requirement list. */\n requirements: string;\n ruleLength: string;\n ruleLowercase: string;\n ruleUppercase: string;\n ruleNumber: string;\n ruleSymbol: string;\n}\n\nexport interface PasswordChecklistProps {\n labels: PasswordChecklistLabels;\n password: string;\n}\n",
|
|
35
35
|
"type": "registry:block"
|
|
36
36
|
},
|
|
37
37
|
{
|
|
38
|
-
"path": "src/
|
|
38
|
+
"path": "src/features/password-checklist/password-checklist.tsx",
|
|
39
39
|
"content": "\"use client\";\n\nimport { Check, X } from \"lucide-react\";\n\nimport type { PasswordChecklistLabels, PasswordChecklistProps } from \"./types\";\n\n/** Rule keys in display order; each is also a field of `PasswordPolicyChecks`. */\nexport type PasswordRuleKey = \"length\" | \"lowercase\" | \"uppercase\" | \"number\" | \"symbol\";\n\nexport type PasswordPolicyChecks = Record<PasswordRuleKey, boolean>;\n\n/**\n * validator.isStrongPassword's symbol set, copied verbatim from\n * `validator/lib/isStrongPassword.js`. It includes `_`, space and `£`, and\n * excludes non-ASCII symbols such as `€` and `§` (R84-01).\n */\nconst SYMBOL_PATTERN = /^[-#!$@£%^&*()_+|~=`{}\\[\\]:\";'<>?,.\\/\\\\ ]$/;\n\n/**\n * The backend password policy, mirrored exactly (R84-01): the newbie account\n * module calls `validator.isStrongPassword` with its default options — at\n * least 8 UTF-16 code units, one lowercase, one uppercase, one digit and one\n * symbol from the set above. Keep this in sync with\n * `newbie-modules/packages/modules/account/helpers/validator.ts`.\n */\nexport function checkPasswordPolicy(password: string): PasswordPolicyChecks {\n return {\n length: password.length >= 8,\n lowercase: /[a-z]/.test(password),\n uppercase: /[A-Z]/.test(password),\n number: /[0-9]/.test(password),\n // validator classifies characters one code point at a time, so emoji and\n // other surrogate pairs never count as a symbol.\n symbol: Array.from(password).some((char) => SYMBOL_PATTERN.test(char)),\n };\n}\n\nexport function isStrongPassword(password: string): boolean {\n const checks = checkPasswordPolicy(password);\n return checks.length && checks.lowercase && checks.uppercase && checks.number && checks.symbol;\n}\n\nconst RULES: ReadonlyArray<{ key: PasswordRuleKey; labelKey: keyof PasswordChecklistLabels }> = [\n { key: \"length\", labelKey: \"ruleLength\" },\n { key: \"lowercase\", labelKey: \"ruleLowercase\" },\n { key: \"uppercase\", labelKey: \"ruleUppercase\" },\n { key: \"number\", labelKey: \"ruleNumber\" },\n { key: \"symbol\", labelKey: \"ruleSymbol\" },\n];\n\nexport function PasswordChecklist({ labels, password }: PasswordChecklistProps) {\n // Show nothing until the user starts typing, to keep the form calm.\n if (!password) return null;\n\n const checks = checkPasswordPolicy(password);\n\n return (\n <ul className=\"space-y-1.5 rounded-md border bg-muted/40 p-3\" aria-label={labels.requirements}>\n {RULES.map((rule) => {\n const met = checks[rule.key];\n return (\n <li\n key={rule.key}\n className={`flex items-center gap-2 text-xs ${met ? \"text-green-600 dark:text-green-500\" : \"text-muted-foreground\"}`}\n >\n {met ? <Check className=\"h-3.5 w-3.5\" /> : <X className=\"h-3.5 w-3.5\" />}\n {labels[rule.labelKey]}\n </li>\n );\n })}\n </ul>\n );\n}\n",
|
|
40
40
|
"type": "registry:block"
|
|
41
41
|
}
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"x-fewbie.contract": {
|
|
9
9
|
"version": "1.0.0",
|
|
10
10
|
"framework": "^1.7.0",
|
|
11
|
-
"entry": "src/
|
|
11
|
+
"entry": "src/features/preferences-settings/index.ts",
|
|
12
12
|
"labels": [
|
|
13
13
|
"languageTitle",
|
|
14
14
|
"languageDesc",
|
|
@@ -44,17 +44,17 @@
|
|
|
44
44
|
},
|
|
45
45
|
"files": [
|
|
46
46
|
{
|
|
47
|
-
"path": "src/
|
|
47
|
+
"path": "src/features/preferences-settings/index.ts",
|
|
48
48
|
"content": "export { PreferencesSettings } from \"./preferences-settings\";\nexport type {\n PreferencesLanguageOption,\n PreferencesSettingsLabels,\n PreferencesSettingsPort,\n PreferencesSettingsProps,\n PreferencesSettingsValues,\n ThemePreferenceValue,\n} from \"./types\";\n",
|
|
49
49
|
"type": "registry:block"
|
|
50
50
|
},
|
|
51
51
|
{
|
|
52
|
-
"path": "src/
|
|
52
|
+
"path": "src/features/preferences-settings/types.ts",
|
|
53
53
|
"content": "export type ThemePreferenceValue = \"LIGHT\" | \"DARK\" | \"SYSTEM\";\n\nexport interface PreferencesLanguageOption {\n value: string;\n label: string;\n}\n\n/**\n * Every string the cards render. The host supplies translated copy, including\n * the labels of the language options it passes in.\n */\nexport interface PreferencesSettingsLabels {\n languageTitle: string;\n languageDesc: string;\n themeTitle: string;\n themeDesc: string;\n themeLight: string;\n themeDark: string;\n themeSystem: string;\n timezoneTitle: string;\n timezoneDesc: string;\n timezonePlaceholder: string;\n useBrowserTimezone: string;\n saveTimezone: string;\n updateFailed: string;\n}\n\nexport interface PreferencesSettingsValues {\n language: string;\n theme: ThemePreferenceValue;\n timezone: string;\n}\n\n/**\n * Host-owned write path. The module never calls fetch, a router or a toast\n * library: the host persists each preference and decides how to apply it.\n */\nexport interface PreferencesSettingsPort {\n saveLanguage(language: string): Promise<void>;\n saveTheme(theme: ThemePreferenceValue): Promise<void>;\n saveTimezone(timezone: string): Promise<void>;\n}\n\nexport interface PreferencesSettingsProps {\n labels: PreferencesSettingsLabels;\n values: PreferencesSettingsValues;\n /** Languages the host ships dictionaries for. */\n languages: PreferencesLanguageOption[];\n port: PreferencesSettingsPort;\n /** Called after a language was saved; the host refreshes its locale. */\n onLanguageChanged?: (language: string) => void;\n /** Called after a theme was saved; the host applies it locally. */\n onThemeChanged?: (theme: ThemePreferenceValue) => void;\n /** Called after a timezone was saved; the host refreshes its cache. */\n onTimezoneChanged?: (timezone: string) => void;\n}\n",
|
|
54
54
|
"type": "registry:block"
|
|
55
55
|
},
|
|
56
56
|
{
|
|
57
|
-
"path": "src/
|
|
57
|
+
"path": "src/features/preferences-settings/preferences-settings.tsx",
|
|
58
58
|
"content": "\"use client\";\n\nimport { useState } from \"react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \"@/components/ui/select\";\nimport type { PreferencesSettingsProps, ThemePreferenceValue } from \"./types\";\n\nfunction Spinner() {\n return (\n <span\n aria-hidden=\"true\"\n className=\"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent\"\n />\n );\n}\n\nfunction SunIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"4\" />\n <path d=\"M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4\" />\n </svg>\n );\n}\n\nfunction MoonIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8Z\" />\n </svg>\n );\n}\n\nfunction MonitorIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <rect x=\"2\" y=\"3\" width=\"20\" height=\"14\" rx=\"2\" />\n <path d=\"M8 21h8M12 17v4\" />\n </svg>\n );\n}\n\nfunction SaveIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2Z\" />\n <path d=\"M17 21v-8H7v8M7 3v5h8\" />\n </svg>\n );\n}\n\n/**\n * Account display preferences: interface language, theme and timezone. The\n * host owns transport and the side effects of each change (locale cookie,\n * theme class, caching), which enter through `port` and the `on*` callbacks.\n */\nexport function PreferencesSettings({\n labels,\n values,\n languages,\n port,\n onLanguageChanged,\n onThemeChanged,\n onTimezoneChanged,\n}: PreferencesSettingsProps) {\n const [timezone, setTimezone] = useState(values.timezone);\n // Re-seed when the host supplies a different account, comparing values (not\n // object identity) so a parent re-render never overwrites in-progress edits.\n const [seedTimezone, setSeedTimezone] = useState(values.timezone);\n if (values.timezone !== seedTimezone) {\n setSeedTimezone(values.timezone);\n setTimezone(values.timezone);\n }\n\n const [languagePending, setLanguagePending] = useState(false);\n const [themePending, setThemePending] = useState(false);\n const [timezonePending, setTimezonePending] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n async function handleLanguage(value: string): Promise<void> {\n if (languagePending) return;\n setLanguagePending(true);\n setError(null);\n try {\n await port.saveLanguage(value);\n onLanguageChanged?.(value);\n } catch {\n setError(labels.updateFailed);\n } finally {\n setLanguagePending(false);\n }\n }\n\n async function handleTheme(value: ThemePreferenceValue): Promise<void> {\n if (themePending) return;\n setThemePending(true);\n setError(null);\n try {\n await port.saveTheme(value);\n onThemeChanged?.(value);\n } catch {\n setError(labels.updateFailed);\n } finally {\n setThemePending(false);\n }\n }\n\n async function handleTimezone(): Promise<void> {\n if (timezonePending) return;\n setTimezonePending(true);\n setError(null);\n try {\n await port.saveTimezone(timezone.trim());\n onTimezoneChanged?.(timezone.trim());\n } catch {\n setError(labels.updateFailed);\n } finally {\n setTimezonePending(false);\n }\n }\n\n // Read the browser zone only inside the click handler: resolving it during\n // render would differ between the server and the browser.\n function fillBrowserTimezone(): void {\n setTimezone(Intl.DateTimeFormat().resolvedOptions().timeZone);\n }\n\n const themeOptions: { value: ThemePreferenceValue; label: string; icon: React.ReactNode }[] = [\n { value: \"LIGHT\", label: labels.themeLight, icon: <SunIcon /> },\n { value: \"DARK\", label: labels.themeDark, icon: <MoonIcon /> },\n { value: \"SYSTEM\", label: labels.themeSystem, icon: <MonitorIcon /> },\n ];\n\n return (\n <div className=\"grid max-w-3xl gap-6\">\n <Card>\n <CardHeader>\n <CardTitle className=\"text-base\">{labels.languageTitle}</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-3\">\n <p className=\"text-sm text-muted-foreground\">{labels.languageDesc}</p>\n <Select\n value={values.language}\n onValueChange={(value) => void handleLanguage(value)}\n disabled={languagePending}\n >\n <SelectTrigger id=\"preferences-settings-language\" aria-label={labels.languageTitle} className=\"w-60\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {languages.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </CardContent>\n </Card>\n\n <Card>\n <CardHeader>\n <CardTitle className=\"text-base\">{labels.themeTitle}</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-3\">\n <p className=\"text-sm text-muted-foreground\">{labels.themeDesc}</p>\n <div className=\"flex flex-wrap gap-2\">\n {themeOptions.map((option) => {\n const active = values.theme === option.value;\n return (\n <Button\n key={option.value}\n type=\"button\"\n variant={active ? \"default\" : \"outline\"}\n aria-pressed={active}\n disabled={themePending}\n onClick={() => void handleTheme(option.value)}\n >\n {option.icon}\n {option.label}\n </Button>\n );\n })}\n </div>\n </CardContent>\n </Card>\n\n <Card>\n <CardHeader>\n <CardTitle className=\"text-base\">{labels.timezoneTitle}</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <p className=\"text-sm text-muted-foreground\">{labels.timezoneDesc}</p>\n <div className=\"space-y-2\">\n <Label htmlFor=\"preferences-settings-timezone\">{labels.timezoneTitle}</Label>\n <div className=\"flex flex-wrap items-center gap-2\">\n <Input\n id=\"preferences-settings-timezone\"\n value={timezone}\n onChange={(event) => setTimezone(event.target.value)}\n placeholder={labels.timezonePlaceholder}\n className=\"w-72\"\n disabled={timezonePending}\n />\n <Button\n type=\"button\"\n onClick={() => void handleTimezone()}\n disabled={timezonePending || timezone.trim() === \"\"}\n >\n {timezonePending ? <Spinner /> : <SaveIcon />}\n {labels.saveTimezone}\n </Button>\n <Button type=\"button\" variant=\"outline\" onClick={fillBrowserTimezone} disabled={timezonePending}>\n {labels.useBrowserTimezone}\n </Button>\n </div>\n </div>\n </CardContent>\n </Card>\n\n {error && <p className=\"text-sm text-destructive\">{error}</p>}\n </div>\n );\n}\n",
|
|
59
59
|
"type": "registry:block"
|
|
60
60
|
}
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"x-fewbie.contract": {
|
|
9
9
|
"version": "1.0.0",
|
|
10
10
|
"framework": "^1.7.0",
|
|
11
|
-
"entry": "src/
|
|
11
|
+
"entry": "src/features/profile-settings/index.ts",
|
|
12
12
|
"labels": [
|
|
13
13
|
"personalInfo",
|
|
14
14
|
"firstName",
|
|
@@ -37,17 +37,17 @@
|
|
|
37
37
|
},
|
|
38
38
|
"files": [
|
|
39
39
|
{
|
|
40
|
-
"path": "src/
|
|
40
|
+
"path": "src/features/profile-settings/index.ts",
|
|
41
41
|
"content": "export { ProfileSettings } from \"./profile-settings\";\nexport type { ProfileSettingsLabels, ProfileSettingsProps, ProfileSettingsValues } from \"./types\";\n",
|
|
42
42
|
"type": "registry:block"
|
|
43
43
|
},
|
|
44
44
|
{
|
|
45
|
-
"path": "src/
|
|
45
|
+
"path": "src/features/profile-settings/types.ts",
|
|
46
46
|
"content": "/**\n * Every string the card renders. The host supplies translated copy.\n */\nexport interface ProfileSettingsLabels {\n personalInfo: string;\n firstName: string;\n middleName: string;\n lastName: string;\n displayName: string;\n displayNamePlaceholder: string;\n saveChanges: string;\n email: string;\n saveFailed: string;\n}\n\nexport interface ProfileSettingsValues {\n name: string;\n firstName: string;\n middleName: string;\n lastName: string;\n email?: string;\n}\n\n/**\n * Host-owned write path. The module never calls fetch or a toast library: the\n * host persists the values and decides how to report the outcome.\n */\nexport interface ProfileSettingsProps {\n labels: ProfileSettingsLabels;\n /** Current account values; the form re-seeds when these change. */\n profile: ProfileSettingsValues;\n /** Persist the edited values; the host toasts and refreshes its cache. */\n onSave(values: ProfileSettingsValues): Promise<void>;\n}\n",
|
|
47
47
|
"type": "registry:block"
|
|
48
48
|
},
|
|
49
49
|
{
|
|
50
|
-
"path": "src/
|
|
50
|
+
"path": "src/features/profile-settings/profile-settings.tsx",
|
|
51
51
|
"content": "\"use client\";\n\nimport { useState } from \"react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport type { ProfileSettingsProps, ProfileSettingsValues } from \"./types\";\n\nfunction Spinner() {\n return (\n <span\n aria-hidden=\"true\"\n className=\"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent\"\n />\n );\n}\n\nfunction SaveIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2Z\" />\n <path d=\"M17 21v-8H7v8M7 3v5h8\" />\n </svg>\n );\n}\n\nfunction sameValues(left: ProfileSettingsValues, right: ProfileSettingsValues): boolean {\n return (\n left.name === right.name &&\n left.firstName === right.firstName &&\n left.middleName === right.middleName &&\n left.lastName === right.lastName &&\n left.email === right.email\n );\n}\n\n/**\n * Account profile card: first/middle/last name plus the display name. The host\n * owns data loading, persistence and toasts; the module only edits the values.\n */\nexport function ProfileSettings({ labels, profile, onSave }: ProfileSettingsProps) {\n const [form, setForm] = useState<ProfileSettingsValues>(profile);\n // Re-seed when the host supplies a different account, comparing values (not\n // object identity) so a parent re-render never overwrites in-progress edits.\n const [seed, setSeed] = useState<ProfileSettingsValues>(profile);\n if (!sameValues(profile, seed)) {\n setSeed(profile);\n setForm(profile);\n }\n\n const [pending, setPending] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n function updateField(field: keyof ProfileSettingsValues, value: string): void {\n setForm((prev) => ({ ...prev, [field]: value }));\n }\n\n async function handleSave(): Promise<void> {\n if (pending) return;\n setPending(true);\n setError(null);\n try {\n await onSave(form);\n } catch {\n setError(labels.saveFailed);\n } finally {\n setPending(false);\n }\n }\n\n return (\n <Card>\n <CardHeader>\n <CardTitle className=\"text-base\">{labels.personalInfo}</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <div className=\"grid gap-4 sm:grid-cols-3\">\n <div className=\"space-y-2\">\n <Label htmlFor=\"profile-settings-first-name\">{labels.firstName}</Label>\n <Input\n id=\"profile-settings-first-name\"\n value={form.firstName}\n onChange={(event) => updateField(\"firstName\", event.target.value)}\n placeholder={labels.firstName}\n />\n </div>\n <div className=\"space-y-2\">\n <Label htmlFor=\"profile-settings-middle-name\">{labels.middleName}</Label>\n <Input\n id=\"profile-settings-middle-name\"\n value={form.middleName}\n onChange={(event) => updateField(\"middleName\", event.target.value)}\n placeholder={labels.middleName}\n />\n </div>\n <div className=\"space-y-2\">\n <Label htmlFor=\"profile-settings-last-name\">{labels.lastName}</Label>\n <Input\n id=\"profile-settings-last-name\"\n value={form.lastName}\n onChange={(event) => updateField(\"lastName\", event.target.value)}\n placeholder={labels.lastName}\n />\n </div>\n </div>\n\n <div className=\"space-y-2\">\n <Label htmlFor=\"profile-settings-name\">{labels.displayName}</Label>\n <Input\n id=\"profile-settings-name\"\n value={form.name}\n onChange={(event) => updateField(\"name\", event.target.value)}\n placeholder={labels.displayNamePlaceholder}\n />\n </div>\n\n {error && <p className=\"text-sm text-destructive\">{error}</p>}\n\n <div className=\"flex items-center gap-3 border-t pt-4\">\n <Button type=\"button\" onClick={() => void handleSave()} disabled={pending}>\n {pending ? <Spinner /> : <SaveIcon />}\n {labels.saveChanges}\n </Button>\n <p className=\"text-xs text-muted-foreground\">\n {labels.email}: {profile.email ?? \"—\"}\n </p>\n </div>\n </CardContent>\n </Card>\n );\n}\n",
|
|
52
52
|
"type": "registry:block"
|
|
53
53
|
}
|