@molecule/app-settings-panel-angular
Feature · settings-panel · App (browser) · v3.0.5 · Apache-2.0
Composable settings panel — a SettingsContainer + family of section sub-components (Account, Auth, Notifications, Billing, Devices, ThisDevice, LogOutDelete). Apps compose via content projection, picking which sections to include and what order.
npm install @molecule/app-settings-panel-angularHow it works
@molecule/app-settings-panel-angular is a ready-made settings-panel feature for the app (browser) side. It composes the core interfaces it needs, so it works with whichever providers your app has bonded.
import { Component } from '@angular/core'
import {
AccountSection,
AppearanceSection,
AuthSection,
BillingSection,
DevicesSection,
LogOutDeleteSection,
NotificationsSection,
SettingsContainer,
ThisDeviceSection,
} from '@molecule/app-settings-panel-angular'
@Component({
selector: 'app-settings-panel',
standalone: true,
imports: [
AccountSection,
AppearanceSection,
AuthSection,
BillingSection,
DevicesSection,
LogOutDeleteSection,
NotificationsSection,
SettingsContainer,
ThisDeviceSection,
],
template: `
<!-- Pick sections, order them, and interleave custom ones. -->
<div mol-settings-container [onClose]="close">
<section mol-settings-account></section>
<section mol-settings-appearance></section>
<mol-auth-section></mol-auth-section>
<section mol-settings-notifications></section>
<section mol-settings-billing></section>
<section mol-settings-devices></section>
<section mol-settings-this-device></section>
<mol-log-out-delete-section></mol-log-out-delete-section>
</div>
`,
})
export class SettingsPanel {
close(): void {
// dismiss the drawer / panel hosting the settings
}
}Works with: @molecule/app-angular, @molecule/app-auth, @molecule/app-http, @molecule/app-push, @molecule/app-ui, @molecule/app-ui-angular, @molecule/app-utilities
Reference
@molecule/app-settings-panel-angular — the Angular counterpart of
@molecule/app-settings-panel-react: the same runtime export names, the
same props, and the same DOM for the same input. A composable,
batteries-included settings panel.
<SettingsContainer [onClose]="…"> owns the layout and publishes onClose
via the settings-panel context; each section component is standalone and
loads its own data through the binding's hooks:
AccountSection(as<section mol-settings-account>) — name/email edit (PATCH /api/users/:idover the auth client's profile transport).AppearanceSection— dark-mode toggle (useTheme()).AuthSection— password change + TOTP two-factor (POST /api/users/:id/verify-two-factor).NotificationsSection— web-push toggle (see the exportedenablePushOnCurrentDevice/disablePushOnCurrentDevicehelpers and their documented device-row contract).BillingSection— read-only plan display (GET /api/billing/status), orTiersUpgradeSection— full Stripe upgrade/cancel flow (/api/billing/tiers|checkout|cancel). Use one or the other, not both.DevicesSection/ThisDeviceSection— device list + current device (GET/DELETE /api/devices).LogOutDeleteSection— sign out + delete account (DELETE /api/users/:id).
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Quick Start
import { Component } from '@angular/core'
import {
AccountSection,
AppearanceSection,
AuthSection,
BillingSection,
DevicesSection,
LogOutDeleteSection,
NotificationsSection,
SettingsContainer,
ThisDeviceSection,
} from '@molecule/app-settings-panel-angular'
@Component({
selector: 'app-settings-panel',
standalone: true,
imports: [
AccountSection,
AppearanceSection,
AuthSection,
BillingSection,
DevicesSection,
LogOutDeleteSection,
NotificationsSection,
SettingsContainer,
ThisDeviceSection,
],
template: `
<!-- Pick sections, order them, and interleave custom ones. -->
<div mol-settings-container [onClose]="close">
<section mol-settings-account></section>
<section mol-settings-appearance></section>
<mol-auth-section></mol-auth-section>
<section mol-settings-notifications></section>
<section mol-settings-billing></section>
<section mol-settings-devices></section>
<section mol-settings-this-device></section>
<mol-log-out-delete-section></mol-log-out-delete-section>
</div>
`,
})
export class SettingsPanel {
close(): void {
// dismiss the drawer / panel hosting the settings
}
}
Type
feature
Installation
npm install @molecule/app-settings-panel-angular @angular/common @angular/core @angular/platform-browser @molecule/app-angular @molecule/app-auth @molecule/app-http @molecule/app-push @molecule/app-ui @molecule/app-ui-angular @molecule/app-utilities
API
Interfaces
AccountValues
The controlled values the account form edits (React's local AccountValues).
interface AccountValues {
name: string
email: string
}
TwoFactorSetup
The two-factor enrollment data POST /users/:id/verify-two-factor returns.
interface TwoFactorSetup {
QRImageUrl?: string
keyUrl?: string
secret?: string
}
DevicesSectionProps
Props for DevicesSection — the same props React's DevicesSection accepts.
interface DevicesSectionProps {
/**
* Custom trailing element per device row, replacing the built-in revoke
* control. It is a template in Angular (its context carries the device as
* `$implicit`); pass an empty template to suppress the control entirely.
*/
renderRowIcon?: TemplateRef<unknown> | null
}
SettingsContainerProps
Props for SettingsContainer — the same props React's SettingsContainer accepts.
interface SettingsContainerProps {
/** Dismiss-the-panel handler, published to every section through context. */
onClose?: () => void
/**
* The section sub-components to host. They are projected content in Angular
* (an input cannot carry a node), so this is typed `unknown`: pass them in
* the host template, not as a value.
*/
children?: unknown
}
TierPrice
One tier price as the section renders it (React's local TierPrice).
interface TierPrice {
stripePriceId?: string
interval: string
priceLabel: string
}
Tier
One upgrade tier with its subscribe-able prices (React's local Tier).
interface Tier {
planKey: string
name: string
prices: TierPrice[]
}
SettingsPanelContextValue
Context published by <SettingsContainer> to its children (the same shape
React's SettingsPanelContext carries).
The container owns the dismiss-the-panel handler; sub-components that need to close after an action (logout, delete account) read it from the context rather than threading the prop down.
interface SettingsPanelContextValue {
/** Closes the settings panel (the container's `onClose` prop). */
onClose: () => void
}
Device
A user's registered device (subset rendered in the settings list) — the
same shape React's DevicesSection renders.
interface Device {
/** The device row's id. */
id: string
/** Display name (blank rows fall back to the platform). */
name: string
/** Platform label. */
platform: string
/** Human-readable last-seen text, when the API supplies one. */
lastSeen?: string
/** `true` for the device making the current request (the API marks it). */
isCurrent?: boolean
}
AuthSectionProps
Props for AuthSection. Same name and meaning as the React component's.
interface AuthSectionProps {
/**
* Show the two-factor row. Set false when the API has no two-factor provider
* (no `POST /users/:id/verify-two-factor` route). Default true. Bound in a template as
* `[twoFactor]="false"`.
*/
twoFactor?: boolean
}
TiersUpgradeSectionProps
Props for TiersUpgradeSection — the same props
@molecule/app-settings-panel-react accepts.
interface TiersUpgradeSectionProps {
/**
* How the page leaves for the checkout URL the server returns. Defaults to a
* full-page navigation (`openUrl` from `@molecule/app-utilities`).
*/
redirectToCheckout?: (checkoutUrl: string) => void
}
PushToggleHttp
Minimal structural slice of @molecule/app-http's HttpClient used here.
interface PushToggleHttp {
get<T = unknown>(url: string): Promise<{ data: T }>
patch<T = unknown>(url: string, data?: unknown): Promise<{ data: T }>
}
PushToggleDevice
Device row slice returned by GET /api/devices.
interface PushToggleDevice {
id: string
isCurrent?: boolean
hasPushSubscription?: boolean
}
PushToggleToken
Push token slice returned by @molecule/app-push register().
interface PushToggleToken {
value: string
platform: 'web' | 'ios' | 'android'
}
Types
PushToggleFailureReason
Why an enable/disable attempt failed (mapped to i18n by the component).
type PushToggleFailureReason =
'permission-denied' | 'server-unconfigured' | 'register-failed' | 'persist-failed'
PushToggleResult
Result of an enable/disable attempt.
type PushToggleResult =
{ ok: true } | { ok: false; reason: PushToggleFailureReason; message?: string }
Classes
AccountSection
AccountSection component.
Account fields over the shared profile lifecycle. Background validation uses the auth client's configured route, mapping and session ownership guards.
UserProfile.email is optional (phone/handle accounts have none), so email
is validated only when non-empty and a blank email is never sent: clearing
the field leaves the stored address untouched, and a name-only account can
still save its name.
The host IS the <section> React renders. Blur-to-save is wired on the
<form> (focusout bubbles from the inputs, which the Angular Input
component does not re-emit) and dispatches on the blurred control's id —
exactly React's per-input saveOnBlur.
The email input's aria-invalid / aria-describedby are synced onto its
native control by an effect, the way React's rest props do
(aria-invalid={emailError ? …} : undefined — absent when valid, so the
attribute must be REMOVED, which the UI Input's own always-on binding
cannot express); this mirrors what the UI package's FormField does when it
patches a control directly.
@Component({
selector: 'section[mol-settings-account]',
standalone: true,
imports: [Flex, Input, Spinner],
template: `<div mol-flex [align]="'center'" [gap]="'sm'" [className]="cm.sp('mb', 3)">
<h3 [class]="cm.sectionHeading">
{{ t('settings.account', undefined, { defaultValue: 'Account' }) }}
</h3>
@if (profile.isSubmitting()) {
<div mol-spinner [size]="'xs'"></div>
}
</div>
<form [class]="cm.stack(3)" (submit)="submitForm($event)" (focusout)="saveOnFormBlur($event)">
<div>
<label for="settings-name" [class]="cm.formLabelSmall">{{
t('settings.name', undefined, { defaultValue: 'Name' })
}}</label>
<div
mol-input
#nameField
[id]="'settings-name'"
type="text"
autocomplete="name"
[size]="'sm'"
[value]="nameValue()"
[name]="'name'"
(change)="nameChange($event)"
></div>
</div>
<div>
<label for="settings-email" [class]="cm.formLabelSmall">{{
t('settings.email', undefined, { defaultValue: 'Email' })
}}</label>
<div
mol-input
#emailField
[id]="'settings-email'"
type="email"
autocomplete="email"
[size]="'sm'"
[value]="emailValue()"
[name]="'email'"
(change)="emailChange($event)"
></div>
@if (emailError(); as fieldError) {
<p
id="settings-email-error"
role="alert"
[class]="cm.cn(cm.textSize('xs'), cm.textError, cm.sp('mt', 1))"
>
{{ fieldError }}
</p>
}
@if (saveError(); as submitError) {
<p role="alert" [class]="cm.cn(cm.textSize('xs'), cm.textError, cm.sp('mt', 1))">
{{ submitError }}
</p>
}
</div>
</form>`,
})
export class AccountSection implements AfterViewInit {
/** The account fields over the shared profile lifecycle. */
protected readonly profile = useProfileForm<UserProfile, AccountValues>({
defaultValues: { name: '', email: '' },
toValues: (user) => ({ name: user.name ?? '', email: user.email ?? '' }),
toPatch: ({ email, ...changes }) => (email ? { ...changes, email } : changes),
})
/** The name field's registration (its onChange marks the field edited). */
protected readonly nameReg = this.profile.register('name')
/** The email field's registration, with the email format validation. */
protected readonly emailReg = this.profile.register('email', { email: true })
/** Reactive translation, read in the injection context. */
protected readonly i18n = useTranslation()
private readonly authClient = useAuthClient<UserProfile>()
/** The name field's host (the native control is looked up inside it). */
@ViewChild('nameField', { read: ElementRef }) nameField?: ElementRef<HTMLElement>
/** The email field's host. */
@ViewChild('emailField', { read: ElementRef }) emailField?: ElementRef<HTMLElement>
/** The bonded ClassMap (styling tokens resolve at render time). */
protected readonly cm: UIClassMap = getClassMap()
/** The translation function for the template. */
protected t = this.i18n.t
/** The name field's controlled value (form state is the change signal). */
protected readonly nameValue = computed(() => {
void this.profile.formState()
return this.profile.getValue('name')
})
/** The email field's controlled value. */
protected readonly emailValue = computed(() => {
void this.profile.formState()
return this.profile.getValue('email')
})
/** The email field's validation message, or null when valid. */
protected readonly emailError = computed(() => {
void this.profile.formState()
return this.profile.getError('email') ?? null
})
/** The latest save failure's display text, or null. */
protected readonly saveError = computed((): string | null => {
const error = this.profile.error()
if (!error) return null
return error instanceof Error
? error.message
: this.t('settings.failedToUpdateProfile', undefined, {
defaultValue: 'Failed to update profile',
})
})
/** The cached native email control (re-resolved when the view is rebuilt). */
private emailControl: HTMLInputElement | null = null
/** Starts the auth client's background session validation (React's mount effect) and wires the email control's aria sync. */
constructor() {
// A provider's background validation must not cause an unhandled
// rejection: render its auth state while useProfileForm reports mutation
// failures.
void this.authClient.validateSession?.().catch((_error) => {})
// React's rest props on the email input: present with the error target
// while the field is invalid, REMOVED while valid. An effect (view hooks
// are skipped by signal-driven refreshes) keeps it exact.
effect(() => {
const error = this.emailError()
untracked(() => this.syncEmailAria(error))
})
}
/** Applies the initial rest-prop state (hooks run on the mount passes). */
ngAfterViewInit(): void {
const name = this.nameField?.nativeElement.querySelector('input')
if (name) this.nameReg.ref?.(name)
this.resolveEmailControl()
this.syncEmailAria(this.emailError())
}
/**
* Forwards the field's `change` (React's text-input onChange).
* @param event - The native input event the UI Input re-emitted.
*/
protected nameChange(event: Event): void {
this.nameReg.onChange(event)
}
/**
* Forwards the field's `change` (React's text-input onChange).
* @param event - The native input event the UI Input re-emitted.
*/
protected emailChange(event: Event): void {
this.emailReg.onChange(event)
}
/**
* Submits the form (React's `profile.formProps` onSubmit).
* @param event - The native submit event.
*/
protected submitForm(event: Event): void {
this.profile.formProps.onSubmit(event)
}
/**
* Saves on blur, exactly React's per-input `saveOnBlur`: the field's
* registration blur first (touch + field validation), then the profile
* submit.
* @param event - The bubbling focusout from one of the two inputs.
*/
protected saveOnFormBlur(event: FocusEvent): void {
const id = (event.target as HTMLElement | null)?.id
if (id === 'settings-name') this.saveOnBlur(this.nameReg)
else if (id === 'settings-email') this.saveOnBlur(this.emailReg)
}
/**
* React's `saveOnBlur` wrapper: one blur, then one submit.
* @param registration - The blurred field's registration.
*/
private saveOnBlur(registration: { onBlur: () => void }): void {
registration.onBlur()
void this.profile.submit()
}
/**
* Looks the native email control up inside the UI `Input`'s host and
* registers it as the field ref (React's spread `ref`, so a failed submit
* focuses the first invalid field).
*/
private resolveEmailControl(): void {
this.emailControl =
(this.emailField?.nativeElement.querySelector('input') as HTMLInputElement | null) ?? null
if (this.emailControl) this.emailReg.ref?.(this.emailControl)
}
/**
* Applies React's rest-prop state for one error value: `aria-invalid` is
* `"true"` while invalid and `"false"` while valid; `aria-describedby` is set
* while invalid and removed while valid.
* @param error - The field's validation message, or null.
*/
private syncEmailAria(error: string | null): void {
this.resolveEmailControl()
const control = this.emailControl
if (!control) return
if (error) {
control.setAttribute('aria-invalid', 'true')
control.setAttribute('aria-describedby', 'settings-email-error')
} else {
control.setAttribute('aria-invalid', 'false')
control.removeAttribute('aria-describedby')
}
}
}
(The longest member comment is shortened to its first sentence to fit; the full declaration is in node_modules/@molecule/app-settings-panel-angular/dist/account-section.component.d.ts.)
AppearanceSection
AppearanceSection component.
Appearance section — dark-mode toggle wired to the theme bond. The host IS
the <section> React renders.
Apps that expose other appearance knobs (font size, density, etc.) can either add more sub-components to this package or render their own section in line with this one.
The id / aria-label rest props of React's <Switch> are host
attributes here: the UI Switch moves host attributes onto its visible
trigger on every check, so the label follows the locale the same way. The
controlled checked is re-synced by an effect (React re-renders the hidden
checkbox's property; see ControlledSwitchSync).
@Component({
selector: 'section[mol-settings-appearance]',
standalone: true,
imports: [Flex, Switch],
template: `<h3 [class]="cm.cn(cm.sectionHeading, cm.sp('mb', 3))">
{{ t('settings.appearance', undefined, { defaultValue: 'Appearance' }) }}
</h3>
<div mol-flex [align]="'center'" [justify]="'between'">
<span [class]="cm.textSize('sm')">{{
t('settings.darkMode', undefined, { defaultValue: 'Dark mode' })
}}</span>
<mol-switch
#themeSwitch
id="settings-theme-toggle"
[attr.aria-label]="t('theme.toggle', undefined, { defaultValue: 'Toggle theme' })"
[checked]="isDark()"
(change)="theme.toggleTheme()"
[size]="'sm'"
></mol-switch>
</div>`,
})
export class AppearanceSection implements AfterViewInit {
/** The theme bond's state and actions. */
protected readonly theme = useTheme()
/** Reactive translation, read in the injection context. */
protected readonly i18n = useTranslation()
/** The translation function for the template. */
protected t = this.i18n.t
/** Whether the dark mode is on (React's `mode === 'dark'`). */
protected readonly isDark = computed(() => this.theme.mode() === 'dark')
/** The bonded ClassMap (styling tokens resolve at render time). */
protected readonly cm: UIClassMap = getClassMap()
/** The theme switch's host element (the hidden checkbox lives inside). */
@ViewChild('themeSwitch', { read: ElementRef }) themeSwitch?: ElementRef<HTMLElement>
/** The controlled-`checked` sync (created once the host exists). */
private sync?: ControlledSwitchSync
/** Re-syncs the switch's hidden checkbox whenever the mode changes. */
constructor() {
effect(() => {
const checked = this.isDark()
untracked(() => this.runSync(checked))
})
}
/** Captures the mount-time attribute state (hooks run on the mount passes). */
ngAfterViewInit(): void {
this.runSync(this.isDark())
}
/**
* Runs the controlled-`checked` sync once the switch host exists.
* @param checked - The controlled value this render shows.
*/
private runSync(checked: boolean): void {
if (!this.sync && this.themeSwitch) {
this.sync = new ControlledSwitchSync(this.themeSwitch.nativeElement)
}
this.sync?.sync(checked)
}
}
AuthSection
AuthSection component.
Authentication section — change password (modal) + two-factor (TOTP) setup.
React's root is a fragment (the <section> plus two modals) or nothing at
all for an OAuth-only user (React's return null); those nodes render in the
host's place and the host itself never appears in the page.
Two-factor uses the real enrollment flow against the user resource's
POST /users/:id/verify-two-factor endpoint (@molecule/api-two-factor):
- Enable →
{action:'setup'}returns a QR code + secret to scan into an authenticator app → user enters the 6-digit code →{action:'enable', token}. - Disable → user enters a current code →
{action:'disable', token}. The current status is read from/users/me. (This replaces the previous boolean toggle, which PATCHedtwoFactorEnabled— a field the update handler deliberately ignores — so it never actually enrolled 2FA.)
Auto-hides for OAuth-only users (user.oauthServer truthy) since
password / 2FA wouldn't apply. Pass [twoFactor]="false" when the app's API
has no two-factor provider: it then serves no verify-two-factor route, so
the section shows only the password change and reads no 2FA status.
useChangePassword's state is a live getter over a plain object (the
Angular binding's usePromise port), so the pending/error reads are
mediated by a version signal the handlers bump at React's re-render points.
@Component({
selector: 'mol-auth-section',
standalone: true,
hostDirectives: [MolPlacement],
imports: [Alert, Button, Flex, Input, Modal],
template: `@if (!isOauthOnly()) {<section>
<h3 [class]="cm.cn(cm.sectionHeading, cm.sp('mb', 3))">
{{ t('settings.authentication', undefined, { defaultValue: 'Authentication' }) }}
</h3>
<div [class]="cm.stack(3)">
<button
mol-button
[variant]="'outline'"
[size]="'sm'"
(click)="showPasswordModal.set(true)"
>
{{ t('settings.changePassword', undefined, { defaultValue: 'Change password' }) }}
</button>
@if (showTwoFactor()) {
<div mol-flex [align]="'center'" [justify]="'between'">
<span [class]="cm.textSize('sm')">{{ t('settings.twoFactor', undefined, { defaultValue: 'Two-factor authentication' }) }}@if (twoFactorEnabled()) {<span [class]="cm.cn(cm.textSize('xs'), cm.textSubtle, cm.sp('ml', 2))">{{ t('settings.twoFactorOn', undefined, { defaultValue: 'On' }) }}</span>}</span>
@if (twoFactorEnabled()) {
<button
mol-button
[variant]="'outline'"
[size]="'sm'"
(click)="openDisableTf()"
data-mol-id="two-factor-disable"
>
{{ t('settings.twoFactorDisable', undefined, { defaultValue: 'Disable' }) }}
</button>
} @else {
<button
mol-button
[variant]="'outline'"
[size]="'sm'"
(click)="startEnable()"
data-mol-id="two-factor-enable"
>
{{ t('settings.twoFactorEnable', undefined, { defaultValue: 'Enable' }) }}
</button>
}
</div>
}
</div>
</section>
<mol-modal
[open]="showPasswordModal()"
(close)="closePasswordModal()"
[title]="
t('settings.changePasswordModal.title', undefined, { defaultValue: 'Change Password' })
"
>
@if (pwError(); as changeError) {
<div mol-alert [status]="'error'" [className]="cm.sp('mb', 4)">{{ changeError }}</div>
}
<form [class]="cm.stack(4)" (submit)="submitPassword($event)">
<div>
<label for="current-pw" [class]="cm.formLabel">{{
t('settings.changePasswordModal.currentPassword', undefined, {
defaultValue: 'Current Password',
})
}}</label>
<div
mol-input
[id]="'current-pw'"
type="password"
autocomplete="current-password"
[required]="true"
[value]="currentPassword()"
(change)="currentPassword.set($any($event.target).value)"
></div>
</div>
<div>
<label for="new-pw" [class]="cm.formLabel">{{
t('settings.changePasswordModal.newPassword', undefined, {
defaultValue: 'New Password',
})
}}</label>
<div
mol-input
[id]="'new-pw'"
type="password"
autocomplete="new-password"
[required]="true"
[value]="newPassword()"
(change)="newPassword.set($any($event.target).value)"
></div>
</div>
<button mol-button type="submit" [fullWidth]="true" [loading]="pwStatus() === 'pending'">
@if (pwStatus() === 'pending') {
{{
t('settings.changePasswordModal.changing', undefined, { defaultValue: 'Changing...' })
}}
} @else {
{{ t('settings.changePassword', undefined, { defaultValue: 'Change password' }) }}
}
</button>
</form>
</mol-modal>
@if (showTwoFactor()) {
<mol-modal [open]="tfModal() !== null" (close)="closeTf()" [title]="tfTitle()">
@if (tfError(); as tfFailure) {
<div mol-alert [status]="'error'" [className]="cm.sp('mb', 4)">{{ tfFailure }}</div>
}
@if (tfModal() === 'enable' && tfSetup()?.QRImageUrl) {
<div [class]="cm.cn(cm.stack(3), cm.sp('mb', 4))">
<p [class]="cm.cn(cm.textSize('sm'), cm.textMuted)">
{{
t('settings.twoFactorScan', undefined, {
defaultValue:
'Scan this QR code with your authenticator app, then enter the 6-digit code.',
})
}}
</p>
<img
[attr.src]="tfSetup()?.QRImageUrl"
[attr.alt]="
t('settings.twoFactorQrAlt', undefined, { defaultValue: 'Two-factor QR code' })
"
[class]="cm.cn(cm.mxAuto, cm.maxW('xs'))"
/>
@if (tfSetup()?.secret) {
<p [class]="cm.cn(cm.textSize('xs'), cm.textSubtle, cm.settingsPanelTwoFactorSecret)">
{{ tfSetup()?.secret }}
</p>
}
</div>
}
@if (tfModal() === 'disable' || tfSetup()) {
<form [class]="cm.stack(4)" (submit)="submitTfForm($event)">
<div>
<label for="tf-token" [class]="cm.formLabel">{{
t('settings.twoFactorCode', undefined, { defaultValue: 'Authentication code' })
}}</label>
<div
mol-input
[id]="'tf-token'"
type="text"
autocomplete="one-time-code"
[required]="true"
[value]="tfToken()"
(change)="tfToken.set($any($event.target).value)"
></div>
</div>
<button
mol-button
type="submit"
[color]="tfModal() === 'disable' ? 'error' : 'primary'"
[fullWidth]="true"
[loading]="tfLoading()"
>
@if (tfModal() === 'disable') {
{{ t('settings.twoFactorDisable', undefined, { defaultValue: 'Disable' }) }}
} @else {
{{ t('settings.twoFactorVerify', undefined, { defaultValue: 'Verify & enable' }) }}
}
</button>
</form>
}
</mol-modal>}}`,
})
export class AuthSection implements OnInit {
@InputProperty() set twoFactor(value: boolean) {
this.showTwoFactor.set(value)
}
protected readonly showTwoFactor = signal(true)
protected readonly auth = useAuth<UserProfile>()
protected readonly i18n = useTranslation()
protected t = this.i18n.t
private readonly http = useHttpClient()
private readonly pw = useChangePassword()
protected readonly showPasswordModal = signal(false)
protected readonly currentPassword = signal('')
protected readonly newPassword = signal('')
protected readonly twoFactorEnabled = signal(false)
protected readonly tfModal = signal<null | 'enable' | 'disable'>(null)
protected readonly tfSetup = signal<TwoFactorSetup | null>(null)
protected readonly tfToken = signal('')
protected readonly tfLoading = signal(false)
protected readonly tfError = signal('')
private readonly pwVersion = signal(0)
protected readonly pwStatus = computed(() => {
void this.pwVersion()
return this.pw.status
})
protected readonly pwError = computed((): string | null => {
void this.pwVersion()
const error = this.pw.error
if (!error) return null
return (
error.message ||
this.t('settings.changePasswordModal.error', undefined, {
defaultValue: 'Failed to change password.',
})
)
})
private readonly twoFactorRead = { cancelled: false }
private readonly host: ElementRef<HTMLElement> = inject(ElementRef)
protected readonly cm: UIClassMap = getClassMap()
protected isOauthOnly(): boolean {
return !!this.auth.user()?.oauthServer
}
// … truncated — 10 more members: tfTitle, constructor, ngOnInit, closePasswordModal, openDisableTf, startEnable, submitTf, submitTfForm, closeTf, submitPassword; the full declaration is in node_modules/@molecule/app-settings-panel-angular/dist/auth-section.component.d.ts
(Member comments are left out to fit; the full declaration is in node_modules/@molecule/app-settings-panel-angular/dist/auth-section.component.d.ts.)
BillingSection
BillingSection component.
Billing section — current plan + Upgrade button. The host IS the
<section> React renders.
Fetches /api/billing/status on mount and uses the returned plan name as a
more accurate label than the parent-supplied default. The plan input
remains a fallback (e.g. for offline rendering or apps that don't expose
/billing/status).
The Upgrade button opens upgradeTo, the app's page for choosing a plan
(/pricing, /billing). It has no default: no one route is right for
every app, and the settings page this section sits in has no plans to
choose. An app with no such page renders TiersUpgradeSection, which lists
the tiers and starts the checkout itself. A section given no upgradeTo
anyway (from JavaScript, or a template the compiler does not check) shows the
plan without the button.
@Component({
selector: 'section[mol-settings-billing]',
standalone: true,
imports: [Button, Flex],
inputs: ['plan', { name: 'upgradeTo', required: true }],
template: `<h3 [class]="cm.cn(cm.sectionHeading, cm.sp('mb', 3))">
{{ t('settings.billing', undefined, { defaultValue: 'Billing' }) }}
</h3>
<div mol-flex [align]="'center'" [justify]="'between'">
<span [class]="cm.textSize('sm')"
>{{ t('settings.plan', undefined, { defaultValue: 'Plan: ' })
}}<strong>{{ planLabel() }}</strong></span
>
@if (upgradeTo) {
<button mol-button [variant]="'outline'" [size]="'sm'" (click)="upgrade()">
{{ t('settings.upgrade', undefined, { defaultValue: 'Upgrade' }) }}
</button>
}
</div>`,
})
export class BillingSection {
/** Fallback plan name when `/api/billing/status` is unavailable. */
plan?: string
/** The app's page for choosing a plan, which the Upgrade button opens. */
upgradeTo!: string
/** Reactive translation, read in the injection context. */
protected readonly i18n = useTranslation()
/** The translation function for the template. */
protected t = this.i18n.t
private readonly http = useHttpClient()
/** The binding's router (throws outside one, like react-router's useNavigate). */
private readonly router = useRouter()
/** The plan name loaded from `/api/billing/status`, or null. */
private readonly livePlan = signal<string | null>(null)
/** The bonded ClassMap (styling tokens resolve at render time). */
protected readonly cm: UIClassMap = getClassMap()
/**
* The displayed plan label (React's `livePlan ?? plan`).
* @returns The plan name.
*/
protected planLabel(): string {
return (
this.livePlan() ??
this.plan ??
this.t('settings.billing.freePlan', undefined, { defaultValue: 'Free' })
)
}
/**
* Reads the current plan from the bonded entitlements/billing status
* endpoint on mount (React's mount effect). Fire-and-forget; the
* input-supplied `plan` is the fallback if the fetch fails. A result that
* lands after unmount is dropped like React's cancelled one.
*/
constructor() {
let cancelled = false
inject(DestroyRef).onDestroy(() => {
cancelled = true
})
void this.http
.get<{ name?: string }>('/api/billing/status')
.then((res) => {
if (cancelled) return
const body =
(res as { data?: { name?: string }; name?: string }).data ?? (res as { name?: string })
const name = body?.name
if (typeof name === 'string' && name) this.livePlan.set(name)
})
.catch((_error) => {
// fallback to the input-supplied plan label
})
}
/** Navigates to the upgrade route (React's `navigate(upgradeTo)`). */
protected upgrade(): void {
this.router.navigate(this.upgradeTo)
}
}
DevicesSection
DevicesSection component.
Devices section — lists the user's registered devices and lets them
revoke (sign out) any device other than the one they're currently using.
The host IS the <section> React renders.
Revoking deletes the device row (DELETE /api/devices/:id). The API's
authorization layer enforces server-side revocation: it rejects that
device's session the next time it makes a request (within the
device-exists cache TTL), so the removed device is actually signed out —
not just hidden from the list. The current device is labelled
"This device" and is not revocable here (use Sign out for the current
session). Recreates molecule v1's device-revocation behaviour.
Apps that want a different trailing element per row can pass a
renderRowIcon template (its context carries the device as $implicit
and a0, the way the conformance kit maps a React render function), which
then replaces the built-in revoke control; pass an empty template to
suppress it entirely.
@Component({
selector: 'section[mol-settings-devices]',
standalone: true,
imports: [Button, Flex, Icon, NgTemplateOutlet, Spinner],
inputs: ['renderRowIcon'],
// prettier-ignore
template: `<div mol-flex [align]="'center'" [gap]="'sm'" [className]="cm.sp('mb', 3)">
<h3 [class]="cm.sectionHeading">
{{ t('settings.devices', undefined, { defaultValue: 'Devices' }) }}
</h3>
@if (loading()) {
<div mol-spinner [size]="'xs'"></div>
}
</div>
@if (devices().length > 0) {
<ul [class]="cm.stack(2)">
@for (device of devices(); track device.id) {
<li>
<div
mol-flex
[align]="'center'"
[justify]="'between'"
[className]="cm.cn(cm.textSize('sm'), cm.sp('py', 1))"
>
<span>{{ device.name || device.platform }}@if (device.isCurrent) {<span [class]="cm.cn(cm.textSize('xs'), cm.textSubtle, cm.sp('ml', 2))">{{ t('settings.thisDevice', undefined, { defaultValue: 'This Device' }) }}</span>}</span>
@if (renderRowIcon) {
<ng-container
[ngTemplateOutlet]="renderRowIcon"
[ngTemplateOutletContext]="rowContext(device)"
/>
} @else if (device.isCurrent) {
<svg
mol-icon-root
[name]="'chevron-right'"
[size]="16"
[className]="cm.textSubtle"
></svg>
} @else if (isConfirming(device)) {
<div mol-flex [align]="'center'" [gap]="'sm'">
<button
mol-button
[variant]="'ghost'"
[size]="'sm'"
[disabled]="isRevoking(device)"
(click)="confirmingId.set(null)"
>
{{ t('common.cancel', undefined, { defaultValue: 'Cancel' }) }}
</button>
<button
mol-button
[color]="'error'"
[size]="'sm'"
[loading]="isRevoking(device)"
(click)="revoke(device.id)"
data-mol-id="device-revoke-confirm"
>
{{ t('settings.signOutDevice', undefined, { defaultValue: 'Sign out' }) }}
</button>
</div>
} @else {
<button
mol-button
[variant]="'ghost'"
[size]="'sm'"
(click)="confirmingId.set(device.id)"
data-mol-id="device-revoke"
>
{{ t('settings.signOutDevice', undefined, { defaultValue: 'Sign out' }) }}
</button>
}
</div>
@if (isConfirming(device)) {
<p [class]="cm.cn(cm.textSize('xs'), cm.textMuted, cm.sp('mt', 1))">
{{
t('settings.revokeDeviceWarning', undefined, {
defaultValue: "This device's access will be revoked shortly. Sign it out?",
})
}}
</p>
}
</li>
}
</ul>
} @else {
@if (!loading()) {
<p [class]="cm.cn(cm.textSize('sm'), cm.textMuted)">
{{ t('settings.noDevices', undefined, { defaultValue: 'No devices found' }) }}
</p>
}
}`,
})
export class DevicesSection {
/**
* A custom trailing element per row (React's `renderRowIcon` callback).
* The template's context carries the device as `$implicit` / `a0`; giving
* one replaces the built-in revoke control.
*/
renderRowIcon?: TemplateRef<unknown> | null
/** Reactive translation, read in the injection context. */
protected readonly i18n = useTranslation()
/** The translation function for the template. */
protected t = this.i18n.t
private readonly http = useHttpClient()
/** The registered devices. */
protected readonly devices = signal<Device[]>([])
/** Whether the device list is loading. */
protected readonly loading = signal(true)
/** The id of the row showing its revoke confirmation. */
protected readonly confirmingId = signal<string | null>(null)
/** The id of the device whose revoke request is running. */
protected readonly revokingId = signal<string | null>(null)
/** The bonded ClassMap (styling tokens resolve at render time). */
protected readonly cm: UIClassMap = getClassMap()
/**
* Whether one row shows its revoke confirmation.
* @param device - The row's device.
* @returns True when the row is confirming.
*/
protected isConfirming(device: Device): boolean {
return this.confirmingId() === device.id
}
/**
* Whether one row's revoke request is running.
* @param device - The row's device.
* @returns True when the row is revoking.
*/
protected isRevoking(device: Device): boolean {
return this.revokingId() === device.id
}
/**
* The template context for one row's custom renderer (the way the
* conformance kit maps a React render function: `$implicit` = the first
* argument, `a0`… the argument list).
* @param device - The row's device.
* @returns The template context.
*/
protected rowContext(device: Device): Record<string, unknown> {
return { $implicit: device, a0: device, a1: undefined, a2: undefined }
}
/**
* Loads the devices (React's `load`): GET /api/devices responds with the
* ARRAY itself (see the device resource's query handler) — response.data IS
* the rows. This used to read `response.data.data`, which is always
* undefined for that shape, so the section rendered "No devices" for
* everyone. Devices endpoint is optional; the section renders empty when
* unavailable.
*/
private async load(): Promise<void> {
try {
const response = await this.http.get<Device[]>('/api/devices')
this.devices.set(Array.isArray(response.data) ? response.data : [])
} catch (_error) {
// Devices endpoint is optional; the section renders empty when unavailable.
} finally {
this.loading.set(false)
}
}
/** Loads once on mount (React's mount effect). */
constructor() {
inject(DestroyRef)
void this.load()
}
/**
* Signs one device out and reloads (React's `revoke`); best-effort — the
* row is kept so the user can retry the revoke.
* @param id - The device row's id.
*/
protected async revoke(id: string): Promise<void> {
this.revokingId.set(id)
try {
await this.http.delete(`/api/devices/${id}`)
this.confirmingId.set(null)
await this.load()
} catch (_error) {
// Best-effort — keep the row so the user can retry the revoke.
} finally {
this.revokingId.set(null)
}
}
}
LogOutDeleteSection
LogOutDeleteSection component.
Bottom actions section — Log out + Delete account. React's root is a
fragment (the <section> plus the delete-account modal), so those nodes
render in the host's place and the host itself never appears in the page.
Owns the delete-account modal internally (the trigger lives in the
same section so the modal lives here too). Reads onClose from
the <SettingsContainer> context to dismiss the panel after either
action and navigates to /login.
@Component({
selector: 'mol-log-out-delete-section',
standalone: true,
hostDirectives: [MolPlacement],
imports: [Alert, Button, Input, Modal],
template: `<section [class]="cm.stack(3)">
<button
mol-button
[color]="'error'"
[fullWidth]="true"
(click)="logout()"
data-mol-id="user-menu-logout"
>
{{ t('settings.logOut', undefined, { defaultValue: 'Sign out' }) }}
</button>
<button
mol-button
[variant]="'ghost'"
[fullWidth]="true"
(click)="showModal.set(true)"
data-mol-id="user-menu-delete-account"
>
{{ t('settings.deleteAccount', undefined, { defaultValue: 'Delete account' }) }}
</button>
</section>
<mol-modal
[open]="showModal()"
(close)="showModal.set(false)"
[title]="
t('settings.deleteAccountModal.title', undefined, { defaultValue: 'Delete Account' })
"
>
<p [class]="cm.cn(cm.textSize('sm'), cm.textMuted, cm.sp('mb', 4))">
{{
t('settings.deleteAccountModal.warning', undefined, {
defaultValue: 'This action cannot be undone. Please enter your password to confirm.',
})
}}
</p>
@if (deleteError(); as submitError) {
<div mol-alert [status]="'error'" [className]="cm.sp('mb', 4)">{{ submitError }}</div>
}
<form [class]="cm.stack(4)" (submit)="deleteAccount($event)">
<div>
<label for="delete-pw" [class]="cm.formLabel">{{
t('settings.deleteAccountModal.password', undefined, { defaultValue: 'Password' })
}}</label>
<div
mol-input
[id]="'delete-pw'"
type="password"
[required]="true"
[value]="password()"
(change)="password.set($any($event.target).value)"
></div>
</div>
<button mol-button type="submit" [color]="'error'" [fullWidth]="true" [loading]="loading()">
@if (loading()) {
{{
t('settings.deleteAccountModal.deleting', undefined, { defaultValue: 'Deleting...' })
}}
} @else {
{{ t('settings.deleteAccount', undefined, { defaultValue: 'Delete account' }) }}
}
</button>
</form>
</mol-modal>`,
})
export class LogOutDeleteSection {
/** Reactive translation, read in the injection context. */
protected readonly i18n = useTranslation()
/** The translation function for the template. */
protected t = this.i18n.t
/** The binding's router (throws outside one, like react-router's useNavigate). */
private readonly router = useRouter()
/** The signed-in user and the auth actions. */
private readonly auth = useAuth<UserProfile>()
private readonly http = useHttpClient()
/** The container's `onClose` (throws outside a `<SettingsContainer>`). */
private readonly panel = useSettingsPanelContext()
/** Whether the delete-account modal is open. */
protected readonly showModal = signal(false)
/** The delete-account password field's value. */
protected readonly password = signal('')
/** Whether the delete request is running. */
protected readonly loading = signal(false)
/** The delete-account modal's error message. */
protected readonly deleteError = signal('')
/** The bonded ClassMap (styling tokens resolve at render time). */
protected readonly cm: UIClassMap = getClassMap()
private readonly host: ElementRef<HTMLElement> = inject(ElementRef)
constructor() {
usePlacement(() => {
// React's fragment (the section plus the delete-account modal) renders in
// the host's place; the host itself leaves the page.
placeContentBefore(this.host.nativeElement, this.host.nativeElement)
setElementPresent(this.host.nativeElement, false)
})
}
/** Closes the settings panel (the container context's callback). */
private closePanel(): void {
this.panel.onClose()
}
/** Signs out, closes the panel and returns to `/login` (React's `handleLogout`). */
protected async logout(): Promise<void> {
await this.auth.logout()
this.closePanel()
this.router.navigate('/login')
}
/**
* Deletes the account (React's `handleDelete`): submits the password,
* signs out, closes the panel and returns to `/login`; a failure shows the
* server's message and keeps the modal.
* @param event - The native submit event.
*/
protected async deleteAccount(event: Event): Promise<void> {
event.preventDefault()
this.loading.set(true)
this.deleteError.set('')
try {
await this.http.delete(`/api/users/${this.auth.user()?.id}`, {
data: { password: this.password() },
})
await this.auth.logout()
this.closePanel()
this.router.navigate('/login')
} catch (err) {
this.deleteError.set(
serverErrorMessage(err) ??
this.t('settings.failedToDeleteAccount', undefined, {
defaultValue: 'Failed to delete account.',
}),
)
} finally {
this.loading.set(false)
}
}
}
NotificationsSection
NotificationsSection component.
Push-notification toggle section — the full receive-side enable chain:
browser permission → runtime VAPID public key
(GET /api/devices/push/public-key) → pushManager.subscribe with
applicationServerKey → PATCH the subscription onto the current device
row (/api/devices/:id { pushSubscription, hasPushSubscription }), which
is where the api-side push fan-outs look for it. The host IS the
<section> React renders.
Initial state reflects SERVER truth (the current device row's
hasPushSubscription), and every failure surfaces as an honest inline
message — a dev build without a service worker fails fast instead of
hanging the switch.
@Component({
selector: 'section[mol-settings-notifications]',
standalone: true,
imports: [Flex, Switch],
template: `<h3 [class]="cm.cn(cm.sectionHeading, cm.sp('mb', 3))">
{{ t('settings.notifications', undefined, { defaultValue: 'Notifications' }) }}
</h3>
<div mol-flex [align]="'center'" [justify]="'between'">
<span [class]="cm.textSize('sm')">{{
t('settings.pushNotifications', undefined, { defaultValue: 'Push notifications' })
}}</span>
<mol-switch
#pushSwitch
[checked]="enabled()"
[disabled]="busy()"
[attr.aria-label]="
t('settings.pushNotifications', undefined, { defaultValue: 'Push notifications' })
"
(change)="pushToggleChanged($event)"
[size]="'sm'"
data-mol-id="settings-push-toggle"
></mol-switch>
</div>
@if (error(); as pushError) {
<p
[class]="cm.cn(cm.textSize('xs'), cm.textError, cm.sp('mt', 1))"
role="alert"
data-mol-id="settings-push-error"
>
{{ pushError }}
</p>
}`,
})
export class NotificationsSection implements AfterViewInit {
/** Reactive translation, read in the injection context. */
protected readonly i18n = useTranslation()
/** The translation function for the template. */
protected t = this.i18n.t
private readonly http = useHttpClient()
/** The push provider's permission/registration actions. */
private readonly push = usePush()
/** Whether the current device's push subscription is on. */
protected readonly enabled = signal(false)
/** Whether an enable/disable chain is running (the switch is disabled). */
protected readonly busy = signal(false)
/** The inline failure message, or null. */
protected readonly error = signal<string | null>(null)
/** The push switch's host element (the hidden checkbox lives inside). */
@ViewChild('pushSwitch', { read: ElementRef }) pushSwitch?: ElementRef<HTMLElement>
/** The controlled-`checked` sync (created once the host exists). */
private sync?: ControlledSwitchSync
/** The bonded ClassMap (styling tokens resolve at render time). */
protected readonly cm: UIClassMap = getClassMap()
/**
* Reads the server's push state for THIS device (React's mount effect).
* Resolves false (never throws) when the devices endpoint is unavailable;
* a result that lands after unmount is dropped like React's cancelled one.
*/
constructor() {
let cancelled = false
inject(DestroyRef).onDestroy(() => {
cancelled = true
})
// Server truth for THIS device; resolves false (never throws) when the
// devices endpoint is unavailable.
void readCurrentDevicePushEnabled(this.http).then((serverEnabled) => {
if (!cancelled && serverEnabled) this.enabled.set(true)
})
// React's controlled `checked` re-render, as an effect (view hooks are
// skipped by signal-driven refreshes).
effect(() => {
const checked = this.enabled()
untracked(() => this.runSync(checked))
})
}
/** Captures the mount-time attribute state (hooks run on the mount passes). */
ngAfterViewInit(): void {
this.runSync(this.enabled())
}
/**
* Runs the controlled-`checked` sync once the switch host exists.
* @param checked - The controlled value this render shows.
*/
private runSync(checked: boolean): void {
if (!this.sync && this.pushSwitch) {
this.sync = new ControlledSwitchSync(this.pushSwitch.nativeElement)
}
this.sync?.sync(checked)
}
/**
* The switch's change: the hidden checkbox's `checked` at emit time (React
* reads `e.target.checked` before its controlled restore).
* @param event - The native change event the UI Switch re-emitted.
*/
protected pushToggleChanged(event: Event): void {
const checked = (event.target as HTMLInputElement | null)?.checked ?? false
void this.handleToggle(checked)
}
/**
* The localized message for one toggle failure (React's `failureMessage`).
* @param result - The failed toggle result.
* @returns The message text.
*/
private failureMessage(result: Extract<PushToggleResult, { ok: false }>): string {
switch (result.reason) {
case 'permission-denied':
return this.t('settings.pushPermissionDenied', undefined, {
defaultValue: 'Notification permission was denied.',
})
case 'server-unconfigured':
return this.t('settings.pushServerUnavailable', undefined, {
defaultValue: 'Push notifications are not configured on this server.',
})
case 'register-failed':
// The push provider throws already-localized messages (not supported /
// no service worker in a dev build / push-service rejection).
return (
result.message ||
this.t('settings.pushUpdateFailed', undefined, {
defaultValue: 'Could not update push notification settings.',
})
)
case 'persist-failed':
// `result.message` here is the HTTP client's error (a status line or a
// network error), not text written for the user, so it is not shown.
return this.t('settings.pushUpdateFailed', undefined, {
defaultValue: 'Could not update push notification settings.',
})
}
}
/**
* Runs one enable/disable chain (React's `handleToggle`).
* @param next - Whether the switch turned on.
*/
private async handleToggle(next: boolean): Promise<void> {
if (this.busy()) return
this.busy.set(true)
this.error.set(null)
try {
if (next) {
const result = await enablePushOnCurrentDevice({
http: this.http,
requestPermission: this.push.requestPermission,
register: this.push.register,
})
if (result.ok) {
this.enabled.set(true)
} else {
this.error.set(this.failureMessage(result))
}
} else {
const result = await disablePushOnCurrentDevice({
http: this.http,
unregister: this.push.unregister,
})
// The switch goes off locally either way; a failed server clear is
// still reported so the user knows sends may continue.
this.enabled.set(false)
if (!result.ok) {
this.error.set(this.failureMessage(result))
}
}
} finally {
this.busy.set(false)
}
}
}
SettingsContainer
SettingsContainer component.
Outer settings-panel layout: padded vertical stack that hosts the section
sub-components (projected content). The host IS the <div> React renders
(div[mol-settings-container]), with cm.sp('p', 6) + cm.stack(6).
Publishes onClose to descendants via the settings-panel context so
<LogOutDeleteSection> etc. can dismiss the panel after an action without
explicit prop threading. The registration happens in the constructor, which
Angular runs before any projected child is created.
@Component({
selector: 'div[mol-settings-container]',
standalone: true,
inputs: ['onClose'],
host: {
'[class]': 'classes()',
},
template: `<ng-content></ng-content>`,
})
export class SettingsContainer {
/** Closes the settings panel, published to sections through the container context. */
onClose?: () => void
private readonly host = inject(ElementRef)
/** The context registration removal (set in the constructor). */
private removeContext: () => void = () => {}
/** Registers the container context before any projected child resolves it. */
constructor() {
this.removeContext = provideSettingsPanelContext(this.host.nativeElement, () => this.onClose)
inject(DestroyRef).onDestroy(this.removeContext)
}
/** The bonded ClassMap (styling tokens resolve at render time). */
protected readonly cm: UIClassMap = getClassMap()
/**
* Computes the container class list (`cm.sp('p', 6)` + `cm.stack(6)`).
* @returns The class string.
*/
classes(): string {
return this.cm.cn(this.cm.sp('p', 6), this.cm.stack(6))
}
}
ThisDeviceSection
ThisDeviceSection component.
"This device" detail strip — OS, browser, online/offline. The host IS the
<section> React renders.
Reads everything from @molecule/app-device through the useDevice hook
(deviceInfo and isOnline()), so the bonded device provider decides what
it shows. No side effects, no app-specific state.
The network line's isOnline() call is mediated by a computed over the
i18n notifications (its only change signal), so the provider is read once
per render — the same call count React's render records — and again on a
locale switch, exactly like a React re-render.
@Component({
selector: 'section[mol-settings-this-device]',
standalone: true,
imports: [Flex],
template: `<h3 [class]="cm.cn(cm.sectionHeading, cm.sp('mb', 3))">
{{ t('settings.thisDevice', undefined, { defaultValue: 'This Device' }) }}
</h3>
<dl [class]="cm.cn(cm.stack(1), cm.textSize('sm'))">
<div mol-flex [justify]="'between'">
<dt [class]="cm.textMuted">
{{ t('settings.platform', undefined, { defaultValue: 'Platform' }) }}
</dt>
<dd>{{ platformLabel() }}</dd>
</div>
<div mol-flex [justify]="'between'">
<dt [class]="cm.textMuted">
{{ t('settings.browser', undefined, { defaultValue: 'Browser' }) }}
</dt>
<dd>{{ browserLabel() }}</dd>
</div>
<div mol-flex [justify]="'between'">
<dt [class]="cm.textMuted">
{{ t('settings.network', undefined, { defaultValue: 'Network' }) }}
</dt>
<dd>{{ networkLabel() }}</dd>
</div>
</dl>`,
})
export class ThisDeviceSection {
/** The bonded device provider's info (read once, like React's memoized hook). */
protected readonly device = useDevice()
/** Reactive translation, read in the injection context. */
protected readonly i18n = useTranslation()
/** The translation function for the template. */
protected t = this.i18n.t
/** The bonded ClassMap (styling tokens resolve at render time). */
protected readonly cm: UIClassMap = getClassMap()
/** The OS name, or the localized Unknown fallback. */
protected readonly platformLabel = computed(() => {
return (
this.device.deviceInfo.os.name ||
this.t('settings.unknown', undefined, { defaultValue: 'Unknown' })
)
})
/** The browser name, or the localized Unknown fallback. */
protected readonly browserLabel = computed(() => {
return (
this.device.deviceInfo.browser.name ||
this.t('settings.unknown', undefined, { defaultValue: 'Unknown' })
)
})
/**
* The network line: `isOnline()` runs when this computed first renders and
* again whenever the locale changes (the t() calls track the i18n
* notifications), matching React's per-render call exactly.
*/
protected readonly networkLabel = computed(() => {
return this.device.isOnline()
? this.t('settings.online', undefined, { defaultValue: 'Online' })
: this.t('settings.offline', undefined, { defaultValue: 'Offline' })
})
}
TiersUpgradeSection
TiersUpgradeSection component.
Billing section with full multi-tier upgrade flow. React's root is a
fragment (the <section> plus the upgrade modal), so those nodes render in
the host's place and the host itself never appears in the page.
Replaces the simpler BillingSection for apps backed by
@molecule/api-payments-stripe + @molecule/api-resource-payment — loads
the user's current plan from /api/billing/status, loads available tiers
from /api/billing/tiers, and renders an Upgrade modal with a Subscribe
button per price that is for sale (one the server lists with a price id).
Upgrade appears only for a free user and only when something is for sale.
Subscribe POSTs to /api/billing/checkout and redirects to the checkout
URL; a paid user (isFree: false in the status) sees a Cancel button that
POSTs to /api/billing/cancel. A refused request shows the server's
message.
@Component({
selector: 'mol-tiers-upgrade-section',
standalone: true,
hostDirectives: [MolPlacement],
imports: [Alert, Button, ConfirmButton, Flex, Modal],
inputs: ['redirectToCheckout'],
template: `<section>
<h3 [class]="cm.cn(cm.sectionHeading, cm.sp('mb', 3))">
{{ t('settings.billing', undefined, { defaultValue: 'Billing' }) }}
</h3>
<div mol-flex [align]="'center'" [justify]="'between'">
<!-- The plan line waits for the server: there is no plan name to guess. -->
@if (plan(); as planName) {
<span [class]="cm.textSize('sm')"
>{{ t('settings.plan', undefined, { defaultValue: 'Plan: ' })
}}<strong>{{ planName }}</strong></span
>
} @else {
<span></span>
}
@if (isFree()) {
@if (forSale().length > 0) {
<button mol-button [variant]="'outline'" [size]="'sm'" (click)="showUpgrade.set(true)">
{{ t('settings.upgrade', undefined, { defaultValue: 'Upgrade' }) }}
</button>
}
} @else {
<button
mol-confirm-button
[variant]="'outline'"
[size]="'sm'"
[onConfirm]="cancelSubscription"
data-mol-id="billing-cancel-subscription"
>
<ng-container ngProjectAs="[slot=label]">{{
t('settings.billing.cancel', undefined, { defaultValue: 'Cancel' })
}}</ng-container
><ng-container ngProjectAs="[slot=confirmLabel]">{{
t('settings.billing.cancelConfirm', undefined, {
defaultValue: 'Cancel your subscription?',
})
}}</ng-container>
</button>
}
</div>
@if (cancelError(); as cancelMessage) {
<div mol-alert [status]="'error'" [className]="cm.sp('mt', 3)">{{ cancelMessage }}</div>
}
</section>
<mol-modal
[open]="showUpgrade()"
(close)="showUpgrade.set(false)"
[title]="t('settings.billing.upgradeTitle', undefined, { defaultValue: 'Upgrade your plan' })"
>
@if (upgradeError(); as checkoutError) {
<div mol-alert [status]="'error'" [className]="cm.sp('mb', 4)">{{ checkoutError }}</div>
}
<ul [class]="cm.stack(3)">
@for (entry of forSale(); track entry.key) {
<li [class]="cm.sp('p', 4)">
<div mol-flex [align]="'center'" [justify]="'between'">
<div>
<p [class]="cm.fontWeight('semibold')">
{{ entry.tier.name }} ({{ entry.price.interval }})
</p>
<p [class]="cm.cn(cm.textSize('xs'), cm.textMuted)">
{{ entry.price.priceLabel }}
</p>
</div>
<button
mol-button
[size]="'sm'"
[loading]="upgradeLoading() === entry.priceId"
(click)="startCheckout(entry.priceId)"
>
{{ t('settings.billing.subscribe', undefined, { defaultValue: 'Subscribe' }) }}
</button>
</div>
</li>
}
</ul>
</mol-modal>`,
})
export class TiersUpgradeSection {
redirectToCheckout: (checkoutUrl: string) => void = openUrl
/** Reactive translation, read in the injection context. */
protected readonly i18n = useTranslation()
/** The translation function for the template. */
protected t = this.i18n.t
private readonly http = useHttpClient()
protected readonly plan = signal<string | null>(null)
protected readonly planKey = signal<string | null>(null)
protected readonly isFree = signal(true)
/** The tiers loaded from `/api/billing/tiers`. */
protected readonly tiers = signal<Tier[]>([])
/** Whether the upgrade modal is open. */
protected readonly showUpgrade = signal(false)
/** The price id whose checkout request is running, or null. */
protected readonly upgradeLoading = signal<string | null>(null)
/** The upgrade modal's error message. */
protected readonly upgradeError = signal('')
protected readonly cancelError = signal('')
protected readonly cm: UIClassMap = getClassMap()
private readonly host: ElementRef<HTMLElement> = inject(ElementRef)
private loads = 0
private destroyed = false
protected forSale(): { key: string; tier: Tier; price: TierPrice; priceId: string }[] {
const entries: { key: string; tier: Tier; price: TierPrice; priceId: string }[] = []
for (const tier of this.tiers()) {
if (tier.planKey === this.planKey()) continue
for (const price of tier.prices) {
if (!price.stripePriceId) continue
entries.push({
key: `${tier.planKey}-${price.stripePriceId}`,
tier,
price,
priceId: price.stripePriceId,
})
}
}
return entries
}
/** Loads the current plan and the available tiers on mount. */
constructor() {
usePlacement(() => {
// host's place; the host itself leaves the page.
placeContentBefore(this.host.nativeElement, this.host.nativeElement)
setElementPresent(this.host.nativeElement, false)
})
inject(DestroyRef).onDestroy(() => {
this.destroyed = true
})
this.load()
}
private load(): void {
const seq = ++this.loads
void Promise.all([
this.http
.get<{ planKey?: string; name?: string; isFree?: boolean }>('/api/billing/status')
.catch((_error) => null),
this.http
.get<{
data?: Array<{
key: string
name: string
prices: Array<{ stripePriceId: string | null; period: string; price: string }>
}>
}>('/api/billing/tiers')
.catch((_error) => null),
])
.then(([statusRes, tiersRes]) => {
if (this.destroyed || seq !== this.loads) return
const status = statusRes?.data ?? null
if (status?.name) this.plan.set(status.name)
if (status?.planKey) this.planKey.set(status.planKey)
if (typeof status?.isFree === 'boolean') this.isFree.set(status.isFree)
const list = tiersRes?.data?.data
if (Array.isArray(list)) {
this.tiers.set(
list.map((tier) => ({
planKey: tier.key,
name: tier.name,
prices: (tier.prices || []).map((p) => ({
stripePriceId: p.stripePriceId ?? undefined,
interval: p.period,
priceLabel: p.price,
})),
})),
)
}
})
.catch((_error) => {})
}
protected async startCheckout(stripePriceId: string): Promise<void> {
this.upgradeError.set('')
this.upgradeLoading.set(stripePriceId)
try {
const res = await this.http.post<{ checkoutUrl?: string; updated?: boolean }>(
'/api/billing/checkout',
{ priceId: stripePriceId },
)
const data = res.data
if (data?.checkoutUrl) {
this.redirectToCheckout(data.checkoutUrl)
return
}
if (data?.updated) {
this.showUpgrade.set(false)
return
}
this.upgradeError.set(
this.t('settings.billing.checkoutFailed', undefined, {
defaultValue: 'Could not start checkout.',
}),
)
} catch (err) {
this.upgradeError.set(
serverErrorMessage(err) ??
this.t('settings.billing.checkoutFailed', undefined, {
defaultValue: 'Could not start checkout.',
}),
)
} finally {
this.upgradeLoading.set(null)
}
}
protected cancelSubscription = async (): Promise<void> => {
this.cancelError.set('')
try {
await this.http.post('/api/billing/cancel', {})
this.load()
} catch (err) {
this.cancelError.set(
serverErrorMessage(err) ??
this.t('settings.billing.cancelFailed', undefined, {
defaultValue: 'Could not cancel.',
}),
)
}
}
}
(The 16 longest member comments are left out to fit; the full declaration is in node_modules/@molecule/app-settings-panel-angular/dist/tiers-upgrade-section.component.d.ts.)
Functions
useSettingsPanelContext()
Reads the onClose handler exposed by the parent <SettingsContainer>.
Throws if used outside the container so component misuse is loud.
The lookup is deferred to the first property read (an event handler, long after Angular has created and attached every element), so a section nested in projected content resolves the container reliably.
function useSettingsPanelContext(): SettingsPanelContextValue
Returns: The container context.
findCurrentDevice(devices)
Picks the caller's own device row: the api flags the session device
isCurrent; fall back to the first row for sessions predating the flag.
function findCurrentDevice(devices: PushToggleDevice[] | undefined): PushToggleDevice | undefined
devices— Rows fromGET /api/devices.
Returns: The current device row, or undefined when the user has none.
subscriptionFromToken(token)
Converts an @molecule/app-push token into the device resource's
pushSubscription shape (web PushSubscription JSON, FCM registration for
Android, APNs registration for iOS).
function subscriptionFromToken(token: PushToggleToken): unknown
token— The push token returned byregister().
Returns: The pushSubscription value to PATCH onto the device row.
enablePushOnCurrentDevice(deps)
Runs the full enable chain: browser permission → runtime VAPID public key
(GET /api/devices/push/public-key) → register({ vapidPublicKey }) →
persist the subscription on the current device row.
Every failure is returned as a typed reason (never thrown) so the UI can show an honest, specific message instead of hanging or silently reverting.
function enablePushOnCurrentDevice(deps: {
http: PushToggleHttp
requestPermission: () => Promise<string>
register: (options?: { vapidPublicKey?: string }) => Promise<PushToggleToken>
}): Promise<PushToggleResult>
deps— The http client + push actions fromusePush().deps.http— Authenticated http client (useHttpClient()).deps.requestPermission—usePush().requestPermission.deps.register—usePush().register.
Returns: { ok: true } or a typed failure.
disablePushOnCurrentDevice(deps)
Disables push: unsubscribes the browser (best-effort — a dev build without a service worker has nothing to unsubscribe) and ALWAYS clears the server state so no further pushes target this device.
function disablePushOnCurrentDevice(deps: {
http: PushToggleHttp
unregister: () => Promise<void>
}): Promise<PushToggleResult>
deps— The http client + push action fromusePush().deps.http— Authenticated http client (useHttpClient()).deps.unregister—usePush().unregister.
Returns: { ok: true } or a typed failure (server state not cleared).
readCurrentDevicePushEnabled(http)
Reads whether push is currently enabled for THIS device (server truth:
the current device row's hasPushSubscription).
function readCurrentDevicePushEnabled(http: PushToggleHttp): Promise<boolean>
http— Authenticated http client (useHttpClient()).
Returns: true when the current device has a stored subscription.
Constants
SettingsPanelContext
Names the container context SettingsContainer publishes and sections
consume (React's SettingsPanelContext object). Angular's counterpart is
the DOM-scoped registration on the container's host element; this constant
documents and keys that contract.
const SettingsPanelContext: 'molecule-settings-panel-context'
Injection Notes
Requirements
Peer dependencies:
@angular/common^22.0.0@angular/core^22.0.0@angular/platform-browser^22.0.0@molecule/app-angular^3.17.0 || ^4.0.0@molecule/app-auth^3.4.0@molecule/app-http^1.8.0@molecule/app-push^1.1.0@molecule/app-ui^1.3.11@molecule/app-ui-angular^1.5.0@molecule/app-utilities^1.0.6
Runtime Dependencies
-
@angular/common -
@angular/core -
@angular/platform-browser -
@molecule/app-angular -
@molecule/app-auth -
@molecule/app-http -
@molecule/app-push -
@molecule/app-ui -
@molecule/app-ui-angular -
@molecule/app-utilities -
Wiring prereqs: sections need the standard
@molecule/app-angularprovider stack —provideI18n,provideHttp(authenticated client),provideAuth,provideTheme(AppearanceSection), the bonded device and push providers (NotificationsSection/ThisDeviceSection) — plus a bonded ClassMap.BillingSectionandLogOutDeleteSectionalso need the binding's router (provideRouter) and throw outside one. -
Section components throw if rendered outside
<SettingsContainer>(they read its context foronClose). -
Server contract: the molecule API surface from
@molecule/api-resource-user,@molecule/api-resource-device,@molecule/api-two-factor, and the billing endpoints (/api/billing/*) wired by the payments stack. Missing read endpoints degrade gracefully (sections render empty); the mutating actions do not. -
Translations:
@molecule/app-locales-settings-panelcompanion bond.
Translations
Translation strings are provided by @molecule/app-locales-settings-panel.