- Accordion
- Alert
- Alert Dialog
- Aspect Ratio
- Attachment
- Autocomplete
- Avatar
- Badge
- Breadcrumb
- Bubble
- Button
- Button Group
- Calendar
- Card
- Carousel
- Checkbox
- Collapsible
- Combobox
- Command
- Context Menu
- Data Table
- Date Picker
- Dialog
- Drawer
- Dropdown Menu
- Empty
- Field
- Hover Card
- Input Group
- Input OTP
- Input
- Item
- Kbd
- Label
- Marker
- Menubar
- Message
- Native Select
- Navigation Menu
- Pagination
- Popover
- Progress
- Radio Group
- Resizable
- Scroll Area
- Select
- Separator
- Sheet
- Sidebar
- Skeleton
- Slider
- Sonner (Toast)
- Spinner
- Switch
- Table
- Tabs
- Textarea
- Toggle
- Toggle Group
- Tooltip
Message
Displays a message in a conversation, with optional avatar, header, footer, and alignment.
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { HlmAvatarImports } from '@spartan-ng/helm/avatar';
import { HlmBubbleImports } from '@spartan-ng/helm/bubble';
import { HlmMarkerImports } from '@spartan-ng/helm/marker';
import { HlmMessageImports } from '@spartan-ng/helm/message';
@Component({
selector: 'spartan-message-preview',
imports: [HlmMessageImports, HlmBubbleImports, HlmAvatarImports, HlmMarkerImports],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
class: 'flex w-full max-w-sm flex-col gap-6 py-12',
},
template: `
<div hlmMessage align="end">
<div hlmMessageAvatar>
<hlm-avatar>
<img hlmAvatarImage src="/assets/avatar.png" alt="@me" class="grayscale" />
<span hlmAvatarFallback>ME</span>
</hlm-avatar>
</div>
<div hlmMessageContent>
<div hlmBubble>
<div hlmBubbleContent>Deploying to prod real quick.</div>
</div>
</div>
</div>
<div hlmMessage>
<div hlmMessageAvatar>
<hlm-avatar>
<img hlmAvatarImage src="https://github.com/spartan-ng.png" alt="@spartan-ng" class="grayscale" />
<span hlmAvatarFallback>R</span>
</hlm-avatar>
</div>
<div hlmMessageContent>
<div hlmBubble variant="muted">
<div hlmBubbleContent>It's 4:55 PM. On a Friday.</div>
</div>
</div>
</div>
<div hlmMessage align="end">
<div hlmMessageAvatar>
<hlm-avatar>
<img hlmAvatarImage src="/assets/avatar.png" alt="@me" class="grayscale" />
<span hlmAvatarFallback>ME</span>
</hlm-avatar>
</div>
<div hlmMessageContent>
<div hlmBubble>
<div hlmBubbleContent>It's a one-line change.</div>
</div>
<div hlmMessageFooter>Delivered</div>
</div>
</div>
<div hlmMessage>
<div hlmMessageAvatar>
<hlm-avatar>
<img hlmAvatarImage src="https://github.com/spartan-ng.png" alt="@spartan-ng" class="grayscale" />
<span hlmAvatarFallback>R</span>
</hlm-avatar>
</div>
<div hlmMessageContent>
<div hlmBubbleGroup>
<div hlmBubble variant="muted">
<div hlmBubbleContent>It's always a one-line change 😭.</div>
</div>
<div hlmBubble variant="muted">
<div hlmBubbleContent>Alright, let me take a look.</div>
<div hlmBubbleReactions aria-label="Reactions: thumbs up">
<span>👍</span>
</div>
</div>
</div>
</div>
</div>
<div hlmMarker role="status">
<span hlmMarkerContent class="shimmer">
<span class="font-medium">Spartan</span>
is typing...
</span>
</div>
`,
})
export class MessagePreview {}Installation
ng g @spartan-ng/cli:ui messagenx g @spartan-ng/cli:ui messageimport { DestroyRef, ElementRef, HostAttributeToken, Injector, PLATFORM_ID, effect, inject, makeEnvironmentProviders, runInInjectionContext, type EnvironmentProviders } from '@angular/core';
import { OVERLAY_DEFAULT_CONFIG } from '@angular/cdk/overlay';
import { clsx, type ClassValue } from 'clsx';
import { isPlatformBrowser } from '@angular/common';
import { provideSpartanHlm } from '@spartan-ng/helm/utils';
import { twMerge } from 'tailwind-merge';
export function hlm(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
// Global map to track class managers per element
const elementClassManagers = new WeakMap<HTMLElement, ElementClassManager>();
// Global mutation observer for all elements
let globalObserver: MutationObserver | null = null;
const observedElements = new Set<HTMLElement>();
interface ElementClassManager {
element: HTMLElement;
sources: Map<number, { classes: Set<string>; order: number }>;
baseClasses: Set<string>;
isUpdating: boolean;
nextOrder: number;
hasInitialized: boolean;
restoreRafId: number | null;
/** Transitions are suppressed until the first effect writes correct classes */
transitionsSuppressed: boolean;
/** Original inline transition value to restore after suppression (empty string = none was set) */
previousTransition: string;
/** Original inline transition priority to preserve !important when restoring */
previousTransitionPriority: string;
}
let sourceCounter = 0;
/**
* This function dynamically adds and removes classes for a given element without requiring
* the a class binding (e.g. `[class]="..."`) which may interfere with other class bindings.
*
* 1. This will merge the existing classes on the element with the new classes.
* 2. It will also remove any classes that were previously added by this function but are no longer present in the new classes.
* 3. Multiple calls to this function on the same element will be merged efficiently.
*/
export function classes(computed: () => ClassValue[] | string, options: ClassesOptions = {}) {
runInInjectionContext(options.injector ?? inject(Injector), () => {
const elementRef = options.elementRef ?? inject(ElementRef);
const platformId = inject(PLATFORM_ID);
const destroyRef = inject(DestroyRef);
const baseClasses = inject(new HostAttributeToken('class'), { optional: true });
const element = elementRef.nativeElement;
// Create unique identifier for this source
const sourceId = sourceCounter++;
// Get or create the class manager for this element
let manager = elementClassManagers.get(element);
if (!manager) {
// Initialize base classes from variation (host attribute 'class')
const initialBaseClasses = new Set<string>();
if (baseClasses) {
toClassList(baseClasses).forEach((cls) => initialBaseClasses.add(cls));
}
manager = {
element,
sources: new Map(),
baseClasses: initialBaseClasses,
isUpdating: false,
nextOrder: 0,
hasInitialized: false,
restoreRafId: null,
transitionsSuppressed: false,
previousTransition: '',
previousTransitionPriority: '',
};
elementClassManagers.set(element, manager);
// Setup global observer if needed and register this element
setupGlobalObserver(platformId);
observedElements.add(element);
// Suppress transitions until the first effect writes correct classes and
// the browser has painted them. This prevents CSS transition animations
// during hydration when classes change from SSR state to client state.
if (isPlatformBrowser(platformId)) {
manager.previousTransition = element.style.getPropertyValue('transition');
manager.previousTransitionPriority = element.style.getPropertyPriority('transition');
element.style.setProperty('transition', 'none', 'important');
manager.transitionsSuppressed = true;
}
}
// Assign order once at registration time
const sourceOrder = manager.nextOrder++;
function updateClasses(): void {
// Get the new classes from the computed function
const newClasses = toClassList(computed());
// Update this source's classes, keeping the original order
manager!.sources.set(sourceId, {
classes: new Set(newClasses),
order: sourceOrder,
});
// Update the element
updateElement(manager!);
// Re-enable transitions after the first effect writes correct classes.
// Deferred to next animation frame so the browser paints the class change
// with transitions disabled first, then re-enables them.
if (manager!.transitionsSuppressed) {
manager!.transitionsSuppressed = false;
manager!.restoreRafId = requestAnimationFrame(() => {
manager!.restoreRafId = null;
restoreTransitionSuppression(manager!);
});
}
}
// Register cleanup with DestroyRef
destroyRef.onDestroy(() => {
if (manager!.restoreRafId !== null) {
cancelAnimationFrame(manager!.restoreRafId);
manager!.restoreRafId = null;
}
if (manager!.transitionsSuppressed) {
manager!.transitionsSuppressed = false;
restoreTransitionSuppression(manager!);
}
// Remove this source from the manager
manager!.sources.delete(sourceId);
// If no more sources, clean up the manager
if (manager!.sources.size === 0) {
cleanupManager(element);
} else {
// Update element without this source's classes
updateElement(manager!);
}
});
/**
* We need this effect to track changes to the computed classes. Ideally, we would use
* afterRenderEffect here, but that doesn't run in SSR contexts, so we use a standard
* effect which works in both browser and SSR.
*/
effect(updateClasses);
});
}
function restoreTransitionSuppression(manager: ElementClassManager): void {
const prev = manager.previousTransition;
if (prev) {
manager.element.style.setProperty('transition', prev, manager.previousTransitionPriority || undefined);
} else {
manager.element.style.removeProperty('transition');
}
}
// eslint-disable-next-line @typescript-eslint/no-wrapper-object-types
function setupGlobalObserver(platformId: Object): void {
if (isPlatformBrowser(platformId) && !globalObserver) {
// Create single global observer that watches the entire document
globalObserver = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
const element = mutation.target as HTMLElement;
const manager = elementClassManagers.get(element);
// Only process elements we're managing
if (manager && observedElements.has(element)) {
if (manager.isUpdating) continue; // Ignore changes we're making
// Update base classes to include any externally added classes
const currentClasses = toClassList(element.className);
const allSourceClasses = new Set<string>();
// Collect all classes from all sources
for (const source of manager.sources.values()) {
for (const className of source.classes) {
allSourceClasses.add(className);
}
}
// Any classes not from sources become new base classes
manager.baseClasses.clear();
for (const className of currentClasses) {
if (!allSourceClasses.has(className)) {
manager.baseClasses.add(className);
}
}
updateElement(manager);
}
}
}
});
// Start observing the entire document for class attribute changes
globalObserver.observe(document, {
attributes: true,
attributeFilter: ['class'],
subtree: true, // Watch all descendants
});
}
}
function updateElement(manager: ElementClassManager): void {
if (manager.isUpdating) return; // Prevent recursive updates
manager.isUpdating = true;
// Handle initialization: capture base classes after first source registration
if (!manager.hasInitialized && manager.sources.size > 0) {
// Get current classes on element (may include SSR classes)
const currentClasses = toClassList(manager.element.className);
// Get all classes that will be applied by sources
const allSourceClasses = new Set<string>();
for (const source of manager.sources.values()) {
source.classes.forEach((className) => allSourceClasses.add(className));
}
// Only consider classes as "base" if they're not produced by any source
// This prevents SSR-rendered classes from being preserved as base classes
currentClasses.forEach((className) => {
if (!allSourceClasses.has(className)) {
manager.baseClasses.add(className);
}
});
manager.hasInitialized = true;
}
// Get classes from all sources, sorted by registration order (later takes precedence)
const sortedSources = Array.from(manager.sources.entries()).sort(([, a], [, b]) => a.order - b.order);
const allSourceClasses: string[] = [];
for (const [, source] of sortedSources) {
allSourceClasses.push(...source.classes);
}
// Combine base classes with all source classes, ensuring base classes take precedence
const classesToApply =
allSourceClasses.length > 0 || manager.baseClasses.size > 0
? hlm([...allSourceClasses, ...manager.baseClasses])
: '';
// Apply the classes to the element
if (manager.element.className !== classesToApply) {
manager.element.className = classesToApply;
}
manager.isUpdating = false;
}
function cleanupManager(element: HTMLElement): void {
// Remove from global tracking
observedElements.delete(element);
elementClassManagers.delete(element);
// If no more elements being tracked, cleanup global observer
if (observedElements.size === 0 && globalObserver) {
globalObserver.disconnect();
globalObserver = null;
}
}
interface ClassesOptions {
elementRef?: ElementRef<HTMLElement>;
injector?: Injector;
}
// Cache for parsed class lists to avoid repeated string operations
const classListCache = new Map<string, string[]>();
function toClassList(className: string | ClassValue[]): string[] {
// For simple string inputs, use cache to avoid repeated parsing
if (typeof className === 'string' && classListCache.has(className)) {
return classListCache.get(className)!;
}
const result = clsx(className)
.split(' ')
.filter((c) => c.length > 0);
// Cache string results, but limit cache size to prevent memory growth
if (typeof className === 'string' && classListCache.size < 1000) {
classListCache.set(className, result);
}
return result;
}
/**
* Provides default configuration for Spartan Helm components.
*
* This utility configures the Angular CDK overlay to disable the `usePopover`
* behavior introduced in Angular 21, which causes CDK overlay-based components
* (sheets, dialogs, tooltips, etc.) to render above `position: fixed` elements
* like `<hlm-toaster>`.
*
* @returns {EnvironmentProviders} Environment providers to be added to the application config.
*
* @example
* ```ts
* // app.config.ts
*
*
* export const appConfig: ApplicationConfig = {
* providers: [
* provideSpartanHlm(),
* // ... other providers
* ],
* };
* ```
*/
export function provideSpartanHlm(): EnvironmentProviders {
return makeEnvironmentProviders([
{
provide: OVERLAY_DEFAULT_CONFIG,
useValue: { usePopover: false },
},
]);
}import { Directive, input } from '@angular/core';
import { classes } from '@spartan-ng/helm/utils';
@Directive({
selector: '[hlmMessageAvatar],hlm-message-avatar',
host: { 'data-slot': 'message-avatar' },
})
export class HlmMessageAvatar {
constructor() {
classes(
() =>
'bg-muted min-w-8 rounded-full flex w-fit shrink-0 items-center justify-center self-end overflow-hidden group-has-data-[slot=message-footer]/message:-translate-y-8',
);
}
}
@Directive({
selector: '[hlmMessageContent],hlm-message-content',
host: { 'data-slot': 'message-content' },
})
export class HlmMessageContent {
constructor() {
classes(
() =>
'gap-2.5 flex w-full min-w-0 flex-col wrap-break-word group-data-[align=end]/message:*:data-slot:self-end',
);
}
}
@Directive({
selector: '[hlmMessageFooter],hlm-message-footer',
host: { 'data-slot': 'message-footer' },
})
export class HlmMessageFooter {
constructor() {
classes(
() =>
'text-muted-foreground px-3 text-xs font-medium flex max-w-full min-w-0 items-center group-has-data-[variant=ghost]/message:px-0 group-data-[align=end]/message:justify-end',
);
}
}
@Directive({
selector: '[hlmMessageGroup],hlm-message-group',
host: { 'data-slot': 'message-group' },
})
export class HlmMessageGroup {
constructor() {
classes(() => 'gap-2 flex min-w-0 flex-col');
}
}
@Directive({
selector: '[hlmMessageHeader],hlm-message-header',
host: { 'data-slot': 'message-header' },
})
export class HlmMessageHeader {
constructor() {
classes(
() => 'text-muted-foreground px-3 text-xs font-medium flex max-w-full min-w-0 items-center group-has-data-[variant=ghost]/message:px-0',
);
}
}
export type MessageAlign = 'start' | 'end';
@Directive({
selector: '[hlmMessage],hlm-message',
host: {
'data-slot': 'message',
'[attr.data-align]': 'align()',
// Prevent the legacy HTML `align` attribute from forcing text-align.
'[attr.align]': 'null',
},
})
export class HlmMessage {
public readonly align = input<MessageAlign>('start');
constructor() {
classes(() => 'gap-2 text-sm group/message relative flex w-full min-w-0 data-[align=end]:flex-row-reverse');
}
}
export const HlmMessageImports = [
HlmMessage,
HlmMessageAvatar,
HlmMessageContent,
HlmMessageFooter,
HlmMessageGroup,
HlmMessageHeader,
] as const;import { Directive, input } from '@angular/core';
import { classes } from '@spartan-ng/helm/utils';
@Directive({
selector: '[hlmMessageAvatar],hlm-message-avatar',
host: { 'data-slot': 'message-avatar' },
})
export class HlmMessageAvatar {
constructor() {
classes(
() =>
'bg-muted min-w-9 rounded-full flex w-fit shrink-0 items-center justify-center self-end overflow-hidden group-has-data-[slot=message-footer]/message:-translate-y-8',
);
}
}
@Directive({
selector: '[hlmMessageContent],hlm-message-content',
host: { 'data-slot': 'message-content' },
})
export class HlmMessageContent {
constructor() {
classes(
() =>
'gap-3 flex w-full min-w-0 flex-col wrap-break-word group-data-[align=end]/message:*:data-slot:self-end',
);
}
}
@Directive({
selector: '[hlmMessageFooter],hlm-message-footer',
host: { 'data-slot': 'message-footer' },
})
export class HlmMessageFooter {
constructor() {
classes(
() =>
'text-muted-foreground px-3.5 text-xs font-medium flex max-w-full min-w-0 items-center group-has-data-[variant=ghost]/message:px-0 group-data-[align=end]/message:justify-end',
);
}
}
@Directive({
selector: '[hlmMessageGroup],hlm-message-group',
host: { 'data-slot': 'message-group' },
})
export class HlmMessageGroup {
constructor() {
classes(() => 'gap-2.5 flex min-w-0 flex-col');
}
}
@Directive({
selector: '[hlmMessageHeader],hlm-message-header',
host: { 'data-slot': 'message-header' },
})
export class HlmMessageHeader {
constructor() {
classes(
() => 'text-muted-foreground px-3.5 text-xs font-medium flex max-w-full min-w-0 items-center group-has-data-[variant=ghost]/message:px-0',
);
}
}
export type MessageAlign = 'start' | 'end';
@Directive({
selector: '[hlmMessage],hlm-message',
host: {
'data-slot': 'message',
'[attr.data-align]': 'align()',
// Prevent the legacy HTML `align` attribute from forcing text-align.
'[attr.align]': 'null',
},
})
export class HlmMessage {
public readonly align = input<MessageAlign>('start');
constructor() {
classes(() => 'gap-2.5 text-sm group/message relative flex w-full min-w-0 data-[align=end]:flex-row-reverse');
}
}
export const HlmMessageImports = [
HlmMessage,
HlmMessageAvatar,
HlmMessageContent,
HlmMessageFooter,
HlmMessageGroup,
HlmMessageHeader,
] as const;import { Directive, input } from '@angular/core';
import { classes } from '@spartan-ng/helm/utils';
@Directive({
selector: '[hlmMessageAvatar],hlm-message-avatar',
host: { 'data-slot': 'message-avatar' },
})
export class HlmMessageAvatar {
constructor() {
classes(
() =>
'bg-muted min-w-8 rounded-none flex w-fit shrink-0 items-center justify-center self-end overflow-hidden group-has-data-[slot=message-footer]/message:-translate-y-8',
);
}
}
@Directive({
selector: '[hlmMessageContent],hlm-message-content',
host: { 'data-slot': 'message-content' },
})
export class HlmMessageContent {
constructor() {
classes(
() =>
'gap-2.5 flex w-full min-w-0 flex-col wrap-break-word group-data-[align=end]/message:*:data-slot:self-end',
);
}
}
@Directive({
selector: '[hlmMessageFooter],hlm-message-footer',
host: { 'data-slot': 'message-footer' },
})
export class HlmMessageFooter {
constructor() {
classes(
() =>
'text-muted-foreground px-3 text-xs font-medium flex max-w-full min-w-0 items-center group-has-data-[variant=ghost]/message:px-0 group-data-[align=end]/message:justify-end',
);
}
}
@Directive({
selector: '[hlmMessageGroup],hlm-message-group',
host: { 'data-slot': 'message-group' },
})
export class HlmMessageGroup {
constructor() {
classes(() => 'gap-2 flex min-w-0 flex-col');
}
}
@Directive({
selector: '[hlmMessageHeader],hlm-message-header',
host: { 'data-slot': 'message-header' },
})
export class HlmMessageHeader {
constructor() {
classes(
() => 'text-muted-foreground px-3 text-xs font-medium flex max-w-full min-w-0 items-center group-has-data-[variant=ghost]/message:px-0',
);
}
}
export type MessageAlign = 'start' | 'end';
@Directive({
selector: '[hlmMessage],hlm-message',
host: {
'data-slot': 'message',
'[attr.data-align]': 'align()',
// Prevent the legacy HTML `align` attribute from forcing text-align.
'[attr.align]': 'null',
},
})
export class HlmMessage {
public readonly align = input<MessageAlign>('start');
constructor() {
classes(() => 'gap-2 text-xs group/message relative flex w-full min-w-0 data-[align=end]:flex-row-reverse');
}
}
export const HlmMessageImports = [
HlmMessage,
HlmMessageAvatar,
HlmMessageContent,
HlmMessageFooter,
HlmMessageGroup,
HlmMessageHeader,
] as const;import { Directive, input } from '@angular/core';
import { classes } from '@spartan-ng/helm/utils';
@Directive({
selector: '[hlmMessageAvatar],hlm-message-avatar',
host: { 'data-slot': 'message-avatar' },
})
export class HlmMessageAvatar {
constructor() {
classes(
() =>
'bg-muted min-w-9 rounded-full flex w-fit shrink-0 items-center justify-center self-end overflow-hidden group-has-data-[slot=message-footer]/message:-translate-y-8',
);
}
}
@Directive({
selector: '[hlmMessageContent],hlm-message-content',
host: { 'data-slot': 'message-content' },
})
export class HlmMessageContent {
constructor() {
classes(
() =>
'gap-3 flex w-full min-w-0 flex-col wrap-break-word group-data-[align=end]/message:*:data-slot:self-end',
);
}
}
@Directive({
selector: '[hlmMessageFooter],hlm-message-footer',
host: { 'data-slot': 'message-footer' },
})
export class HlmMessageFooter {
constructor() {
classes(
() =>
'text-muted-foreground px-3.5 text-xs font-medium flex max-w-full min-w-0 items-center group-has-data-[variant=ghost]/message:px-0 group-data-[align=end]/message:justify-end',
);
}
}
@Directive({
selector: '[hlmMessageGroup],hlm-message-group',
host: { 'data-slot': 'message-group' },
})
export class HlmMessageGroup {
constructor() {
classes(() => 'gap-2.5 flex min-w-0 flex-col');
}
}
@Directive({
selector: '[hlmMessageHeader],hlm-message-header',
host: { 'data-slot': 'message-header' },
})
export class HlmMessageHeader {
constructor() {
classes(
() => 'text-muted-foreground px-3.5 text-xs font-medium flex max-w-full min-w-0 items-center group-has-data-[variant=ghost]/message:px-0',
);
}
}
export type MessageAlign = 'start' | 'end';
@Directive({
selector: '[hlmMessage],hlm-message',
host: {
'data-slot': 'message',
'[attr.data-align]': 'align()',
// Prevent the legacy HTML `align` attribute from forcing text-align.
'[attr.align]': 'null',
},
})
export class HlmMessage {
public readonly align = input<MessageAlign>('start');
constructor() {
classes(() => 'gap-2.5 text-sm group/message relative flex w-full min-w-0 data-[align=end]:flex-row-reverse');
}
}
export const HlmMessageImports = [
HlmMessage,
HlmMessageAvatar,
HlmMessageContent,
HlmMessageFooter,
HlmMessageGroup,
HlmMessageHeader,
] as const;import { Directive, input } from '@angular/core';
import { classes } from '@spartan-ng/helm/utils';
@Directive({
selector: '[hlmMessageAvatar],hlm-message-avatar',
host: { 'data-slot': 'message-avatar' },
})
export class HlmMessageAvatar {
constructor() {
classes(
() =>
'bg-muted min-w-7 rounded-full flex w-fit shrink-0 items-center justify-center self-end overflow-hidden group-has-data-[slot=message-footer]/message:-translate-y-8',
);
}
}
@Directive({
selector: '[hlmMessageContent],hlm-message-content',
host: { 'data-slot': 'message-content' },
})
export class HlmMessageContent {
constructor() {
classes(
() =>
'gap-2 flex w-full min-w-0 flex-col wrap-break-word group-data-[align=end]/message:*:data-slot:self-end',
);
}
}
@Directive({
selector: '[hlmMessageFooter],hlm-message-footer',
host: { 'data-slot': 'message-footer' },
})
export class HlmMessageFooter {
constructor() {
classes(
() =>
'text-muted-foreground px-2.5 text-[0.625rem] font-medium flex max-w-full min-w-0 items-center group-has-data-[variant=ghost]/message:px-0 group-data-[align=end]/message:justify-end',
);
}
}
@Directive({
selector: '[hlmMessageGroup],hlm-message-group',
host: { 'data-slot': 'message-group' },
})
export class HlmMessageGroup {
constructor() {
classes(() => 'gap-1.5 flex min-w-0 flex-col');
}
}
@Directive({
selector: '[hlmMessageHeader],hlm-message-header',
host: { 'data-slot': 'message-header' },
})
export class HlmMessageHeader {
constructor() {
classes(
() => 'text-muted-foreground px-2.5 text-[0.625rem] font-medium flex max-w-full min-w-0 items-center group-has-data-[variant=ghost]/message:px-0',
);
}
}
export type MessageAlign = 'start' | 'end';
@Directive({
selector: '[hlmMessage],hlm-message',
host: {
'data-slot': 'message',
'[attr.data-align]': 'align()',
// Prevent the legacy HTML `align` attribute from forcing text-align.
'[attr.align]': 'null',
},
})
export class HlmMessage {
public readonly align = input<MessageAlign>('start');
constructor() {
classes(() => 'gap-1.5 text-xs/relaxed group/message relative flex w-full min-w-0 data-[align=end]:flex-row-reverse');
}
}
export const HlmMessageImports = [
HlmMessage,
HlmMessageAvatar,
HlmMessageContent,
HlmMessageFooter,
HlmMessageGroup,
HlmMessageHeader,
] as const;import { Directive, input } from '@angular/core';
import { classes } from '@spartan-ng/helm/utils';
@Directive({
selector: '[hlmMessageAvatar],hlm-message-avatar',
host: { 'data-slot': 'message-avatar' },
})
export class HlmMessageAvatar {
constructor() {
classes(
() =>
'bg-muted min-w-9 rounded-full flex w-fit shrink-0 items-center justify-center self-end overflow-hidden group-has-data-[slot=message-footer]/message:-translate-y-8',
);
}
}
@Directive({
selector: '[hlmMessageContent],hlm-message-content',
host: { 'data-slot': 'message-content' },
})
export class HlmMessageContent {
constructor() {
classes(
() =>
'gap-3 flex w-full min-w-0 flex-col wrap-break-word group-data-[align=end]/message:*:data-slot:self-end',
);
}
}
@Directive({
selector: '[hlmMessageFooter],hlm-message-footer',
host: { 'data-slot': 'message-footer' },
})
export class HlmMessageFooter {
constructor() {
classes(
() =>
'text-muted-foreground px-4 text-xs font-medium flex max-w-full min-w-0 items-center group-has-data-[variant=ghost]/message:px-0 group-data-[align=end]/message:justify-end',
);
}
}
@Directive({
selector: '[hlmMessageGroup],hlm-message-group',
host: { 'data-slot': 'message-group' },
})
export class HlmMessageGroup {
constructor() {
classes(() => 'gap-3 flex min-w-0 flex-col');
}
}
@Directive({
selector: '[hlmMessageHeader],hlm-message-header',
host: { 'data-slot': 'message-header' },
})
export class HlmMessageHeader {
constructor() {
classes(
() => 'text-muted-foreground px-4 text-xs font-medium flex max-w-full min-w-0 items-center group-has-data-[variant=ghost]/message:px-0',
);
}
}
export type MessageAlign = 'start' | 'end';
@Directive({
selector: '[hlmMessage],hlm-message',
host: {
'data-slot': 'message',
'[attr.data-align]': 'align()',
// Prevent the legacy HTML `align` attribute from forcing text-align.
'[attr.align]': 'null',
},
})
export class HlmMessage {
public readonly align = input<MessageAlign>('start');
constructor() {
classes(() => 'gap-3 text-sm group/message relative flex w-full min-w-0 data-[align=end]:flex-row-reverse');
}
}
export const HlmMessageImports = [
HlmMessage,
HlmMessageAvatar,
HlmMessageContent,
HlmMessageFooter,
HlmMessageGroup,
HlmMessageHeader,
] as const;Usage
import { HlmAvatarImports } from '@spartan-ng/helm/avatar';
import { HlmBubbleImports } from '@spartan-ng/helm/bubble';
import { HlmMarkerImports } from '@spartan-ng/helm/marker';
import { HlmMessageImports } from '@spartan-ng/helm/message';<div hlmMessage>
<div hlmMessageAvatar>
<hlm-avatar>
<img hlmAvatarImage src="/assets/avatar.png" alt="@spartan" />
<span hlmAvatarFallback>SP</span>
</hlm-avatar>
</div>
<div hlmMessageContent>
<div hlmBubble>
<div hlmBubbleContent>How can I help you today?</div>
</div>
</div>
</div>Message owns the row layout — avatar, alignment, header, and footer. Render the visible message surface with Bubble .
Examples
Avatar
Use hlmMessageAvatar to render an avatar next to the message. Set align="end" to flip the row.
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { HlmAvatarImports } from '@spartan-ng/helm/avatar';
import { HlmBubbleImports } from '@spartan-ng/helm/bubble';
import { HlmMessageImports } from '@spartan-ng/helm/message';
@Component({
selector: 'spartan-message-avatar-preview',
imports: [HlmMessageImports, HlmBubbleImports, HlmAvatarImports],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
class: 'flex w-full max-w-sm flex-col gap-6 py-12',
},
template: `
<div hlmMessage>
<div hlmMessageAvatar>
<hlm-avatar>
<img hlmAvatarImage src="https://github.com/spartan-ng.png" alt="@spartan-ng" class="grayscale" />
<span hlmAvatarFallback>R</span>
</hlm-avatar>
</div>
<div hlmMessageContent>
<div hlmBubble variant="muted">
<div hlmBubbleContent>The build failed during dependency installation.</div>
</div>
</div>
</div>
<div hlmMessage align="end">
<div hlmMessageAvatar>
<hlm-avatar>
<img hlmAvatarImage src="/assets/avatar.png" alt="@me" class="grayscale" />
<span hlmAvatarFallback>ME</span>
</hlm-avatar>
</div>
<div hlmMessageContent>
<div hlmBubble>
<div hlmBubbleContent>Can you share the exact error?</div>
</div>
</div>
</div>
<div hlmMessage>
<div hlmMessageAvatar>
<hlm-avatar>
<img hlmAvatarImage src="https://github.com/spartan-ng.png" alt="@spartan-ng" class="grayscale" />
<span hlmAvatarFallback>R</span>
</hlm-avatar>
</div>
<div hlmMessageContent>
<div hlmBubbleGroup>
<div hlmBubble variant="muted">
<div hlmBubbleContent>Here's the error from the logs</div>
</div>
<div hlmBubble variant="muted">
<div hlmBubbleContent>
Something went wrong with the build. The libraries are not installed correctly. Try running the build
again.
</div>
</div>
</div>
</div>
</div>
`,
})
export class MessageAvatarPreview {}Group
Use hlmMessageGroup to stack consecutive messages from the same sender. Render an empty avatar slot on earlier messages to keep alignment.
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { HlmAvatarImports } from '@spartan-ng/helm/avatar';
import { HlmBubbleImports } from '@spartan-ng/helm/bubble';
import { HlmMessageImports } from '@spartan-ng/helm/message';
@Component({
selector: 'spartan-message-group-preview',
imports: [HlmMessageImports, HlmBubbleImports, HlmAvatarImports],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
class: 'flex w-full max-w-sm flex-col gap-6 py-12',
},
template: `
<div hlmMessageGroup>
<div hlmMessage>
<div hlmMessageAvatar></div>
<div hlmMessageContent>
<div hlmBubble variant="muted">
<div hlmBubbleContent>I checked the registry addresses.</div>
</div>
</div>
</div>
<div hlmMessage>
<div hlmMessageAvatar>
<hlm-avatar>
<img hlmAvatarImage src="https://github.com/spartan-ng.png" alt="@spartan-ng" class="grayscale" />
<span hlmAvatarFallback>CN</span>
</hlm-avatar>
</div>
<div hlmMessageContent>
<div hlmBubble variant="muted">
<div hlmBubbleContent>The component and example JSON now live under the UI registry.</div>
</div>
</div>
</div>
</div>
`,
})
export class MessageGroupPreview {}Header and Footer
Use hlmMessageHeader for a sender name and hlmMessageFooter for metadata such as delivery status.
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { HlmBubbleImports } from '@spartan-ng/helm/bubble';
import { HlmMessageImports } from '@spartan-ng/helm/message';
@Component({
selector: 'spartan-message-header-footer-preview',
imports: [HlmMessageImports, HlmBubbleImports],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
class: 'flex w-full max-w-sm flex-col gap-8 py-12',
},
template: `
<div hlmMessage>
<div hlmMessageContent>
<div hlmMessageHeader>Olivia</div>
<div hlmBubble variant="muted">
<div hlmBubbleContent>I already checked the logs.</div>
</div>
</div>
</div>
<div hlmMessage align="end">
<div hlmMessageContent>
<div hlmBubble>
<div hlmBubbleContent>Send the report to the team. Ping @spartan if you need help.</div>
</div>
<div hlmMessageFooter>
<div>
Read
<span class="font-normal">Yesterday</span>
</div>
</div>
</div>
</div>
`,
})
export class MessageHeaderFooterPreview {}Actions
Place message-level actions in hlmMessageFooter , such as copy, retry, or feedback buttons.
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideCopy, lucideRefreshCcw, lucideThumbsDown, lucideThumbsUp } from '@ng-icons/lucide';
import { HlmBubbleImports } from '@spartan-ng/helm/bubble';
import { HlmButton } from '@spartan-ng/helm/button';
import { HlmMessageImports } from '@spartan-ng/helm/message';
@Component({
selector: 'spartan-message-actions-preview',
imports: [HlmMessageImports, HlmBubbleImports, HlmButton, NgIcon],
providers: [provideIcons({ lucideCopy, lucideThumbsUp, lucideThumbsDown, lucideRefreshCcw })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
class: 'flex w-full max-w-sm flex-col gap-8 py-12',
},
template: `
<div hlmMessage>
<div hlmMessageContent>
<div hlmBubble variant="muted">
<div hlmBubbleContent>The install failure is coming from the workspace package.</div>
</div>
<div hlmMessageFooter>
<button hlmBtn variant="ghost" size="icon" aria-label="Copy" title="Copy">
<ng-icon name="lucideCopy" />
</button>
<button hlmBtn variant="ghost" size="icon" aria-label="Like" title="Like">
<ng-icon name="lucideThumbsUp" />
</button>
<button hlmBtn variant="ghost" size="icon" aria-label="Dislike" title="Dislike">
<ng-icon name="lucideThumbsDown" />
</button>
</div>
</div>
</div>
<div hlmMessage align="end">
<div hlmMessageContent>
<div hlmBubble>
<div hlmBubbleContent>Okay drop me a link. Taking a look...</div>
</div>
<div hlmMessageFooter class="gap-2">
<span class="text-destructive font-normal">Failed to send</span>
<button hlmBtn variant="ghost" size="icon-xs" title="Retry" aria-label="Retry">
<ng-icon name="lucideRefreshCcw" />
</button>
</div>
</div>
</div>
`,
})
export class MessageActionsPreview {}Attachment
Compose Attachment inside hlmMessageContent alongside bubbles.
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideDownload, lucideFileText } from '@ng-icons/lucide';
import { HlmAttachmentImports } from '@spartan-ng/helm/attachment';
import { HlmBubbleImports } from '@spartan-ng/helm/bubble';
import { HlmMessageImports } from '@spartan-ng/helm/message';
@Component({
selector: 'spartan-message-attachment-preview',
imports: [HlmMessageImports, HlmBubbleImports, HlmAttachmentImports, NgIcon],
providers: [provideIcons({ lucideFileText, lucideDownload })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
class: 'flex w-full max-w-sm flex-col gap-8 py-12',
},
template: `
<div hlmMessage align="end">
<div hlmMessageContent>
<div hlmAttachment orientation="vertical">
<div hlmAttachmentMedia variant="image">
<img
src="https://images.unsplash.com/photo-1497366754035-f200968a6e72?w=900&auto=format&fit=crop&q=80"
alt="Workspace"
/>
</div>
</div>
<div hlmBubble>
<div hlmBubbleContent>Here's the image. Can you add it to the PDF? Use it for the cover page.</div>
</div>
</div>
</div>
<div hlmMessage>
<div hlmMessageContent>
<div hlmBubble variant="muted">
<div hlmBubbleContent>Done. Here's the PDF with the image added as the cover page.</div>
</div>
<div hlmAttachment>
<div hlmAttachmentMedia>
<ng-icon name="lucideFileText" />
</div>
<div hlmAttachmentContent>
<span hlmAttachmentTitle>sales-dashboard.pdf</span>
<span hlmAttachmentDescription>PDF · 2.4 MB</span>
</div>
<div hlmAttachmentActions>
<button
hlmAttachmentAction
type="button"
title="Download"
aria-label="Download"
size="icon-sm"
variant="secondary"
>
<ng-icon name="lucideDownload" />
</button>
</div>
</div>
</div>
</div>
<div hlmMessage align="end">
<div hlmMessageContent>
<div hlmBubble>
<div hlmBubbleContent>Thanks. Looks good.</div>
</div>
</div>
</div>
`,
})
export class MessageAttachmentPreview {}RTL
To enable RTL support in spartan-ng, see the RTL configuration guide.
import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core';
import { TranslateService, Translations } from '@spartan-ng/app/app/shared/translate.service';
import { HlmAvatarImports } from '@spartan-ng/helm/avatar';
import { HlmBubbleImports } from '@spartan-ng/helm/bubble';
import { HlmMarkerImports } from '@spartan-ng/helm/marker';
import { HlmMessageImports } from '@spartan-ng/helm/message';
@Component({
selector: 'spartan-message-rtl-preview',
imports: [HlmMessageImports, HlmBubbleImports, HlmAvatarImports, HlmMarkerImports],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
class: 'theme-blue flex w-full max-w-sm flex-col gap-6',
},
template: `
<div class="flex w-full flex-col gap-6" [dir]="_dir()">
<div hlmMessage align="end">
<div hlmMessageAvatar>
<hlm-avatar>
<img hlmAvatarImage src="/assets/avatar.png" alt="@me" class="grayscale" />
<span hlmAvatarFallback>ME</span>
</hlm-avatar>
</div>
<div hlmMessageContent>
<div hlmBubble>
<div hlmBubbleContent>{{ _t()['user'] }}</div>
</div>
<div hlmMessageFooter>{{ _t()['delivered'] }}</div>
</div>
</div>
<div hlmMessage>
<div hlmMessageAvatar>
<hlm-avatar>
<img hlmAvatarImage src="https://github.com/spartan-ng.png" alt="@spartan-ng" class="grayscale" />
<span hlmAvatarFallback>SP</span>
</hlm-avatar>
</div>
<div hlmMessageContent>
<div hlmBubble variant="muted">
<div hlmBubbleContent>{{ _t()['assistant'] }}</div>
</div>
</div>
</div>
<div hlmMarker role="status">
<span hlmMarkerContent class="shimmer">{{ _t()['typing'] }}</span>
</div>
</div>
`,
})
export class MessageRtlPreview {
private readonly _language = inject(TranslateService).language;
private readonly _translations: Translations = {
en: {
dir: 'ltr',
values: {
user: "It's a one-line change.",
delivered: 'Delivered',
assistant: 'Alright, let me take a look.',
typing: 'Spartan is typing...',
},
},
ar: {
dir: 'rtl',
values: {
user: 'إنه تغيير بسطر واحد.',
delivered: 'تم التسليم',
assistant: 'حسنًا، دعني ألقي نظرة.',
typing: 'سبارتان يكتب...',
},
},
he: {
dir: 'rtl',
values: {
user: 'זה שינוי של שורה אחת.',
delivered: 'נמסר',
assistant: 'בסדר, תן לי להסתכל.',
typing: 'ספרטאן מקליד...',
},
},
};
private readonly _translation = computed(() => this._translations[this._language()]);
protected readonly _t = computed(() => this._translation().values);
protected readonly _dir = computed(() => this._translation().dir);
}Helm API
HlmMessageAvatar
Selector: [hlmMessageAvatar],hlm-message-avatar
HlmMessageContent
Selector: [hlmMessageContent],hlm-message-content
HlmMessageFooter
Selector: [hlmMessageFooter],hlm-message-footer
HlmMessageGroup
Selector: [hlmMessageGroup],hlm-message-group
HlmMessageHeader
Selector: [hlmMessageHeader],hlm-message-header
HlmMessage
Selector: [hlmMessage],hlm-message
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| align | MessageAlign | 'start' | - |
On This Page