Horizontal bar of menus like a desktop app, built on the Popover API, with keyboard support following the WAI-ARIA Menubar pattern.
<x-markas.menubar
:menus="[
['label' => 'File', 'items' => [
['label' => 'New file', 'value' => 'new'],
['label' => 'Open', 'value' => 'open'],
['label' => 'Save', 'value' => 'save'],
['separator' => true],
['label' => 'Close window', 'value' => 'close'],
]],
['label' => 'Edit', 'items' => [
['label' => 'Undo', 'value' => 'undo'],
['label' => 'Redo', 'value' => 'redo'],
['separator' => true],
['label' => 'Cut', 'value' => 'cut'],
['label' => 'Copy', 'value' => 'copy'],
['label' => 'Paste', 'value' => 'paste'],
]],
['label' => 'View', 'items' => [
['label' => 'Zoom in', 'value' => 'zoom-in'],
['label' => 'Zoom out', 'value' => 'zoom-out'],
['label' => 'Full screen', 'value' => 'full-screen', 'disabled' => true],
]],
['label' => 'Help', 'items' => [
['label' => 'Documentation', 'href' => '/docs'],
['label' => 'About', 'value' => 'about'],
]],
]"
/>import { Menubar } from "@/components/markas/Menubar";
const menus = [
{
label: "File",
items: [
{
label: "New file",
value: "new",
},
{
label: "Open",
value: "open",
},
{
label: "Save",
value: "save",
},
{
separator: true as const,
},
{
label: "Close window",
value: "close",
},
],
},
{
label: "Edit",
items: [
{
label: "Undo",
value: "undo",
},
{
label: "Redo",
value: "redo",
},
{
separator: true as const,
},
{
label: "Cut",
value: "cut",
},
{
label: "Copy",
value: "copy",
},
{
label: "Paste",
value: "paste",
},
],
},
{
label: "View",
items: [
{
label: "Zoom in",
value: "zoom-in",
},
{
label: "Zoom out",
value: "zoom-out",
},
{
label: "Full screen",
value: "full-screen",
disabled: true,
},
],
},
{
label: "Help",
items: [
{
label: "Documentation",
href: "/docs",
},
{
label: "About",
value: "about",
},
],
},
];
export default function MenubarExample() {
return <Menubar menus={menus} />;
}<script setup lang="ts">
import Menubar from "@/components/markas/Menubar.vue";
const menus = [
{
label: "File",
items: [
{
label: "New file",
value: "new",
},
{
label: "Open",
value: "open",
},
{
label: "Save",
value: "save",
},
{
separator: true as const,
},
{
label: "Close window",
value: "close",
},
],
},
{
label: "Edit",
items: [
{
label: "Undo",
value: "undo",
},
{
label: "Redo",
value: "redo",
},
{
separator: true as const,
},
{
label: "Cut",
value: "cut",
},
{
label: "Copy",
value: "copy",
},
{
label: "Paste",
value: "paste",
},
],
},
{
label: "View",
items: [
{
label: "Zoom in",
value: "zoom-in",
},
{
label: "Zoom out",
value: "zoom-out",
},
{
label: "Full screen",
value: "full-screen",
disabled: true,
},
],
},
{
label: "Help",
items: [
{
label: "Documentation",
href: "/docs",
},
{
label: "About",
value: "about",
},
],
},
];
</script>
<template>
<Menubar :menus="menus" />
</template><script lang="ts">
import Menubar from "$lib/components/markas/Menubar.svelte";
const menus = [
{
label: "File",
items: [
{
label: "New file",
value: "new",
},
{
label: "Open",
value: "open",
},
{
label: "Save",
value: "save",
},
{
separator: true as const,
},
{
label: "Close window",
value: "close",
},
],
},
{
label: "Edit",
items: [
{
label: "Undo",
value: "undo",
},
{
label: "Redo",
value: "redo",
},
{
separator: true as const,
},
{
label: "Cut",
value: "cut",
},
{
label: "Copy",
value: "copy",
},
{
label: "Paste",
value: "paste",
},
],
},
{
label: "View",
items: [
{
label: "Zoom in",
value: "zoom-in",
},
{
label: "Zoom out",
value: "zoom-out",
},
{
label: "Full screen",
value: "full-screen",
disabled: true,
},
],
},
{
label: "Help",
items: [
{
label: "Documentation",
href: "/docs",
},
{
label: "About",
value: "about",
},
],
},
];
</script>
<Menubar {menus} />---
import Menubar from "@/components/markas/Menubar.astro";
const menus = [
{
label: "File",
items: [
{
label: "New file",
value: "new",
},
{
label: "Open",
value: "open",
},
{
label: "Save",
value: "save",
},
{
separator: true as const,
},
{
label: "Close window",
value: "close",
},
],
},
{
label: "Edit",
items: [
{
label: "Undo",
value: "undo",
},
{
label: "Redo",
value: "redo",
},
{
separator: true as const,
},
{
label: "Cut",
value: "cut",
},
{
label: "Copy",
value: "copy",
},
{
label: "Paste",
value: "paste",
},
],
},
{
label: "View",
items: [
{
label: "Zoom in",
value: "zoom-in",
},
{
label: "Zoom out",
value: "zoom-out",
},
{
label: "Full screen",
value: "full-screen",
disabled: true,
},
],
},
{
label: "Help",
items: [
{
label: "Documentation",
href: "/docs",
},
{
label: "About",
value: "about",
},
],
},
];
---
<Menubar menus={menus} />import { Component } from "@angular/core";
import { Menubar } from "./markas/menubar.component";
const menus = [
{
label: "File",
items: [
{
label: "New file",
value: "new",
},
{
label: "Open",
value: "open",
},
{
label: "Save",
value: "save",
},
{
separator: true as const,
},
{
label: "Close window",
value: "close",
},
],
},
{
label: "Edit",
items: [
{
label: "Undo",
value: "undo",
},
{
label: "Redo",
value: "redo",
},
{
separator: true as const,
},
{
label: "Cut",
value: "cut",
},
{
label: "Copy",
value: "copy",
},
{
label: "Paste",
value: "paste",
},
],
},
{
label: "View",
items: [
{
label: "Zoom in",
value: "zoom-in",
},
{
label: "Zoom out",
value: "zoom-out",
},
{
label: "Full screen",
value: "full-screen",
disabled: true,
},
],
},
{
label: "Help",
items: [
{
label: "Documentation",
href: "/docs",
},
{
label: "About",
value: "about",
},
],
},
];
@Component({
selector: "markas-example",
imports: [Menubar],
template: ` <markas-menubar [menus]="menus" /> `,
})
export default class MenubarFixture {
protected readonly menus = menus;
}Examples
In an editor
Version 2.4
Faster search, a new export dialog, and dark mode for the editor.
Version 2.4
Faster search, a new export dialog, and dark mode for the editor.
Version 2.4
Faster search, a new export dialog, and dark mode for the editor.
Version 2.4
Faster search, a new export dialog, and dark mode for the editor.
Version 2.4
Faster search, a new export dialog, and dark mode for the editor.
<div class="overflow-hidden rounded-xl border border-line bg-surface">
<div class="flex items-center justify-between gap-3 border-b border-line bg-canvas px-3 py-2">
<x-markas.menubar
label="Editor"
:menus="[
['label' => 'File', 'items' => [
['label' => 'New document', 'value' => 'new'],
['label' => 'Save', 'value' => 'save'],
['label' => 'Export as PDF', 'value' => 'pdf'],
]],
['label' => 'Edit', 'items' => [
['label' => 'Undo', 'value' => 'undo'],
['label' => 'Redo', 'value' => 'redo'],
['separator' => true],
['label' => 'Find and replace', 'value' => 'find'],
]],
['label' => 'Insert', 'items' => [
['label' => 'Image', 'value' => 'image'],
['label' => 'Table', 'value' => 'table'],
['label' => 'Link', 'value' => 'link'],
]],
['label' => 'Format', 'items' => [
['label' => 'Bold', 'value' => 'bold'],
['label' => 'Italic', 'value' => 'italic'],
['label' => 'Clear formatting', 'value' => 'clear'],
]],
]"
/>
<span class="text-sm text-muted">notes.md</span>
</div>
<div class="space-y-2 p-4 text-sm text-ink">
<p class="font-medium">Version 2.4</p>
<p class="text-muted">Faster search, a new export dialog, and dark mode for the editor.</p>
</div>
</div>import { Menubar } from "@/components/markas/Menubar";
const menus = [
{
label: "File",
items: [
{
label: "New document",
value: "new",
},
{
label: "Save",
value: "save",
},
{
label: "Export as PDF",
value: "pdf",
},
],
},
{
label: "Edit",
items: [
{
label: "Undo",
value: "undo",
},
{
label: "Redo",
value: "redo",
},
{
separator: true as const,
},
{
label: "Find and replace",
value: "find",
},
],
},
{
label: "Insert",
items: [
{
label: "Image",
value: "image",
},
{
label: "Table",
value: "table",
},
{
label: "Link",
value: "link",
},
],
},
{
label: "Format",
items: [
{
label: "Bold",
value: "bold",
},
{
label: "Italic",
value: "italic",
},
{
label: "Clear formatting",
value: "clear",
},
],
},
];
export default function Example() {
return (
<div className="overflow-hidden rounded-xl border border-line bg-surface">
<div className="flex items-center justify-between gap-3 border-b border-line bg-canvas px-3 py-2">
<Menubar label="Editor" menus={menus} />
<span className="text-sm text-muted">notes.md</span>
</div>
<div className="space-y-2 p-4 text-sm text-ink">
<p className="font-medium">Version 2.4</p>
<p className="text-muted">
Faster search, a new export dialog, and dark mode for the editor.
</p>
</div>
</div>
);
}<script setup lang="ts">
import Menubar from "@/components/markas/Menubar.vue";
const menus = [
{
label: "File",
items: [
{
label: "New document",
value: "new",
},
{
label: "Save",
value: "save",
},
{
label: "Export as PDF",
value: "pdf",
},
],
},
{
label: "Edit",
items: [
{
label: "Undo",
value: "undo",
},
{
label: "Redo",
value: "redo",
},
{
separator: true as const,
},
{
label: "Find and replace",
value: "find",
},
],
},
{
label: "Insert",
items: [
{
label: "Image",
value: "image",
},
{
label: "Table",
value: "table",
},
{
label: "Link",
value: "link",
},
],
},
{
label: "Format",
items: [
{
label: "Bold",
value: "bold",
},
{
label: "Italic",
value: "italic",
},
{
label: "Clear formatting",
value: "clear",
},
],
},
];
</script>
<template>
<div class="overflow-hidden rounded-xl border border-line bg-surface">
<div
class="flex items-center justify-between gap-3 border-b border-line bg-canvas px-3 py-2"
>
<Menubar label="Editor" :menus="menus" />
<span class="text-sm text-muted">notes.md</span>
</div>
<div class="space-y-2 p-4 text-sm text-ink">
<p class="font-medium">Version 2.4</p>
<p class="text-muted">
Faster search, a new export dialog, and dark mode for the editor.
</p>
</div>
</div>
</template><script lang="ts">
import Menubar from "$lib/components/markas/Menubar.svelte";
const menus = [
{
label: "File",
items: [
{
label: "New document",
value: "new",
},
{
label: "Save",
value: "save",
},
{
label: "Export as PDF",
value: "pdf",
},
],
},
{
label: "Edit",
items: [
{
label: "Undo",
value: "undo",
},
{
label: "Redo",
value: "redo",
},
{
separator: true as const,
},
{
label: "Find and replace",
value: "find",
},
],
},
{
label: "Insert",
items: [
{
label: "Image",
value: "image",
},
{
label: "Table",
value: "table",
},
{
label: "Link",
value: "link",
},
],
},
{
label: "Format",
items: [
{
label: "Bold",
value: "bold",
},
{
label: "Italic",
value: "italic",
},
{
label: "Clear formatting",
value: "clear",
},
],
},
];
</script>
<div class="overflow-hidden rounded-xl border border-line bg-surface">
<div
class="flex items-center justify-between gap-3 border-b border-line bg-canvas px-3 py-2"
>
<Menubar label="Editor" {menus} />
<span class="text-sm text-muted">notes.md</span>
</div>
<div class="space-y-2 p-4 text-sm text-ink">
<p class="font-medium">Version 2.4</p>
<p class="text-muted">
Faster search, a new export dialog, and dark mode for the editor.
</p>
</div>
</div>---
import Menubar from "@/components/markas/Menubar.astro";
const menus = [
{
label: "File",
items: [
{
label: "New document",
value: "new",
},
{
label: "Save",
value: "save",
},
{
label: "Export as PDF",
value: "pdf",
},
],
},
{
label: "Edit",
items: [
{
label: "Undo",
value: "undo",
},
{
label: "Redo",
value: "redo",
},
{
separator: true as const,
},
{
label: "Find and replace",
value: "find",
},
],
},
{
label: "Insert",
items: [
{
label: "Image",
value: "image",
},
{
label: "Table",
value: "table",
},
{
label: "Link",
value: "link",
},
],
},
{
label: "Format",
items: [
{
label: "Bold",
value: "bold",
},
{
label: "Italic",
value: "italic",
},
{
label: "Clear formatting",
value: "clear",
},
],
},
];
---
<div class="overflow-hidden rounded-xl border border-line bg-surface">
<div class="flex items-center justify-between gap-3 border-b border-line bg-canvas px-3 py-2">
<Menubar label="Editor" menus={menus} />
<span class="text-sm text-muted">notes.md</span>
</div>
<div class="space-y-2 p-4 text-sm text-ink">
<p class="font-medium">Version 2.4</p>
<p class="text-muted">
Faster search, a new export dialog, and dark mode for the editor.
</p>
</div>
</div>import { Component } from "@angular/core";
import { Menubar } from "./markas/menubar.component";
const menus = [
{
label: "File",
items: [
{
label: "New document",
value: "new",
},
{
label: "Save",
value: "save",
},
{
label: "Export as PDF",
value: "pdf",
},
],
},
{
label: "Edit",
items: [
{
label: "Undo",
value: "undo",
},
{
label: "Redo",
value: "redo",
},
{
separator: true as const,
},
{
label: "Find and replace",
value: "find",
},
],
},
{
label: "Insert",
items: [
{
label: "Image",
value: "image",
},
{
label: "Table",
value: "table",
},
{
label: "Link",
value: "link",
},
],
},
{
label: "Format",
items: [
{
label: "Bold",
value: "bold",
},
{
label: "Italic",
value: "italic",
},
{
label: "Clear formatting",
value: "clear",
},
],
},
];
@Component({
selector: "markas-example",
imports: [Menubar],
template: `
<div class="overflow-hidden rounded-xl border border-line bg-surface">
<div
class="flex items-center justify-between gap-3 border-b border-line bg-canvas px-3 py-2"
>
<markas-menubar label="Editor" [menus]="menus" />
<span class="text-sm text-muted">notes.md</span>
</div>
<div class="space-y-2 p-4 text-sm text-ink">
<p class="font-medium">Version 2.4</p>
<p class="text-muted">
Faster search, a new export dialog, and dark mode for the editor.
</p>
</div>
</div>
`,
})
export default class MenubarEditorExample {
protected readonly menus = menus;
}With links
<x-markas.menubar
label="Site"
:menus="[
['label' => 'Products', 'items' => [
['label' => 'Analytics', 'href' => '/analytics'],
['label' => 'Automation', 'href' => '/automation'],
['label' => 'Reports', 'href' => '/reports'],
]],
['label' => 'Resources', 'items' => [
['label' => 'Documentation', 'href' => '/docs'],
['label' => 'Blog', 'href' => '/blog'],
['label' => 'Changelog', 'href' => '/changelog'],
]],
['label' => 'Company', 'items' => [
['label' => 'About', 'href' => '/about'],
['label' => 'Careers', 'href' => '/careers'],
['label' => 'Contact', 'href' => 'mailto:hello@example.com'],
]],
]"
/>import { Menubar } from "@/components/markas/Menubar";
const menus = [
{
label: "Products",
items: [
{
label: "Analytics",
href: "/analytics",
},
{
label: "Automation",
href: "/automation",
},
{
label: "Reports",
href: "/reports",
},
],
},
{
label: "Resources",
items: [
{
label: "Documentation",
href: "/docs",
},
{
label: "Blog",
href: "/blog",
},
{
label: "Changelog",
href: "/changelog",
},
],
},
{
label: "Company",
items: [
{
label: "About",
href: "/about",
},
{
label: "Careers",
href: "/careers",
},
{
label: "Contact",
href: "mailto:hello@example.com",
},
],
},
];
export default function Example() {
return <Menubar label="Site" menus={menus} />;
}<script setup lang="ts">
import Menubar from "@/components/markas/Menubar.vue";
const menus = [
{
label: "Products",
items: [
{
label: "Analytics",
href: "/analytics",
},
{
label: "Automation",
href: "/automation",
},
{
label: "Reports",
href: "/reports",
},
],
},
{
label: "Resources",
items: [
{
label: "Documentation",
href: "/docs",
},
{
label: "Blog",
href: "/blog",
},
{
label: "Changelog",
href: "/changelog",
},
],
},
{
label: "Company",
items: [
{
label: "About",
href: "/about",
},
{
label: "Careers",
href: "/careers",
},
{
label: "Contact",
href: "mailto:hello@example.com",
},
],
},
];
</script>
<template>
<Menubar label="Site" :menus="menus" />
</template><script lang="ts">
import Menubar from "$lib/components/markas/Menubar.svelte";
const menus = [
{
label: "Products",
items: [
{
label: "Analytics",
href: "/analytics",
},
{
label: "Automation",
href: "/automation",
},
{
label: "Reports",
href: "/reports",
},
],
},
{
label: "Resources",
items: [
{
label: "Documentation",
href: "/docs",
},
{
label: "Blog",
href: "/blog",
},
{
label: "Changelog",
href: "/changelog",
},
],
},
{
label: "Company",
items: [
{
label: "About",
href: "/about",
},
{
label: "Careers",
href: "/careers",
},
{
label: "Contact",
href: "mailto:hello@example.com",
},
],
},
];
</script>
<Menubar label="Site" {menus} />---
import Menubar from "@/components/markas/Menubar.astro";
const menus = [
{
label: "Products",
items: [
{
label: "Analytics",
href: "/analytics",
},
{
label: "Automation",
href: "/automation",
},
{
label: "Reports",
href: "/reports",
},
],
},
{
label: "Resources",
items: [
{
label: "Documentation",
href: "/docs",
},
{
label: "Blog",
href: "/blog",
},
{
label: "Changelog",
href: "/changelog",
},
],
},
{
label: "Company",
items: [
{
label: "About",
href: "/about",
},
{
label: "Careers",
href: "/careers",
},
{
label: "Contact",
href: "mailto:hello@example.com",
},
],
},
];
---
<Menubar label="Site" menus={menus} />import { Component } from "@angular/core";
import { Menubar } from "./markas/menubar.component";
const menus = [
{
label: "Products",
items: [
{
label: "Analytics",
href: "/analytics",
},
{
label: "Automation",
href: "/automation",
},
{
label: "Reports",
href: "/reports",
},
],
},
{
label: "Resources",
items: [
{
label: "Documentation",
href: "/docs",
},
{
label: "Blog",
href: "/blog",
},
{
label: "Changelog",
href: "/changelog",
},
],
},
{
label: "Company",
items: [
{
label: "About",
href: "/about",
},
{
label: "Careers",
href: "/careers",
},
{
label: "Contact",
href: "mailto:hello@example.com",
},
],
},
];
@Component({
selector: "markas-example",
imports: [Menubar],
template: ` <markas-menubar label="Site" [menus]="menus" /> `,
})
export default class MenubarLinksExample {
protected readonly menus = menus;
}Destructive and disabled items
<x-markas.menubar
label="Project"
:menus="[
['label' => 'Project', 'items' => [
['label' => 'Rename', 'value' => 'rename'],
['label' => 'Duplicate', 'value' => 'duplicate'],
['label' => 'Archive', 'value' => 'archive', 'disabled' => true],
['separator' => true],
['label' => 'Delete project', 'value' => 'delete', 'danger' => true],
]],
['label' => 'Members', 'items' => [
['label' => 'Invite people', 'value' => 'invite'],
['label' => 'Manage roles', 'value' => 'roles'],
['separator' => true],
['label' => 'Remove all guests', 'value' => 'remove-guests', 'danger' => true],
]],
['label' => 'Billing', 'items' => [
['label' => 'View invoices', 'value' => 'invoices'],
['label' => 'Change plan', 'value' => 'plan', 'disabled' => true],
]],
]"
/>import { Menubar } from "@/components/markas/Menubar";
const menus = [
{
label: "Project",
items: [
{
label: "Rename",
value: "rename",
},
{
label: "Duplicate",
value: "duplicate",
},
{
label: "Archive",
value: "archive",
disabled: true,
},
{
separator: true as const,
},
{
label: "Delete project",
value: "delete",
danger: true,
},
],
},
{
label: "Members",
items: [
{
label: "Invite people",
value: "invite",
},
{
label: "Manage roles",
value: "roles",
},
{
separator: true as const,
},
{
label: "Remove all guests",
value: "remove-guests",
danger: true,
},
],
},
{
label: "Billing",
items: [
{
label: "View invoices",
value: "invoices",
},
{
label: "Change plan",
value: "plan",
disabled: true,
},
],
},
];
export default function Example() {
return <Menubar label="Project" menus={menus} />;
}<script setup lang="ts">
import Menubar from "@/components/markas/Menubar.vue";
const menus = [
{
label: "Project",
items: [
{
label: "Rename",
value: "rename",
},
{
label: "Duplicate",
value: "duplicate",
},
{
label: "Archive",
value: "archive",
disabled: true,
},
{
separator: true as const,
},
{
label: "Delete project",
value: "delete",
danger: true,
},
],
},
{
label: "Members",
items: [
{
label: "Invite people",
value: "invite",
},
{
label: "Manage roles",
value: "roles",
},
{
separator: true as const,
},
{
label: "Remove all guests",
value: "remove-guests",
danger: true,
},
],
},
{
label: "Billing",
items: [
{
label: "View invoices",
value: "invoices",
},
{
label: "Change plan",
value: "plan",
disabled: true,
},
],
},
];
</script>
<template>
<Menubar label="Project" :menus="menus" />
</template><script lang="ts">
import Menubar from "$lib/components/markas/Menubar.svelte";
const menus = [
{
label: "Project",
items: [
{
label: "Rename",
value: "rename",
},
{
label: "Duplicate",
value: "duplicate",
},
{
label: "Archive",
value: "archive",
disabled: true,
},
{
separator: true as const,
},
{
label: "Delete project",
value: "delete",
danger: true,
},
],
},
{
label: "Members",
items: [
{
label: "Invite people",
value: "invite",
},
{
label: "Manage roles",
value: "roles",
},
{
separator: true as const,
},
{
label: "Remove all guests",
value: "remove-guests",
danger: true,
},
],
},
{
label: "Billing",
items: [
{
label: "View invoices",
value: "invoices",
},
{
label: "Change plan",
value: "plan",
disabled: true,
},
],
},
];
</script>
<Menubar label="Project" {menus} />---
import Menubar from "@/components/markas/Menubar.astro";
const menus = [
{
label: "Project",
items: [
{
label: "Rename",
value: "rename",
},
{
label: "Duplicate",
value: "duplicate",
},
{
label: "Archive",
value: "archive",
disabled: true,
},
{
separator: true as const,
},
{
label: "Delete project",
value: "delete",
danger: true,
},
],
},
{
label: "Members",
items: [
{
label: "Invite people",
value: "invite",
},
{
label: "Manage roles",
value: "roles",
},
{
separator: true as const,
},
{
label: "Remove all guests",
value: "remove-guests",
danger: true,
},
],
},
{
label: "Billing",
items: [
{
label: "View invoices",
value: "invoices",
},
{
label: "Change plan",
value: "plan",
disabled: true,
},
],
},
];
---
<Menubar label="Project" menus={menus} />import { Component } from "@angular/core";
import { Menubar } from "./markas/menubar.component";
const menus = [
{
label: "Project",
items: [
{
label: "Rename",
value: "rename",
},
{
label: "Duplicate",
value: "duplicate",
},
{
label: "Archive",
value: "archive",
disabled: true,
},
{
separator: true as const,
},
{
label: "Delete project",
value: "delete",
danger: true,
},
],
},
{
label: "Members",
items: [
{
label: "Invite people",
value: "invite",
},
{
label: "Manage roles",
value: "roles",
},
{
separator: true as const,
},
{
label: "Remove all guests",
value: "remove-guests",
danger: true,
},
],
},
{
label: "Billing",
items: [
{
label: "View invoices",
value: "invoices",
},
{
label: "Change plan",
value: "plan",
disabled: true,
},
],
},
];
@Component({
selector: "markas-example",
imports: [Menubar],
template: ` <markas-menubar label="Project" [menus]="menus" /> `,
})
export default class MenubarDangerExample {
protected readonly menus = menus;
}Installation
npx markasui@latest add menubarpnpm dlx markasui@latest add menubaryarn dlx markasui@latest add menubarbunx --bun markasui@latest add menubar- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Install the dependency:
npm install alpinejs - Copy the component source below to
resources/views/components/markas/menubar.blade.php.
@props([
'menus' => [],
'label' => 'Menu',
])
@php
$bar = 'inline-flex items-center gap-1 rounded-lg border border-line bg-surface p-1';
$wrapper = 'contents';
$triggerClass = 'inline-flex h-8 items-center rounded-md px-3 text-sm font-medium whitespace-nowrap text-ink transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=open]:bg-subtle motion-reduce:transition-none';
$menu = 'inset-auto m-0 min-w-48 rounded-lg border border-line bg-surface p-1 text-ink shadow-overlay';
$item = 'flex w-full items-center rounded-md px-3 py-2 text-left text-sm transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none';
$tones = [
'default' => 'text-ink hover:bg-subtle focus:bg-subtle',
'danger' => 'text-danger hover:bg-danger/10 focus:bg-danger/10',
];
$separator = 'my-1 h-px bg-line';
// Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#".
$safeHref = function (string $href): string {
$value = ltrim(str_replace(["\t", "\n", "\r"], '', $href), "\x00..\x20");
$hasScheme = preg_match('/^[a-z][a-z0-9+.\-]*:/i', $value) === 1;
return $hasScheme && preg_match('/^(https?|mailto|tel):/i', $value) !== 1 ? '#' : $href;
};
// Same id on every render, so Livewire's morph (which matches elements by id) keeps the element. Pass `id` to set it.
$idKey = 'markas-menubar|'.(isset($this) && $this instanceof \Livewire\Component ? $this->getId() : '').'|'.($attributes->get('wire:key') ?? $attributes->whereStartsWith('wire:model')->first() ?? $attributes->get('name')).'|';
for ($idIndex = 0; $__env->hasRenderedOnce($idKey.$idIndex); $idIndex++);
$__env->markAsRenderedOnce($idKey.$idIndex);
$id = $attributes->get('id') ?? 'markas-menubar-'.hash('xxh32', $idKey.$idIndex);
@endphp
<div
x-data="{
openIndex: null,
activeIndex: 0,
focusTarget: 'first',
wrap(index, length) {
return (index + length) % length;
},
triggers() {
return Array.from(this.$root.querySelectorAll(':scope > [role=none] > [role=menuitem]'));
},
panels() {
return Array.from(this.$root.querySelectorAll(':scope > [role=none] > [role=menu]'));
},
menuItems(index) {
return Array.from(this.panels()[index]?.querySelectorAll('[role=menuitem]:not(:disabled)') ?? []);
},
focusItem(menuIndex, index) {
const list = this.menuItems(menuIndex);
if (list.length === 0) return;
list[this.wrap(index, list.length)].focus();
},
focusEdge(menuIndex, target) {
this.focusItem(menuIndex, target === 'first' ? 0 : -1);
},
focusTrigger(index) {
const next = this.wrap(index, this.triggers().length);
this.activeIndex = next;
this.triggers()[next].focus();
return next;
},
openMenu(index, target) {
this.focusTarget = target;
this.panels()[index].showPopover();
},
close(index) {
this.panels()[index].hidePopover();
this.triggers()[index].focus();
},
{{-- Tutup menu sekarang, pindah ke menu di sebelahnya, lalu buka. --}}
switchMenu(from, to) {
this.panels()[from].hidePopover();
this.openMenu(this.focusTrigger(to), 'first');
},
select(index, value) {
this.$dispatch('markas-select', value);
this.close(index);
},
{{-- Letakkan menu di bawah pemicu rata kiri, pindah ke atas kalau tidak muat. --}}
place(index) {
const gap = 4;
const trigger = this.triggers()[index];
const panel = this.panels()[index];
if (!trigger || !panel) return;
const anchor = trigger.getBoundingClientRect();
const { width, height } = panel.getBoundingClientRect();
const below = anchor.bottom + gap;
const above = anchor.top - gap - height;
const fitsBelow = below + height <= window.innerHeight;
panel.style.top = (fitsBelow || above < 0 ? below : above) + 'px';
panel.style.left = Math.max(gap, Math.min(anchor.left, window.innerWidth - width - gap)) + 'px';
},
unfollow: null,
{{-- Jalankan ulang penempatan saat halaman digulir atau jendela berubah ukuran. --}}
follow(index) {
this.unfollow?.();
const update = () => this.place(index);
const scrollOptions = { capture: true, passive: true };
window.addEventListener('scroll', update, scrollOptions);
window.addEventListener('resize', update, { passive: true });
this.unfollow = () => {
window.removeEventListener('scroll', update, scrollOptions);
window.removeEventListener('resize', update);
this.unfollow = null;
};
},
destroy() {
this.unfollow?.();
},
{{-- beforetoggle berjalan sinkron, jadi status selalu terbaru untuk tombol berikutnya. --}}
onBeforeToggle(index, event) {
if (event.newState === 'open') {
this.openIndex = index;
this.activeIndex = index;
return;
}
if (this.openIndex === index) this.openIndex = null;
},
onToggle(index, event) {
if (event.newState !== 'open') {
if (this.openIndex === null) this.unfollow?.();
return;
}
this.place(index);
this.follow(index);
this.focusEdge(index, this.focusTarget);
this.focusTarget = 'first';
},
onTriggerKeydown(index, event) {
const move = { ArrowRight: index + 1, ArrowLeft: index - 1, Home: 0, End: -1 }[event.key];
if (move !== undefined) {
event.preventDefault();
this.focusTrigger(move);
return;
}
const target = { ArrowDown: 'first', ArrowUp: 'last' }[event.key];
if (target === undefined) return;
event.preventDefault();
if (this.openIndex === index) return this.focusEdge(index, target);
this.openMenu(index, target);
},
onMenuKeydown(index, event) {
if (event.key === 'Escape') {
event.preventDefault();
return this.close(index);
}
if (event.key === 'Tab') return this.panels()[index].hidePopover();
const side = { ArrowRight: index + 1, ArrowLeft: index - 1 }[event.key];
if (side !== undefined) {
event.preventDefault();
return this.switchMenu(index, side);
}
const current = this.menuItems(index).indexOf(document.activeElement);
const target = { ArrowDown: current + 1, ArrowUp: current - 1, Home: 0, End: -1 }[event.key];
if (target === undefined) return;
event.preventDefault();
this.focusItem(index, target);
},
}"
id="{{ $id }}"
role="menubar"
aria-label="{{ $label }}"
{{ $attributes->except('id')->class([$bar]) }}
>
@foreach ($menus as $menuIndex => $entry)
@php
$menuId = $id.'-menu-'.$menuIndex;
$triggerId = $id.'-trigger-'.$menuIndex;
@endphp
<div role="none" class="{{ $wrapper }}">
<button
id="{{ $triggerId }}"
type="button"
role="menuitem"
tabindex="{{ $loop->first ? 0 : -1 }}"
popovertarget="{{ $menuId }}"
aria-haspopup="menu"
aria-expanded="false"
aria-controls="{{ $menuId }}"
data-state="closed"
:tabindex="activeIndex === {{ $menuIndex }} ? 0 : -1"
:aria-expanded="openIndex === {{ $menuIndex }} ? 'true' : 'false'"
:data-state="openIndex === {{ $menuIndex }} ? 'open' : 'closed'"
@focus="activeIndex = {{ $menuIndex }}"
@keydown="onTriggerKeydown({{ $menuIndex }}, $event)"
class="{{ $triggerClass }}"
>{{ $entry['label'] }}</button>
<div
id="{{ $menuId }}"
popover="auto"
wire:ignore.self
role="menu"
aria-labelledby="{{ $triggerId }}"
data-state="closed"
:data-state="openIndex === {{ $menuIndex }} ? 'open' : 'closed'"
@beforetoggle="onBeforeToggle({{ $menuIndex }}, $event)"
@toggle="onToggle({{ $menuIndex }}, $event)"
@keydown="onMenuKeydown({{ $menuIndex }}, $event)"
class="{{ $menu }}"
>
@foreach ($entry['items'] ?? [] as $option)
@if ($option['separator'] ?? false)
<div role="separator" class="{{ $separator }}"></div>
@else
@php
$itemClass = $item.' '.$tones[($option['danger'] ?? false) ? 'danger' : 'default'];
$value = (string) ($option['value'] ?? $option['label']);
$disabled = (bool) ($option['disabled'] ?? false);
@endphp
@if (isset($option['href']) && ! $disabled)
<a href="{{ $safeHref((string) $option['href']) }}" role="menuitem" tabindex="-1" class="{{ $itemClass }}" @click="select({{ $menuIndex }}, @js($value))">{{ $option['label'] }}</a>
@else
<button type="button" role="menuitem" tabindex="-1" @disabled($disabled) class="{{ $itemClass }}" @click="select({{ $menuIndex }}, @js($value))">{{ $option['label'] }}</button>
@endif
@endif
@endforeach
</div>
</div>
@endforeach
</div>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/components/markas/Menubar.tsx.
"use client";
import {
useEffect,
useId,
useRef,
useState,
type ComponentProps,
type KeyboardEvent,
type ToggleEvent,
} from "react";
const bar =
"inline-flex items-center gap-1 rounded-lg border border-line bg-surface p-1";
const wrapper = "contents";
const triggerClass =
"inline-flex h-8 items-center rounded-md px-3 text-sm font-medium whitespace-nowrap text-ink transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=open]:bg-subtle motion-reduce:transition-none";
const menu =
"inset-auto m-0 min-w-48 rounded-lg border border-line bg-surface p-1 text-ink shadow-overlay";
const item =
"flex w-full items-center rounded-md px-3 py-2 text-left text-sm transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const tones = {
default: "text-ink hover:bg-subtle focus:bg-subtle",
danger: "text-danger hover:bg-danger/10 focus:bg-danger/10",
};
const separator = "my-1 h-px bg-line";
const cx = (...c: (string | false | null | undefined)[]) =>
c.filter(Boolean).join(" ");
const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;
/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". */
const safeHref = (href: string) => {
const cleaned = href.replace(/[\t\n\r]/g, "");
const start = [...cleaned].findIndex((char) => char > " ");
const value = cleaned.slice(Math.max(start, 0));
return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};
const GAP = 4;
const TRIGGER_SELECTOR = ':scope > [role="none"] > [role="menuitem"]';
const MENU_SELECTOR = ':scope > [role="none"] > [role="menu"]';
const ITEM_SELECTOR = '[role="menuitem"]:not(:disabled)';
/** Letakkan menu di bawah pemicu rata kiri, pindah ke atas kalau tidak muat. */
function placeMenu(trigger: HTMLElement, panel: HTMLElement) {
const anchor = trigger.getBoundingClientRect();
const { width, height } = panel.getBoundingClientRect();
const below = anchor.bottom + GAP;
const above = anchor.top - GAP - height;
const fitsBelow = below + height <= window.innerHeight;
const top = fitsBelow || above < 0 ? below : above;
const left = Math.max(
GAP,
Math.min(anchor.left, window.innerWidth - width - GAP),
);
panel.style.top = `${top}px`;
panel.style.left = `${left}px`;
}
/** Jalankan ulang penempatan saat halaman digulir atau jendela berubah ukuran. Mengembalikan fungsi pelepas. */
function followViewport(update: () => void) {
const scrollOptions = { capture: true, passive: true };
window.addEventListener("scroll", update, scrollOptions);
window.addEventListener("resize", update, { passive: true });
return () => {
window.removeEventListener("scroll", update, scrollOptions);
window.removeEventListener("resize", update);
};
}
export type MenubarItem =
| { separator: true }
| {
separator?: false;
label: string;
value?: string;
href?: string;
danger?: boolean;
disabled?: boolean;
};
export type MenubarMenu = { label: string; items: MenubarItem[] };
export type MenubarProps = Omit<ComponentProps<"div">, "onSelect"> & {
menus: MenubarMenu[];
/** Nama aksesibel bar (aria-label). */
label?: string;
onSelect?: (value: string) => void;
};
type FocusTarget = "first" | "last";
const wrap = (index: number, length: number) => (index + length) % length;
export function Menubar({
menus,
label = "Menu",
onSelect,
id,
className,
...props
}: MenubarProps) {
const generatedId = useId();
const baseId = id ?? generatedId;
const barRef = useRef<HTMLDivElement>(null);
const focusTarget = useRef<FocusTarget>("first");
const [openIndex, setOpenIndex] = useState<number | null>(null);
const [activeIndex, setActiveIndex] = useState(0);
const triggers = () =>
Array.from(
barRef.current?.querySelectorAll<HTMLElement>(TRIGGER_SELECTOR) ?? [],
);
const panels = () =>
Array.from(
barRef.current?.querySelectorAll<HTMLElement>(MENU_SELECTOR) ?? [],
);
const menuItems = (index: number) =>
Array.from(
panels()[index]?.querySelectorAll<HTMLElement>(ITEM_SELECTOR) ?? [],
);
useEffect(() => {
if (openIndex === null) return;
return followViewport(() => {
const trigger = triggers()[openIndex];
const panel = panels()[openIndex];
if (trigger && panel) placeMenu(trigger, panel);
});
}, [openIndex]);
const focusItem = (menuIndex: number, index: number) => {
const list = menuItems(menuIndex);
if (list.length === 0) return;
list[wrap(index, list.length)]?.focus();
};
const focusEdge = (menuIndex: number, target: FocusTarget) =>
focusItem(menuIndex, target === "first" ? 0 : -1);
const focusTrigger = (index: number) => {
const next = wrap(index, menus.length);
setActiveIndex(next);
triggers()[next]?.focus();
return next;
};
const openMenu = (index: number, target: FocusTarget) => {
focusTarget.current = target;
panels()[index]?.showPopover();
};
const close = (index: number) => {
panels()[index]?.hidePopover();
triggers()[index]?.focus();
};
/** Tutup menu sekarang, pindah ke menu di sebelahnya, lalu buka. */
const switchMenu = (from: number, to: number) => {
panels()[from]?.hidePopover();
openMenu(focusTrigger(to), "first");
};
const select = (index: number, value: string) => {
onSelect?.(value);
close(index);
};
// beforetoggle berjalan sinkron, jadi status selalu terbaru untuk tombol berikutnya.
const handleBeforeToggle = (
index: number,
event: ToggleEvent<HTMLDivElement>,
) => {
if (event.newState === "open") {
setOpenIndex(index);
setActiveIndex(index);
return;
}
setOpenIndex((current) => (current === index ? null : current));
};
const handleToggle = (index: number, event: ToggleEvent<HTMLDivElement>) => {
const trigger = triggers()[index];
const panel = panels()[index];
if (event.newState !== "open" || !trigger || !panel) return;
placeMenu(trigger, panel);
focusEdge(index, focusTarget.current);
focusTarget.current = "first";
};
const handleTriggerKeyDown = (
index: number,
event: KeyboardEvent<HTMLButtonElement>,
) => {
const moves: Record<string, number | undefined> = {
ArrowRight: index + 1,
ArrowLeft: index - 1,
Home: 0,
End: -1,
};
const move = moves[event.key];
if (move !== undefined) {
event.preventDefault();
focusTrigger(move);
return;
}
const targets: Record<string, FocusTarget | undefined> = {
ArrowDown: "first",
ArrowUp: "last",
};
const target = targets[event.key];
if (target === undefined) return;
event.preventDefault();
if (openIndex === index) return focusEdge(index, target);
openMenu(index, target);
};
const handleMenuKeyDown = (
index: number,
event: KeyboardEvent<HTMLDivElement>,
) => {
if (event.key === "Escape") {
event.preventDefault();
return close(index);
}
if (event.key === "Tab") return panels()[index]?.hidePopover();
const sideways: Record<string, number | undefined> = {
ArrowRight: index + 1,
ArrowLeft: index - 1,
};
const side = sideways[event.key];
if (side !== undefined) {
event.preventDefault();
return switchMenu(index, side);
}
const current = menuItems(index).indexOf(
document.activeElement as HTMLElement,
);
const targets: Record<string, number | undefined> = {
ArrowDown: current + 1,
ArrowUp: current - 1,
Home: 0,
End: -1,
};
const target = targets[event.key];
if (target === undefined) return;
event.preventDefault();
focusItem(index, target);
};
return (
<div
ref={barRef}
id={baseId}
role="menubar"
aria-label={label}
className={cx(bar, className)}
{...props}
>
{menus.map((entry, menuIndex) => {
const menuId = `${baseId}-menu-${menuIndex}`;
const triggerId = `${baseId}-trigger-${menuIndex}`;
const state = openIndex === menuIndex ? "open" : "closed";
return (
<div key={menuIndex} role="none" className={wrapper}>
<button
id={triggerId}
type="button"
role="menuitem"
tabIndex={activeIndex === menuIndex ? 0 : -1}
popoverTarget={menuId}
aria-haspopup="menu"
aria-expanded={openIndex === menuIndex}
aria-controls={menuId}
data-state={state}
className={triggerClass}
onFocus={() => setActiveIndex(menuIndex)}
onKeyDown={(event) => handleTriggerKeyDown(menuIndex, event)}
>
{entry.label}
</button>
<div
id={menuId}
popover="auto"
role="menu"
aria-labelledby={triggerId}
data-state={state}
className={menu}
onBeforeToggle={(event) => handleBeforeToggle(menuIndex, event)}
onToggle={(event) => handleToggle(menuIndex, event)}
onKeyDown={(event) => handleMenuKeyDown(menuIndex, event)}
>
{entry.items.map((option, index) => {
if (option.separator)
return (
<div key={index} role="separator" className={separator} />
);
const itemClass = cx(
item,
tones[option.danger ? "danger" : "default"],
);
const handleClick = () =>
select(menuIndex, option.value ?? option.label);
if (option.href && !option.disabled)
return (
<a
key={index}
href={safeHref(option.href)}
role="menuitem"
tabIndex={-1}
className={itemClass}
onClick={handleClick}
>
{option.label}
</a>
);
return (
<button
key={index}
type="button"
role="menuitem"
tabIndex={-1}
disabled={option.disabled}
className={itemClass}
onClick={handleClick}
>
{option.label}
</button>
);
})}
</div>
</div>
);
})}
</div>
);
}- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/components/markas/Menubar.vue.
<script setup lang="ts">
import { onBeforeUnmount, ref, useId, useTemplateRef } from "vue";
export type MenubarItem =
| { separator: true }
| {
separator?: false;
label: string;
value?: string;
href?: string;
danger?: boolean;
disabled?: boolean;
};
export type MenubarMenu = { label: string; items: MenubarItem[] };
type FocusTarget = "first" | "last";
const props = withDefaults(
defineProps<{
menus: MenubarMenu[];
label?: string;
id?: string;
}>(),
{ label: "Menu", id: undefined },
);
const emit = defineEmits<{ select: [value: string] }>();
const bar =
"inline-flex items-center gap-1 rounded-lg border border-line bg-surface p-1";
const wrapper = "contents";
const triggerClass =
"inline-flex h-8 items-center rounded-md px-3 text-sm font-medium whitespace-nowrap text-ink transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=open]:bg-subtle motion-reduce:transition-none";
const menu =
"inset-auto m-0 min-w-48 rounded-lg border border-line bg-surface p-1 text-ink shadow-overlay";
const item =
"flex w-full items-center rounded-md px-3 py-2 text-left text-sm transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const tones = {
default: "text-ink hover:bg-subtle focus:bg-subtle",
danger: "text-danger hover:bg-danger/10 focus:bg-danger/10",
};
const separator = "my-1 h-px bg-line";
const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;
/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". */
const safeHref = (href: string) => {
const cleaned = href.replace(/[\t\n\r]/g, "");
const start = [...cleaned].findIndex((char) => char > " ");
const value = cleaned.slice(Math.max(start, 0));
return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};
const GAP = 4;
const TRIGGER_SELECTOR = ':scope > [role="none"] > [role="menuitem"]';
const MENU_SELECTOR = ':scope > [role="none"] > [role="menu"]';
const ITEM_SELECTOR = '[role="menuitem"]:not(:disabled)';
/** Letakkan menu di bawah pemicu rata kiri, pindah ke atas kalau tidak muat. */
function placeMenu(trigger: HTMLElement, panel: HTMLElement) {
const anchor = trigger.getBoundingClientRect();
const { width, height } = panel.getBoundingClientRect();
const below = anchor.bottom + GAP;
const above = anchor.top - GAP - height;
const fitsBelow = below + height <= window.innerHeight;
const top = fitsBelow || above < 0 ? below : above;
const left = Math.max(
GAP,
Math.min(anchor.left, window.innerWidth - width - GAP),
);
panel.style.top = `${top}px`;
panel.style.left = `${left}px`;
}
/** Jalankan ulang penempatan saat halaman digulir atau jendela berubah ukuran. Mengembalikan fungsi pelepas. */
function followViewport(update: () => void) {
const scrollOptions = { capture: true, passive: true };
window.addEventListener("scroll", update, scrollOptions);
window.addEventListener("resize", update, { passive: true });
return () => {
window.removeEventListener("scroll", update, scrollOptions);
window.removeEventListener("resize", update);
};
}
const wrap = (index: number, length: number) => (index + length) % length;
const generatedId = useId();
const baseId = props.id ?? generatedId;
const barEl = useTemplateRef<HTMLDivElement>("barRef");
const openIndex = ref<number | null>(null);
const activeIndex = ref(0);
let focusTarget: FocusTarget = "first";
let unfollow: (() => void) | undefined;
const triggers = () =>
Array.from(
barEl.value?.querySelectorAll<HTMLElement>(TRIGGER_SELECTOR) ?? [],
);
const panels = () =>
Array.from(barEl.value?.querySelectorAll<HTMLElement>(MENU_SELECTOR) ?? []);
const menuItems = (index: number) =>
Array.from(
panels()[index]?.querySelectorAll<HTMLElement>(ITEM_SELECTOR) ?? [],
);
function focusItem(menuIndex: number, index: number) {
const list = menuItems(menuIndex);
if (list.length === 0) return;
list[wrap(index, list.length)]?.focus();
}
const focusEdge = (menuIndex: number, target: FocusTarget) =>
focusItem(menuIndex, target === "first" ? 0 : -1);
function focusTrigger(index: number) {
const next = wrap(index, props.menus.length);
activeIndex.value = next;
triggers()[next]?.focus();
return next;
}
function openMenu(index: number, target: FocusTarget) {
focusTarget = target;
panels()[index]?.showPopover();
}
function close(index: number) {
panels()[index]?.hidePopover();
triggers()[index]?.focus();
}
/** Tutup menu sekarang, pindah ke menu di sebelahnya, lalu buka. */
function switchMenu(from: number, to: number) {
panels()[from]?.hidePopover();
openMenu(focusTrigger(to), "first");
}
function select(index: number, value: string) {
emit("select", value);
close(index);
}
function stopFollowing() {
unfollow?.();
unfollow = undefined;
}
function place(index: number) {
const trigger = triggers()[index];
const panel = panels()[index];
if (trigger && panel) placeMenu(trigger, panel);
}
// beforetoggle berjalan sinkron, jadi status selalu terbaru untuk tombol berikutnya.
function onBeforeToggle(index: number, event: Event) {
if ((event as ToggleEvent).newState === "open") {
openIndex.value = index;
activeIndex.value = index;
return;
}
if (openIndex.value === index) openIndex.value = null;
}
function onToggle(index: number, event: Event) {
if ((event as ToggleEvent).newState !== "open") {
if (openIndex.value === null) stopFollowing();
return;
}
stopFollowing();
place(index);
unfollow = followViewport(() => place(index));
focusEdge(index, focusTarget);
focusTarget = "first";
}
onBeforeUnmount(stopFollowing);
function onTriggerKeydown(index: number, event: KeyboardEvent) {
const moves: Record<string, number | undefined> = {
ArrowRight: index + 1,
ArrowLeft: index - 1,
Home: 0,
End: -1,
};
const move = moves[event.key];
if (move !== undefined) {
event.preventDefault();
focusTrigger(move);
return;
}
const targets: Record<string, FocusTarget | undefined> = {
ArrowDown: "first",
ArrowUp: "last",
};
const target = targets[event.key];
if (target === undefined) return;
event.preventDefault();
if (openIndex.value === index) return focusEdge(index, target);
openMenu(index, target);
}
function onMenuKeydown(index: number, event: KeyboardEvent) {
if (event.key === "Escape") {
event.preventDefault();
return close(index);
}
if (event.key === "Tab") return panels()[index]?.hidePopover();
const sideways: Record<string, number | undefined> = {
ArrowRight: index + 1,
ArrowLeft: index - 1,
};
const side = sideways[event.key];
if (side !== undefined) {
event.preventDefault();
return switchMenu(index, side);
}
const current = menuItems(index).indexOf(
document.activeElement as HTMLElement,
);
const targets: Record<string, number | undefined> = {
ArrowDown: current + 1,
ArrowUp: current - 1,
Home: 0,
End: -1,
};
const target = targets[event.key];
if (target === undefined) return;
event.preventDefault();
focusItem(index, target);
}
</script>
<template>
<div
:id="baseId"
ref="barRef"
role="menubar"
:aria-label="props.label"
:class="bar"
>
<div
v-for="(entry, menuIndex) in props.menus"
:key="menuIndex"
role="none"
:class="wrapper"
>
<button
:id="`${baseId}-trigger-${menuIndex}`"
type="button"
role="menuitem"
:tabindex="activeIndex === menuIndex ? 0 : -1"
:popovertarget="`${baseId}-menu-${menuIndex}`"
aria-haspopup="menu"
:aria-expanded="openIndex === menuIndex ? 'true' : 'false'"
:aria-controls="`${baseId}-menu-${menuIndex}`"
:data-state="openIndex === menuIndex ? 'open' : 'closed'"
:class="triggerClass"
@focus="activeIndex = menuIndex"
@keydown="onTriggerKeydown(menuIndex, $event)"
>
{{ entry.label }}
</button>
<div
:id="`${baseId}-menu-${menuIndex}`"
popover="auto"
role="menu"
:aria-labelledby="`${baseId}-trigger-${menuIndex}`"
:data-state="openIndex === menuIndex ? 'open' : 'closed'"
:class="menu"
@beforetoggle="onBeforeToggle(menuIndex, $event)"
@toggle="onToggle(menuIndex, $event)"
@keydown="onMenuKeydown(menuIndex, $event)"
>
<template v-for="(option, index) in entry.items" :key="index">
<div v-if="option.separator" role="separator" :class="separator" />
<a
v-else-if="option.href && !option.disabled"
:href="safeHref(option.href)"
role="menuitem"
tabindex="-1"
:class="[item, tones[option.danger ? 'danger' : 'default']]"
@click="select(menuIndex, option.value ?? option.label)"
>{{ option.label }}</a
>
<button
v-else
type="button"
role="menuitem"
tabindex="-1"
:disabled="option.disabled"
:class="[item, tones[option.danger ? 'danger' : 'default']]"
@click="select(menuIndex, option.value ?? option.label)"
>
{{ option.label }}
</button>
</template>
</div>
</div>
</div>
</template>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/lib/components/markas/Menubar.svelte.
<script lang="ts" module>
export type MenubarItem =
| { separator: true }
| {
separator?: false;
label: string;
value?: string;
href?: string;
danger?: boolean;
disabled?: boolean;
};
export type MenubarMenu = { label: string; items: MenubarItem[] };
</script>
<script lang="ts">
import type { HTMLAttributes } from "svelte/elements";
const bar =
"inline-flex items-center gap-1 rounded-lg border border-line bg-surface p-1";
const wrapper = "contents";
const triggerClass =
"inline-flex h-8 items-center rounded-md px-3 text-sm font-medium whitespace-nowrap text-ink transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=open]:bg-subtle motion-reduce:transition-none";
const menu =
"inset-auto m-0 min-w-48 rounded-lg border border-line bg-surface p-1 text-ink shadow-overlay";
const item =
"flex w-full items-center rounded-md px-3 py-2 text-left text-sm transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const tones = {
default: "text-ink hover:bg-subtle focus:bg-subtle",
danger: "text-danger hover:bg-danger/10 focus:bg-danger/10",
};
const separator = "my-1 h-px bg-line";
const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;
/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". */
const safeHref = (href: string) => {
const cleaned = href.replace(/[\t\n\r]/g, "");
const start = [...cleaned].findIndex((char) => char > " ");
const value = cleaned.slice(Math.max(start, 0));
return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};
const GAP = 4;
const TRIGGER_SELECTOR = ':scope > [role="none"] > [role="menuitem"]';
const MENU_SELECTOR = ':scope > [role="none"] > [role="menu"]';
const ITEM_SELECTOR = '[role="menuitem"]:not(:disabled)';
/** Letakkan menu di bawah pemicu rata kiri, pindah ke atas kalau tidak muat. */
function placeMenu(trigger: HTMLElement, panel: HTMLElement) {
const anchor = trigger.getBoundingClientRect();
const { width, height } = panel.getBoundingClientRect();
const below = anchor.bottom + GAP;
const above = anchor.top - GAP - height;
const fitsBelow = below + height <= window.innerHeight;
const top = fitsBelow || above < 0 ? below : above;
const left = Math.max(
GAP,
Math.min(anchor.left, window.innerWidth - width - GAP),
);
panel.style.top = `${top}px`;
panel.style.left = `${left}px`;
}
/** Jalankan ulang penempatan saat halaman digulir atau jendela berubah ukuran. Mengembalikan fungsi pelepas. */
function followViewport(update: () => void) {
const scrollOptions = { capture: true, passive: true };
window.addEventListener("scroll", update, scrollOptions);
window.addEventListener("resize", update, { passive: true });
return () => {
window.removeEventListener("scroll", update, scrollOptions);
window.removeEventListener("resize", update);
};
}
type FocusTarget = "first" | "last";
const wrap = (index: number, length: number) => (index + length) % length;
type Props = Omit<HTMLAttributes<HTMLDivElement>, "onselect"> & {
menus: MenubarMenu[];
/** Nama aksesibel bar (aria-label). */
label?: string;
onselect?: (value: string) => void;
};
let {
menus,
label = "Menu",
onselect,
id,
class: className,
...rest
}: Props = $props();
const generatedId = $props.id();
const baseId = $derived(id ?? generatedId);
let barEl = $state<HTMLDivElement>();
let openIndex = $state<number | null>(null);
let activeIndex = $state(0);
let focusTarget: FocusTarget = "first";
const triggers = () =>
Array.from(barEl?.querySelectorAll<HTMLElement>(TRIGGER_SELECTOR) ?? []);
const panels = () =>
Array.from(barEl?.querySelectorAll<HTMLElement>(MENU_SELECTOR) ?? []);
const menuItems = (index: number) =>
Array.from(
panels()[index]?.querySelectorAll<HTMLElement>(ITEM_SELECTOR) ?? [],
);
$effect(() => {
const index = openIndex;
if (index === null) return;
return followViewport(() => {
const trigger = triggers()[index];
const panel = panels()[index];
if (trigger && panel) placeMenu(trigger, panel);
});
});
const focusItem = (menuIndex: number, index: number) => {
const list = menuItems(menuIndex);
if (list.length === 0) return;
list[wrap(index, list.length)]?.focus();
};
const focusEdge = (menuIndex: number, target: FocusTarget) =>
focusItem(menuIndex, target === "first" ? 0 : -1);
const focusTrigger = (index: number) => {
const next = wrap(index, menus.length);
activeIndex = next;
triggers()[next]?.focus();
return next;
};
const openMenu = (index: number, target: FocusTarget) => {
focusTarget = target;
panels()[index]?.showPopover();
};
const close = (index: number) => {
panels()[index]?.hidePopover();
triggers()[index]?.focus();
};
/** Tutup menu sekarang, pindah ke menu di sebelahnya, lalu buka. */
const switchMenu = (from: number, to: number) => {
panels()[from]?.hidePopover();
openMenu(focusTrigger(to), "first");
};
const select = (index: number, value: string) => {
onselect?.(value);
close(index);
};
// beforetoggle berjalan sinkron, jadi status selalu terbaru untuk tombol berikutnya.
function handleBeforeToggle(index: number, event: ToggleEvent) {
if (event.newState === "open") {
openIndex = index;
activeIndex = index;
return;
}
if (openIndex === index) openIndex = null;
}
function handleToggle(index: number, event: ToggleEvent) {
const trigger = triggers()[index];
const panel = panels()[index];
if (event.newState !== "open" || !trigger || !panel) return;
placeMenu(trigger, panel);
focusEdge(index, focusTarget);
focusTarget = "first";
}
function handleTriggerKeydown(index: number, event: KeyboardEvent) {
const moves: Record<string, number | undefined> = {
ArrowRight: index + 1,
ArrowLeft: index - 1,
Home: 0,
End: -1,
};
const move = moves[event.key];
if (move !== undefined) {
event.preventDefault();
focusTrigger(move);
return;
}
const targets: Record<string, FocusTarget | undefined> = {
ArrowDown: "first",
ArrowUp: "last",
};
const target = targets[event.key];
if (target === undefined) return;
event.preventDefault();
if (openIndex === index) return focusEdge(index, target);
openMenu(index, target);
}
function handleMenuKeydown(index: number, event: KeyboardEvent) {
if (event.key === "Escape") {
event.preventDefault();
return close(index);
}
if (event.key === "Tab") return panels()[index]?.hidePopover();
const sideways: Record<string, number | undefined> = {
ArrowRight: index + 1,
ArrowLeft: index - 1,
};
const side = sideways[event.key];
if (side !== undefined) {
event.preventDefault();
return switchMenu(index, side);
}
const current = menuItems(index).indexOf(
document.activeElement as HTMLElement,
);
const targets: Record<string, number | undefined> = {
ArrowDown: current + 1,
ArrowUp: current - 1,
Home: 0,
End: -1,
};
const target = targets[event.key];
if (target === undefined) return;
event.preventDefault();
focusItem(index, target);
}
</script>
<div
bind:this={barEl}
id={baseId}
role="menubar"
aria-label={label}
class={[bar, className]}
{...rest}
>
{#each menus as entry, menuIndex (menuIndex)}
{@const menuId = `${baseId}-menu-${menuIndex}`}
{@const triggerId = `${baseId}-trigger-${menuIndex}`}
{@const state = openIndex === menuIndex ? "open" : "closed"}
<div role="none" class={wrapper}>
<button
id={triggerId}
type="button"
role="menuitem"
tabindex={activeIndex === menuIndex ? 0 : -1}
popovertarget={menuId}
aria-haspopup="menu"
aria-expanded={openIndex === menuIndex}
aria-controls={menuId}
data-state={state}
class={triggerClass}
onfocus={() => (activeIndex = menuIndex)}
onkeydown={(event) => handleTriggerKeydown(menuIndex, event)}
>{entry.label}</button
>
<!-- Fokus ada di item menu, bukan di wadah menu (sama dengan React). -->
<!-- svelte-ignore a11y_interactive_supports_focus -->
<div
id={menuId}
popover="auto"
role="menu"
aria-labelledby={triggerId}
data-state={state}
class={menu}
onbeforetoggle={(event) => handleBeforeToggle(menuIndex, event)}
ontoggle={(event) => handleToggle(menuIndex, event)}
onkeydown={(event) => handleMenuKeydown(menuIndex, event)}
>
{#each entry.items as option, index (index)}
{#if option.separator}
<div role="separator" class={separator}></div>
{:else if option.href && !option.disabled}
<a
href={safeHref(option.href)}
role="menuitem"
tabindex="-1"
class={[item, tones[option.danger ? "danger" : "default"]]}
onclick={() => select(menuIndex, option.value ?? option.label)}
>{option.label}</a
>
{:else}
<button
type="button"
role="menuitem"
tabindex="-1"
disabled={option.disabled}
class={[item, tones[option.danger ? "danger" : "default"]]}
onclick={() => select(menuIndex, option.value ?? option.label)}
>{option.label}</button
>
{/if}
{/each}
</div>
</div>
{/each}
</div>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/components/markas/Menubar.astro.
---
import type { HTMLAttributes } from "astro/types";
const bar =
"inline-flex items-center gap-1 rounded-lg border border-line bg-surface p-1";
const wrapper = "contents";
const triggerClass =
"inline-flex h-8 items-center rounded-md px-3 text-sm font-medium whitespace-nowrap text-ink transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=open]:bg-subtle motion-reduce:transition-none";
const menu =
"inset-auto m-0 min-w-48 rounded-lg border border-line bg-surface p-1 text-ink shadow-overlay";
const item =
"flex w-full items-center rounded-md px-3 py-2 text-left text-sm transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const tones = {
default: "text-ink hover:bg-subtle focus:bg-subtle",
danger: "text-danger hover:bg-danger/10 focus:bg-danger/10",
};
const separator = "my-1 h-px bg-line";
const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;
/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". */
const safeHref = (href: string) => {
const cleaned = href.replace(/[\t\n\r]/g, "");
const start = [...cleaned].findIndex((char) => char > " ");
const value = cleaned.slice(Math.max(start, 0));
return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};
export type MenubarItem =
| { separator: true }
| {
separator?: false;
label: string;
value?: string;
href?: string;
danger?: boolean;
disabled?: boolean;
};
export type MenubarMenu = { label: string; items: MenubarItem[] };
type Props = HTMLAttributes<"div"> & {
menus: MenubarMenu[];
/** Nama aksesibel bar (aria-label). */
label?: string;
};
const { menus, label = "Menu", id, class: className, ...rest } = Astro.props;
const baseId = id ?? `markas-menubar-${crypto.randomUUID().slice(0, 8)}`;
---
<markas-menubar class="contents">
<div
id={baseId}
role="menubar"
aria-label={label}
class:list={[bar, className]}
{...rest}
>
{
menus.map((entry, menuIndex) => {
const menuId = `${baseId}-menu-${menuIndex}`;
const triggerId = `${baseId}-trigger-${menuIndex}`;
return (
<div role="none" class={wrapper}>
<button
id={triggerId}
type="button"
role="menuitem"
tabindex={menuIndex === 0 ? 0 : -1}
popovertarget={menuId}
aria-haspopup="menu"
aria-expanded="false"
aria-controls={menuId}
data-state="closed"
class={triggerClass}
>
{entry.label}
</button>
<div
id={menuId}
popover="auto"
role="menu"
aria-labelledby={triggerId}
data-state="closed"
class={menu}
>
{entry.items.map((option) => {
if (option.separator)
return <div role="separator" class={separator} />;
const itemClass = [
item,
tones[option.danger ? "danger" : "default"],
];
const value = option.value ?? option.label;
return option.href && !option.disabled ? (
<a
href={safeHref(option.href)}
role="menuitem"
tabindex="-1"
data-value={value}
class:list={itemClass}
>
{option.label}
</a>
) : (
<button
type="button"
role="menuitem"
tabindex="-1"
disabled={option.disabled}
data-value={value}
class:list={itemClass}
>
{option.label}
</button>
);
})}
</div>
</div>
);
})
}
</div>
</markas-menubar>
<script>
type FocusTarget = "first" | "last";
type Moves = Record<string, number | undefined>;
const GAP = 4;
const TRIGGER_SELECTOR = ':scope > [role="none"] > [role="menuitem"]';
const MENU_SELECTOR = ':scope > [role="none"] > [role="menu"]';
const ITEM_SELECTOR = '[role="menuitem"]:not(:disabled)';
const wrap = (index: number, length: number) => (index + length) % length;
/** Letakkan menu di bawah pemicu rata kiri, pindah ke atas kalau tidak muat. */
function placeMenu(trigger: HTMLElement, panel: HTMLElement) {
const anchor = trigger.getBoundingClientRect();
const { width, height } = panel.getBoundingClientRect();
const below = anchor.bottom + GAP;
const above = anchor.top - GAP - height;
const fitsBelow = below + height <= innerHeight;
panel.style.top = `${fitsBelow || above < 0 ? below : above}px`;
panel.style.left = `${Math.max(GAP, Math.min(anchor.left, innerWidth - width - GAP))}px`;
}
// Satu custom element per bar: ia menyimpan menu terbuka dan item aktif (roving tabindex), dan
// mengikuti gulir dan ukuran jendela hanya selama sebuah menu terbuka.
class MarkasMenubar extends HTMLElement {
private bar!: HTMLElement;
private openIndex: number | null = null;
private focusTarget: FocusTarget = "first";
private readonly place = () => {
const index = this.openIndex;
if (index !== null) placeMenu(this.triggers()[index]!, this.panels()[index]!);
};
connectedCallback() {
if (this.bar) return;
this.bar = this.querySelector("[role=menubar]")!;
this.bar.addEventListener("keydown", (event) => this.onKeydown(event));
this.bar.addEventListener("focusin", (event) => {
const index = this.triggers().indexOf(event.target as HTMLElement);
if (index >= 0) this.setActive(index);
});
this.bar.addEventListener("click", (event) => {
const entry = (event.target as Element).closest<HTMLElement>(
"[role=menu] [role=menuitem]",
);
if (!entry) return;
this.dispatchEvent(
new CustomEvent("markas-select", {
bubbles: true,
detail: entry.dataset.value,
}),
);
this.close(this.panels().indexOf(entry.closest("[role=menu]")!));
});
// beforetoggle dan toggle tidak bubble; dengarkan di fase capture. beforetoggle berjalan
// sinkron, jadi status selalu terbaru untuk tombol berikutnya.
this.bar.addEventListener(
"beforetoggle",
(event) => this.onBeforeToggle(event as ToggleEvent),
true,
);
this.bar.addEventListener(
"toggle",
(event) => this.onToggle(event as ToggleEvent),
true,
);
}
disconnectedCallback() {
this.unfollow();
}
private triggers() {
return [...this.bar.querySelectorAll<HTMLElement>(TRIGGER_SELECTOR)];
}
private panels() {
return [...this.bar.querySelectorAll<HTMLElement>(MENU_SELECTOR)];
}
private menuItems(index: number) {
return [
...(this.panels()[index]?.querySelectorAll<HTMLElement>(
ITEM_SELECTOR,
) ?? []),
];
}
private follow() {
addEventListener("scroll", this.place, { capture: true, passive: true });
addEventListener("resize", this.place, { passive: true });
}
private unfollow() {
removeEventListener("scroll", this.place, true);
removeEventListener("resize", this.place);
}
private setActive(index: number) {
this.triggers().forEach((trigger, i) => (trigger.tabIndex = i === index ? 0 : -1));
}
private setState(index: number, open: boolean) {
const state = open ? "open" : "closed";
const trigger = this.triggers()[index]!;
trigger.ariaExpanded = `${open}`;
trigger.dataset.state = state;
this.panels()[index]!.dataset.state = state;
}
private focusItem(menuIndex: number, index: number) {
const list = this.menuItems(menuIndex);
if (list.length > 0) list[wrap(index, list.length)]!.focus();
}
private focusEdge(menuIndex: number, target: FocusTarget) {
this.focusItem(menuIndex, target === "first" ? 0 : -1);
}
private focusTrigger(index: number) {
const all = this.triggers();
const next = wrap(index, all.length);
this.setActive(next);
all[next]!.focus();
return next;
}
private openMenu(index: number, target: FocusTarget) {
this.focusTarget = target;
this.panels()[index]?.showPopover();
}
private close(index: number) {
this.panels()[index]?.hidePopover();
this.triggers()[index]?.focus();
}
private onBeforeToggle(event: ToggleEvent) {
const index = this.panels().indexOf(event.target as HTMLElement);
if (index < 0) return;
const open = event.newState === "open";
this.setState(index, open);
if (open) {
this.openIndex = index;
this.setActive(index);
} else if (this.openIndex === index) {
this.openIndex = null;
}
}
private onToggle(event: ToggleEvent) {
const index = this.panels().indexOf(event.target as HTMLElement);
if (index < 0) return;
this.unfollow();
if (event.newState !== "open") {
if (this.openIndex !== null) this.follow();
return;
}
this.place();
this.follow();
this.focusEdge(index, this.focusTarget);
this.focusTarget = "first";
}
private onKeydown(event: KeyboardEvent) {
const target = event.target as HTMLElement;
const trigger = this.triggers().indexOf(target);
if (trigger >= 0) return this.onTriggerKeydown(trigger, event);
const menu = this.panels().indexOf(target.closest("[role=menu]")!);
if (menu >= 0) this.onMenuKeydown(menu, event);
}
private onTriggerKeydown(index: number, event: KeyboardEvent) {
const moves: Moves = { ArrowRight: index + 1, ArrowLeft: index - 1, Home: 0, End: -1 };
const move = moves[event.key];
if (move !== undefined) {
event.preventDefault();
this.focusTrigger(move);
return;
}
const targets: Record<string, FocusTarget | undefined> = {
ArrowDown: "first",
ArrowUp: "last",
};
const target = targets[event.key];
if (target === undefined) return;
event.preventDefault();
if (this.openIndex === index) return this.focusEdge(index, target);
this.openMenu(index, target);
}
private onMenuKeydown(index: number, event: KeyboardEvent) {
if (event.key === "Escape") {
event.preventDefault();
return this.close(index);
}
if (event.key === "Tab") return this.panels()[index]?.hidePopover();
const sideways: Moves = { ArrowRight: index + 1, ArrowLeft: index - 1 };
const side = sideways[event.key];
if (side !== undefined) {
event.preventDefault();
// Tutup menu sekarang, pindah ke menu di sebelahnya, lalu buka.
this.panels()[index]?.hidePopover();
return this.openMenu(this.focusTrigger(side), "first");
}
const current = this.menuItems(index).indexOf(
document.activeElement as HTMLElement,
);
const targets: Moves = {
ArrowDown: current + 1,
ArrowUp: current - 1,
Home: 0,
End: -1,
};
const target = targets[event.key];
if (target === undefined) return;
event.preventDefault();
this.focusItem(index, target);
}
}
if (!customElements.get("markas-menubar"))
customElements.define("markas-menubar", MarkasMenubar);
</script>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/app/markas/menubar.component.ts.
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
computed,
DestroyRef,
type ElementRef,
inject,
input,
output,
signal,
viewChild,
} from "@angular/core";
const bar =
"inline-flex items-center gap-1 rounded-lg border border-line bg-surface p-1";
const wrapper = "contents";
const triggerClass =
"inline-flex h-8 items-center rounded-md px-3 text-sm font-medium whitespace-nowrap text-ink transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=open]:bg-subtle motion-reduce:transition-none";
const menu =
"inset-auto m-0 min-w-48 rounded-lg border border-line bg-surface p-1 text-ink shadow-overlay";
const item =
"flex w-full items-center rounded-md px-3 py-2 text-left text-sm transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const tones = {
default: "text-ink hover:bg-subtle focus:bg-subtle",
danger: "text-danger hover:bg-danger/10 focus:bg-danger/10",
};
const separator = "my-1 h-px bg-line";
const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;
/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". */
const safeHref = (href: string) => {
const cleaned = href.replace(/[\t\n\r]/g, "");
const start = [...cleaned].findIndex((char) => char > " ");
const value = cleaned.slice(Math.max(start, 0));
return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};
const GAP = 4;
const TRIGGER_SELECTOR = ':scope > [role="none"] > [role="menuitem"]';
const MENU_SELECTOR = ':scope > [role="none"] > [role="menu"]';
const ITEM_SELECTOR = '[role="menuitem"]:not(:disabled)';
/** Letakkan menu di bawah pemicu rata kiri, pindah ke atas kalau tidak muat. */
function placeMenu(trigger: HTMLElement, panel: HTMLElement) {
const anchor = trigger.getBoundingClientRect();
const { width, height } = panel.getBoundingClientRect();
const below = anchor.bottom + GAP;
const above = anchor.top - GAP - height;
const fitsBelow = below + height <= window.innerHeight;
const top = fitsBelow || above < 0 ? below : above;
const left = Math.max(
GAP,
Math.min(anchor.left, window.innerWidth - width - GAP),
);
panel.style.top = `${top}px`;
panel.style.left = `${left}px`;
}
/** Jalankan ulang penempatan saat halaman digulir atau jendela berubah ukuran. Mengembalikan fungsi pelepas. */
function followViewport(update: () => void) {
const scrollOptions = { capture: true, passive: true };
window.addEventListener("scroll", update, scrollOptions);
window.addEventListener("resize", update, { passive: true });
return () => {
window.removeEventListener("scroll", update, scrollOptions);
window.removeEventListener("resize", update);
};
}
export type MenubarItem =
| { separator: true }
| {
separator?: false;
label: string;
value?: string;
href?: string;
danger?: boolean;
disabled?: boolean;
};
export type MenubarMenu = { label: string; items: MenubarItem[] };
type FocusTarget = "first" | "last";
type Option = Exclude<MenubarItem, { separator: true }>;
const wrap = (index: number, length: number) => (index + length) % length;
let nextId = 0;
/** Host stays out of layout; id, title, and class move to the bar. */
@Component({
selector: "markas-menubar",
changeDetection: ChangeDetectionStrategy.OnPush,
host: { class: "contents", "[attr.id]": "null", "[attr.title]": "null" },
template: `
<div
#bar
[id]="baseId()"
role="menubar"
[attr.aria-label]="label()"
[class]="barClasses()"
>
@for (entry of menus(); track $index; let menuIndex = $index) {
<div role="none" [class]="wrapper">
<button
[id]="baseId() + '-trigger-' + menuIndex"
type="button"
role="menuitem"
[tabIndex]="activeIndex() === menuIndex ? 0 : -1"
[attr.popovertarget]="baseId() + '-menu-' + menuIndex"
aria-haspopup="menu"
[attr.aria-expanded]="openIndex() === menuIndex"
[attr.aria-controls]="baseId() + '-menu-' + menuIndex"
[attr.data-state]="openIndex() === menuIndex ? 'open' : 'closed'"
[class]="triggerClass"
(focus)="activeIndex.set(menuIndex)"
(keydown)="handleTriggerKeydown(menuIndex, $event)"
>
{{ entry.label }}
</button>
<div
[id]="baseId() + '-menu-' + menuIndex"
popover="auto"
role="menu"
[attr.aria-labelledby]="baseId() + '-trigger-' + menuIndex"
[attr.data-state]="openIndex() === menuIndex ? 'open' : 'closed'"
[class]="menu"
(beforetoggle)="handleBeforeToggle(menuIndex, $event)"
(toggle)="handleToggle(menuIndex, $event)"
(keydown)="handleMenuKeydown(menuIndex, $event)"
>
@for (option of entry.items; track $index) {
@if (option.separator) {
<div role="separator" [class]="separator"></div>
} @else if (option.href && !option.disabled) {
<a
[href]="safeHref(option.href)"
role="menuitem"
tabindex="-1"
[class]="itemClass(option)"
(click)="select(menuIndex, option)"
>{{ option.label }}</a
>
} @else {
<button
type="button"
role="menuitem"
tabindex="-1"
[disabled]="option.disabled"
[class]="itemClass(option)"
(click)="select(menuIndex, option)"
>
{{ option.label }}
</button>
}
}
</div>
</div>
}
</div>
`,
})
export class Menubar {
readonly menus = input.required<MenubarMenu[]>();
/** Nama aksesibel bar (aria-label). */
readonly label = input("Menu");
readonly id = input<string>();
readonly userClass = input("", { alias: "class" });
/** Emits the item value (or label) when an item is selected. */
readonly selected = output<string>();
protected readonly wrapper = wrapper;
protected readonly triggerClass = triggerClass;
protected readonly menu = menu;
protected readonly separator = separator;
protected readonly safeHref = safeHref;
protected readonly openIndex = signal<number | null>(null);
protected readonly activeIndex = signal(0);
private readonly generatedId = `markas-menubar-${nextId++}`;
protected readonly baseId = computed(() => this.id() ?? this.generatedId);
protected readonly barClasses = computed(() =>
[bar, this.userClass()].filter(Boolean).join(" "),
);
private readonly bar = viewChild.required<ElementRef<HTMLElement>>("bar");
private readonly changes = inject(ChangeDetectorRef);
private focusTarget: FocusTarget = "first";
private unfollow?: () => void;
constructor() {
inject(DestroyRef).onDestroy(() => this.unfollow?.());
}
protected itemClass(option: Option) {
return `${item} ${tones[option.danger ? "danger" : "default"]}`;
}
private triggers() {
return Array.from(
this.bar().nativeElement.querySelectorAll<HTMLElement>(TRIGGER_SELECTOR),
);
}
private panels() {
return Array.from(
this.bar().nativeElement.querySelectorAll<HTMLElement>(MENU_SELECTOR),
);
}
private menuItems(index: number) {
return Array.from(
this.panels()[index]?.querySelectorAll<HTMLElement>(ITEM_SELECTOR) ?? [],
);
}
private focusItem(menuIndex: number, index: number) {
const list = this.menuItems(menuIndex);
if (list.length === 0) return;
list[wrap(index, list.length)]?.focus();
}
private focusEdge(menuIndex: number, target: FocusTarget) {
this.focusItem(menuIndex, target === "first" ? 0 : -1);
}
private focusTrigger(index: number) {
const next = wrap(index, this.menus().length);
this.activeIndex.set(next);
// Render the roving tabindex now (like React's sync update), so a Tab pressed right after lands correctly.
this.changes.detectChanges();
this.triggers()[next]?.focus();
return next;
}
private openMenu(index: number, target: FocusTarget) {
this.focusTarget = target;
this.panels()[index]?.showPopover();
}
private close(index: number) {
this.panels()[index]?.hidePopover();
this.triggers()[index]?.focus();
}
protected select(index: number, option: Option) {
this.selected.emit(option.value ?? option.label);
this.close(index);
}
/** beforetoggle berjalan sinkron, jadi status selalu terbaru untuk tombol berikutnya. */
protected handleBeforeToggle(index: number, event: Event) {
if ((event as ToggleEvent).newState === "open") {
this.openIndex.set(index);
this.activeIndex.set(index);
return;
}
this.openIndex.update((current) => (current === index ? null : current));
}
protected handleToggle(index: number, event: Event) {
this.unfollow?.();
this.unfollow = undefined;
const open = this.openIndex();
if (open !== null)
this.unfollow = followViewport(() => {
const trigger = this.triggers()[open];
const panel = this.panels()[open];
if (trigger && panel) placeMenu(trigger, panel);
});
const trigger = this.triggers()[index];
const panel = this.panels()[index];
if ((event as ToggleEvent).newState !== "open" || !trigger || !panel)
return;
placeMenu(trigger, panel);
this.focusEdge(index, this.focusTarget);
this.focusTarget = "first";
}
protected handleTriggerKeydown(index: number, event: KeyboardEvent) {
const moves: Record<string, number | undefined> = {
ArrowRight: index + 1,
ArrowLeft: index - 1,
Home: 0,
End: -1,
};
const move = moves[event.key];
if (move !== undefined) {
event.preventDefault();
this.focusTrigger(move);
return;
}
const targets: Record<string, FocusTarget | undefined> = {
ArrowDown: "first",
ArrowUp: "last",
};
const target = targets[event.key];
if (target === undefined) return;
event.preventDefault();
if (this.openIndex() === index) return this.focusEdge(index, target);
this.openMenu(index, target);
}
protected handleMenuKeydown(index: number, event: KeyboardEvent) {
if (event.key === "Escape") {
event.preventDefault();
return this.close(index);
}
if (event.key === "Tab") return this.panels()[index]?.hidePopover();
const sideways: Record<string, number | undefined> = {
ArrowRight: index + 1,
ArrowLeft: index - 1,
};
const side = sideways[event.key];
if (side !== undefined) {
event.preventDefault();
// Tutup menu sekarang, pindah ke menu di sebelahnya, lalu buka.
this.panels()[index]?.hidePopover();
return this.openMenu(this.focusTrigger(side), "first");
}
const current = this.menuItems(index).indexOf(
document.activeElement as HTMLElement,
);
const targets: Record<string, number | undefined> = {
ArrowDown: current + 1,
ArrowUp: current - 1,
Home: 0,
End: -1,
};
const target = targets[event.key];
if (target === undefined) return;
event.preventDefault();
this.focusItem(index, target);
}
}Usage
<x-markas.menubar
:menus="[
['label' => 'File', 'items' => [
['label' => 'New file', 'value' => 'new'],
['label' => 'Save', 'value' => 'save'],
]],
['label' => 'Edit', 'items' => [
['label' => 'Undo', 'value' => 'undo'],
['separator' => true],
['label' => 'Delete', 'value' => 'delete', 'danger' => true],
]],
['label' => 'Help', 'items' => [
['label' => 'Documentation', 'href' => '/docs'],
]],
]"
x-on:markas-select="console.log($event.detail)"
/>Needs Alpine.js. Selecting an item dispatches a markas-select event with the item value in $event.detail. In Livewire: x-on:markas-select="$wire.
import { Menubar } from "@/components/markas/Menubar";
<Menubar
menus={[
{
label: "File",
items: [
{ label: "New file", value: "new" },
{ label: "Save", value: "save" },
],
},
{
label: "Edit",
items: [
{ label: "Undo", value: "undo" },
{ separator: true },
{ label: "Delete", value: "delete", danger: true },
],
},
{ label: "Help", items: [{ label: "Documentation", href: "/docs" }] },
]}
onSelect={(value) => console.log(value)}
/>;<template>
<Menubar
:menus="[
{
label: 'File',
items: [
{ label: 'New file', value: 'new' },
{ label: 'Save', value: 'save' },
],
},
{
label: 'Edit',
items: [
{ label: 'Undo', value: 'undo' },
{ separator: true },
{ label: 'Delete', value: 'delete', danger: true },
],
},
{ label: 'Help', items: [{ label: 'Documentation', href: '/docs' }] },
]"
@select="(value) => console.log(value)"
/>
</template><script lang="ts">
import Menubar, {
type MenubarMenu,
} from "$lib/components/markas/Menubar.svelte";
const menus: MenubarMenu[] = [
{
label: "File",
items: [
{ label: "New file", value: "new" },
{ label: "Save", value: "save" },
],
},
{
label: "Edit",
items: [
{ label: "Undo", value: "undo" },
{ separator: true },
{ label: "Delete", value: "delete", danger: true },
],
},
{ label: "Help", items: [{ label: "Documentation", href: "/docs" }] },
];
</script>
<Menubar {menus} onselect={(value) => console.log(value)} />---
import Menubar from "@/components/markas/Menubar.astro";
---
<Menubar
id="app-menu"
menus={[
{
label: "File",
items: [
{ label: "New file", value: "new" },
{ label: "Save", value: "save" },
],
},
{
label: "Edit",
items: [
{ label: "Undo", value: "undo" },
{ separator: true },
{ label: "Delete", value: "delete", danger: true },
],
},
{ label: "Help", items: [{ label: "Documentation", href: "/docs" }] },
]}
/>
<script>
document
.getElementById("app-menu")
?.addEventListener("markas-select", (event) =>
console.log((event as CustomEvent<string>).detail),
);
</script>A small bundled script powers every menubar on the page, also after view transitions. Selecting an item dispatches a bubbling markas-select event with the value in detail, like Blade.
import { Component } from "@angular/core";
import { Menubar, type MenubarMenu } from "./markas/menubar.component";
@Component({
selector: "app-editor-menu",
imports: [Menubar],
template: `
<markas-menubar [menus]="menus" (selected)="onSelected($event)" />
`,
})
export class EditorMenu {
protected readonly menus: MenubarMenu[] = [
{
label: "File",
items: [
{ label: "New file", value: "new" },
{ label: "Save", value: "save" },
],
},
{
label: "Edit",
items: [
{ label: "Undo", value: "undo" },
{ separator: true },
{ label: "Delete", value: "delete", danger: true },
],
},
{ label: "Help", items: [{ label: "Documentation", href: "/docs" }] },
];
protected onSelected(value: string) {
console.log(value);
}
}- Menu items take the same shape as Dropdown Menu items:
value,href,danger,disabled, or{ separator: true }. - When
valueis empty, the callback receives the itemlabel. - Menus render in the top layer through the Popover API, so a parent with
overflow: hiddennever clips them. Only one menu is open at a time. - The bar’s accessible name defaults to “Menu”. Translate it with
label.
Props
| Name | Type | Default | Description |
|---|---|---|---|
menus | { label, items: ({ label, value?, href?, danger?, disabled? } | { separator: true })[] }[] | [] | Menus in the bar. Each menu has a label and items in the same shape as Dropdown Menu items. |
label | string | Menu | Accessible name of the bar (aria-label). |
onSelect / @select / markas-select | (value: string) => void | - | Called when an item is selected, with the item value (or label when value is empty). Blade dispatches a markas-select event. |
id | string | auto | Bar id. Triggers and menus use it with -trigger-<index> and -menu-<index> suffixes. |
selected | output<string> | - | Angular only. Emits the item value (or label) when an item is selected. Svelte uses the onselect prop, Astro dispatches a markas-select event like Blade. |
Accessibility
- The bar uses role=menubar with an aria-label; each top-level button is a menuitem with aria-haspopup=menu, aria-expanded, and aria-controls.
- Only one top-level item is in the tab order (roving tabindex). Arrow Left and Arrow Right move between them, Home and End jump to the ends.
- Enter, Space, or Arrow Down opens a menu and focuses the first item; Arrow Up focuses the last item. Arrow Up and Arrow Down move inside the menu, skipping disabled items.
- With a menu open, Arrow Left and Arrow Right close it and open the neighboring menu. Escape closes the menu and returns focus to its top-level item.
Related components
More navigation components with the same classes in every framework.
- AccordionCollapsible sections built on native details and summary, no JavaScript needed.
- BreadcrumbTrail of the current page's location in the site hierarchy, with the current page marked by aria-current.
- CollapsibleA single section that opens and closes, built on native details and summary without JavaScript. Good for show more content.
- FooterSite footer with six layouts: link columns, centered glow, newsletter pill card, giant cropped wordmark, dark glowing call to action, and a floating pill.
- NavbarSite header with a brand, links, dropdown menus, a sliding hover pill, an actions area, and a mobile menu with collapsible groups.
- Navigation MenuDesktop site navigation with mega menu panels on the Popover API, a sliding active indicator, hover intent, and WAI-ARIA disclosure keyboard support.