110 lines
2.3 KiB
Svelte
110 lines
2.3 KiB
Svelte
<script lang="ts">
|
|
import { menu } from '$lib/state/menu.svelte';
|
|
|
|
let el = $state<HTMLDivElement>();
|
|
let pos = $state({ x: 0, y: 0 });
|
|
|
|
// Keep the menu on screen.
|
|
$effect(() => {
|
|
if (!menu.open || !el) return;
|
|
void menu.items;
|
|
const r = el.getBoundingClientRect();
|
|
let y = menu.above ? menu.y - r.height : menu.y;
|
|
const x = Math.min(menu.x, window.innerWidth - r.width - 8);
|
|
if (y + r.height > window.innerHeight - 8) y = window.innerHeight - r.height - 8;
|
|
pos = { x: Math.max(8, x), y: Math.max(8, y) };
|
|
});
|
|
|
|
function onDown(e: PointerEvent) {
|
|
if (menu.open && el && !el.contains(e.target as Node)) menu.close();
|
|
}
|
|
</script>
|
|
|
|
<svelte:window
|
|
onpointerdowncapture={onDown}
|
|
onkeydown={(e) => e.key === 'Escape' && menu.close()}
|
|
onblur={() => menu.close()}
|
|
onresize={() => menu.close()}
|
|
/>
|
|
|
|
{#if menu.open}
|
|
<div class="menu" role="menu" bind:this={el} style="left:{pos.x}px; top:{pos.y}px">
|
|
{#each menu.items as item, i (i)}
|
|
{#if item === 'separator'}
|
|
<div class="sep"></div>
|
|
{:else}
|
|
<button
|
|
role="menuitem"
|
|
class:danger={item.danger}
|
|
disabled={item.disabled}
|
|
onclick={() => {
|
|
menu.close();
|
|
item.action();
|
|
}}
|
|
>
|
|
<span class="icon">{#if item.icon}<item.icon size={15} strokeWidth={1.75} />{/if}</span>
|
|
<span class="label">{item.label}</span>
|
|
{#if item.hint}<span class="hint">{item.hint}</span>{/if}
|
|
</button>
|
|
{/if}
|
|
{/each}
|
|
</div>
|
|
{/if}
|
|
|
|
<style>
|
|
.menu {
|
|
position: fixed;
|
|
z-index: 100;
|
|
min-width: 190px;
|
|
padding: 4px;
|
|
background: var(--bg);
|
|
border: 1px solid var(--border);
|
|
border-radius: 8px;
|
|
box-shadow: var(--shadow);
|
|
}
|
|
button {
|
|
display: flex;
|
|
align-items: center;
|
|
gap: 8px;
|
|
width: 100%;
|
|
padding: 6px 10px 6px 6px;
|
|
border: 0;
|
|
background: none;
|
|
border-radius: 4px;
|
|
text-align: left;
|
|
cursor: pointer;
|
|
color: var(--text);
|
|
}
|
|
button:hover:not(:disabled) {
|
|
background: var(--hover);
|
|
}
|
|
button:disabled {
|
|
color: var(--faint);
|
|
cursor: default;
|
|
}
|
|
.danger {
|
|
color: var(--danger);
|
|
}
|
|
.icon {
|
|
display: inline-grid;
|
|
place-items: center;
|
|
width: 18px;
|
|
color: var(--muted);
|
|
}
|
|
.danger .icon {
|
|
color: inherit;
|
|
}
|
|
.label {
|
|
flex: 1;
|
|
}
|
|
.hint {
|
|
color: var(--faint);
|
|
font-size: 11px;
|
|
font-variant-numeric: tabular-nums;
|
|
}
|
|
.sep {
|
|
height: 1px;
|
|
margin: 4px 6px;
|
|
background: var(--border);
|
|
}
|
|
</style>
|