- Accordion
- Alert
- Alert Dialog
- Aspect Ratio
- Autocomplete
- Avatar
- Badge
- Breadcrumb
- Button
- Button Group
- Calendar
- Card
- Carousel
- Checkbox
- Collapsible
- Combobox
- Command
- Context Menu
- Data Table
- Date Picker
- Dialog
- Drawer
- Dropdown Menu
- Empty
- Field
- Hover Card
- Icon
- Input Group
- Input OTP
- Input
- Item
- Kbd
- Label
- Menubar
- 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
Dropdown
Displays a menu to the user — such as a set of actions or functions — triggered by a button.
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
@Component({
selector: 'spartan-dropdown-preview',
imports: [HlmDropdownMenuImports, HlmButtonImports],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<button hlmBtn variant="outline" [hlmDropdownMenuTrigger]="menu" align="start">Open</button>
<ng-template #menu>
<hlm-dropdown-menu class="w-40">
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>My Account</hlm-dropdown-menu-label>
<button hlmDropdownMenuItem>
Profile
<hlm-dropdown-menu-shortcut>⇧⌘P</hlm-dropdown-menu-shortcut>
</button>
<button hlmDropdownMenuItem>
Billing
<hlm-dropdown-menu-shortcut>⌘B</hlm-dropdown-menu-shortcut>
</button>
<button hlmDropdownMenuItem>
Settings
<hlm-dropdown-menu-shortcut>⌘S</hlm-dropdown-menu-shortcut>
</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<hlm-dropdown-menu-group>
<button hlmDropdownMenuItem>
Team
<hlm-dropdown-menu-shortcut>⌘B</hlm-dropdown-menu-shortcut>
</button>
<button hlmDropdownMenuItem side="right" align="start" [hlmDropdownMenuSubTrigger]="invite">
Invite Users
<hlm-dropdown-menu-item-sub-indicator />
</button>
<button hlmDropdownMenuItem>
New Team
<hlm-dropdown-menu-shortcut>⌘+T</hlm-dropdown-menu-shortcut>
</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<hlm-dropdown-menu-group>
<button hlmDropdownMenuItem>GitHub</button>
<button hlmDropdownMenuItem>Support</button>
<button hlmDropdownMenuItem disabled>API</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<button hlmDropdownMenuItem>
Log out
<hlm-dropdown-menu-shortcut>⇧⌘Q</hlm-dropdown-menu-shortcut>
</button>
</hlm-dropdown-menu>
</ng-template>
<ng-template #invite>
<hlm-dropdown-menu-sub>
<button hlmDropdownMenuItem>Email</button>
<button hlmDropdownMenuItem>Message</button>
<hlm-dropdown-menu-separator />
<button hlmDropdownMenuItem>More...</button>
</hlm-dropdown-menu-sub>
</ng-template>
`,
})
export class DropdownPreview {}About
Dropdown Menu is built with the help of Menu from Material CDK .
Installation
ng g @spartan-ng/cli:ui dropdown-menunx g @spartan-ng/cli:ui dropdown-menuimport { DestroyRef, ElementRef, HostAttributeToken, Injector, PLATFORM_ID, effect, inject, runInInjectionContext } from '@angular/core';
import { clsx, type ClassValue } from 'clsx';
import { isPlatformBrowser } from '@angular/common';
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;
}import { CdkMenu, CdkMenuGroup, CdkMenuItem, CdkMenuItemCheckbox, CdkMenuItemRadio, CdkMenuItemSelectable, CdkMenuTrigger } from '@angular/cdk/menu';
import { ChangeDetectionStrategy, Component, Directive, HOST_TAG_NAME, InjectionToken, booleanAttribute, computed, effect, inject, input, numberAttribute, signal, type ValueProvider } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { classes } from '@spartan-ng/helm/utils';
import { createMenuPosition, type MenuAlign, type MenuSide } from '@spartan-ng/brain/core';
import { lucideCheck, lucideChevronRight } from '@ng-icons/lucide';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { type BooleanInput, type NumberInput } from '@angular/cdk/coercion';
@Component({
selector: 'hlm-dropdown-menu-checkbox-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideCheck })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { 'data-slot': 'dropdown-menu-checkbox-item-indicator' },
template: `
<ng-icon name="lucideCheck" />
`,
})
export class HlmDropdownMenuCheckboxIndicator {
constructor() {
classes(
() =>
'absolute end-2 flex items-center justify-center [&_ng-icon]:text-[calc(var(--spacing)*4)] pointer-events-none opacity-0 group-data-checked/dropdown-menu-checkbox:opacity-100',
);
}
}
/** @internal. Use HlmDropdownMenuCheckbox instead. */
@Directive({
selector: '[hlmDropdownMenuCheckboxCdk]',
providers: [
{ provide: CdkMenuItemCheckbox, useExisting: HlmDropdownMenuCheckboxCdk },
{ provide: CdkMenuItemSelectable, useExisting: HlmDropdownMenuCheckboxCdk },
{ provide: CdkMenuItem, useExisting: CdkMenuItemSelectable },
],
})
export class HlmDropdownMenuCheckboxCdk extends CdkMenuItemCheckbox {
public readonly keepOpen = input<boolean, BooleanInput>(true, { transform: booleanAttribute });
public override trigger(options?: { keepOpen: boolean }) {
super.trigger({ ...options, keepOpen: this.keepOpen() });
}
}
@Directive({
selector: '[hlmDropdownMenuCheckbox],[hlmDropdownMenuCheckboxItem]',
hostDirectives: [
{
directive: HlmDropdownMenuCheckboxCdk,
inputs: ['cdkMenuItemDisabled: disabled', 'cdkMenuItemChecked: checked', 'keepOpen'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-checkbox-item',
'[attr.data-disabled]': '_cdkMenuItem.disabled ? "" : null',
'[attr.data-checked]': '_cdkMenuItem.checked ? "" : null',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuCheckbox {
protected readonly _cdkMenuItem = inject(HlmDropdownMenuCheckboxCdk);
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(
() =>
'hover:bg-accent focus:bg-accent hover:text-accent-foreground focus:text-accent-foreground gap-2 rounded-sm py-1.5 ps-2 pe-8 text-sm data-inset:ps-8 [&_ng-icon:not([class*=\'text-\'])]:text-[calc(var(--spacing)*4)] group/dropdown-menu-checkbox relative flex w-full cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0',
);
}
}
@Directive({
selector: '[hlmDropdownMenuGroup],hlm-dropdown-menu-group',
hostDirectives: [CdkMenuGroup],
host: { 'data-slot': 'dropdown-menu-group' },
})
export class HlmDropdownMenuGroup {
constructor() {
classes(() => 'block');
}
}
@Component({
selector: 'hlm-dropdown-menu-item-sub-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideChevronRight })],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ng-icon name="lucideChevronRight" class="text-[calc(var(--spacing)*4)] rtl:rotate-180" />
`,
})
export class HlmDropdownMenuItemSubIndicator {
constructor() {
classes(() => 'ms-auto flex items-center justify-center');
}
}
@Directive({
selector: '[hlmDropdownMenuItem],hlm-dropdown-menu-item',
hostDirectives: [
{
directive: CdkMenuItem,
inputs: ['cdkMenuItemDisabled: disabled'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-item',
'[attr.disabled]': '_isButton && disabled() ? "" : null',
'[attr.data-disabled]': 'disabled() ? "" : null',
'[attr.data-variant]': 'variant()',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuItem {
protected readonly _isButton = inject(HOST_TAG_NAME) === 'button';
public readonly disabled = input<boolean, BooleanInput>(false, { transform: booleanAttribute });
public readonly variant = input<'default' | 'destructive'>('default');
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(
() =>
'hover:bg-accent focus:bg-accent hover:text-accent-foreground focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[ng-icon]:text-destructive not-data-[variant=destructive]:hover:**:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground gap-2 rounded-sm px-2 py-1.5 text-sm data-inset:ps-8 [&_ng-icon:not([class*=\'text-\'])]:text-[calc(var(--spacing)*4)] group/dropdown-menu-item relative flex w-full cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0',
);
}
}
@Directive({
selector: '[hlmDropdownMenuLabel],hlm-dropdown-menu-label',
host: {
'data-slot': 'dropdown-menu-label',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuLabel {
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(() => 'text-muted-foreground px-2 py-1.5 text-xs font-medium data-inset:ps-8 block');
}
}
@Component({
selector: 'hlm-dropdown-menu-radio-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideCheck })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { 'data-slot': 'dropdown-menu-radio-item-indicator' },
template: `
<ng-icon name="lucideCheck" />
`,
})
export class HlmDropdownMenuRadioIndicator {
constructor() {
classes(
() =>
'absolute end-2 flex items-center justify-center [&_ng-icon]:text-[calc(var(--spacing)*4)] pointer-events-none opacity-0 group-data-checked/dropdown-menu-radio:opacity-100',
);
}
}
/** @internal. Use HlmDropdownMenuRadio instead. */
@Directive({
selector: '[hlmDropdownMenuRadioCdk]',
providers: [
{ provide: CdkMenuItemRadio, useExisting: HlmDropdownMenuRadioCdk },
{ provide: CdkMenuItemSelectable, useExisting: HlmDropdownMenuRadioCdk },
{ provide: CdkMenuItem, useExisting: CdkMenuItemSelectable },
],
})
export class HlmDropdownMenuRadioCdk extends CdkMenuItemRadio {
public readonly keepOpen = input<boolean, BooleanInput>(true, { transform: booleanAttribute });
public override trigger(options?: { keepOpen: boolean }) {
super.trigger({ ...options, keepOpen: this.keepOpen() });
}
}
@Directive({
selector: '[hlmDropdownMenuRadio]',
hostDirectives: [
{
directive: HlmDropdownMenuRadioCdk,
inputs: ['cdkMenuItemDisabled: disabled', 'cdkMenuItemChecked: checked', 'keepOpen'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-radio-item',
'[attr.data-disabled]': '_cdkMenuItem.disabled ? "" : null',
'[attr.data-checked]': '_cdkMenuItem.checked ? "" : null',
},
})
export class HlmDropdownMenuRadio {
protected readonly _cdkMenuItem = inject(HlmDropdownMenuRadioCdk);
constructor() {
classes(
() =>
'hover:bg-accent focus:bg-accent hover:text-accent-foreground focus:text-accent-foreground gap-2 rounded-sm py-1.5 ps-2 pe-8 text-sm data-inset:ps-8 [&_ng-icon:not([class*=\'text-\'])]:text-[calc(var(--spacing)*4)] group/dropdown-menu-radio relative flex w-full cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0',
);
}
}
@Directive({
selector: '[hlmDropdownMenuSeparator],hlm-dropdown-menu-separator',
host: { 'data-slot': 'dropdown-menu-separator' },
})
export class HlmDropdownMenuSeparator {
constructor() {
classes(() => 'bg-border -mx-1 my-1 h-px block');
}
}
@Directive({
selector: '[hlmDropdownMenuShortcut],hlm-dropdown-menu-shortcut',
host: { 'data-slot': 'dropdown-menu-shortcut' },
})
export class HlmDropdownMenuShortcut {
constructor() {
classes(() => 'text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground ms-auto text-xs tracking-widest');
}
}
@Directive({
selector: '[hlmDropdownMenuSubTrigger]',
hostDirectives: [
{
directive: CdkMenuTrigger,
inputs: ['cdkMenuTriggerFor: hlmDropdownMenuSubTrigger', 'cdkMenuTriggerData: hlmDropdownMenuTriggerData'],
outputs: ['cdkMenuOpened: hlmDropdownMenuSubOpened', 'cdkMenuClosed: hlmDropdownMenuSubClosed'],
},
],
host: { 'data-slot': 'dropdown-menu-sub-trigger' },
})
export class HlmDropdownMenuSubTrigger {
private readonly _cdkTrigger = inject(CdkMenuTrigger, { host: true });
private readonly _config = injectHlmDropdownMenuConfig();
public readonly align = input<MenuAlign>(this._config.align);
public readonly side = input<MenuSide>(this._config.side);
private readonly _menuPosition = computed(() => createMenuPosition(this.align(), this.side()));
constructor() {
this._cdkTrigger.opened.pipe(takeUntilDestroyed()).subscribe(() =>
setTimeout(
() =>
// eslint-disable-next-line
((this._cdkTrigger as any)._spartanLastPosition = // eslint-disable-next-line
(this._cdkTrigger as any).overlayRef._positionStrategy._lastPosition),
),
);
effect(() => {
this._cdkTrigger.menuPosition = this._menuPosition();
});
classes(() => 'aria-expanded:bg-accent aria-expanded:text-accent-foreground');
}
}
@Directive({
selector: '[hlmDropdownMenuSub],hlm-dropdown-menu-sub',
hostDirectives: [CdkMenu],
host: {
'data-slot': 'dropdown-menu-sub',
'[attr.data-state]': '_state()',
'[attr.data-side]': '_side()',
},
})
export class HlmDropdownMenuSub {
private readonly _host = inject(CdkMenu);
protected readonly _state = signal('open');
protected readonly _side = signal('top');
constructor() {
this.setSideWithDarkMagic();
// this is a best effort, but does not seem to work currently
// TODO: figure out a way for us to know the host is about to be closed. might not be possible with CDK
this._host.closed.pipe(takeUntilDestroyed()).subscribe(() => this._state.set('closed'));
classes(() => 'data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 bg-popover text-popover-foreground min-w-24 rounded-md p-1 shadow-lg ring-1 duration-100 w-auto');
}
private setSideWithDarkMagic() {
/**
* This is an ugly workaround to at least figure out the correct side of where a submenu
* will appear and set the attribute to the host accordingly
*
* First of all we take advantage of the menu stack not being aware of the root
* object immediately after it is added. This code executes before the root element is added,
* which means the stack is still empty and the peek method returns undefined.
*/
const isRoot = this._host.menuStack.peek() === undefined;
setTimeout(() => {
// our menu trigger directive leaves the last position used for use immediately after opening
// we can access it here and determine the correct side.
// eslint-disable-next-line
const ps = (this._host as any)._parentTrigger._spartanLastPosition;
if (!ps) {
// if we have no last position we default to the most likely option
// I hate that we have to do this and hope we can revisit soon and improve
this._side.set(isRoot ? 'top' : 'left');
return;
}
const side = isRoot ? ps.originY : ps.originX === 'end' ? 'right' : 'left';
this._side.set(side);
});
}
}
export interface HlmDropdownMenuConfig {
align: MenuAlign;
side: MenuSide;
}
const defaultConfig: HlmDropdownMenuConfig = {
align: 'start',
side: 'bottom',
};
const HlmDropdownMenuConfigToken = new InjectionToken<HlmDropdownMenuConfig>('HlmDropdownMenuConfig');
export function provideHlmDropdownMenuConfig(config: Partial<HlmDropdownMenuConfig>): ValueProvider {
return { provide: HlmDropdownMenuConfigToken, useValue: { ...defaultConfig, ...config } };
}
export function injectHlmDropdownMenuConfig(): HlmDropdownMenuConfig {
return inject(HlmDropdownMenuConfigToken, { optional: true }) ?? defaultConfig;
}
@Directive({
selector: '[hlmDropdownMenuTrigger]',
hostDirectives: [
{
directive: CdkMenuTrigger,
inputs: ['cdkMenuTriggerFor: hlmDropdownMenuTrigger', 'cdkMenuTriggerData: hlmDropdownMenuTriggerData'],
outputs: ['cdkMenuOpened: hlmDropdownMenuOpened', 'cdkMenuClosed: hlmDropdownMenuClosed'],
},
],
host: { 'data-slot': 'dropdown-menu-trigger' },
})
export class HlmDropdownMenuTrigger {
private readonly _cdkTrigger = inject(CdkMenuTrigger, { host: true });
private readonly _config = injectHlmDropdownMenuConfig();
public readonly align = input<MenuAlign>(this._config.align);
public readonly side = input<MenuSide>(this._config.side);
private readonly _menuPosition = computed(() => createMenuPosition(this.align(), this.side()));
constructor() {
// once the trigger opens we wait until the next tick and then grab the last position
// used to position the menu. we store this in our trigger which the brnMenu directive has
// access to through DI
this._cdkTrigger.opened.pipe(takeUntilDestroyed()).subscribe(() =>
setTimeout(
() =>
// eslint-disable-next-line
((this._cdkTrigger as any)._spartanLastPosition = // eslint-disable-next-line
(this._cdkTrigger as any).overlayRef._positionStrategy._lastPosition),
),
);
effect(() => {
this._cdkTrigger.menuPosition = this._menuPosition();
});
}
}
@Directive({
selector: '[hlmDropdownMenu],hlm-dropdown-menu',
hostDirectives: [CdkMenu],
host: {
'data-slot': 'dropdown-menu',
'[attr.data-state]': '_state()',
'[attr.data-side]': '_side()',
'[style.--side-offset]': 'sideOffset()',
},
})
export class HlmDropdownMenu {
private readonly _host = inject(CdkMenu);
protected readonly _state = signal('open');
protected readonly _side = signal('top');
public readonly sideOffset = input<number, NumberInput>(1, { transform: numberAttribute });
constructor() {
classes(
() =>
'data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 bg-popover text-popover-foreground min-w-32 rounded-md p-1 shadow-md ring-1 duration-100 my-[--spacing(var(--side-offset))] overflow-x-hidden overflow-y-auto outline-none',
);
this.setSideWithDarkMagic();
// this is a best effort, but does not seem to work currently
// TODO: figure out a way for us to know the host is about to be closed. might not be possible with CDK
this._host.closed.pipe(takeUntilDestroyed()).subscribe(() => this._state.set('closed'));
}
private setSideWithDarkMagic() {
/**
* This is an ugly workaround to at least figure out the correct side of where a submenu
* will appear and set the attribute to the host accordingly
*
* First of all we take advantage of the menu stack not being aware of the root
* object immediately after it is added. This code executes before the root element is added,
* which means the stack is still empty and the peek method returns undefined.
*/
const isRoot = this._host.menuStack.peek() === undefined;
setTimeout(() => {
// our menu trigger directive leaves the last position used for use immediately after opening
// we can access it here and determine the correct side.
// eslint-disable-next-line
const ps = (this._host as any)._parentTrigger._spartanLastPosition;
if (!ps) {
// if we have no last position we default to the most likely option
// I hate that we have to do this and hope we can revisit soon and improve
this._side.set(isRoot ? 'top' : 'left');
return;
}
const side = isRoot ? ps.originY : ps.originX === 'end' ? 'right' : 'left';
this._side.set(side);
});
}
}
export const HlmDropdownMenuImports = [
HlmDropdownMenu,
HlmDropdownMenuCheckbox,
HlmDropdownMenuCheckboxIndicator,
HlmDropdownMenuGroup,
HlmDropdownMenuItem,
HlmDropdownMenuItemSubIndicator,
HlmDropdownMenuLabel,
HlmDropdownMenuRadio,
HlmDropdownMenuRadioIndicator,
HlmDropdownMenuSeparator,
HlmDropdownMenuShortcut,
HlmDropdownMenuSub,
HlmDropdownMenuSubTrigger,
HlmDropdownMenuTrigger,
] as const;import { CdkMenu, CdkMenuGroup, CdkMenuItem, CdkMenuItemCheckbox, CdkMenuItemRadio, CdkMenuItemSelectable, CdkMenuTrigger } from '@angular/cdk/menu';
import { ChangeDetectionStrategy, Component, Directive, HOST_TAG_NAME, InjectionToken, booleanAttribute, computed, effect, inject, input, numberAttribute, signal, type ValueProvider } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { classes } from '@spartan-ng/helm/utils';
import { createMenuPosition, type MenuAlign, type MenuSide } from '@spartan-ng/brain/core';
import { lucideCheck, lucideChevronRight } from '@ng-icons/lucide';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { type BooleanInput, type NumberInput } from '@angular/cdk/coercion';
@Component({
selector: 'hlm-dropdown-menu-checkbox-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideCheck })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { 'data-slot': 'dropdown-menu-checkbox-item-indicator' },
template: `
<ng-icon name="lucideCheck" />
`,
})
export class HlmDropdownMenuCheckboxIndicator {
constructor() {
classes(
() =>
'absolute end-2 flex items-center justify-center [&_ng-icon]:text-[calc(var(--spacing)*4)] pointer-events-none opacity-0 group-data-checked/dropdown-menu-checkbox:opacity-100',
);
}
}
/** @internal. Use HlmDropdownMenuCheckbox instead. */
@Directive({
selector: '[hlmDropdownMenuCheckboxCdk]',
providers: [
{ provide: CdkMenuItemCheckbox, useExisting: HlmDropdownMenuCheckboxCdk },
{ provide: CdkMenuItemSelectable, useExisting: HlmDropdownMenuCheckboxCdk },
{ provide: CdkMenuItem, useExisting: CdkMenuItemSelectable },
],
})
export class HlmDropdownMenuCheckboxCdk extends CdkMenuItemCheckbox {
public readonly keepOpen = input<boolean, BooleanInput>(true, { transform: booleanAttribute });
public override trigger(options?: { keepOpen: boolean }) {
super.trigger({ ...options, keepOpen: this.keepOpen() });
}
}
@Directive({
selector: '[hlmDropdownMenuCheckbox],[hlmDropdownMenuCheckboxItem]',
hostDirectives: [
{
directive: HlmDropdownMenuCheckboxCdk,
inputs: ['cdkMenuItemDisabled: disabled', 'cdkMenuItemChecked: checked', 'keepOpen'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-checkbox-item',
'[attr.data-disabled]': '_cdkMenuItem.disabled ? "" : null',
'[attr.data-checked]': '_cdkMenuItem.checked ? "" : null',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuCheckbox {
protected readonly _cdkMenuItem = inject(HlmDropdownMenuCheckboxCdk);
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(
() =>
'hover:bg-accent focus:bg-accent hover:text-accent-foreground focus:text-accent-foreground hover:**:text-accent-foreground focus:**:text-accent-foreground gap-2 rounded-none py-2 ps-2 pe-8 text-xs data-inset:ps-7 [&_ng-icon:not([class*=\'text-\'])]:text-[calc(var(--spacing)*4)] group/dropdown-menu-checkbox relative flex w-full cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0',
);
}
}
@Directive({
selector: '[hlmDropdownMenuGroup],hlm-dropdown-menu-group',
hostDirectives: [CdkMenuGroup],
host: { 'data-slot': 'dropdown-menu-group' },
})
export class HlmDropdownMenuGroup {
constructor() {
classes(() => 'block');
}
}
@Component({
selector: 'hlm-dropdown-menu-item-sub-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideChevronRight })],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ng-icon name="lucideChevronRight" class="text-[calc(var(--spacing)*4)] rtl:rotate-180" />
`,
})
export class HlmDropdownMenuItemSubIndicator {
constructor() {
classes(() => 'ms-auto flex items-center justify-center');
}
}
@Directive({
selector: '[hlmDropdownMenuItem],hlm-dropdown-menu-item',
hostDirectives: [
{
directive: CdkMenuItem,
inputs: ['cdkMenuItemDisabled: disabled'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-item',
'[attr.disabled]': '_isButton && disabled() ? "" : null',
'[attr.data-disabled]': 'disabled() ? "" : null',
'[attr.data-variant]': 'variant()',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuItem {
protected readonly _isButton = inject(HOST_TAG_NAME) === 'button';
public readonly disabled = input<boolean, BooleanInput>(false, { transform: booleanAttribute });
public readonly variant = input<'default' | 'destructive'>('default');
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(
() =>
'hover:bg-accent focus:bg-accent hover:text-accent-foreground focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[ng-icon]:text-destructive not-data-[variant=destructive]:hover:**:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground gap-2 rounded-none px-2 py-2 text-xs data-inset:ps-7 [&_ng-icon:not([class*=\'text-\'])]:text-[calc(var(--spacing)*4)] group/dropdown-menu-item relative flex w-full cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0',
);
}
}
@Directive({
selector: '[hlmDropdownMenuLabel],hlm-dropdown-menu-label',
host: {
'data-slot': 'dropdown-menu-label',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuLabel {
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(() => 'text-muted-foreground px-2 py-2 text-xs data-inset:ps-7 block');
}
}
@Component({
selector: 'hlm-dropdown-menu-radio-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideCheck })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { 'data-slot': 'dropdown-menu-radio-item-indicator' },
template: `
<ng-icon name="lucideCheck" />
`,
})
export class HlmDropdownMenuRadioIndicator {
constructor() {
classes(
() =>
'absolute end-2 flex items-center justify-center [&_ng-icon]:text-[calc(var(--spacing)*4)] pointer-events-none opacity-0 group-data-checked/dropdown-menu-radio:opacity-100',
);
}
}
/** @internal. Use HlmDropdownMenuRadio instead. */
@Directive({
selector: '[hlmDropdownMenuRadioCdk]',
providers: [
{ provide: CdkMenuItemRadio, useExisting: HlmDropdownMenuRadioCdk },
{ provide: CdkMenuItemSelectable, useExisting: HlmDropdownMenuRadioCdk },
{ provide: CdkMenuItem, useExisting: CdkMenuItemSelectable },
],
})
export class HlmDropdownMenuRadioCdk extends CdkMenuItemRadio {
public readonly keepOpen = input<boolean, BooleanInput>(true, { transform: booleanAttribute });
public override trigger(options?: { keepOpen: boolean }) {
super.trigger({ ...options, keepOpen: this.keepOpen() });
}
}
@Directive({
selector: '[hlmDropdownMenuRadio]',
hostDirectives: [
{
directive: HlmDropdownMenuRadioCdk,
inputs: ['cdkMenuItemDisabled: disabled', 'cdkMenuItemChecked: checked', 'keepOpen'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-radio-item',
'[attr.data-disabled]': '_cdkMenuItem.disabled ? "" : null',
'[attr.data-checked]': '_cdkMenuItem.checked ? "" : null',
},
})
export class HlmDropdownMenuRadio {
protected readonly _cdkMenuItem = inject(HlmDropdownMenuRadioCdk);
constructor() {
classes(
() =>
'hover:bg-accent focus:bg-accent hover:text-accent-foreground focus:text-accent-foreground hover:**:text-accent-foreground focus:**:text-accent-foreground gap-2 rounded-none py-2 ps-2 pe-8 text-xs data-inset:ps-7 [&_ng-icon:not([class*=\'text-\'])]:text-[calc(var(--spacing)*4)] group/dropdown-menu-radio relative flex w-full cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0',
);
}
}
@Directive({
selector: '[hlmDropdownMenuSeparator],hlm-dropdown-menu-separator',
host: { 'data-slot': 'dropdown-menu-separator' },
})
export class HlmDropdownMenuSeparator {
constructor() {
classes(() => 'bg-border -mx-1 h-px block');
}
}
@Directive({
selector: '[hlmDropdownMenuShortcut],hlm-dropdown-menu-shortcut',
host: { 'data-slot': 'dropdown-menu-shortcut' },
})
export class HlmDropdownMenuShortcut {
constructor() {
classes(() => 'text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground ms-auto text-xs tracking-widest');
}
}
@Directive({
selector: '[hlmDropdownMenuSubTrigger]',
hostDirectives: [
{
directive: CdkMenuTrigger,
inputs: ['cdkMenuTriggerFor: hlmDropdownMenuSubTrigger', 'cdkMenuTriggerData: hlmDropdownMenuTriggerData'],
outputs: ['cdkMenuOpened: hlmDropdownMenuSubOpened', 'cdkMenuClosed: hlmDropdownMenuSubClosed'],
},
],
host: { 'data-slot': 'dropdown-menu-sub-trigger' },
})
export class HlmDropdownMenuSubTrigger {
private readonly _cdkTrigger = inject(CdkMenuTrigger, { host: true });
private readonly _config = injectHlmDropdownMenuConfig();
public readonly align = input<MenuAlign>(this._config.align);
public readonly side = input<MenuSide>(this._config.side);
private readonly _menuPosition = computed(() => createMenuPosition(this.align(), this.side()));
constructor() {
this._cdkTrigger.opened.pipe(takeUntilDestroyed()).subscribe(() =>
setTimeout(
() =>
// eslint-disable-next-line
((this._cdkTrigger as any)._spartanLastPosition = // eslint-disable-next-line
(this._cdkTrigger as any).overlayRef._positionStrategy._lastPosition),
),
);
effect(() => {
this._cdkTrigger.menuPosition = this._menuPosition();
});
classes(() => 'aria-expanded:bg-accent aria-expanded:text-accent-foreground');
}
}
@Directive({
selector: '[hlmDropdownMenuSub],hlm-dropdown-menu-sub',
hostDirectives: [CdkMenu],
host: {
'data-slot': 'dropdown-menu-sub',
'[attr.data-state]': '_state()',
'[attr.data-side]': '_side()',
},
})
export class HlmDropdownMenuSub {
private readonly _host = inject(CdkMenu);
protected readonly _state = signal('open');
protected readonly _side = signal('top');
constructor() {
this.setSideWithDarkMagic();
// this is a best effort, but does not seem to work currently
// TODO: figure out a way for us to know the host is about to be closed. might not be possible with CDK
this._host.closed.pipe(takeUntilDestroyed()).subscribe(() => this._state.set('closed'));
classes(() => 'data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 bg-popover text-popover-foreground min-w-[96px] rounded-none shadow-lg ring-1 duration-100 w-auto');
}
private setSideWithDarkMagic() {
/**
* This is an ugly workaround to at least figure out the correct side of where a submenu
* will appear and set the attribute to the host accordingly
*
* First of all we take advantage of the menu stack not being aware of the root
* object immediately after it is added. This code executes before the root element is added,
* which means the stack is still empty and the peek method returns undefined.
*/
const isRoot = this._host.menuStack.peek() === undefined;
setTimeout(() => {
// our menu trigger directive leaves the last position used for use immediately after opening
// we can access it here and determine the correct side.
// eslint-disable-next-line
const ps = (this._host as any)._parentTrigger._spartanLastPosition;
if (!ps) {
// if we have no last position we default to the most likely option
// I hate that we have to do this and hope we can revisit soon and improve
this._side.set(isRoot ? 'top' : 'left');
return;
}
const side = isRoot ? ps.originY : ps.originX === 'end' ? 'right' : 'left';
this._side.set(side);
});
}
}
export interface HlmDropdownMenuConfig {
align: MenuAlign;
side: MenuSide;
}
const defaultConfig: HlmDropdownMenuConfig = {
align: 'start',
side: 'bottom',
};
const HlmDropdownMenuConfigToken = new InjectionToken<HlmDropdownMenuConfig>('HlmDropdownMenuConfig');
export function provideHlmDropdownMenuConfig(config: Partial<HlmDropdownMenuConfig>): ValueProvider {
return { provide: HlmDropdownMenuConfigToken, useValue: { ...defaultConfig, ...config } };
}
export function injectHlmDropdownMenuConfig(): HlmDropdownMenuConfig {
return inject(HlmDropdownMenuConfigToken, { optional: true }) ?? defaultConfig;
}
@Directive({
selector: '[hlmDropdownMenuTrigger]',
hostDirectives: [
{
directive: CdkMenuTrigger,
inputs: ['cdkMenuTriggerFor: hlmDropdownMenuTrigger', 'cdkMenuTriggerData: hlmDropdownMenuTriggerData'],
outputs: ['cdkMenuOpened: hlmDropdownMenuOpened', 'cdkMenuClosed: hlmDropdownMenuClosed'],
},
],
host: { 'data-slot': 'dropdown-menu-trigger' },
})
export class HlmDropdownMenuTrigger {
private readonly _cdkTrigger = inject(CdkMenuTrigger, { host: true });
private readonly _config = injectHlmDropdownMenuConfig();
public readonly align = input<MenuAlign>(this._config.align);
public readonly side = input<MenuSide>(this._config.side);
private readonly _menuPosition = computed(() => createMenuPosition(this.align(), this.side()));
constructor() {
// once the trigger opens we wait until the next tick and then grab the last position
// used to position the menu. we store this in our trigger which the brnMenu directive has
// access to through DI
this._cdkTrigger.opened.pipe(takeUntilDestroyed()).subscribe(() =>
setTimeout(
() =>
// eslint-disable-next-line
((this._cdkTrigger as any)._spartanLastPosition = // eslint-disable-next-line
(this._cdkTrigger as any).overlayRef._positionStrategy._lastPosition),
),
);
effect(() => {
this._cdkTrigger.menuPosition = this._menuPosition();
});
}
}
@Directive({
selector: '[hlmDropdownMenu],hlm-dropdown-menu',
hostDirectives: [CdkMenu],
host: {
'data-slot': 'dropdown-menu',
'[attr.data-state]': '_state()',
'[attr.data-side]': '_side()',
'[style.--side-offset]': 'sideOffset()',
},
})
export class HlmDropdownMenu {
private readonly _host = inject(CdkMenu);
protected readonly _state = signal('open');
protected readonly _side = signal('top');
public readonly sideOffset = input<number, NumberInput>(1, { transform: numberAttribute });
constructor() {
classes(
() =>
'data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 bg-popover text-popover-foreground min-w-32 rounded-none shadow-md ring-1 duration-100 my-[--spacing(var(--side-offset))] overflow-x-hidden overflow-y-auto outline-none',
);
this.setSideWithDarkMagic();
// this is a best effort, but does not seem to work currently
// TODO: figure out a way for us to know the host is about to be closed. might not be possible with CDK
this._host.closed.pipe(takeUntilDestroyed()).subscribe(() => this._state.set('closed'));
}
private setSideWithDarkMagic() {
/**
* This is an ugly workaround to at least figure out the correct side of where a submenu
* will appear and set the attribute to the host accordingly
*
* First of all we take advantage of the menu stack not being aware of the root
* object immediately after it is added. This code executes before the root element is added,
* which means the stack is still empty and the peek method returns undefined.
*/
const isRoot = this._host.menuStack.peek() === undefined;
setTimeout(() => {
// our menu trigger directive leaves the last position used for use immediately after opening
// we can access it here and determine the correct side.
// eslint-disable-next-line
const ps = (this._host as any)._parentTrigger._spartanLastPosition;
if (!ps) {
// if we have no last position we default to the most likely option
// I hate that we have to do this and hope we can revisit soon and improve
this._side.set(isRoot ? 'top' : 'left');
return;
}
const side = isRoot ? ps.originY : ps.originX === 'end' ? 'right' : 'left';
this._side.set(side);
});
}
}
export const HlmDropdownMenuImports = [
HlmDropdownMenu,
HlmDropdownMenuCheckbox,
HlmDropdownMenuCheckboxIndicator,
HlmDropdownMenuGroup,
HlmDropdownMenuItem,
HlmDropdownMenuItemSubIndicator,
HlmDropdownMenuLabel,
HlmDropdownMenuRadio,
HlmDropdownMenuRadioIndicator,
HlmDropdownMenuSeparator,
HlmDropdownMenuShortcut,
HlmDropdownMenuSub,
HlmDropdownMenuSubTrigger,
HlmDropdownMenuTrigger,
] as const;import { CdkMenu, CdkMenuGroup, CdkMenuItem, CdkMenuItemCheckbox, CdkMenuItemRadio, CdkMenuItemSelectable, CdkMenuTrigger } from '@angular/cdk/menu';
import { ChangeDetectionStrategy, Component, Directive, HOST_TAG_NAME, InjectionToken, booleanAttribute, computed, effect, inject, input, numberAttribute, signal, type ValueProvider } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { classes } from '@spartan-ng/helm/utils';
import { createMenuPosition, type MenuAlign, type MenuSide } from '@spartan-ng/brain/core';
import { lucideCheck, lucideChevronRight } from '@ng-icons/lucide';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { type BooleanInput, type NumberInput } from '@angular/cdk/coercion';
@Component({
selector: 'hlm-dropdown-menu-checkbox-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideCheck })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { 'data-slot': 'dropdown-menu-checkbox-item-indicator' },
template: `
<ng-icon name="lucideCheck" />
`,
})
export class HlmDropdownMenuCheckboxIndicator {
constructor() {
classes(
() =>
'absolute end-2 flex items-center justify-center [&_ng-icon]:text-[calc(var(--spacing)*4)] pointer-events-none opacity-0 group-data-checked/dropdown-menu-checkbox:opacity-100',
);
}
}
/** @internal. Use HlmDropdownMenuCheckbox instead. */
@Directive({
selector: '[hlmDropdownMenuCheckboxCdk]',
providers: [
{ provide: CdkMenuItemCheckbox, useExisting: HlmDropdownMenuCheckboxCdk },
{ provide: CdkMenuItemSelectable, useExisting: HlmDropdownMenuCheckboxCdk },
{ provide: CdkMenuItem, useExisting: CdkMenuItemSelectable },
],
})
export class HlmDropdownMenuCheckboxCdk extends CdkMenuItemCheckbox {
public readonly keepOpen = input<boolean, BooleanInput>(true, { transform: booleanAttribute });
public override trigger(options?: { keepOpen: boolean }) {
super.trigger({ ...options, keepOpen: this.keepOpen() });
}
}
@Directive({
selector: '[hlmDropdownMenuCheckbox],[hlmDropdownMenuCheckboxItem]',
hostDirectives: [
{
directive: HlmDropdownMenuCheckboxCdk,
inputs: ['cdkMenuItemDisabled: disabled', 'cdkMenuItemChecked: checked', 'keepOpen'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-checkbox-item',
'[attr.data-disabled]': '_cdkMenuItem.disabled ? "" : null',
'[attr.data-checked]': '_cdkMenuItem.checked ? "" : null',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuCheckbox {
protected readonly _cdkMenuItem = inject(HlmDropdownMenuCheckboxCdk);
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(
() =>
'hover:bg-accent focus:bg-accent hover:text-accent-foreground focus:text-accent-foreground hover:**:text-accent-foreground focus:**:text-accent-foreground gap-2.5 rounded-xl py-2 ps-3 pe-8 text-sm data-inset:ps-9.5 [&_ng-icon:not([class*=\'text-\'])]:text-[calc(var(--spacing)*4)] group/dropdown-menu-checkbox relative flex w-full cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0',
);
}
}
@Directive({
selector: '[hlmDropdownMenuGroup],hlm-dropdown-menu-group',
hostDirectives: [CdkMenuGroup],
host: { 'data-slot': 'dropdown-menu-group' },
})
export class HlmDropdownMenuGroup {
constructor() {
classes(() => 'block');
}
}
@Component({
selector: 'hlm-dropdown-menu-item-sub-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideChevronRight })],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ng-icon name="lucideChevronRight" class="text-[calc(var(--spacing)*4)] rtl:rotate-180" />
`,
})
export class HlmDropdownMenuItemSubIndicator {
constructor() {
classes(() => 'ms-auto flex items-center justify-center');
}
}
@Directive({
selector: '[hlmDropdownMenuItem],hlm-dropdown-menu-item',
hostDirectives: [
{
directive: CdkMenuItem,
inputs: ['cdkMenuItemDisabled: disabled'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-item',
'[attr.disabled]': '_isButton && disabled() ? "" : null',
'[attr.data-disabled]': 'disabled() ? "" : null',
'[attr.data-variant]': 'variant()',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuItem {
protected readonly _isButton = inject(HOST_TAG_NAME) === 'button';
public readonly disabled = input<boolean, BooleanInput>(false, { transform: booleanAttribute });
public readonly variant = input<'default' | 'destructive'>('default');
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(
() =>
'hover:bg-accent focus:bg-accent hover:text-accent-foreground focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[ng-icon]:text-destructive not-data-[variant=destructive]:hover:**:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground gap-2.5 rounded-xl px-3 py-2 text-sm data-inset:ps-9.5 [&_ng-icon:not([class*=\'text-\'])]:text-[calc(var(--spacing)*4)] group/dropdown-menu-item relative flex w-full cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0',
);
}
}
@Directive({
selector: '[hlmDropdownMenuLabel],hlm-dropdown-menu-label',
host: {
'data-slot': 'dropdown-menu-label',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuLabel {
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(() => 'text-muted-foreground px-3 py-2.5 text-xs data-inset:ps-9.5 block');
}
}
@Component({
selector: 'hlm-dropdown-menu-radio-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideCheck })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { 'data-slot': 'dropdown-menu-radio-item-indicator' },
template: `
<ng-icon name="lucideCheck" />
`,
})
export class HlmDropdownMenuRadioIndicator {
constructor() {
classes(
() =>
'absolute end-2 flex items-center justify-center [&_ng-icon]:text-[calc(var(--spacing)*4)] pointer-events-none opacity-0 group-data-checked/dropdown-menu-radio:opacity-100',
);
}
}
/** @internal. Use HlmDropdownMenuRadio instead. */
@Directive({
selector: '[hlmDropdownMenuRadioCdk]',
providers: [
{ provide: CdkMenuItemRadio, useExisting: HlmDropdownMenuRadioCdk },
{ provide: CdkMenuItemSelectable, useExisting: HlmDropdownMenuRadioCdk },
{ provide: CdkMenuItem, useExisting: CdkMenuItemSelectable },
],
})
export class HlmDropdownMenuRadioCdk extends CdkMenuItemRadio {
public readonly keepOpen = input<boolean, BooleanInput>(true, { transform: booleanAttribute });
public override trigger(options?: { keepOpen: boolean }) {
super.trigger({ ...options, keepOpen: this.keepOpen() });
}
}
@Directive({
selector: '[hlmDropdownMenuRadio]',
hostDirectives: [
{
directive: HlmDropdownMenuRadioCdk,
inputs: ['cdkMenuItemDisabled: disabled', 'cdkMenuItemChecked: checked', 'keepOpen'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-radio-item',
'[attr.data-disabled]': '_cdkMenuItem.disabled ? "" : null',
'[attr.data-checked]': '_cdkMenuItem.checked ? "" : null',
},
})
export class HlmDropdownMenuRadio {
protected readonly _cdkMenuItem = inject(HlmDropdownMenuRadioCdk);
constructor() {
classes(
() =>
'hover:bg-accent focus:bg-accent hover:text-accent-foreground focus:text-accent-foreground hover:**:text-accent-foreground focus:**:text-accent-foreground gap-2.5 rounded-xl py-2 ps-3 pe-8 text-sm data-inset:ps-9.5 [&_ng-icon:not([class*=\'text-\'])]:text-[calc(var(--spacing)*4)] group/dropdown-menu-radio relative flex w-full cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0',
);
}
}
@Directive({
selector: '[hlmDropdownMenuSeparator],hlm-dropdown-menu-separator',
host: { 'data-slot': 'dropdown-menu-separator' },
})
export class HlmDropdownMenuSeparator {
constructor() {
classes(() => 'bg-border/50 -mx-1 my-1 h-px block');
}
}
@Directive({
selector: '[hlmDropdownMenuShortcut],hlm-dropdown-menu-shortcut',
host: { 'data-slot': 'dropdown-menu-shortcut' },
})
export class HlmDropdownMenuShortcut {
constructor() {
classes(() => 'text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground ms-auto text-xs tracking-widest');
}
}
@Directive({
selector: '[hlmDropdownMenuSubTrigger]',
hostDirectives: [
{
directive: CdkMenuTrigger,
inputs: ['cdkMenuTriggerFor: hlmDropdownMenuSubTrigger', 'cdkMenuTriggerData: hlmDropdownMenuTriggerData'],
outputs: ['cdkMenuOpened: hlmDropdownMenuSubOpened', 'cdkMenuClosed: hlmDropdownMenuSubClosed'],
},
],
host: { 'data-slot': 'dropdown-menu-sub-trigger' },
})
export class HlmDropdownMenuSubTrigger {
private readonly _cdkTrigger = inject(CdkMenuTrigger, { host: true });
private readonly _config = injectHlmDropdownMenuConfig();
public readonly align = input<MenuAlign>(this._config.align);
public readonly side = input<MenuSide>(this._config.side);
private readonly _menuPosition = computed(() => createMenuPosition(this.align(), this.side()));
constructor() {
this._cdkTrigger.opened.pipe(takeUntilDestroyed()).subscribe(() =>
setTimeout(
() =>
// eslint-disable-next-line
((this._cdkTrigger as any)._spartanLastPosition = // eslint-disable-next-line
(this._cdkTrigger as any).overlayRef._positionStrategy._lastPosition),
),
);
effect(() => {
this._cdkTrigger.menuPosition = this._menuPosition();
});
classes(() => 'aria-expanded:bg-accent aria-expanded:text-accent-foreground');
}
}
@Directive({
selector: '[hlmDropdownMenuSub],hlm-dropdown-menu-sub',
hostDirectives: [CdkMenu],
host: {
'data-slot': 'dropdown-menu-sub',
'[attr.data-state]': '_state()',
'[attr.data-side]': '_side()',
},
})
export class HlmDropdownMenuSub {
private readonly _host = inject(CdkMenu);
protected readonly _state = signal('open');
protected readonly _side = signal('top');
constructor() {
this.setSideWithDarkMagic();
// this is a best effort, but does not seem to work currently
// TODO: figure out a way for us to know the host is about to be closed. might not be possible with CDK
this._host.closed.pipe(takeUntilDestroyed()).subscribe(() => this._state.set('closed'));
classes(() => 'data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/5 bg-popover text-popover-foreground min-w-36 rounded-2xl p-1 shadow-2xl ring-1 duration-100 w-auto');
}
private setSideWithDarkMagic() {
/**
* This is an ugly workaround to at least figure out the correct side of where a submenu
* will appear and set the attribute to the host accordingly
*
* First of all we take advantage of the menu stack not being aware of the root
* object immediately after it is added. This code executes before the root element is added,
* which means the stack is still empty and the peek method returns undefined.
*/
const isRoot = this._host.menuStack.peek() === undefined;
setTimeout(() => {
// our menu trigger directive leaves the last position used for use immediately after opening
// we can access it here and determine the correct side.
// eslint-disable-next-line
const ps = (this._host as any)._parentTrigger._spartanLastPosition;
if (!ps) {
// if we have no last position we default to the most likely option
// I hate that we have to do this and hope we can revisit soon and improve
this._side.set(isRoot ? 'top' : 'left');
return;
}
const side = isRoot ? ps.originY : ps.originX === 'end' ? 'right' : 'left';
this._side.set(side);
});
}
}
export interface HlmDropdownMenuConfig {
align: MenuAlign;
side: MenuSide;
}
const defaultConfig: HlmDropdownMenuConfig = {
align: 'start',
side: 'bottom',
};
const HlmDropdownMenuConfigToken = new InjectionToken<HlmDropdownMenuConfig>('HlmDropdownMenuConfig');
export function provideHlmDropdownMenuConfig(config: Partial<HlmDropdownMenuConfig>): ValueProvider {
return { provide: HlmDropdownMenuConfigToken, useValue: { ...defaultConfig, ...config } };
}
export function injectHlmDropdownMenuConfig(): HlmDropdownMenuConfig {
return inject(HlmDropdownMenuConfigToken, { optional: true }) ?? defaultConfig;
}
@Directive({
selector: '[hlmDropdownMenuTrigger]',
hostDirectives: [
{
directive: CdkMenuTrigger,
inputs: ['cdkMenuTriggerFor: hlmDropdownMenuTrigger', 'cdkMenuTriggerData: hlmDropdownMenuTriggerData'],
outputs: ['cdkMenuOpened: hlmDropdownMenuOpened', 'cdkMenuClosed: hlmDropdownMenuClosed'],
},
],
host: { 'data-slot': 'dropdown-menu-trigger' },
})
export class HlmDropdownMenuTrigger {
private readonly _cdkTrigger = inject(CdkMenuTrigger, { host: true });
private readonly _config = injectHlmDropdownMenuConfig();
public readonly align = input<MenuAlign>(this._config.align);
public readonly side = input<MenuSide>(this._config.side);
private readonly _menuPosition = computed(() => createMenuPosition(this.align(), this.side()));
constructor() {
// once the trigger opens we wait until the next tick and then grab the last position
// used to position the menu. we store this in our trigger which the brnMenu directive has
// access to through DI
this._cdkTrigger.opened.pipe(takeUntilDestroyed()).subscribe(() =>
setTimeout(
() =>
// eslint-disable-next-line
((this._cdkTrigger as any)._spartanLastPosition = // eslint-disable-next-line
(this._cdkTrigger as any).overlayRef._positionStrategy._lastPosition),
),
);
effect(() => {
this._cdkTrigger.menuPosition = this._menuPosition();
});
}
}
@Directive({
selector: '[hlmDropdownMenu],hlm-dropdown-menu',
hostDirectives: [CdkMenu],
host: {
'data-slot': 'dropdown-menu',
'[attr.data-state]': '_state()',
'[attr.data-side]': '_side()',
'[style.--side-offset]': 'sideOffset()',
},
})
export class HlmDropdownMenu {
private readonly _host = inject(CdkMenu);
protected readonly _state = signal('open');
protected readonly _side = signal('top');
public readonly sideOffset = input<number, NumberInput>(1, { transform: numberAttribute });
constructor() {
classes(
() =>
'data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/5 bg-popover text-popover-foreground dark:ring-foreground/10 min-w-48 rounded-2xl p-1 shadow-2xl ring-1 duration-100 my-[--spacing(var(--side-offset))] overflow-x-hidden overflow-y-auto outline-none',
);
this.setSideWithDarkMagic();
// this is a best effort, but does not seem to work currently
// TODO: figure out a way for us to know the host is about to be closed. might not be possible with CDK
this._host.closed.pipe(takeUntilDestroyed()).subscribe(() => this._state.set('closed'));
}
private setSideWithDarkMagic() {
/**
* This is an ugly workaround to at least figure out the correct side of where a submenu
* will appear and set the attribute to the host accordingly
*
* First of all we take advantage of the menu stack not being aware of the root
* object immediately after it is added. This code executes before the root element is added,
* which means the stack is still empty and the peek method returns undefined.
*/
const isRoot = this._host.menuStack.peek() === undefined;
setTimeout(() => {
// our menu trigger directive leaves the last position used for use immediately after opening
// we can access it here and determine the correct side.
// eslint-disable-next-line
const ps = (this._host as any)._parentTrigger._spartanLastPosition;
if (!ps) {
// if we have no last position we default to the most likely option
// I hate that we have to do this and hope we can revisit soon and improve
this._side.set(isRoot ? 'top' : 'left');
return;
}
const side = isRoot ? ps.originY : ps.originX === 'end' ? 'right' : 'left';
this._side.set(side);
});
}
}
export const HlmDropdownMenuImports = [
HlmDropdownMenu,
HlmDropdownMenuCheckbox,
HlmDropdownMenuCheckboxIndicator,
HlmDropdownMenuGroup,
HlmDropdownMenuItem,
HlmDropdownMenuItemSubIndicator,
HlmDropdownMenuLabel,
HlmDropdownMenuRadio,
HlmDropdownMenuRadioIndicator,
HlmDropdownMenuSeparator,
HlmDropdownMenuShortcut,
HlmDropdownMenuSub,
HlmDropdownMenuSubTrigger,
HlmDropdownMenuTrigger,
] as const;import { CdkMenu, CdkMenuGroup, CdkMenuItem, CdkMenuItemCheckbox, CdkMenuItemRadio, CdkMenuItemSelectable, CdkMenuTrigger } from '@angular/cdk/menu';
import { ChangeDetectionStrategy, Component, Directive, HOST_TAG_NAME, InjectionToken, booleanAttribute, computed, effect, inject, input, numberAttribute, signal, type ValueProvider } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { classes } from '@spartan-ng/helm/utils';
import { createMenuPosition, type MenuAlign, type MenuSide } from '@spartan-ng/brain/core';
import { lucideCheck, lucideChevronRight } from '@ng-icons/lucide';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { type BooleanInput, type NumberInput } from '@angular/cdk/coercion';
@Component({
selector: 'hlm-dropdown-menu-checkbox-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideCheck })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { 'data-slot': 'dropdown-menu-checkbox-item-indicator' },
template: `
<ng-icon name="lucideCheck" />
`,
})
export class HlmDropdownMenuCheckboxIndicator {
constructor() {
classes(
() =>
'absolute end-2 flex items-center justify-center [&_ng-icon]:text-[calc(var(--spacing)*3.5)] pointer-events-none opacity-0 group-data-checked/dropdown-menu-checkbox:opacity-100',
);
}
}
/** @internal. Use HlmDropdownMenuCheckbox instead. */
@Directive({
selector: '[hlmDropdownMenuCheckboxCdk]',
providers: [
{ provide: CdkMenuItemCheckbox, useExisting: HlmDropdownMenuCheckboxCdk },
{ provide: CdkMenuItemSelectable, useExisting: HlmDropdownMenuCheckboxCdk },
{ provide: CdkMenuItem, useExisting: CdkMenuItemSelectable },
],
})
export class HlmDropdownMenuCheckboxCdk extends CdkMenuItemCheckbox {
public readonly keepOpen = input<boolean, BooleanInput>(true, { transform: booleanAttribute });
public override trigger(options?: { keepOpen: boolean }) {
super.trigger({ ...options, keepOpen: this.keepOpen() });
}
}
@Directive({
selector: '[hlmDropdownMenuCheckbox],[hlmDropdownMenuCheckboxItem]',
hostDirectives: [
{
directive: HlmDropdownMenuCheckboxCdk,
inputs: ['cdkMenuItemDisabled: disabled', 'cdkMenuItemChecked: checked', 'keepOpen'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-checkbox-item',
'[attr.data-disabled]': '_cdkMenuItem.disabled ? "" : null',
'[attr.data-checked]': '_cdkMenuItem.checked ? "" : null',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuCheckbox {
protected readonly _cdkMenuItem = inject(HlmDropdownMenuCheckboxCdk);
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(
() =>
'hover:bg-accent focus:bg-accent hover:text-accent-foreground focus:text-accent-foreground hover:**:text-accent-foreground focus:**:text-accent-foreground min-h-7 gap-2 rounded-md py-1.5 ps-2 pe-8 text-xs data-inset:ps-7.5 [&_ng-icon:not([class*=\'text-\'])]:text-[calc(var(--spacing)*3.5)] group/dropdown-menu-checkbox relative flex w-full cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0',
);
}
}
@Directive({
selector: '[hlmDropdownMenuGroup],hlm-dropdown-menu-group',
hostDirectives: [CdkMenuGroup],
host: { 'data-slot': 'dropdown-menu-group' },
})
export class HlmDropdownMenuGroup {
constructor() {
classes(() => 'block');
}
}
@Component({
selector: 'hlm-dropdown-menu-item-sub-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideChevronRight })],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ng-icon name="lucideChevronRight" class="text-[calc(var(--spacing)*4)] rtl:rotate-180" />
`,
})
export class HlmDropdownMenuItemSubIndicator {
constructor() {
classes(() => 'ms-auto flex items-center justify-center');
}
}
@Directive({
selector: '[hlmDropdownMenuItem],hlm-dropdown-menu-item',
hostDirectives: [
{
directive: CdkMenuItem,
inputs: ['cdkMenuItemDisabled: disabled'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-item',
'[attr.disabled]': '_isButton && disabled() ? "" : null',
'[attr.data-disabled]': 'disabled() ? "" : null',
'[attr.data-variant]': 'variant()',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuItem {
protected readonly _isButton = inject(HOST_TAG_NAME) === 'button';
public readonly disabled = input<boolean, BooleanInput>(false, { transform: booleanAttribute });
public readonly variant = input<'default' | 'destructive'>('default');
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(
() =>
'hover:bg-accent focus:bg-accent hover:text-accent-foreground focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[ng-icon]:text-destructive not-data-[variant=destructive]:hover:**:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground min-h-7 gap-2 rounded-md px-2 py-1 text-xs/relaxed data-inset:ps-7.5 [&_ng-icon:not([class*=\'text-\'])]:text-[calc(var(--spacing)*3.5)] group/dropdown-menu-item relative flex w-full cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0',
);
}
}
@Directive({
selector: '[hlmDropdownMenuLabel],hlm-dropdown-menu-label',
host: {
'data-slot': 'dropdown-menu-label',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuLabel {
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(() => 'text-muted-foreground px-2 py-1.5 text-xs data-inset:ps-7.5 block');
}
}
@Component({
selector: 'hlm-dropdown-menu-radio-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideCheck })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { 'data-slot': 'dropdown-menu-radio-item-indicator' },
template: `
<ng-icon name="lucideCheck" />
`,
})
export class HlmDropdownMenuRadioIndicator {
constructor() {
classes(
() =>
'absolute end-2 flex items-center justify-center [&_ng-icon]:text-[calc(var(--spacing)*3.5)] pointer-events-none opacity-0 group-data-checked/dropdown-menu-radio:opacity-100',
);
}
}
/** @internal. Use HlmDropdownMenuRadio instead. */
@Directive({
selector: '[hlmDropdownMenuRadioCdk]',
providers: [
{ provide: CdkMenuItemRadio, useExisting: HlmDropdownMenuRadioCdk },
{ provide: CdkMenuItemSelectable, useExisting: HlmDropdownMenuRadioCdk },
{ provide: CdkMenuItem, useExisting: CdkMenuItemSelectable },
],
})
export class HlmDropdownMenuRadioCdk extends CdkMenuItemRadio {
public readonly keepOpen = input<boolean, BooleanInput>(true, { transform: booleanAttribute });
public override trigger(options?: { keepOpen: boolean }) {
super.trigger({ ...options, keepOpen: this.keepOpen() });
}
}
@Directive({
selector: '[hlmDropdownMenuRadio]',
hostDirectives: [
{
directive: HlmDropdownMenuRadioCdk,
inputs: ['cdkMenuItemDisabled: disabled', 'cdkMenuItemChecked: checked', 'keepOpen'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-radio-item',
'[attr.data-disabled]': '_cdkMenuItem.disabled ? "" : null',
'[attr.data-checked]': '_cdkMenuItem.checked ? "" : null',
},
})
export class HlmDropdownMenuRadio {
protected readonly _cdkMenuItem = inject(HlmDropdownMenuRadioCdk);
constructor() {
classes(
() =>
'hover:bg-accent focus:bg-accent hover:text-accent-foreground focus:text-accent-foreground hover:**:text-accent-foreground focus:**:text-accent-foreground min-h-7 gap-2 rounded-md py-1.5 ps-2 pe-8 text-xs data-inset:ps-7.5 [&_ng-icon:not([class*=\'text-\'])]:text-[calc(var(--spacing)*3.5)] group/dropdown-menu-radio relative flex w-full cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0',
);
}
}
@Directive({
selector: '[hlmDropdownMenuSeparator],hlm-dropdown-menu-separator',
host: { 'data-slot': 'dropdown-menu-separator' },
})
export class HlmDropdownMenuSeparator {
constructor() {
classes(() => 'bg-border/50 -mx-1 my-1 h-px block');
}
}
@Directive({
selector: '[hlmDropdownMenuShortcut],hlm-dropdown-menu-shortcut',
host: { 'data-slot': 'dropdown-menu-shortcut' },
})
export class HlmDropdownMenuShortcut {
constructor() {
classes(() => 'text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground ms-auto text-[0.625rem] tracking-widest');
}
}
@Directive({
selector: '[hlmDropdownMenuSubTrigger]',
hostDirectives: [
{
directive: CdkMenuTrigger,
inputs: ['cdkMenuTriggerFor: hlmDropdownMenuSubTrigger', 'cdkMenuTriggerData: hlmDropdownMenuTriggerData'],
outputs: ['cdkMenuOpened: hlmDropdownMenuSubOpened', 'cdkMenuClosed: hlmDropdownMenuSubClosed'],
},
],
host: { 'data-slot': 'dropdown-menu-sub-trigger' },
})
export class HlmDropdownMenuSubTrigger {
private readonly _cdkTrigger = inject(CdkMenuTrigger, { host: true });
private readonly _config = injectHlmDropdownMenuConfig();
public readonly align = input<MenuAlign>(this._config.align);
public readonly side = input<MenuSide>(this._config.side);
private readonly _menuPosition = computed(() => createMenuPosition(this.align(), this.side()));
constructor() {
this._cdkTrigger.opened.pipe(takeUntilDestroyed()).subscribe(() =>
setTimeout(
() =>
// eslint-disable-next-line
((this._cdkTrigger as any)._spartanLastPosition = // eslint-disable-next-line
(this._cdkTrigger as any).overlayRef._positionStrategy._lastPosition),
),
);
effect(() => {
this._cdkTrigger.menuPosition = this._menuPosition();
});
classes(() => 'aria-expanded:bg-accent aria-expanded:text-accent-foreground');
}
}
@Directive({
selector: '[hlmDropdownMenuSub],hlm-dropdown-menu-sub',
hostDirectives: [CdkMenu],
host: {
'data-slot': 'dropdown-menu-sub',
'[attr.data-state]': '_state()',
'[attr.data-side]': '_side()',
},
})
export class HlmDropdownMenuSub {
private readonly _host = inject(CdkMenu);
protected readonly _state = signal('open');
protected readonly _side = signal('top');
constructor() {
this.setSideWithDarkMagic();
// this is a best effort, but does not seem to work currently
// TODO: figure out a way for us to know the host is about to be closed. might not be possible with CDK
this._host.closed.pipe(takeUntilDestroyed()).subscribe(() => this._state.set('closed'));
classes(() => 'data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 bg-popover text-popover-foreground min-w-32 rounded-lg p-1 shadow-md ring-1 duration-100 w-auto');
}
private setSideWithDarkMagic() {
/**
* This is an ugly workaround to at least figure out the correct side of where a submenu
* will appear and set the attribute to the host accordingly
*
* First of all we take advantage of the menu stack not being aware of the root
* object immediately after it is added. This code executes before the root element is added,
* which means the stack is still empty and the peek method returns undefined.
*/
const isRoot = this._host.menuStack.peek() === undefined;
setTimeout(() => {
// our menu trigger directive leaves the last position used for use immediately after opening
// we can access it here and determine the correct side.
// eslint-disable-next-line
const ps = (this._host as any)._parentTrigger._spartanLastPosition;
if (!ps) {
// if we have no last position we default to the most likely option
// I hate that we have to do this and hope we can revisit soon and improve
this._side.set(isRoot ? 'top' : 'left');
return;
}
const side = isRoot ? ps.originY : ps.originX === 'end' ? 'right' : 'left';
this._side.set(side);
});
}
}
export interface HlmDropdownMenuConfig {
align: MenuAlign;
side: MenuSide;
}
const defaultConfig: HlmDropdownMenuConfig = {
align: 'start',
side: 'bottom',
};
const HlmDropdownMenuConfigToken = new InjectionToken<HlmDropdownMenuConfig>('HlmDropdownMenuConfig');
export function provideHlmDropdownMenuConfig(config: Partial<HlmDropdownMenuConfig>): ValueProvider {
return { provide: HlmDropdownMenuConfigToken, useValue: { ...defaultConfig, ...config } };
}
export function injectHlmDropdownMenuConfig(): HlmDropdownMenuConfig {
return inject(HlmDropdownMenuConfigToken, { optional: true }) ?? defaultConfig;
}
@Directive({
selector: '[hlmDropdownMenuTrigger]',
hostDirectives: [
{
directive: CdkMenuTrigger,
inputs: ['cdkMenuTriggerFor: hlmDropdownMenuTrigger', 'cdkMenuTriggerData: hlmDropdownMenuTriggerData'],
outputs: ['cdkMenuOpened: hlmDropdownMenuOpened', 'cdkMenuClosed: hlmDropdownMenuClosed'],
},
],
host: { 'data-slot': 'dropdown-menu-trigger' },
})
export class HlmDropdownMenuTrigger {
private readonly _cdkTrigger = inject(CdkMenuTrigger, { host: true });
private readonly _config = injectHlmDropdownMenuConfig();
public readonly align = input<MenuAlign>(this._config.align);
public readonly side = input<MenuSide>(this._config.side);
private readonly _menuPosition = computed(() => createMenuPosition(this.align(), this.side()));
constructor() {
// once the trigger opens we wait until the next tick and then grab the last position
// used to position the menu. we store this in our trigger which the brnMenu directive has
// access to through DI
this._cdkTrigger.opened.pipe(takeUntilDestroyed()).subscribe(() =>
setTimeout(
() =>
// eslint-disable-next-line
((this._cdkTrigger as any)._spartanLastPosition = // eslint-disable-next-line
(this._cdkTrigger as any).overlayRef._positionStrategy._lastPosition),
),
);
effect(() => {
this._cdkTrigger.menuPosition = this._menuPosition();
});
}
}
@Directive({
selector: '[hlmDropdownMenu],hlm-dropdown-menu',
hostDirectives: [CdkMenu],
host: {
'data-slot': 'dropdown-menu',
'[attr.data-state]': '_state()',
'[attr.data-side]': '_side()',
'[style.--side-offset]': 'sideOffset()',
},
})
export class HlmDropdownMenu {
private readonly _host = inject(CdkMenu);
protected readonly _state = signal('open');
protected readonly _side = signal('top');
public readonly sideOffset = input<number, NumberInput>(1, { transform: numberAttribute });
constructor() {
classes(
() =>
'data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 bg-popover text-popover-foreground min-w-32 rounded-lg p-1 shadow-md ring-1 duration-100 my-[--spacing(var(--side-offset))] overflow-x-hidden overflow-y-auto outline-none',
);
this.setSideWithDarkMagic();
// this is a best effort, but does not seem to work currently
// TODO: figure out a way for us to know the host is about to be closed. might not be possible with CDK
this._host.closed.pipe(takeUntilDestroyed()).subscribe(() => this._state.set('closed'));
}
private setSideWithDarkMagic() {
/**
* This is an ugly workaround to at least figure out the correct side of where a submenu
* will appear and set the attribute to the host accordingly
*
* First of all we take advantage of the menu stack not being aware of the root
* object immediately after it is added. This code executes before the root element is added,
* which means the stack is still empty and the peek method returns undefined.
*/
const isRoot = this._host.menuStack.peek() === undefined;
setTimeout(() => {
// our menu trigger directive leaves the last position used for use immediately after opening
// we can access it here and determine the correct side.
// eslint-disable-next-line
const ps = (this._host as any)._parentTrigger._spartanLastPosition;
if (!ps) {
// if we have no last position we default to the most likely option
// I hate that we have to do this and hope we can revisit soon and improve
this._side.set(isRoot ? 'top' : 'left');
return;
}
const side = isRoot ? ps.originY : ps.originX === 'end' ? 'right' : 'left';
this._side.set(side);
});
}
}
export const HlmDropdownMenuImports = [
HlmDropdownMenu,
HlmDropdownMenuCheckbox,
HlmDropdownMenuCheckboxIndicator,
HlmDropdownMenuGroup,
HlmDropdownMenuItem,
HlmDropdownMenuItemSubIndicator,
HlmDropdownMenuLabel,
HlmDropdownMenuRadio,
HlmDropdownMenuRadioIndicator,
HlmDropdownMenuSeparator,
HlmDropdownMenuShortcut,
HlmDropdownMenuSub,
HlmDropdownMenuSubTrigger,
HlmDropdownMenuTrigger,
] as const;import { CdkMenu, CdkMenuGroup, CdkMenuItem, CdkMenuItemCheckbox, CdkMenuItemRadio, CdkMenuItemSelectable, CdkMenuTrigger } from '@angular/cdk/menu';
import { ChangeDetectionStrategy, Component, Directive, HOST_TAG_NAME, InjectionToken, booleanAttribute, computed, effect, inject, input, numberAttribute, signal, type ValueProvider } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { classes } from '@spartan-ng/helm/utils';
import { createMenuPosition, type MenuAlign, type MenuSide } from '@spartan-ng/brain/core';
import { lucideCheck, lucideChevronRight } from '@ng-icons/lucide';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { type BooleanInput, type NumberInput } from '@angular/cdk/coercion';
@Component({
selector: 'hlm-dropdown-menu-checkbox-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideCheck })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { 'data-slot': 'dropdown-menu-checkbox-item-indicator' },
template: `
<ng-icon name="lucideCheck" />
`,
})
export class HlmDropdownMenuCheckboxIndicator {
constructor() {
classes(
() =>
'absolute end-2 flex items-center justify-center [&_ng-icon]:text-[calc(var(--spacing)*4)] pointer-events-none opacity-0 group-data-checked/dropdown-menu-checkbox:opacity-100',
);
}
}
/** @internal. Use HlmDropdownMenuCheckbox instead. */
@Directive({
selector: '[hlmDropdownMenuCheckboxCdk]',
providers: [
{ provide: CdkMenuItemCheckbox, useExisting: HlmDropdownMenuCheckboxCdk },
{ provide: CdkMenuItemSelectable, useExisting: HlmDropdownMenuCheckboxCdk },
{ provide: CdkMenuItem, useExisting: CdkMenuItemSelectable },
],
})
export class HlmDropdownMenuCheckboxCdk extends CdkMenuItemCheckbox {
public readonly keepOpen = input<boolean, BooleanInput>(true, { transform: booleanAttribute });
public override trigger(options?: { keepOpen: boolean }) {
super.trigger({ ...options, keepOpen: this.keepOpen() });
}
}
@Directive({
selector: '[hlmDropdownMenuCheckbox],[hlmDropdownMenuCheckboxItem]',
hostDirectives: [
{
directive: HlmDropdownMenuCheckboxCdk,
inputs: ['cdkMenuItemDisabled: disabled', 'cdkMenuItemChecked: checked', 'keepOpen'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-checkbox-item',
'[attr.data-disabled]': '_cdkMenuItem.disabled ? "" : null',
'[attr.data-checked]': '_cdkMenuItem.checked ? "" : null',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuCheckbox {
protected readonly _cdkMenuItem = inject(HlmDropdownMenuCheckboxCdk);
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(
() =>
'hover:bg-accent focus:bg-accent hover:text-accent-foreground focus:text-accent-foreground hover:**:text-accent-foreground focus:**:text-accent-foreground gap-1.5 rounded-md py-1 ps-1.5 pe-8 text-sm data-inset:ps-7 [&_ng-icon:not([class*=\'text-\'])]:text-[calc(var(--spacing)*4)] group/dropdown-menu-checkbox relative flex w-full cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0',
);
}
}
@Directive({
selector: '[hlmDropdownMenuGroup],hlm-dropdown-menu-group',
hostDirectives: [CdkMenuGroup],
host: { 'data-slot': 'dropdown-menu-group' },
})
export class HlmDropdownMenuGroup {
constructor() {
classes(() => 'block');
}
}
@Component({
selector: 'hlm-dropdown-menu-item-sub-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideChevronRight })],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ng-icon name="lucideChevronRight" class="text-[calc(var(--spacing)*4)] rtl:rotate-180" />
`,
})
export class HlmDropdownMenuItemSubIndicator {
constructor() {
classes(() => 'ms-auto flex items-center justify-center');
}
}
@Directive({
selector: '[hlmDropdownMenuItem],hlm-dropdown-menu-item',
hostDirectives: [
{
directive: CdkMenuItem,
inputs: ['cdkMenuItemDisabled: disabled'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-item',
'[attr.disabled]': '_isButton && disabled() ? "" : null',
'[attr.data-disabled]': 'disabled() ? "" : null',
'[attr.data-variant]': 'variant()',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuItem {
protected readonly _isButton = inject(HOST_TAG_NAME) === 'button';
public readonly disabled = input<boolean, BooleanInput>(false, { transform: booleanAttribute });
public readonly variant = input<'default' | 'destructive'>('default');
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(
() =>
'hover:bg-accent focus:bg-accent hover:text-accent-foreground focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[ng-icon]:text-destructive not-data-[variant=destructive]:hover:**:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground gap-1.5 rounded-md px-1.5 py-1 text-sm data-inset:ps-7 [&_ng-icon:not([class*=\'text-\'])]:text-[calc(var(--spacing)*4)] group/dropdown-menu-item relative flex w-full cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0',
);
}
}
@Directive({
selector: '[hlmDropdownMenuLabel],hlm-dropdown-menu-label',
host: {
'data-slot': 'dropdown-menu-label',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuLabel {
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(() => 'text-muted-foreground px-1.5 py-1 text-xs font-medium data-inset:ps-7 block');
}
}
@Component({
selector: 'hlm-dropdown-menu-radio-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideCheck })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { 'data-slot': 'dropdown-menu-radio-item-indicator' },
template: `
<ng-icon name="lucideCheck" />
`,
})
export class HlmDropdownMenuRadioIndicator {
constructor() {
classes(
() =>
'absolute end-2 flex items-center justify-center [&_ng-icon]:text-[calc(var(--spacing)*4)] pointer-events-none opacity-0 group-data-checked/dropdown-menu-radio:opacity-100',
);
}
}
/** @internal. Use HlmDropdownMenuRadio instead. */
@Directive({
selector: '[hlmDropdownMenuRadioCdk]',
providers: [
{ provide: CdkMenuItemRadio, useExisting: HlmDropdownMenuRadioCdk },
{ provide: CdkMenuItemSelectable, useExisting: HlmDropdownMenuRadioCdk },
{ provide: CdkMenuItem, useExisting: CdkMenuItemSelectable },
],
})
export class HlmDropdownMenuRadioCdk extends CdkMenuItemRadio {
public readonly keepOpen = input<boolean, BooleanInput>(true, { transform: booleanAttribute });
public override trigger(options?: { keepOpen: boolean }) {
super.trigger({ ...options, keepOpen: this.keepOpen() });
}
}
@Directive({
selector: '[hlmDropdownMenuRadio]',
hostDirectives: [
{
directive: HlmDropdownMenuRadioCdk,
inputs: ['cdkMenuItemDisabled: disabled', 'cdkMenuItemChecked: checked', 'keepOpen'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-radio-item',
'[attr.data-disabled]': '_cdkMenuItem.disabled ? "" : null',
'[attr.data-checked]': '_cdkMenuItem.checked ? "" : null',
},
})
export class HlmDropdownMenuRadio {
protected readonly _cdkMenuItem = inject(HlmDropdownMenuRadioCdk);
constructor() {
classes(
() =>
'hover:bg-accent focus:bg-accent hover:text-accent-foreground focus:text-accent-foreground hover:**:text-accent-foreground focus:**:text-accent-foreground gap-1.5 rounded-md py-1 ps-1.5 pe-8 text-sm data-inset:ps-7 [&_ng-icon:not([class*=\'text-\'])]:text-[calc(var(--spacing)*4)] group/dropdown-menu-radio relative flex w-full cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0',
);
}
}
@Directive({
selector: '[hlmDropdownMenuSeparator],hlm-dropdown-menu-separator',
host: { 'data-slot': 'dropdown-menu-separator' },
})
export class HlmDropdownMenuSeparator {
constructor() {
classes(() => 'bg-border -mx-1 my-1 h-px block');
}
}
@Directive({
selector: '[hlmDropdownMenuShortcut],hlm-dropdown-menu-shortcut',
host: { 'data-slot': 'dropdown-menu-shortcut' },
})
export class HlmDropdownMenuShortcut {
constructor() {
classes(() => 'text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground ms-auto text-xs tracking-widest');
}
}
@Directive({
selector: '[hlmDropdownMenuSubTrigger]',
hostDirectives: [
{
directive: CdkMenuTrigger,
inputs: ['cdkMenuTriggerFor: hlmDropdownMenuSubTrigger', 'cdkMenuTriggerData: hlmDropdownMenuTriggerData'],
outputs: ['cdkMenuOpened: hlmDropdownMenuSubOpened', 'cdkMenuClosed: hlmDropdownMenuSubClosed'],
},
],
host: { 'data-slot': 'dropdown-menu-sub-trigger' },
})
export class HlmDropdownMenuSubTrigger {
private readonly _cdkTrigger = inject(CdkMenuTrigger, { host: true });
private readonly _config = injectHlmDropdownMenuConfig();
public readonly align = input<MenuAlign>(this._config.align);
public readonly side = input<MenuSide>(this._config.side);
private readonly _menuPosition = computed(() => createMenuPosition(this.align(), this.side()));
constructor() {
this._cdkTrigger.opened.pipe(takeUntilDestroyed()).subscribe(() =>
setTimeout(
() =>
// eslint-disable-next-line
((this._cdkTrigger as any)._spartanLastPosition = // eslint-disable-next-line
(this._cdkTrigger as any).overlayRef._positionStrategy._lastPosition),
),
);
effect(() => {
this._cdkTrigger.menuPosition = this._menuPosition();
});
classes(() => 'aria-expanded:bg-accent aria-expanded:text-accent-foreground');
}
}
@Directive({
selector: '[hlmDropdownMenuSub],hlm-dropdown-menu-sub',
hostDirectives: [CdkMenu],
host: {
'data-slot': 'dropdown-menu-sub',
'[attr.data-state]': '_state()',
'[attr.data-side]': '_side()',
},
})
export class HlmDropdownMenuSub {
private readonly _host = inject(CdkMenu);
protected readonly _state = signal('open');
protected readonly _side = signal('top');
constructor() {
this.setSideWithDarkMagic();
// this is a best effort, but does not seem to work currently
// TODO: figure out a way for us to know the host is about to be closed. might not be possible with CDK
this._host.closed.pipe(takeUntilDestroyed()).subscribe(() => this._state.set('closed'));
classes(() => 'data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 bg-popover text-popover-foreground min-w-24 rounded-lg p-1 shadow-lg ring-1 duration-100 w-auto');
}
private setSideWithDarkMagic() {
/**
* This is an ugly workaround to at least figure out the correct side of where a submenu
* will appear and set the attribute to the host accordingly
*
* First of all we take advantage of the menu stack not being aware of the root
* object immediately after it is added. This code executes before the root element is added,
* which means the stack is still empty and the peek method returns undefined.
*/
const isRoot = this._host.menuStack.peek() === undefined;
setTimeout(() => {
// our menu trigger directive leaves the last position used for use immediately after opening
// we can access it here and determine the correct side.
// eslint-disable-next-line
const ps = (this._host as any)._parentTrigger._spartanLastPosition;
if (!ps) {
// if we have no last position we default to the most likely option
// I hate that we have to do this and hope we can revisit soon and improve
this._side.set(isRoot ? 'top' : 'left');
return;
}
const side = isRoot ? ps.originY : ps.originX === 'end' ? 'right' : 'left';
this._side.set(side);
});
}
}
export interface HlmDropdownMenuConfig {
align: MenuAlign;
side: MenuSide;
}
const defaultConfig: HlmDropdownMenuConfig = {
align: 'start',
side: 'bottom',
};
const HlmDropdownMenuConfigToken = new InjectionToken<HlmDropdownMenuConfig>('HlmDropdownMenuConfig');
export function provideHlmDropdownMenuConfig(config: Partial<HlmDropdownMenuConfig>): ValueProvider {
return { provide: HlmDropdownMenuConfigToken, useValue: { ...defaultConfig, ...config } };
}
export function injectHlmDropdownMenuConfig(): HlmDropdownMenuConfig {
return inject(HlmDropdownMenuConfigToken, { optional: true }) ?? defaultConfig;
}
@Directive({
selector: '[hlmDropdownMenuTrigger]',
hostDirectives: [
{
directive: CdkMenuTrigger,
inputs: ['cdkMenuTriggerFor: hlmDropdownMenuTrigger', 'cdkMenuTriggerData: hlmDropdownMenuTriggerData'],
outputs: ['cdkMenuOpened: hlmDropdownMenuOpened', 'cdkMenuClosed: hlmDropdownMenuClosed'],
},
],
host: { 'data-slot': 'dropdown-menu-trigger' },
})
export class HlmDropdownMenuTrigger {
private readonly _cdkTrigger = inject(CdkMenuTrigger, { host: true });
private readonly _config = injectHlmDropdownMenuConfig();
public readonly align = input<MenuAlign>(this._config.align);
public readonly side = input<MenuSide>(this._config.side);
private readonly _menuPosition = computed(() => createMenuPosition(this.align(), this.side()));
constructor() {
// once the trigger opens we wait until the next tick and then grab the last position
// used to position the menu. we store this in our trigger which the brnMenu directive has
// access to through DI
this._cdkTrigger.opened.pipe(takeUntilDestroyed()).subscribe(() =>
setTimeout(
() =>
// eslint-disable-next-line
((this._cdkTrigger as any)._spartanLastPosition = // eslint-disable-next-line
(this._cdkTrigger as any).overlayRef._positionStrategy._lastPosition),
),
);
effect(() => {
this._cdkTrigger.menuPosition = this._menuPosition();
});
}
}
@Directive({
selector: '[hlmDropdownMenu],hlm-dropdown-menu',
hostDirectives: [CdkMenu],
host: {
'data-slot': 'dropdown-menu',
'[attr.data-state]': '_state()',
'[attr.data-side]': '_side()',
'[style.--side-offset]': 'sideOffset()',
},
})
export class HlmDropdownMenu {
private readonly _host = inject(CdkMenu);
protected readonly _state = signal('open');
protected readonly _side = signal('top');
public readonly sideOffset = input<number, NumberInput>(1, { transform: numberAttribute });
constructor() {
classes(
() =>
'data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 bg-popover text-popover-foreground min-w-32 rounded-lg p-1 shadow-md ring-1 duration-100 my-[--spacing(var(--side-offset))] overflow-x-hidden overflow-y-auto outline-none',
);
this.setSideWithDarkMagic();
// this is a best effort, but does not seem to work currently
// TODO: figure out a way for us to know the host is about to be closed. might not be possible with CDK
this._host.closed.pipe(takeUntilDestroyed()).subscribe(() => this._state.set('closed'));
}
private setSideWithDarkMagic() {
/**
* This is an ugly workaround to at least figure out the correct side of where a submenu
* will appear and set the attribute to the host accordingly
*
* First of all we take advantage of the menu stack not being aware of the root
* object immediately after it is added. This code executes before the root element is added,
* which means the stack is still empty and the peek method returns undefined.
*/
const isRoot = this._host.menuStack.peek() === undefined;
setTimeout(() => {
// our menu trigger directive leaves the last position used for use immediately after opening
// we can access it here and determine the correct side.
// eslint-disable-next-line
const ps = (this._host as any)._parentTrigger._spartanLastPosition;
if (!ps) {
// if we have no last position we default to the most likely option
// I hate that we have to do this and hope we can revisit soon and improve
this._side.set(isRoot ? 'top' : 'left');
return;
}
const side = isRoot ? ps.originY : ps.originX === 'end' ? 'right' : 'left';
this._side.set(side);
});
}
}
export const HlmDropdownMenuImports = [
HlmDropdownMenu,
HlmDropdownMenuCheckbox,
HlmDropdownMenuCheckboxIndicator,
HlmDropdownMenuGroup,
HlmDropdownMenuItem,
HlmDropdownMenuItemSubIndicator,
HlmDropdownMenuLabel,
HlmDropdownMenuRadio,
HlmDropdownMenuRadioIndicator,
HlmDropdownMenuSeparator,
HlmDropdownMenuShortcut,
HlmDropdownMenuSub,
HlmDropdownMenuSubTrigger,
HlmDropdownMenuTrigger,
] as const;import { CdkMenu, CdkMenuGroup, CdkMenuItem, CdkMenuItemCheckbox, CdkMenuItemRadio, CdkMenuItemSelectable, CdkMenuTrigger } from '@angular/cdk/menu';
import { ChangeDetectionStrategy, Component, Directive, HOST_TAG_NAME, InjectionToken, booleanAttribute, computed, effect, inject, input, numberAttribute, signal, type ValueProvider } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { classes } from '@spartan-ng/helm/utils';
import { createMenuPosition, type MenuAlign, type MenuSide } from '@spartan-ng/brain/core';
import { lucideCheck, lucideChevronRight } from '@ng-icons/lucide';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { type BooleanInput, type NumberInput } from '@angular/cdk/coercion';
@Component({
selector: 'hlm-dropdown-menu-checkbox-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideCheck })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { 'data-slot': 'dropdown-menu-checkbox-item-indicator' },
template: `
<ng-icon name="lucideCheck" />
`,
})
export class HlmDropdownMenuCheckboxIndicator {
constructor() {
classes(
() =>
'absolute end-2 flex items-center justify-center [&_ng-icon]:text-[calc(var(--spacing)*4)] pointer-events-none opacity-0 group-data-checked/dropdown-menu-checkbox:opacity-100',
);
}
}
/** @internal. Use HlmDropdownMenuCheckbox instead. */
@Directive({
selector: '[hlmDropdownMenuCheckboxCdk]',
providers: [
{ provide: CdkMenuItemCheckbox, useExisting: HlmDropdownMenuCheckboxCdk },
{ provide: CdkMenuItemSelectable, useExisting: HlmDropdownMenuCheckboxCdk },
{ provide: CdkMenuItem, useExisting: CdkMenuItemSelectable },
],
})
export class HlmDropdownMenuCheckboxCdk extends CdkMenuItemCheckbox {
public readonly keepOpen = input<boolean, BooleanInput>(true, { transform: booleanAttribute });
public override trigger(options?: { keepOpen: boolean }) {
super.trigger({ ...options, keepOpen: this.keepOpen() });
}
}
@Directive({
selector: '[hlmDropdownMenuCheckbox],[hlmDropdownMenuCheckboxItem]',
hostDirectives: [
{
directive: HlmDropdownMenuCheckboxCdk,
inputs: ['cdkMenuItemDisabled: disabled', 'cdkMenuItemChecked: checked', 'keepOpen'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-checkbox-item',
'[attr.data-disabled]': '_cdkMenuItem.disabled ? "" : null',
'[attr.data-checked]': '_cdkMenuItem.checked ? "" : null',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuCheckbox {
protected readonly _cdkMenuItem = inject(HlmDropdownMenuCheckboxCdk);
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(
() =>
'hover:bg-accent focus:bg-accent hover:text-accent-foreground focus:text-accent-foreground hover:**:text-accent-foreground focus:**:text-accent-foreground gap-2.5 rounded-2xl py-2 ps-3 pe-8 text-sm font-medium data-inset:ps-9.5 [&_ng-icon:not([class*=\'text-\'])]:text-[calc(var(--spacing)*4)] group/dropdown-menu-checkbox relative flex w-full cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0',
);
}
}
@Directive({
selector: '[hlmDropdownMenuGroup],hlm-dropdown-menu-group',
hostDirectives: [CdkMenuGroup],
host: { 'data-slot': 'dropdown-menu-group' },
})
export class HlmDropdownMenuGroup {
constructor() {
classes(() => 'block');
}
}
@Component({
selector: 'hlm-dropdown-menu-item-sub-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideChevronRight })],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ng-icon name="lucideChevronRight" class="text-[calc(var(--spacing)*4)] rtl:rotate-180" />
`,
})
export class HlmDropdownMenuItemSubIndicator {
constructor() {
classes(() => 'ms-auto flex items-center justify-center');
}
}
@Directive({
selector: '[hlmDropdownMenuItem],hlm-dropdown-menu-item',
hostDirectives: [
{
directive: CdkMenuItem,
inputs: ['cdkMenuItemDisabled: disabled'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-item',
'[attr.disabled]': '_isButton && disabled() ? "" : null',
'[attr.data-disabled]': 'disabled() ? "" : null',
'[attr.data-variant]': 'variant()',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuItem {
protected readonly _isButton = inject(HOST_TAG_NAME) === 'button';
public readonly disabled = input<boolean, BooleanInput>(false, { transform: booleanAttribute });
public readonly variant = input<'default' | 'destructive'>('default');
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(
() =>
'hover:bg-accent focus:bg-accent hover:text-accent-foreground focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[ng-icon]:text-destructive not-data-[variant=destructive]:hover:**:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground gap-2.5 rounded-2xl px-3 py-2 text-sm font-medium data-inset:ps-9.5 [&_ng-icon:not([class*=\'text-\'])]:text-[calc(var(--spacing)*4)] group/dropdown-menu-item relative flex w-full cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0',
);
}
}
@Directive({
selector: '[hlmDropdownMenuLabel],hlm-dropdown-menu-label',
host: {
'data-slot': 'dropdown-menu-label',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuLabel {
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(() => 'text-muted-foreground px-3 py-2.5 text-xs data-inset:ps-9.5 block');
}
}
@Component({
selector: 'hlm-dropdown-menu-radio-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideCheck })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { 'data-slot': 'dropdown-menu-radio-item-indicator' },
template: `
<ng-icon name="lucideCheck" />
`,
})
export class HlmDropdownMenuRadioIndicator {
constructor() {
classes(
() =>
'absolute end-2 flex items-center justify-center [&_ng-icon]:text-[calc(var(--spacing)*4)] pointer-events-none opacity-0 group-data-checked/dropdown-menu-radio:opacity-100',
);
}
}
/** @internal. Use HlmDropdownMenuRadio instead. */
@Directive({
selector: '[hlmDropdownMenuRadioCdk]',
providers: [
{ provide: CdkMenuItemRadio, useExisting: HlmDropdownMenuRadioCdk },
{ provide: CdkMenuItemSelectable, useExisting: HlmDropdownMenuRadioCdk },
{ provide: CdkMenuItem, useExisting: CdkMenuItemSelectable },
],
})
export class HlmDropdownMenuRadioCdk extends CdkMenuItemRadio {
public readonly keepOpen = input<boolean, BooleanInput>(true, { transform: booleanAttribute });
public override trigger(options?: { keepOpen: boolean }) {
super.trigger({ ...options, keepOpen: this.keepOpen() });
}
}
@Directive({
selector: '[hlmDropdownMenuRadio]',
hostDirectives: [
{
directive: HlmDropdownMenuRadioCdk,
inputs: ['cdkMenuItemDisabled: disabled', 'cdkMenuItemChecked: checked', 'keepOpen'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-radio-item',
'[attr.data-disabled]': '_cdkMenuItem.disabled ? "" : null',
'[attr.data-checked]': '_cdkMenuItem.checked ? "" : null',
},
})
export class HlmDropdownMenuRadio {
protected readonly _cdkMenuItem = inject(HlmDropdownMenuRadioCdk);
constructor() {
classes(
() =>
'hover:bg-accent focus:bg-accent hover:text-accent-foreground focus:text-accent-foreground hover:**:text-accent-foreground focus:**:text-accent-foreground gap-2.5 rounded-2xl py-2 ps-3 pe-8 text-sm font-medium data-inset:ps-9.5 [&_ng-icon:not([class*=\'text-\'])]:text-[calc(var(--spacing)*4)] group/dropdown-menu-radio relative flex w-full cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0',
);
}
}
@Directive({
selector: '[hlmDropdownMenuSeparator],hlm-dropdown-menu-separator',
host: { 'data-slot': 'dropdown-menu-separator' },
})
export class HlmDropdownMenuSeparator {
constructor() {
classes(() => 'bg-border/50 -mx-1.5 my-1.5 h-px block');
}
}
@Directive({
selector: '[hlmDropdownMenuShortcut],hlm-dropdown-menu-shortcut',
host: { 'data-slot': 'dropdown-menu-shortcut' },
})
export class HlmDropdownMenuShortcut {
constructor() {
classes(() => 'text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground ms-auto text-xs tracking-widest');
}
}
@Directive({
selector: '[hlmDropdownMenuSubTrigger]',
hostDirectives: [
{
directive: CdkMenuTrigger,
inputs: ['cdkMenuTriggerFor: hlmDropdownMenuSubTrigger', 'cdkMenuTriggerData: hlmDropdownMenuTriggerData'],
outputs: ['cdkMenuOpened: hlmDropdownMenuSubOpened', 'cdkMenuClosed: hlmDropdownMenuSubClosed'],
},
],
host: { 'data-slot': 'dropdown-menu-sub-trigger' },
})
export class HlmDropdownMenuSubTrigger {
private readonly _cdkTrigger = inject(CdkMenuTrigger, { host: true });
private readonly _config = injectHlmDropdownMenuConfig();
public readonly align = input<MenuAlign>(this._config.align);
public readonly side = input<MenuSide>(this._config.side);
private readonly _menuPosition = computed(() => createMenuPosition(this.align(), this.side()));
constructor() {
this._cdkTrigger.opened.pipe(takeUntilDestroyed()).subscribe(() =>
setTimeout(
() =>
// eslint-disable-next-line
((this._cdkTrigger as any)._spartanLastPosition = // eslint-disable-next-line
(this._cdkTrigger as any).overlayRef._positionStrategy._lastPosition),
),
);
effect(() => {
this._cdkTrigger.menuPosition = this._menuPosition();
});
classes(() => 'aria-expanded:bg-accent aria-expanded:text-accent-foreground');
}
}
@Directive({
selector: '[hlmDropdownMenuSub],hlm-dropdown-menu-sub',
hostDirectives: [CdkMenu],
host: {
'data-slot': 'dropdown-menu-sub',
'[attr.data-state]': '_state()',
'[attr.data-side]': '_side()',
},
})
export class HlmDropdownMenuSub {
private readonly _host = inject(CdkMenu);
protected readonly _state = signal('open');
protected readonly _side = signal('top');
constructor() {
this.setSideWithDarkMagic();
// this is a best effort, but does not seem to work currently
// TODO: figure out a way for us to know the host is about to be closed. might not be possible with CDK
this._host.closed.pipe(takeUntilDestroyed()).subscribe(() => this._state.set('closed'));
classes(() => 'data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/5 dark:ring-foreground/10 bg-popover text-popover-foreground min-w-36 rounded-3xl p-1.5 shadow-lg ring-1 duration-100 w-auto');
}
private setSideWithDarkMagic() {
/**
* This is an ugly workaround to at least figure out the correct side of where a submenu
* will appear and set the attribute to the host accordingly
*
* First of all we take advantage of the menu stack not being aware of the root
* object immediately after it is added. This code executes before the root element is added,
* which means the stack is still empty and the peek method returns undefined.
*/
const isRoot = this._host.menuStack.peek() === undefined;
setTimeout(() => {
// our menu trigger directive leaves the last position used for use immediately after opening
// we can access it here and determine the correct side.
// eslint-disable-next-line
const ps = (this._host as any)._parentTrigger._spartanLastPosition;
if (!ps) {
// if we have no last position we default to the most likely option
// I hate that we have to do this and hope we can revisit soon and improve
this._side.set(isRoot ? 'top' : 'left');
return;
}
const side = isRoot ? ps.originY : ps.originX === 'end' ? 'right' : 'left';
this._side.set(side);
});
}
}
export interface HlmDropdownMenuConfig {
align: MenuAlign;
side: MenuSide;
}
const defaultConfig: HlmDropdownMenuConfig = {
align: 'start',
side: 'bottom',
};
const HlmDropdownMenuConfigToken = new InjectionToken<HlmDropdownMenuConfig>('HlmDropdownMenuConfig');
export function provideHlmDropdownMenuConfig(config: Partial<HlmDropdownMenuConfig>): ValueProvider {
return { provide: HlmDropdownMenuConfigToken, useValue: { ...defaultConfig, ...config } };
}
export function injectHlmDropdownMenuConfig(): HlmDropdownMenuConfig {
return inject(HlmDropdownMenuConfigToken, { optional: true }) ?? defaultConfig;
}
@Directive({
selector: '[hlmDropdownMenuTrigger]',
hostDirectives: [
{
directive: CdkMenuTrigger,
inputs: ['cdkMenuTriggerFor: hlmDropdownMenuTrigger', 'cdkMenuTriggerData: hlmDropdownMenuTriggerData'],
outputs: ['cdkMenuOpened: hlmDropdownMenuOpened', 'cdkMenuClosed: hlmDropdownMenuClosed'],
},
],
host: { 'data-slot': 'dropdown-menu-trigger' },
})
export class HlmDropdownMenuTrigger {
private readonly _cdkTrigger = inject(CdkMenuTrigger, { host: true });
private readonly _config = injectHlmDropdownMenuConfig();
public readonly align = input<MenuAlign>(this._config.align);
public readonly side = input<MenuSide>(this._config.side);
private readonly _menuPosition = computed(() => createMenuPosition(this.align(), this.side()));
constructor() {
// once the trigger opens we wait until the next tick and then grab the last position
// used to position the menu. we store this in our trigger which the brnMenu directive has
// access to through DI
this._cdkTrigger.opened.pipe(takeUntilDestroyed()).subscribe(() =>
setTimeout(
() =>
// eslint-disable-next-line
((this._cdkTrigger as any)._spartanLastPosition = // eslint-disable-next-line
(this._cdkTrigger as any).overlayRef._positionStrategy._lastPosition),
),
);
effect(() => {
this._cdkTrigger.menuPosition = this._menuPosition();
});
}
}
@Directive({
selector: '[hlmDropdownMenu],hlm-dropdown-menu',
hostDirectives: [CdkMenu],
host: {
'data-slot': 'dropdown-menu',
'[attr.data-state]': '_state()',
'[attr.data-side]': '_side()',
'[style.--side-offset]': 'sideOffset()',
},
})
export class HlmDropdownMenu {
private readonly _host = inject(CdkMenu);
protected readonly _state = signal('open');
protected readonly _side = signal('top');
public readonly sideOffset = input<number, NumberInput>(1, { transform: numberAttribute });
constructor() {
classes(
() =>
'data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/5 dark:ring-foreground/10 bg-popover text-popover-foreground min-w-48 rounded-3xl p-1.5 shadow-lg ring-1 duration-100 my-[--spacing(var(--side-offset))] overflow-x-hidden overflow-y-auto outline-none',
);
this.setSideWithDarkMagic();
// this is a best effort, but does not seem to work currently
// TODO: figure out a way for us to know the host is about to be closed. might not be possible with CDK
this._host.closed.pipe(takeUntilDestroyed()).subscribe(() => this._state.set('closed'));
}
private setSideWithDarkMagic() {
/**
* This is an ugly workaround to at least figure out the correct side of where a submenu
* will appear and set the attribute to the host accordingly
*
* First of all we take advantage of the menu stack not being aware of the root
* object immediately after it is added. This code executes before the root element is added,
* which means the stack is still empty and the peek method returns undefined.
*/
const isRoot = this._host.menuStack.peek() === undefined;
setTimeout(() => {
// our menu trigger directive leaves the last position used for use immediately after opening
// we can access it here and determine the correct side.
// eslint-disable-next-line
const ps = (this._host as any)._parentTrigger._spartanLastPosition;
if (!ps) {
// if we have no last position we default to the most likely option
// I hate that we have to do this and hope we can revisit soon and improve
this._side.set(isRoot ? 'top' : 'left');
return;
}
const side = isRoot ? ps.originY : ps.originX === 'end' ? 'right' : 'left';
this._side.set(side);
});
}
}
export const HlmDropdownMenuImports = [
HlmDropdownMenu,
HlmDropdownMenuCheckbox,
HlmDropdownMenuCheckboxIndicator,
HlmDropdownMenuGroup,
HlmDropdownMenuItem,
HlmDropdownMenuItemSubIndicator,
HlmDropdownMenuLabel,
HlmDropdownMenuRadio,
HlmDropdownMenuRadioIndicator,
HlmDropdownMenuSeparator,
HlmDropdownMenuShortcut,
HlmDropdownMenuSub,
HlmDropdownMenuSubTrigger,
HlmDropdownMenuTrigger,
] as const;Usage
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';<button hlmBtn variant="outline" [hlmDropdownMenuTrigger]="menu">Open</button>
<ng-template #menu>
<hlm-dropdown-menu>
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>My Account</hlm-dropdown-menu-label>
<button hlmDropdownMenuItem>Profile</button>
<button hlmDropdownMenuItem>Billing</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<hlm-dropdown-menu-group>
<button hlmDropdownMenuItem>Team</button>
<button hlmDropdownMenuItem>Subscription</button>
</hlm-dropdown-menu-group>
</hlm-dropdown-menu>
</ng-template>Examples
Basic
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
@Component({
selector: 'spartan-dropdown-basic',
imports: [HlmDropdownMenuImports, HlmButtonImports],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<button hlmBtn variant="outline" [hlmDropdownMenuTrigger]="menu" align="start">Open</button>
<ng-template #menu>
<hlm-dropdown-menu>
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>My Account</hlm-dropdown-menu-label>
<button hlmDropdownMenuItem>Profile</button>
<button hlmDropdownMenuItem>Billing</button>
<button hlmDropdownMenuItem>Settings</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<hlm-dropdown-menu-group>
<button hlmDropdownMenuItem>GitHub</button>
<button hlmDropdownMenuItem>Support</button>
<button hlmDropdownMenuItem disabled>API</button>
</hlm-dropdown-menu-group>
</hlm-dropdown-menu>
</ng-template>
`,
})
export class DropdownBasic {}Submenu
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
@Component({
selector: 'spartan-dropdown-submenu',
imports: [HlmDropdownMenuImports, HlmButtonImports],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<button hlmBtn variant="outline" [hlmDropdownMenuTrigger]="menu" align="start">Open</button>
<ng-template #menu>
<hlm-dropdown-menu>
<hlm-dropdown-menu-group>
<button hlmDropdownMenuItem>Team</button>
<button hlmDropdownMenuItem [hlmDropdownMenuSubTrigger]="invite" side="right" align="start">
Invite users
<hlm-dropdown-menu-item-sub-indicator />
</button>
<button hlmDropdownMenuItem>
New Team
<hlm-dropdown-menu-shortcut>⌘+T</hlm-dropdown-menu-shortcut>
</button>
</hlm-dropdown-menu-group>
</hlm-dropdown-menu>
</ng-template>
<ng-template #invite>
<hlm-dropdown-menu-sub>
<button hlmDropdownMenuItem>Email</button>
<button hlmDropdownMenuItem>Message</button>
<button hlmDropdownMenuItem [hlmDropdownMenuSubTrigger]="moreOptions" side="right" align="start">
More options
<hlm-dropdown-menu-item-sub-indicator />
</button>
<hlm-dropdown-menu-separator />
<button hlmDropdownMenuItem>Advanced...</button>
</hlm-dropdown-menu-sub>
</ng-template>
<ng-template #moreOptions>
<hlm-dropdown-menu-sub>
<button hlmDropdownMenuItem>Calendly</button>
<button hlmDropdownMenuItem>Slack</button>
<hlm-dropdown-menu-separator />
<button hlmDropdownMenuItem>Webhook</button>
</hlm-dropdown-menu-sub>
</ng-template>
`,
})
export class DropdownSubmenu {}Shortcuts
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
@Component({
selector: 'spartan-dropdown-shortcuts',
imports: [HlmDropdownMenuImports, HlmButtonImports],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<button hlmBtn variant="outline" [hlmDropdownMenuTrigger]="menu" align="start">Open</button>
<ng-template #menu>
<hlm-dropdown-menu>
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>My Account</hlm-dropdown-menu-label>
<button hlmDropdownMenuItem>
Profile
<hlm-dropdown-menu-shortcut>⇧⌘P</hlm-dropdown-menu-shortcut>
</button>
<button hlmDropdownMenuItem>
Billing
<hlm-dropdown-menu-shortcut>⌘B</hlm-dropdown-menu-shortcut>
</button>
<button hlmDropdownMenuItem>
Settings
<hlm-dropdown-menu-shortcut>⌘S</hlm-dropdown-menu-shortcut>
</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<hlm-dropdown-menu-group>
<button hlmDropdownMenuItem>
Log out
<hlm-dropdown-menu-shortcut>⇧⌘Q</hlm-dropdown-menu-shortcut>
</button>
</hlm-dropdown-menu-group>
</hlm-dropdown-menu>
</ng-template>
`,
})
export class DropdownShortcuts {}Icons
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideCreditCard, lucideLogOut, lucideSettings, lucideUser } from '@ng-icons/lucide';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
@Component({
selector: 'spartan-dropdown-icons',
imports: [HlmDropdownMenuImports, HlmButtonImports, NgIcon],
providers: [provideIcons({ lucideUser, lucideCreditCard, lucideSettings, lucideLogOut })],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<button hlmBtn variant="outline" [hlmDropdownMenuTrigger]="menu" align="start">Open</button>
<ng-template #menu>
<hlm-dropdown-menu>
<hlm-dropdown-menu-group>
<button hlmDropdownMenuItem>
<ng-icon name="lucideUser" />
Profile
</button>
<button hlmDropdownMenuItem>
<ng-icon name="lucideCreditCard" />
Billing
</button>
<button hlmDropdownMenuItem>
<ng-icon name="lucideSettings" />
Settings
</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<hlm-dropdown-menu-group>
<button hlmDropdownMenuItem variant="destructive">
<ng-icon name="lucideLogOut" />
Log out
</button>
</hlm-dropdown-menu-group>
</hlm-dropdown-menu>
</ng-template>
`,
})
export class DropdownIcons {}Checkboxes
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
@Component({
selector: 'spartan-dropdown-checkboxes',
imports: [HlmDropdownMenuImports, HlmButtonImports],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<button hlmBtn variant="outline" [hlmDropdownMenuTrigger]="menu">Open</button>
<ng-template #menu>
<hlm-dropdown-menu class="w-40">
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>Appearance</hlm-dropdown-menu-label>
<button hlmDropdownMenuCheckbox [checked]="statusBar()" (triggered)="statusBar.set(!statusBar())">
Status Bar
<hlm-dropdown-menu-checkbox-indicator />
</button>
<button
hlmDropdownMenuCheckbox
disabled
[checked]="activityBar()"
(triggered)="activityBar.set(!activityBar())"
>
Activity Bar
<hlm-dropdown-menu-checkbox-indicator />
</button>
<button hlmDropdownMenuCheckbox [checked]="panel()" (triggered)="panel.set(!panel())">
Panel
<hlm-dropdown-menu-checkbox-indicator />
</button>
</hlm-dropdown-menu-group>
</hlm-dropdown-menu>
</ng-template>
`,
})
export class DropdownCheckboxes {
public readonly statusBar = signal(true);
public readonly activityBar = signal(false);
public readonly panel = signal(false);
}Checkboxes Icons
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideBell, lucideMail, lucideMessageSquare } from '@ng-icons/lucide';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
@Component({
selector: 'spartan-dropdown-checkboxes-icons',
imports: [HlmDropdownMenuImports, HlmButtonImports, NgIcon],
providers: [provideIcons({ lucideMail, lucideBell, lucideMessageSquare })],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<button hlmBtn variant="outline" [hlmDropdownMenuTrigger]="menu">Open</button>
<ng-template #menu>
<hlm-dropdown-menu class="w-52">
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>Notification Preferences</hlm-dropdown-menu-label>
<button hlmDropdownMenuCheckbox [checked]="email()" (triggered)="email.set(!email())">
<ng-icon name="lucideMail" />
Email notifications
<hlm-dropdown-menu-checkbox-indicator />
</button>
<button hlmDropdownMenuCheckbox [checked]="sms()" (triggered)="sms.set(!sms())">
<ng-icon name="lucideMessageSquare" />
SMS notifications
<hlm-dropdown-menu-checkbox-indicator />
</button>
<button hlmDropdownMenuCheckbox [checked]="push()" (triggered)="push.set(!push())">
<ng-icon name="lucideBell" />
Push notifications
<hlm-dropdown-menu-checkbox-indicator />
</button>
</hlm-dropdown-menu-group>
</hlm-dropdown-menu>
</ng-template>
`,
})
export class DropdownCheckboxesIcons {
public readonly email = signal(true);
public readonly sms = signal(false);
public readonly push = signal(true);
}Radio Group
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { MenuSide } from '@spartan-ng/brain/core';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
@Component({
selector: 'spartan-dropdown-radio-group',
imports: [HlmDropdownMenuImports, HlmButtonImports],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<button hlmBtn variant="outline" [hlmDropdownMenuTrigger]="menu">Open</button>
<ng-template #menu>
<hlm-dropdown-menu class="w-32">
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>Panel Position</hlm-dropdown-menu-label>
@let p = position();
<button hlmDropdownMenuRadio [checked]="p === 'top'" (triggered)="position.set('top')">
Top
<hlm-dropdown-menu-radio-indicator />
</button>
<button hlmDropdownMenuRadio [checked]="p === 'bottom'" (triggered)="position.set('bottom')">
Bottom
<hlm-dropdown-menu-radio-indicator />
</button>
<button hlmDropdownMenuRadio [checked]="p === 'right'" (triggered)="position.set('right')">
Right
<hlm-dropdown-menu-radio-indicator />
</button>
<button hlmDropdownMenuRadio [checked]="p === 'left'" (triggered)="position.set('left')">
Left
<hlm-dropdown-menu-radio-indicator />
</button>
</hlm-dropdown-menu-group>
</hlm-dropdown-menu>
</ng-template>
`,
})
export class DropdownRadioGroup {
public readonly position = signal<MenuSide>('bottom');
}Radio Group Icons
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideBuilding2, lucideCreditCard, lucideWallet } from '@ng-icons/lucide';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
@Component({
selector: 'spartan-dropdown-radio-group-icons',
imports: [HlmDropdownMenuImports, HlmButtonImports, NgIcon],
providers: [provideIcons({ lucideCreditCard, lucideWallet, lucideBuilding2 })],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<button hlmBtn variant="outline" [hlmDropdownMenuTrigger]="menu">Payment Method</button>
<ng-template #menu>
<hlm-dropdown-menu class="w-56">
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>Select Payment Method</hlm-dropdown-menu-label>
@let p = payment();
<button hlmDropdownMenuRadio [checked]="p === 'card'" (triggered)="payment.set('card')">
<ng-icon name="lucideCreditCard" />
Credit Card
<hlm-dropdown-menu-radio-indicator />
</button>
<button hlmDropdownMenuRadio [checked]="p === 'paypal'" (triggered)="payment.set('paypal')">
<ng-icon name="lucideWallet" />
PayPal
<hlm-dropdown-menu-radio-indicator />
</button>
<button hlmDropdownMenuRadio [checked]="p === 'bank'" (triggered)="payment.set('bank')">
<ng-icon name="lucideBuilding2" />
Bank Transfer
<hlm-dropdown-menu-radio-indicator />
</button>
</hlm-dropdown-menu-group>
</hlm-dropdown-menu>
</ng-template>
`,
})
export class DropdownRadioGroupIcons {
public readonly payment = signal<'card' | 'paypal' | 'bank'>('card');
}Destructive
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucidePencil, lucideShare, lucideTrash2 } from '@ng-icons/lucide';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
@Component({
selector: 'spartan-dropdown-destructive',
imports: [HlmDropdownMenuImports, HlmButtonImports, NgIcon],
providers: [provideIcons({ lucidePencil, lucideShare, lucideTrash2 })],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<button hlmBtn variant="outline" [hlmDropdownMenuTrigger]="menu" align="start">Action</button>
<ng-template #menu>
<hlm-dropdown-menu>
<hlm-dropdown-menu-group>
<button hlmDropdownMenuItem>
<ng-icon name="lucidePencil" />
Edit
</button>
<button hlmDropdownMenuItem>
<ng-icon name="lucideShare" />
Share
</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<hlm-dropdown-menu-group>
<button hlmDropdownMenuItem variant="destructive">
<ng-icon name="lucideTrash2" />
Delete
</button>
</hlm-dropdown-menu-group>
</hlm-dropdown-menu>
</ng-template>
`,
})
export class DropdownDestructive {}Stateful
import { Component, signal } from '@angular/core';
import { provideIcons } from '@ng-icons/core';
import { lucideUndo2 } from '@ng-icons/lucide';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
import { HlmIconImports } from '@spartan-ng/helm/icon';
@Component({
selector: 'spartan-dropdown-with-state',
imports: [HlmDropdownMenuImports, HlmButtonImports, HlmIconImports],
providers: [provideIcons({ lucideUndo2 })],
template: `
<div class="flex w-full items-center justify-center pt-[20%]">
<button hlmBtn variant="outline" align="center" [hlmDropdownMenuTrigger]="menu">Open</button>
</div>
<ng-template #menu>
<hlm-dropdown-menu class="w-56">
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>Appearance</hlm-dropdown-menu-label>
<button hlmDropdownMenuCheckbox [checked]="statusBar()" (triggered)="statusBar.set(!statusBar())">
<hlm-dropdown-menu-checkbox-indicator />
<span>Status Bar</span>
</button>
<button
hlmDropdownMenuCheckbox
disabled
[checked]="activityBar()"
(triggered)="activityBar.set(!activityBar())"
>
<hlm-dropdown-menu-checkbox-indicator />
<span>Activity Bar</span>
</button>
<button hlmDropdownMenuCheckbox [checked]="panel()" (triggered)="panel.set(!panel())">
<hlm-dropdown-menu-checkbox-indicator />
<span>Panel</span>
</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<hlm-dropdown-menu-label>Panel Position</hlm-dropdown-menu-label>
<hlm-dropdown-menu-group>
@for (size of panelPositions; track size) {
<button hlmDropdownMenuRadio [checked]="size === selectedPosition" (triggered)="selectedPosition = size">
<hlm-dropdown-menu-radio-indicator />
<span>{{ size }}</span>
</button>
}
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<button hlmDropdownMenuItem (triggered)="reset()">
<ng-icon hlm name="lucideUndo2" size="sm" />
Reset
</button>
</hlm-dropdown-menu>
</ng-template>
`,
})
export class DropdownWithStatePreview {
public readonly statusBar = signal(true);
public readonly activityBar = signal(false);
public readonly panel = signal(false);
public panelPositions = ['Top', 'Bottom', 'Right', 'Left'] as const;
public selectedPosition: (typeof this.panelPositions)[number] | undefined = 'Bottom';
reset() {
this.statusBar.set(false);
this.panel.set(false);
this.activityBar.set(false);
this.selectedPosition = 'Bottom';
}
}Passing context to menu
import { Component, signal } from '@angular/core';
import { provideIcons } from '@ng-icons/core';
import { lucideUndo2 } from '@ng-icons/lucide';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
import { HlmIconImports } from '@spartan-ng/helm/icon';
@Component({
selector: 'spartan-dropdown-with-context',
imports: [HlmDropdownMenuImports, HlmButtonImports, HlmIconImports],
providers: [provideIcons({ lucideUndo2 })],
template: `
<div class="flex w-full items-center justify-center pt-[20%]">
<button
hlmBtn
variant="outline"
align="center"
[hlmDropdownMenuTrigger]="menu"
[hlmDropdownMenuTriggerData]="{ $implicit: { data: 'Context Window Full' } }"
>
Open
</button>
</div>
<ng-template #menu let-ctx>
<hlm-dropdown-menu class="w-56">
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>Context</hlm-dropdown-menu-label>
<button hlmDropdownMenuItem inset>{{ ctx.data }}</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>Appearance</hlm-dropdown-menu-label>
<button hlmDropdownMenuCheckbox [checked]="statusBar()" (triggered)="statusBar.set(!statusBar())">
<hlm-dropdown-menu-checkbox-indicator />
<span>Status Bar</span>
</button>
<button
hlmDropdownMenuCheckbox
disabled
[checked]="activityBar()"
(triggered)="activityBar.set(!activityBar())"
>
<hlm-dropdown-menu-checkbox-indicator />
<span>Activity Bar</span>
</button>
<button hlmDropdownMenuCheckbox [checked]="panel()" (triggered)="panel.set(!panel())">
<hlm-dropdown-menu-checkbox-indicator />
<span>Panel</span>
</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<hlm-dropdown-menu-label>Panel Position</hlm-dropdown-menu-label>
<hlm-dropdown-menu-group>
@for (size of panelPositions; track size) {
<button hlmDropdownMenuRadio [checked]="size === selectedPosition" (triggered)="selectedPosition = size">
<hlm-dropdown-menu-radio-indicator />
<span>{{ size }}</span>
</button>
}
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<button hlmDropdownMenuItem (triggered)="reset()">
<ng-icon hlm name="lucideUndo2" size="sm" />
Reset
</button>
</hlm-dropdown-menu>
</ng-template>
`,
})
export class DropdownWithContextPreview {
public readonly statusBar = signal(true);
public readonly activityBar = signal(false);
public readonly panel = signal(false);
public panelPositions = ['Top', 'Bottom', 'Right', 'Left'] as const;
public selectedPosition: (typeof this.panelPositions)[number] | undefined = 'Bottom';
reset() {
this.statusBar.set(false);
this.panel.set(false);
this.activityBar.set(false);
this.selectedPosition = 'Bottom';
}
}RTL
To enable RTL support in spartan-ng, see the RTL configuration guide.
import { Directionality } from '@angular/cdk/bidi';
import { ChangeDetectionStrategy, Component, computed, effect, inject, signal, untracked } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideCreditCard, lucideSettings, lucideUser } from '@ng-icons/lucide';
import { TranslateService, Translations } from '@spartan-ng/app/app/shared/translate.service';
import { MenuSide } from '@spartan-ng/brain/core';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
@Component({
selector: 'spartan-dropdown-rtl',
imports: [HlmDropdownMenuImports, HlmButtonImports, NgIcon],
providers: [provideIcons({ lucideUser, lucideCreditCard, lucideSettings }), Directionality],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'[dir]': '_dir()',
},
template: `
<button hlmBtn variant="outline" [hlmDropdownMenuTrigger]="menu" align="start">
{{ _t()['open'] }}
</button>
<ng-template #menu>
<hlm-dropdown-menu class="w-36">
<hlm-dropdown-menu-group>
<button hlmDropdownMenuItem [hlmDropdownMenuSubTrigger]="accountMenu" side="right" align="start">
{{ _t()['account'] }}
<hlm-dropdown-menu-item-sub-indicator />
</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>{{ _t()['team'] }}</hlm-dropdown-menu-label>
<button hlmDropdownMenuItem>
{{ _t()['team'] }}
</button>
<button hlmDropdownMenuItem [hlmDropdownMenuSubTrigger]="inviteMenu" side="right" align="start">
{{ _t()['inviteUsers'] }}
<hlm-dropdown-menu-item-sub-indicator />
</button>
<button hlmDropdownMenuItem>
{{ _t()['newTeam'] }}
<hlm-dropdown-menu-shortcut>⌘+T</hlm-dropdown-menu-shortcut>
</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>{{ _t()['view'] }}</hlm-dropdown-menu-label>
<button hlmDropdownMenuCheckbox [checked]="statusBar()" (triggered)="statusBar.set(!statusBar())">
{{ _t()['statusBar'] }}
<hlm-dropdown-menu-checkbox-indicator />
</button>
<button hlmDropdownMenuCheckbox [checked]="activityBar()" (triggered)="activityBar.set(!activityBar())">
{{ _t()['activityBar'] }}
<hlm-dropdown-menu-checkbox-indicator />
</button>
<button hlmDropdownMenuCheckbox [checked]="panel()" (triggered)="panel.set(!panel())">
{{ _t()['panel'] }}
<hlm-dropdown-menu-checkbox-indicator />
</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>{{ _t()['position'] }}</hlm-dropdown-menu-label>
@let p = position();
<button hlmDropdownMenuRadio [checked]="p === 'top'" (triggered)="position.set('top')">
{{ _t()['top'] }}
<hlm-dropdown-menu-radio-indicator />
</button>
<button hlmDropdownMenuRadio [checked]="p === 'bottom'" (triggered)="position.set('bottom')">
{{ _t()['bottom'] }}
<hlm-dropdown-menu-radio-indicator />
</button>
<button hlmDropdownMenuRadio [checked]="p === 'right'" (triggered)="position.set('right')">
{{ _t()['right'] }}
<hlm-dropdown-menu-radio-indicator />
</button>
<button hlmDropdownMenuRadio [checked]="p === 'left'" (triggered)="position.set('left')">
{{ _t()['left'] }}
<hlm-dropdown-menu-radio-indicator />
</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<hlm-dropdown-menu-group>
<button hlmDropdownMenuItem variant="destructive">
{{ _t()['logout'] }}
</button>
</hlm-dropdown-menu-group>
</hlm-dropdown-menu>
</ng-template>
<ng-template #accountMenu>
<hlm-dropdown-menu-sub>
<button hlmDropdownMenuItem>
<ng-icon name="lucideUser" />
{{ _t()['profile'] }}
</button>
<button hlmDropdownMenuItem>
<ng-icon name="lucideCreditCard" />
{{ _t()['billing'] }}
</button>
<button hlmDropdownMenuItem>
<ng-icon name="lucideSettings" />
{{ _t()['settings'] }}
</button>
</hlm-dropdown-menu-sub>
</ng-template>
<ng-template #inviteMenu>
<hlm-dropdown-menu-sub>
<button hlmDropdownMenuItem>
{{ _t()['email'] }}
</button>
<button hlmDropdownMenuItem>
{{ _t()['message'] }}
</button>
<button hlmDropdownMenuItem [hlmDropdownMenuSubTrigger]="moreMenu" side="right" align="start">
{{ _t()['more'] }}
<hlm-dropdown-menu-item-sub-indicator />
</button>
<hlm-dropdown-menu-separator />
<button hlmDropdownMenuItem>
{{ _t()['advanced'] }}
</button>
</hlm-dropdown-menu-sub>
</ng-template>
<ng-template #moreMenu>
<hlm-dropdown-menu-sub>
<button hlmDropdownMenuItem>
{{ _t()['calendar'] }}
</button>
<button hlmDropdownMenuItem>
{{ _t()['chat'] }}
</button>
<hlm-dropdown-menu-separator />
<button hlmDropdownMenuItem>
{{ _t()['webhook'] }}
</button>
</hlm-dropdown-menu-sub>
</ng-template>
`,
})
export class DropdownRtl {
public readonly statusBar = signal(true);
public readonly activityBar = signal(false);
public readonly panel = signal(false);
public readonly position = signal<MenuSide>('bottom');
private readonly _language = inject(TranslateService).language;
private readonly _translations: Translations = {
en: {
dir: 'ltr',
values: {
open: 'Open',
account: 'Account',
profile: 'Profile',
billing: 'Billing',
settings: 'Settings',
logout: 'Log out',
team: 'Team',
inviteUsers: 'Invite users',
email: 'Email',
message: 'Message',
more: 'More',
calendar: 'Calendar',
chat: 'Chat',
webhook: 'Webhook',
advanced: 'Advanced...',
newTeam: 'New Team',
view: 'View',
statusBar: 'Status Bar',
activityBar: 'Activity Bar',
panel: 'Panel',
position: 'Position',
top: 'Top',
bottom: 'Bottom',
right: 'Right',
left: 'Left',
},
},
ar: {
dir: 'rtl',
values: {
open: 'افتح القائمة',
account: 'الحساب',
profile: 'الملف الشخصي',
billing: 'الفوترة',
settings: 'الإعدادات',
logout: 'تسجيل الخروج',
team: 'الفريق',
inviteUsers: 'دعوة المستخدمين',
email: 'البريد الإلكتروني',
message: 'رسالة',
more: 'المزيد',
calendar: 'تقويم',
chat: 'دردشة',
webhook: 'خطاف ويب',
advanced: 'متقدم...',
newTeam: 'فريق جديد',
view: 'عرض',
statusBar: 'شريط الحالة',
activityBar: 'شريط النشاط',
panel: 'اللوحة',
position: 'الموضع',
top: 'أعلى',
bottom: 'أسفل',
right: 'يمين',
left: 'يسار',
},
},
he: {
dir: 'rtl',
values: {
open: 'פתח תפריט',
account: 'חשבון',
profile: 'פרופיל',
billing: 'חיוב',
settings: 'הגדרות',
logout: 'התנתק',
team: 'הצוות',
inviteUsers: 'הזמן משתמשים',
email: 'אימייל',
message: 'הודעה',
more: 'עוד',
calendar: 'יומן',
chat: "צ'אט",
webhook: 'Webhook',
advanced: 'מתקדם...',
newTeam: 'צוות חדש',
view: 'תצוגה',
statusBar: 'שורת סטטוס',
activityBar: 'שורת פעילות',
panel: 'לוח',
position: 'מיקום',
top: 'למעלה',
bottom: 'למטה',
right: 'ימין',
left: 'שמאל',
},
},
};
private readonly _translation = computed(() => this._translations[this._language()]);
protected readonly _t = computed(() => this._translation().values);
protected readonly _dir = computed(() => this._translation().dir);
private readonly _directionality = inject(Directionality);
constructor() {
effect(() => {
const dir = this._dir();
untracked(() => this._directionality.valueSignal.set(dir));
});
}
}Helm API
HlmDropdownMenuCheckboxIndicator
Selector: hlm-dropdown-menu-checkbox-indicator
HlmDropdownMenuCheckboxCdk
Selector: [hlmDropdownMenuCheckboxCdk]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| keepOpen | boolean | true | - |
HlmDropdownMenuCheckbox
Selector: [hlmDropdownMenuCheckbox],[hlmDropdownMenuCheckboxItem]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| inset | boolean | false | - |
HlmDropdownMenuGroup
Selector: [hlmDropdownMenuGroup],hlm-dropdown-menu-group
HlmDropdownMenuItemSubIndicator
Selector: hlm-dropdown-menu-item-sub-indicator
HlmDropdownMenuItem
Selector: [hlmDropdownMenuItem],hlm-dropdown-menu-item
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| disabled | boolean | false | - |
| variant | 'default' | 'destructive' | default | - |
| inset | boolean | false | - |
HlmDropdownMenuLabel
Selector: [hlmDropdownMenuLabel],hlm-dropdown-menu-label
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| inset | boolean | false | - |
HlmDropdownMenuRadioIndicator
Selector: hlm-dropdown-menu-radio-indicator
HlmDropdownMenuRadioCdk
Selector: [hlmDropdownMenuRadioCdk]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| keepOpen | boolean | true | - |
HlmDropdownMenuRadio
Selector: [hlmDropdownMenuRadio]
HlmDropdownMenuSeparator
Selector: [hlmDropdownMenuSeparator],hlm-dropdown-menu-separator
HlmDropdownMenuShortcut
Selector: [hlmDropdownMenuShortcut],hlm-dropdown-menu-shortcut
HlmDropdownMenuSubTrigger
Selector: [hlmDropdownMenuSubTrigger]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| align | MenuAlign | this._config.align | - |
| side | MenuSide | this._config.side | - |
HlmDropdownMenuSub
Selector: [hlmDropdownMenuSub],hlm-dropdown-menu-sub
HlmDropdownMenuTrigger
Selector: [hlmDropdownMenuTrigger]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| align | MenuAlign | this._config.align | - |
| side | MenuSide | this._config.side | - |
HlmDropdownMenu
Selector: [hlmDropdownMenu],hlm-dropdown-menu
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| sideOffset | number | 1 | - |
On This Page