@molecule/app-oauth-buttons-angular

Feature · oauth-buttons · App (browser) · v1.2.2 · Apache-2.0

Config-driven OAuth provider button row composing @molecule/app-oauth-logos-angular with layout variants (horizontal / vertical / grid) and brand-themed inline colors

npm install @molecule/app-oauth-buttons-angular

npm · Source on GitHub

How it works

@molecule/app-oauth-buttons-angular is a ready-made oauth-buttons 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, inject } from '@angular/core'
import { useOAuth } from '@molecule/app-angular'
import { OAuthButtons } from '@molecule/app-oauth-buttons-angular'
import { oauthConfig } from './config'

@Component({
  selector: 'app-login-page',
  standalone: true,
  imports: [OAuthButtons],
  template: `
    <div
      mol-oauth-buttons
      [providers]="oauth().providers"
      [onSelect]="oauth().redirect"
      layout="grid"
      [showLabels]="true"
    ></div>
  `,
})
export class LoginPage {
  // A hook function runs in an injection context (a field initializer).
  readonly oauth = useOAuth(oauthConfig)
}

Works with: @molecule/app-angular, @molecule/app-oauth-logos-angular, @molecule/app-ui, @molecule/app-ui-angular

Reference

Config-driven OAuthButtons row — the Angular counterpart of @molecule/app-oauth-buttons-react (the same runtime export names, the same props, and the same rendered DOM for the same input).

Lifts the bespoke OAuth button row re-implemented by every flagship Login / Signup page into a single composable component, building on @molecule/app-oauth-logos-angular for the canonical brand marks.

  • providers accepts the canonical OAuthProviderId[] from useOAuth(config).providers (or any other source) — apps no longer need to map provider strings into bespoke button arrays.
  • onSelect(provider) initiates the OAuth flow. Host apps typically pass redirect from useOAuth(config) or signInWithProvider from their auth bond.
  • layout toggles 'horizontal' | 'vertical' | 'grid' — the grid variant auto-paginates into a 2-column layout above 4 providers.
  • brandButtons opt-in paints each button with its provider's exact brand-spec background (#fff for Google, #24292f for GitHub, etc.) via inline style — those are provider-mandated color tokens ClassMap intentionally does not encode. It is independent of iconMode (logo color). Layout, padding, radius, and chrome all come from the wired ClassMap (cm.oauthButtonGroup, cm.oauthButton, cm.oauthButtonIcon).
  • OAuthDivider is the composable "or continue with" rule — the config-driven OAuthButtons in @molecule/app-auth-ui-angular composes it above this row.

Companion locale bond: @molecule/app-locales-oauth-buttons (79 languages).

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.ts JSDoc, not this file.

Quick Start

import { Component, inject } from '@angular/core'
import { useOAuth } from '@molecule/app-angular'
import { OAuthButtons } from '@molecule/app-oauth-buttons-angular'
import { oauthConfig } from './config'

@Component({
  selector: 'app-login-page',
  standalone: true,
  imports: [OAuthButtons],
  template: `
    <div
      mol-oauth-buttons
      [providers]="oauth().providers"
      [onSelect]="oauth().redirect"
      layout="grid"
      [showLabels]="true"
    ></div>
  `,
})
export class LoginPage {
  // A hook function runs in an injection context (a field initializer).
  readonly oauth = useOAuth(oauthConfig)
}

Type

feature

Installation

npm install @molecule/app-oauth-buttons-angular @angular/common @angular/core @angular/platform-browser @molecule/app-angular @molecule/app-oauth-logos-angular @molecule/app-ui @molecule/app-ui-angular

API

Interfaces

BrandStyle

Inline-style payload for a single brand button (Angular style objects are the same React-camelCase records the UI package serializes).

interface BrandStyle {
  /** Background color (CSS color token). */
  background: string
  /** Foreground / label color (CSS color token). */
  color: string
  /** Optional 1px border color when `background` is white/very light. */
  borderColor?: string
}

OAuthButtonsProps

Props accepted by the OAuthButtons component.

interface OAuthButtonsProps {
  /**
   * Ordered list of provider ids to render.
   *
   * Typically the `string[]` from `useOAuth(config).providers`. Known
   * canonical ids (e.g. `'google'`, `'github'` — see `OAuthProviderId`)
   * get their brand logo + localized label; unknown ids fall through to
   * a synthesized label and a ClassMap-neutral button, so any string is
   * safe to pass.
   */
  providers: string[]
  /**
   * Optional click handler. Called with the provider id when the user
   * activates a button.
   *
   * If omitted, buttons render as plain `<button type="button">` with no
   * default behavior — host apps wire the handler (typically calling
   * `redirect(provider)` from `useOAuth(...)` or an auth bond's inline
   * `signInWithProvider(provider)`).
   *
   * May be sync or async. A fire-and-navigate `redirect` returns `void`;
   * an inline flow (popup / PKCE / an auth bond that settles the session
   * in place) returns a `Promise` that resolves when the handshake
   * completes — in that case `onSuccess(provider)` fires on resolve.
   */
  onSelect?: (provider: string) => void | Promise<unknown>
  /**
   * Called with the provider id when the OAuth handshake completes
   * successfully — but ONLY when `onSelect` returns a `Promise` that
   * resolves (an inline / popup / PKCE flow, e.g. an auth bond's
   * `signInWithProvider` that settles the session in place). The
   * component awaits that promise and invokes `onSuccess` on resolve.
   *
   * A full-page `redirect(provider)` onSelect returns `void` and
   * navigates away, so there is nothing to await and `onSuccess` does
   * NOT fire — that flow's completion is observed on the callback page by
   * `useOAuth(config).onSuccess` instead. A rejected handshake also does
   * not fire it.
   */
  onSuccess?: (provider: string) => void
  /**
   * Layout variant. Defaults to `'horizontal'` (flex-wrap row).
   *
   * - `'horizontal'`: row that wraps when crowded.
   * - `'vertical'`: stacked column (one button per line).
   * - `'grid'`: 2-column grid (recommended for >4 providers).
   */
  layout?: OAuthButtonsLayout
  /** Icon size in pixels. Defaults to 30. */
  iconSize?: number
  /** Logo color mode — `'brand'` (default, official multi-color) or `'mono'`. */
  iconMode?: 'brand' | 'mono'
  /**
   * When true, paint each button with its provider's brand-spec
   * background/foreground colors (Google white, GitHub `#24292f`, etc.)
   * via inline `style`. Defaults to `false` — buttons stay
   * ClassMap-neutral so the row is visually uniform.
   *
   * Independent of `iconMode`: `iconMode` controls the *logo's* color
   * rendering, `brandButtons` controls the *button surface*.
   */
  brandButtons?: boolean
  /**
   * When true, render the localized provider label text next to the
   * logo (e.g. `"Continue with GitHub"`). Defaults to `false` (icon-only
   * pixel-identical row across providers).
   */
  showLabels?: boolean
  /** Extra class composed onto the button-group element. */
  className?: string
}

OAuthDividerProps

Props accepted by the OAuthDivider component — the "or continue with" rule rendered above an OAuth button row.

interface OAuthDividerProps {
  /**
   * i18n key for the divider label. Defaults to `'oauth.orContinueWith'`.
   */
  labelKey?: string
  /**
   * Fallback divider text if the i18n key is missing. Defaults to
   * `'or continue with'`.
   */
  labelDefault?: string
  /** Extra class composed onto the divider wrapper. */
  className?: string
}

Types

OAuthButtonsLayout

Layout variants for the OAuth button row.

type OAuthButtonsLayout = 'horizontal' | 'vertical' | 'grid'

OAuthProviderId

Canonical list of supported providers.

type OAuthProviderId =
  | 'github'
  | 'gitlab'
  | 'google'
  | 'twitter'
  | 'x'
  | 'apple'
  | 'facebook'
  | 'microsoft'
  | 'linkedin'
  | 'discord'

Classes

OAuthButtons

Renders one styled button per OAuth provider.

Composes the canonical brand logos from @molecule/app-oauth-logos-angular and pulls layout / chrome from the wired ClassMap (cm.oauthButtonGroup, cm.oauthButton, cm.oauthButtonIcon). When brandButtons is set, each button also gets its provider's exact brand-spec background via inline style (ClassMap intentionally does not encode provider brand colors).

This is the lower-level primitive — host apps that have an oauthConfig object typically use the config-driven OAuthButtons from @molecule/app-auth-ui-angular, which composes this row plus OAuthDivider.

@Component({
  selector: 'div[mol-oauth-buttons]',
  standalone: true,
  imports: [OAuthProviderLogo],
  inputs: [
    'providers',
    'onSelect',
    'layout',
    'iconSize',
    'iconMode',
    'brandButtons',
    'showLabels',
    'className',
  ],
  host: {
    '[class]': 'classes()',
    role: 'group',
    '[attr.aria-label]': 'groupLabel()',
    '[style]': 'wrapperStyleText()',
    'data-mol-id': 'oauth-buttons',
    '[attr.data-layout]': 'layoutVariant()',
  },
  template: `@for (provider of ordered(); track provider) {
    <button
      type="button"
      (click)="activate(provider)"
      [attr.aria-label]="buttonLabel(provider)"
      [class]="cm().oauthButton"
      [attr.data-mol-id]="'oauth-button-' + provider"
      [attr.data-provider]="provider"
      [style]="buttonStyleText(provider)"
    >
      <span [class]="cm().oauthButtonIcon"
        ><mol-oauth-provider-logo
          [provider]="provider"
          [size]="logoSize()"
          [mode]="logoMode()"
          [ariaLabel]="''"
      /></span>
      @if (showLabels) {
        <span [class]="cm().oauthProviderLabel">{{ providerText(provider) }}</span>
      }
    </button>
  }`,
})
export class OAuthButtons {
  /**
   * Ordered list of provider ids to render (see `OAuthButtonsProps.providers`).
   */
  providers: string[] = []
  /**
   * Optional click handler, called with the provider id when the user
   * activates a button (React's `onSelect` — the component inspects the
   * returned promise, so it is a plain input).
   */
  onSelect?: (provider: string) => void | Promise<unknown>
  /**
   * Called with the provider id when an inline `onSelect` promise
   * resolves (React's `onSuccess`).
   */
  @Output() readonly success = new EventEmitter<string>()
  /** Layout variant (default `'horizontal'`). */
  layout?: OAuthButtonsLayout
  /** Icon size in pixels (default 30). */
  iconSize?: number
  /** Logo color mode — `'brand'` (default) or `'mono'`. */
  iconMode?: 'brand' | 'mono'
  /** Paint buttons with their provider's brand-spec colors. */
  brandButtons?: boolean
  /** Render the localized provider label next to the logo. */
  showLabels?: boolean
  /** Extra class composed onto the button-group element. */
  className?: string

  private readonly renderer = inject(Renderer2)

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  constructor() {
    // Leaves no element in the page while there are no providers (React renders null).
    useHostPresence(() => this.ordered().length > 0)
  }

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The button-group class list (React's
   * `cm.cn(cm.oauthButtonGroup, className)`).
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().oauthButtonGroup, this.className)
  }

  /**
   * The de-duplicated provider list, preserving the caller's order
   * (React's `dedupeProviders(providers)`).
   * @returns The ordered provider ids.
   */
  ordered(): string[] {
    return dedupeProviders(this.providers ?? [])
  }

  /**
   * The layout variant (React's `layout` default `'horizontal'`, applied
   * when the input was never set or was bound `undefined`).
   * @returns The layout.
   */
  layoutVariant(): OAuthButtonsLayout {
    return this.layout ?? 'horizontal'
  }

  /**
   * The logo size (React's `iconSize` default 30).
   * @returns The pixel size.
   */
  logoSize(): number {
    return this.iconSize ?? 30
  }

  /**
   * The logo color mode (React's `iconMode` default `'brand'`).
   * @returns The mode.
   */
  logoMode(): 'brand' | 'mono' {
    return this.iconMode ?? 'brand'
  }

  /**
   * The wrapper's inline style text (React's
   * `style={getLayoutStyle(layout, ordered.length)}`); null when empty, so no
   * `style` attribute renders.
   * @returns The style text or null.
   */
  wrapperStyleText(): string | null {
    return styleText(getLayoutStyle(this.layoutVariant(), this.ordered().length))
  }

  /**
   * One button's inline style text (React's
   * `style={{ ...brandStyle, ...buttonStyle }}`); null when empty.
   * @param provider - The provider the button activates.
   * @returns The style text or null.
   */
  buttonStyleText(provider: string): string | null {
    const brand = this.brandButtons ? getBrandStyle(provider) : {}
    return styleText({ ...brand, ...getButtonLayoutStyle(this.layoutVariant()) })
  }

  /**
   * The localized provider name (React's `t(label.key, label.values,
   * { defaultValue: label.default })`).
   * @param provider - The provider id.
   * @returns The localized name.
   */
  providerText(provider: string): string {
    const label = getProviderLabel(provider)
    return this.i18n.t(label.key, label.values, { defaultValue: label.default })
  }

  /**
   * A button's accessible label (React's
   * `t('oauthButtons.continueWith', { provider }, { defaultValue:
   * 'Continue with {{provider}}' })`).
   * @param provider - The provider id.
   * @returns The label text.
   */
  buttonLabel(provider: string): string {
    return this.i18n.t(
      'oauthButtons.continueWith',
      { provider: this.providerText(provider) },
      { defaultValue: 'Continue with {{provider}}' },
    )
  }

  /**
   * The group's accessible label (React's
   * `t('oauthButtons.groupLabel', undefined, { defaultValue: 'Continue
   * with another account' })`).
   * @returns The label text.
   */
  groupLabel(): string {
    return this.i18n.t('oauthButtons.groupLabel', undefined, {
      defaultValue: 'Continue with another account',
    })
  }

  /**
   * Activate a provider button: start the flow via `onSelect`, and — for an
   * inline handler that resolves the handshake in place (popup/PKCE, e.g. an
   * auth bond's `signInWithProvider`) — fire the `success` output with the
   * provider on completion. A full-page `redirect` onSelect returns `void`, so
   * there is nothing to await and `success` correctly never fires (that flow's
   * completion is observed on the callback page by `useOAuth(config).onSuccess`
   * instead). A rejected handshake also does not fire it.
   * @param provider - The provider id.
   */
  activate(provider: string): void {
    const select = this.onSelect
    if (!select) return
    const result = select(provider)
    if (result instanceof Promise) {
      void result.then(
        () => this.success.emit(provider),
        (_error) => {
          // The handshake failed/aborted — `success` must NOT fire. Surfacing
          // the error is the initiating `onSelect` handler's responsibility
          // (e.g. `useOAuth`'s `onError`); this presentational row only reports
          // success. Swallowing here is the documented, correct noop.
        },
      )
    }
  }
}

OAuthDivider

Renders a horizontal rule with centered label text — the "or continue with" divider shown between a login/signup form and the OAuth button row.

Split out as its own component so the config-driven OAuthButtons in @molecule/app-auth-ui-angular can compose it above OAuthButtons (the row) without re-implementing the markup.

@Component({
  selector: 'div[mol-oauth-divider]',
  standalone: true,
  inputs: ['labelKey', 'labelDefault', 'className'],
  host: {
    '[class]': 'classes()',
  },
  template: `<span [class]="lineClasses()"></span><span>{{ labelText() }}</span
    ><span [class]="lineClasses()"></span>`,
})
export class OAuthDivider {
  /** i18n key for the divider label (default `'oauth.orContinueWith'`). */
  labelKey?: string
  /** Fallback divider text if the i18n key is missing. */
  labelDefault?: string
  /** Extra class composed onto the divider wrapper. */
  className?: string

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The divider wrapper's class list (React's `cm.cn(cm.oauthDivider,
   * cm.flex({ align: 'center', gap: 4 }), className)`).
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(
      this.cm().oauthDivider,
      this.cm().flex({ align: 'center', gap: 4 }),
      this.className,
    )
  }

  /**
   * The rule spans' class list (React's `cm.cn(cm.flex1, cm.separator())`).
   * @returns The class string.
   */
  lineClasses(): string {
    return this.cm().cn(this.cm().flex1, this.cm().separator())
  }

  /**
   * The divider text, translated for the active locale (React's
   * `t(labelKey, {}, { defaultValue: labelDefault })`).
   * @returns The text.
   */
  labelText(): string {
    return this.i18n.t(
      this.labelKey ?? 'oauth.orContinueWith',
      {},
      {
        defaultValue: this.labelDefault ?? 'or continue with',
      },
    )
  }
}

Functions

getBrandStyle(provider)

Returns the inline-style payload for a given provider id, in this package's inline-style format (React-camelCase keys; numbers carry no unit and are written to the DOM with React's px rule).

Unknown providers receive an empty object so the wired ClassMap's default surface color governs — matching the icon-only fallback behavior of OAuthProviderLogo's empty fallback.

function getBrandStyle(provider: string): Record<string, string | number>
  • provider — Canonical provider id (e.g. 'google').

Returns: Inline-style object for the button element.

getProviderLabel(provider)

Returns the i18n entry (key + English default) for a given provider id.

Falls back to the bond's one literal fallback key for unknown ids so unrecognized providers still render with a sensible English label rather than a raw key string. The provider id travels as a {{provider}} interpolation value, never inside the key.

function getProviderLabel(provider: string): {
  key: string
  default: string
  values?: Record<string, string>
}
  • provider — Canonical provider id (e.g. 'google').

Returns: Translation key, English default and optional interpolation values.

dedupeProviders(providers)

De-duplicates a provider list while preserving the caller's order.

Mirrors how host apps typically pass providers derived from useOAuth(config).providers plus per-page overrides — duplicates can sneak in via merge-and-pass patterns.

function dedupeProviders<T extends string>(providers: readonly T[]): T[]
  • providers — Raw list (may contain duplicates).

Returns: Ordered list with duplicates removed.

getLayoutStyle(layout, providerCount)

Returns the inline-style overlay applied on top of cm.oauthButtonGroup for a given layout variant, in this package's inline-style format (React-camelCase keys, serialized the way React writes them).

function getLayoutStyle(
  layout: OAuthButtonsLayout,
  providerCount: number,
): Record<string, string | number>
  • layout — Selected layout variant.
  • providerCount — Number of buttons rendered (drives grid columns).

Returns: Inline-style object for the wrapper element.

getButtonLayoutStyle(layout)

Returns the inline-style overlay for an individual button in a given layout. In 'vertical' mode each button stretches to fill the column.

function getButtonLayoutStyle(layout: OAuthButtonsLayout): Record<string, string | number>
  • layout — Selected layout variant.

Returns: Inline-style object for the button element.

Constants

BRAND_STYLES

Brand-spec colors for each supported OAuth provider.

Sourced from each provider's official developer brand guidelines. When a host app wants to override these (dark-mode tweaks, brand exceptions), pass iconMode="mono" and let the wired ClassMap paint everything via cm.oauthButton.

const BRAND_STYLES: Readonly<Record<OAuthProviderId, BrandStyle>>

PROVIDER_LABELS

Canonical i18n key + English default for each supported provider.

Used by the OAuthButtons component to render the localized provider name (e.g. "Continue with {{provider}}"). The key matches the companion locale bond @molecule/app-locales-oauth-buttons.

const PROVIDER_LABELS: Readonly<Record<OAuthProviderId, { key: string; default: string }>>

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.12.0 || ^4.0.0
  • @molecule/app-oauth-logos-angular ^1.0.0
  • @molecule/app-ui ^1.0.1
  • @molecule/app-ui-angular ^1.1.0

Runtime Dependencies

  • @angular/common
  • @angular/core
  • @angular/platform-browser
  • @molecule/app-angular
  • @molecule/app-oauth-logos-angular
  • @molecule/app-ui
  • @molecule/app-ui-angular

Rendering-only: this package draws the buttons; the OAuth handshake itself — authorize redirect, and the callback/code-to-session exchange on return — belongs to useOAuth(config) (which needs the @molecule/app-angular Auth provider) or your auth bond's signInWithProvider. onSuccess (the success output) fires only for an inline onSelect that returns a Promise resolving on handshake completion (popup / PKCE); a full-page redirect onSelect returns void, so success does not fire and completion is observed by useOAuth(config).onSuccess on the callback page instead. Requires a wired ClassMap bond and a Molecule i18n provider — getClassMap() and useTranslation() both throw before wiring. React renders null when the provider list is empty; this component detaches its host from the DOM in that state, so it contributes no markup at all.

Translations

Translation strings are provided by @molecule/app-locales-oauth-buttons.