Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
# Changelog

## [Unreleased]

Needs `@nebulr-group/bridge-auth-core` 1.0.0-alpha.11, which has plan limits, entitlements and the billing lock.

### Added

- **`QuotaGate`, `Entitled` and `useEntitlements`.** `<QuotaGate metric>` disables the actions inside once a metric is at its hard limit and shows an upgrade line; `<Entitled to>` shows its content when the plan has a feature; `useEntitlements().can(key)` reads the same, from the flag `bridge:billing.entitlement.<key>`, fail-closed until Bridge has answered (`ready`).
- **`useQuota(metric)` gives `loading`, `unlimited`, `used`, `limit`, `remaining`, `warningLevel`, `kind` and `snapshot`** (with `policy`), and still `ratio` and `state`.
- **The billing lock.** `<BillingNotice mode="hard" />` blocks the page while the workspace is locked for payment; the lock shows to every person and at once when your API answers a change with its 402 through `bridgeFetch`. `useBillingGate()` and `useBillingLocked()` give it as hooks.
- **`onBridgeQuotaExceeded(handler)`** runs for each limit your API refuses through `bridgeFetch`, for an app with its own dialog.
- `BridgeBillingNotice`, `BridgeQuotaBanner` and `BridgeUpgradeDialog` are other names for `BillingNotice`, `QuotaBanner` and `UpgradeDialog`. `dismissQuotaRefusal()` is another name for `closeUpgrade()`. `useBridgeBilling()` gives `quota(metric)`, `quotas`, `entitlements`, `handle`, `isLocked()`, `gateState()` and `assertNotLocked()` without a hook, as in 0.9; it has no `subscription` (use `useBilling()`).

### Changed

- **`QuotaBanner` and `useQuota` read Bridge's quota numbers** and follow quota and plan changes live, instead of the period's usage read once. The banner shows from 80%, says "limit reached" at the limit, and shows a metered limit's overage. `onActionClick` receives the quota snapshot.
- **`useQuota` always returns an object** (`loading` is true until Bridge has answered) instead of `null` while loading and for a metric without a limit.
- The type `QuotaState` is now what `useQuota` returns; the former `'ok' | 'near' | 'over'` is `QuotaLevel`, and `Quota` is gone.

## [1.0.0-alpha.1] - unreleased

Needs `@nebulr-group/bridge-auth-core` 1.0.0-alpha.8. A new major line, for the new Bridge: the React counterpart of `@nebulr-group/bridge-svelte` 1.0.0-alpha.8, with the same pages, settings and wording, so the guides of either package map to the other. `latest` stays on 0.x.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ In your app's settings in Bridge, add your app's address as a browser address an
|---|---|
| Sign-in | `BridgeAuthRoutes` (sign-in, sign-up, verify-email, forgot-password, set-password, invite, workspaces, magic-link, passkey-setup, handoff, callback), `SignInForm`, `SignUpForm`, `VerifyEmail`, `ForgotPassword`, `SetPassword`, `InviteLanding`, `MagicLinkLanding`, `PasskeySetupLanding`, `PasskeyManager`, `WorkspaceChooser`, `SignOutButton`, `ProfileName` |
| Gates | route `rules`, `FeatureFlag`, `useFlag`, `requireFlag`, the paywall: all on flag results, never a role or the plan |
| Billing | `BridgeBillingRoutes`, `PlanPicker`, `BillingPortalButton`, `SubscriptionStatus`, `BillingNotice`, `QuotaBanner`, `CheckoutNotice`, `UpgradeDialog`, `useQuota`, `bridgeFetch` |
| Billing | `BridgeBillingRoutes`, `PlanPicker`, `BillingPortalButton`, `SubscriptionStatus`, `BillingNotice`, `QuotaBanner`, `QuotaGate`, `Entitled`, `CheckoutNotice`, `UpgradeDialog`, `useQuota`, `useEntitlements`, `bridgeFetch` |
| Team | `TeamPanel`, `MemberList`, `InviteDialog`, `InviteList`, `EditMemberDialog`, `ConfirmDialog`, `WorkspaceForm`, `ProfileForm` |
| State | `useSession`, `useUser`, `useWorkspace`, `useWorkspaces`, `useMe`, `useFlags`, `useBilling`, `usePlans`, `useUsage`, `useLiveStatus`, `getBridge()` |
| Hand-off | `HandoffSignIn`, `readHandoff`, `handoffSignIn`: a sign-in page for a command-line tool |
Expand Down
2 changes: 1 addition & 1 deletion bridge-react/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ In your app's settings in Bridge, add your app's address as a browser address an
|---|---|
| Sign-in | `BridgeAuthRoutes` (sign-in, sign-up, verify-email, forgot-password, set-password, invite, workspaces, magic-link, passkey-setup, handoff, callback), `SignInForm`, `SignUpForm`, `VerifyEmail`, `ForgotPassword`, `SetPassword`, `InviteLanding`, `MagicLinkLanding`, `PasskeySetupLanding`, `PasskeyManager`, `WorkspaceChooser`, `SignOutButton`, `ProfileName` |
| Gates | route `rules`, `FeatureFlag`, `useFlag`, `requireFlag`, the paywall: all on flag results, never a role or the plan |
| Billing | `BridgeBillingRoutes`, `PlanPicker`, `BillingPortalButton`, `SubscriptionStatus`, `BillingNotice`, `QuotaBanner`, `CheckoutNotice`, `UpgradeDialog`, `useQuota`, `bridgeFetch` |
| Billing | `BridgeBillingRoutes`, `PlanPicker`, `BillingPortalButton`, `SubscriptionStatus`, `BillingNotice`, `QuotaBanner`, `QuotaGate`, `Entitled`, `CheckoutNotice`, `UpgradeDialog`, `useQuota`, `useEntitlements`, `bridgeFetch` |
| Team | `TeamPanel`, `MemberList`, `InviteDialog`, `InviteList`, `EditMemberDialog`, `ConfirmDialog`, `WorkspaceForm`, `ProfileForm` |
| State | `useSession`, `useUser`, `useWorkspace`, `useWorkspaces`, `useMe`, `useFlags`, `useBilling`, `usePlans`, `useUsage`, `useLiveStatus`, `getBridge()` |
| Hand-off | `HandoffSignIn`, `readHandoff`, `handoffSignIn`: a sign-in page for a command-line tool |
Expand Down
2 changes: 1 addition & 1 deletion bridge-react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
"react-dom": "^18.0.0 || ^19.0.0"
},
"dependencies": {
"@nebulr-group/bridge-auth-core": "1.0.0-alpha.8"
"@nebulr-group/bridge-auth-core": "1.0.0-alpha.11"
},
"devDependencies": {
"@testing-library/react": "^16.3.0",
Expand Down
41 changes: 39 additions & 2 deletions bridge-react/src/components/billing/BillingNotice.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,15 @@
* change waiting. Renders nothing when all is well. A person with the
* `billingManage` flag gets a link to the billing pages; anyone else is told
* to ask the workspace owner. Not dismissible: it goes when the facts change.
*
* A workspace locked for payment shows to every person, from the lock Bridge
* keeps (`useBillingGate`), and at once when your API refuses a write with the
* lock's 402 through `bridgeFetch`. With `mode="hard"` the lock covers the page
* as a blocking screen; every other notice stays a banner.
*/
import { billingNotice, type BillingFacts, type BillingNotice as Notice, type Plan } from '@nebulr-group/bridge-auth-core';
import type { HTMLAttributes, MouseEvent } from 'react';
import { useBillingGate } from '../../react/billing-gate.js';
import { useBilling, useBridgeConfig, useCanManageBilling, usePlans } from '../../react/hooks.js';
import { Link } from '../shared/Link.js';
import { formatDate } from './plan-format.js';
Expand All @@ -17,6 +23,8 @@ type Severity = 'info' | 'warn' | 'critical' | 'locked';
export interface BillingNoticeProps extends HTMLAttributes<HTMLDivElement> {
/** The notice's shape: a full-width bar, a rail with a left edge, or a card. @default 'rail' */
readonly chassis?: Chassis;
/** `hard` covers the page with a blocking screen while the workspace is locked for payment; other notices stay banners. @default 'soft' */
readonly mode?: 'soft' | 'hard';
/** Where the action link goes. @default the plan page for no plan, else the subscription page */
readonly actionHref?: string;
/** Replaces the action link's navigation. */
Expand All @@ -33,6 +41,7 @@ const SEVERITY: Record<Notice['kind'], Severity> = {
};

const OWNER = 'Please contact your workspace owner.';
const BLOCKED: Notice = { kind: 'blocked' };

function daysLeft(days: number): string {
if (days <= 0) return 'The trial ends today.';
Expand Down Expand Up @@ -72,14 +81,16 @@ function copyFor(n: Notice, admin: boolean, facts: BillingFacts | null, plans: r
}
}

export function BillingNotice({ chassis = 'rail', actionHref, onActionClick, className, ...rest }: BillingNoticeProps) {
export function BillingNotice({ chassis = 'rail', mode = 'soft', actionHref, onActionClick, className, ...rest }: BillingNoticeProps) {
const config = useBridgeConfig();
const base = config?.billingBase ?? '/subscription';
const canManage = useCanManageBilling();
const billing = useBilling();
const plans = usePlans();
const gate = useBillingGate();

const notice = billing.value ? billingNotice(billing.value) : null;
// The lock is shown from the gate as well as the billing facts: the gate is read by every person, and a refusal shows it at once.
const notice: Notice | null = gate.locked ? BLOCKED : billing.value ? billingNotice(billing.value) : null;
if (!notice) return null;
const severity = SEVERITY[notice.kind];
const urgent = severity === 'critical' || severity === 'locked';
Expand All @@ -92,6 +103,32 @@ export function BillingNotice({ chassis = 'rail', actionHref, onActionClick, cla
onActionClick(notice);
}

if (mode === 'hard' && notice.kind === 'blocked') {
return (
<div
className={['bridge-billing-lockscreen', className].filter(Boolean).join(' ')}
data-bridge-billing-lockscreen=""
role="alertdialog"
aria-modal="true"
aria-live="assertive"
aria-labelledby="bridge-lock-title"
{...rest}
>
<div className="bbl-panel">
<strong id="bridge-lock-title" className="bbl-title">
{copy.title}
</strong>
<span className="bbl-body">{copy.body}</span>
{copy.cta && canManage && (
<Link className="bbl-cta" href={href} data-bridge-billing-notice-cta="" onClick={handleAction}>
{copy.cta}
</Link>
)}
</div>
</div>
);
}

return (
<div
className={['bridge-billing-notice', className].filter(Boolean).join(' ')}
Expand Down
39 changes: 39 additions & 0 deletions bridge-react/src/components/billing/Entitled.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* `<Entitled to="analytics">`: the children render when the plan has the feature,
* `fallback` when it does not.
*
* ```tsx
* <Entitled to="analytics" fallback={<a href="/subscription">Upgrade for analytics</a>}>
* <AnalyticsPanel />
* </Entitled>
* ```
*
* Until Bridge has answered (`useEntitlements().ready`) it renders neither, only
* the optional `loading` node, so a cold start never flashes the upgrade prompt
* at a paying workspace, nor the paid feature at a free one.
*
* It reads the flag `bridge:billing.entitlement.<to>`, as
* `useEntitlements().can('analytics')` does. To show something for a flag in
* general, with its reason, use `<FeatureFlag flagKey>`.
*/
import type { ReactNode } from 'react';
import { useEntitlements } from '../../react/entitlements.js';

export interface EntitledProps {
/** The plan feature's key, such as `analytics`. */
readonly to: string;
/** Rendered when the plan has `to`. */
readonly children?: ReactNode;
/** Rendered when Bridge has answered and the plan does not have `to`. */
readonly fallback?: ReactNode;
/** Rendered until Bridge has answered. Nothing by default. */
readonly loading?: ReactNode;
}

export function Entitled({ to, children, fallback = null, loading = null }: EntitledProps) {
const entitlements = useEntitlements();
if (!entitlements.ready) return <>{loading}</>;
return <>{entitlements.can(to) ? children : fallback}</>;
}

export default Entitled;
70 changes: 27 additions & 43 deletions bridge-react/src/components/billing/QuotaBanner.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,89 +5,73 @@
* <QuotaBanner metric="projects" label="Projects" />
* ```
*
* Renders nothing below 80% of the limit, or for a metric with no limit. It
* shows numbers only and blocks nothing: whether something is allowed is a
* flag. A person with the `billingManage` flag gets an Upgrade link; anyone
* else is told to contact the workspace owner.
* Renders nothing while the metric has no limit or is below 80% of it. It moves
* by itself: Bridge's quota notices read the numbers again. It shows numbers
* only and blocks nothing: whether something is allowed is a flag. A person with
* the `billingManage` flag gets an Upgrade link; anyone else is told to contact
* the workspace owner. A metered limit shows the overage instead of a warning.
*/
import type { QuotaSnapshot } from '@nebulr-group/bridge-auth-core';
import type { HTMLAttributes, MouseEvent } from 'react';
import { useBridgeConfig, useCanManageBilling, useUsage } from '../../react/hooks.js';
import { useBridgeConfig, useCanManageBilling } from '../../react/hooks.js';
import { useQuota } from '../../react/quota.js';
import { Link } from '../shared/Link.js';
import { quotaFor, type Quota } from './quota.js';
import { quotaBannerCopy, quotaBannerState } from './quota-copy.js';

export interface QuotaBannerProps extends HTMLAttributes<HTMLDivElement> {
/** The metric to watch, such as `projects`. */
readonly metric: string;
/** The metric's name in the copy. @default the metric key */
/** The metric's name in the copy. @default the metric's label from Bridge, else its key */
readonly label?: string;
/** Where Upgrade goes. @default the subscription page */
readonly actionHref?: string;
/** Replaces Upgrade's navigation. */
readonly onActionClick?: (quota: Quota) => void;
}

const OWNER = 'Contact your workspace owner.';

function copyFor(q: Quota, admin: boolean, what: string): { title: string; body: string } {
const used = q.used.toLocaleString();
const limit = q.limit.toLocaleString();
if (q.used > q.limit) {
return admin
? { title: `${what} over cap`, body: `You've used ${used} of ${limit}. Upgrade your plan to add headroom.` }
: { title: `${what} over cap`, body: `Your workspace is over its ${what} cap. ${OWNER}` };
}
if (q.state === 'over') {
return admin
? { title: `${what} limit reached`, body: `You've used all ${limit} on your plan. Upgrade your plan to add more.` }
: { title: `${what} limit reached`, body: `Your workspace has reached its ${what} limit. ${OWNER}` };
}
const left = Math.max(0, q.limit - q.used).toLocaleString();
return admin
? { title: `${what} approaching cap`, body: `You've used ${used} of ${limit} (${left} left).` }
: { title: `${what} approaching cap`, body: `Your workspace is approaching its ${what} cap.` };
readonly onActionClick?: (snapshot: QuotaSnapshot) => void;
}

export function QuotaBanner({ metric, label, actionHref, onActionClick, className, ...rest }: QuotaBannerProps) {
const base = useBridgeConfig()?.billingBase ?? '/subscription';
const canManage = useCanManageBilling();
const usage = useUsage();
const { snapshot } = useQuota(metric);

const quota = quotaFor(usage.value, metric);
if (quota === null || quota.state === 'ok') return null;
const name = label ?? metric;
const percent = Math.min(100, Math.round(quota.ratio * 100));
const state = quotaBannerState(snapshot);
if (state === 'hidden' || snapshot === null) return null;
const critical = state === 'critical' || state === 'reached' || state === 'over';
const name = label ?? snapshot.label ?? metric;
const percent = snapshot.limit > 0 ? Math.min(100, Math.round((snapshot.used / snapshot.limit) * 100)) : 0;
const href = actionHref ?? (base || '/');
const copy = copyFor(quota, canManage, name);
const copy = quotaBannerCopy(snapshot, canManage, name);

function handleAction(event: MouseEvent<HTMLAnchorElement>) {
if (!onActionClick || !quota) return;
if (!onActionClick || snapshot === null) return;
event.preventDefault();
onActionClick(quota);
onActionClick(snapshot);
}

return (
<div
className={['bridge-quota-banner', className].filter(Boolean).join(' ')}
data-bridge-quota-banner=""
data-metric={metric}
data-state={quota.state}
role={quota.state === 'over' ? 'alert' : 'status'}
aria-live={quota.state === 'over' ? 'assertive' : 'polite'}
data-state={state}
data-severity={critical ? 'critical' : 'warn'}
role={critical ? 'alert' : 'status'}
aria-live={critical ? 'assertive' : 'polite'}
aria-label={`${name} quota ${percent}% used`}
{...rest}
>
<div className="bqb-content">
<strong className="bqb-title">{copy.title}</strong>
<span className="bqb-body">{copy.body}</span>
{quota.limit > 0 && (
{snapshot.limit > 0 && (
<div className="bqb-meter" aria-hidden="true">
<div className="bqb-meter-fill" style={{ width: `${percent}%` }} />
</div>
)}
</div>
{canManage && (
{copy.cta && canManage && (
<Link className="bqb-cta" href={href} data-bridge-quota-banner-cta="" onClick={handleAction}>
Upgrade
{copy.cta}
</Link>
)}
</div>
Expand Down
82 changes: 82 additions & 0 deletions bridge-react/src/components/billing/QuotaGate.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/**
* `<QuotaGate metric="tickets">`: the action inside is disabled once the workspace
* is at its plan's hard limit, and an upgrade prompt shows beside it.
*
* ```tsx
* <QuotaGate metric="tickets">
* <button onClick={createTicket}>New ticket</button>
* </QuotaGate>
*
* <QuotaGate metric="tickets" atLimit={(q) => <>{q.used} of {q.limit} used. <a href="/subscription">Upgrade</a></>}>
* …
* </QuotaGate>
* ```
*
* Disabling is a `<fieldset disabled>` around the children, so every button,
* input, select and textarea inside is disabled natively and announced as such,
* with no props to thread through your markup. Links are not form controls: put
* a link's action behind a button.
*
* Never disables on "don't know yet": while the quota is loading, the plan sets
* no limit on the metric, or the limit is metered (it bills the overage instead
* of blocking), the children are enabled. Only a known hard limit with nothing
* left disables them.
*
* Decoration only. Your server refuses the write; this saves the person a click
* that would be refused.
*/
import type { ReactNode } from 'react';
import type { QuotaState } from '../../core/quota.js';
import { useBridgeConfig } from '../../react/hooks.js';
import { useQuota } from '../../react/quota.js';

export interface QuotaGateProps {
/** The metric's key, such as `tickets`. */
readonly metric: string;
/** The action or actions to disable at the limit. */
readonly children: ReactNode;
/** What to show at the limit instead of the default line. Receives the live quota. */
readonly atLimit?: (quota: QuotaState) => ReactNode;
/** Class on the wrapper. */
readonly className?: string;
}

/** Where the gate stands for a metric. */
export type QuotaGateState = 'loading' | 'unlimited' | 'metered' | 'available' | 'at-limit';

/** The gate's decision for a quota. Exported for tests and custom gates. */
export function quotaGateState(quota: QuotaState): QuotaGateState {
if (quota.loading) return 'loading';
if (quota.unlimited) return 'unlimited';
if (quota.snapshot?.policy === 'metered') return 'metered';
const atCap = (quota.remaining !== null && quota.remaining <= 0) || (quota.used !== null && quota.limit !== null && quota.used >= quota.limit);
return atCap ? 'at-limit' : 'available';
}

export function QuotaGate({ metric, children, atLimit, className }: QuotaGateProps) {
const quota = useQuota(metric);
const base = useBridgeConfig()?.billingBase ?? '/subscription';
const state = quotaGateState(quota);
const blocked = state === 'at-limit';

return (
<div className={['bridge-quota-gate', className].filter(Boolean).join(' ')} data-bridge-quota-gate="" data-metric={metric} data-state={state}>
<fieldset disabled={blocked} className="bridge-quota-gate-controls" style={{ display: 'contents' }}>
{children}
</fieldset>
{blocked && (
<div className="bridge-quota-gate-limit" data-bridge-quota-gate-limit="" role="status">
{atLimit ? (
atLimit(quota)
) : (
<>
You've used all {quota.limit?.toLocaleString()} {metric} on your plan. <a href={base || '/'}>Upgrade</a>
</>
)}
</div>
)}
</div>
);
}

export default QuotaGate;
Loading
Loading