The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(ui): one placement rule for every dropdown, in one unit (GH #149)
purple779bdd733301
diff --git a/e2e/create-model-picker-fits-the-window.spec.ts b/e2e/create-model-picker-fits-the-window.spec.tsnew file mode 100644index 00000000..4a556555--- /dev/null+++ b/e2e/create-model-picker-fits-the-window.spec.ts@@ -0,0 +1,158 @@+import { test, expect, type Page } from '@playwright/test'+import { tauriMockInit, DEFAULT_ASSISTANT_REPLY, DEFAULT_MODEL_NAME, type TauriMockOptions } from './support/tauri-mock'+import { routeCloud, seedOnboardingDone, signInViaGate, cloudSwitch } from './support/cloud-mock'++/**+ * GitHub #149 (nexd3v, CachyOS with Hyprland, AppImage): in Create the model+ * list opened downward and was cut off by the bottom edge of the window, so no+ * model could be picked. A tiling window manager makes short windows normal.+ *+ * What is measured here is the promise itself, in a real layout: the open+ * list lies completely inside the window, it sits on its trigger, and a model+ * at the very end of the list can be reached and picked.+ */++const OPTS: TauriMockOptions = {+ assistantReply: DEFAULT_ASSISTANT_REPLY,+ modelName: DEFAULT_MODEL_NAME,+ platform: 'windows',+}++async function bootIntoCloudCreate(page: Page) {+ await page.addInitScript(tauriMockInit, OPTS)+ await seedOnboardingDone(page)+ await routeCloud(page, { license: 'active', access: true, mediaLive: true, tierCatalog: true })+ await page.goto('/')+ await expect(cloudSwitch(page)).toBeVisible({ timeout: 20_000 })+ await signInViaGate(page)+ await expect(cloudSwitch(page)).toBeChecked({ timeout: 20_000 })+ // Below 1024 px the top navigation folds into its menu.+ const create = page.getByRole('button', { name: /^Create$/ })+ if (await create.isVisible()) await create.click()+ else {+ await page.getByRole('button', { name: 'Main navigation' }).click()+ await page.getByRole('menuitem', { name: 'Create' }).click()+ }+ await page.getByRole('radio', { name: 'Image', exact: true }).click()+}++const picker = (page: Page) => page.locator('button[aria-haspopup="listbox"]').first()++/** Menu, trigger and window, all in visible pixels, once the open animation has settled. */+async function measure(page: Page) {+ const list = page.getByRole('listbox')+ await expect(list).toBeVisible()+ await expect+ .poll(() => list.evaluate((el) => getComputedStyle(el.parentElement as HTMLElement).opacity))+ .toBe('1')+ return page.evaluate(() => {+ const listbox = document.querySelector('[role="listbox"]') as HTMLElement+ const menu = listbox.parentElement as HTMLElement+ const trigger = document.querySelector('button[aria-haspopup="listbox"]') as HTMLElement+ const m = menu.getBoundingClientRect()+ const t = trigger.getBoundingClientRect()+ return {+ menu: { top: m.top, bottom: m.bottom, left: m.left, right: m.right },+ trigger: { top: t.top, bottom: t.bottom, left: t.left, right: t.right },+ width: window.innerWidth,+ height: window.innerHeight,+ listVisible: listbox.clientHeight,+ listContent: listbox.scrollHeight,+ }+ })+}++function expectInsideWindow(m: Awaited<ReturnType<typeof measure>>) {+ expect(m.menu.top, 'the list starts above the window').toBeGreaterThanOrEqual(0)+ expect(m.menu.bottom, `the list runs ${Math.round(m.menu.bottom - m.height)} px below the window`).toBeLessThanOrEqual(m.height)+ expect(m.menu.left, 'the list starts left of the window').toBeGreaterThanOrEqual(0)+ expect(m.menu.right, 'the list runs past the right edge').toBeLessThanOrEqual(m.width)+}++/** The list hangs on its trigger: a few pixels of gap, never a hand's width. */+function expectOnTrigger(m: Awaited<ReturnType<typeof measure>>) {+ const above = m.menu.bottom <= m.trigger.top + 1+ const gap = above ? m.trigger.top - m.menu.bottom : m.menu.top - m.trigger.bottom+ expect(gap, 'gap between trigger and list').toBeGreaterThanOrEqual(0)+ expect(gap, 'gap between trigger and list').toBeLessThanOrEqual(8)+ // The picker is right-aligned: both right edges line up.+ expect(Math.abs(m.menu.right - m.trigger.right), 'right edges of trigger and list').toBeLessThanOrEqual(2)+}++test('in a short window the model list stays inside it and the last model can be picked', async ({ page }) => {+ await page.setViewportSize({ width: 900, height: 420 })+ await bootIntoCloudCreate(page)+ await expect(picker(page)).toBeVisible({ timeout: 15_000 })+ await picker(page).click()++ const m = await measure(page)+ expectInsideWindow(m)+ expectOnTrigger(m)++ // The last row is one of the older models at the far end of the list.+ const last = page.getByRole('option', { name: /Flux Dev \(quality\)/ })+ await last.scrollIntoViewIfNeeded()+ // Not ratio 1: WebKit reports a fully visible row as 0.9986 (subpixels).+ await expect(last).toBeInViewport({ ratio: 0.95 })+ await last.click()+ await expect(page.getByRole('listbox')).toHaveCount(0)+ await expect(picker(page)).toContainText('Flux Dev (quality)')+})++test('in a very short window the list scrolls instead of leaving it', async ({ page }) => {+ // Neither side of the trigger has room for the whole list here. Without the+ // cap it would run out of the window again, and with a minimum height too.+ // The window shrinks after sign-in: the sign-in sheet itself needs more+ // than 230 px, which is not what this test is about.+ await page.setViewportSize({ width: 900, height: 700 })+ await bootIntoCloudCreate(page)+ await page.setViewportSize({ width: 900, height: 230 })+ await expect(picker(page)).toBeVisible({ timeout: 15_000 })+ await picker(page).click()++ const m = await measure(page)+ expectInsideWindow(m)+ expectOnTrigger(m)+ expect(m.listContent, 'the list should have had to scroll here').toBeGreaterThan(m.listVisible)++ const last = page.getByRole('option', { name: /Flux Dev \(quality\)/ })+ await last.scrollIntoViewIfNeeded()+ await last.click()+ await expect(picker(page)).toContainText('Flux Dev (quality)')+})++test('in a tall window the list sits on its trigger as well', async ({ page }) => {+ // The other half of the report: with the window at full height the list was+ // still out of reach. Wherever it opens, it opens at its trigger.+ await page.setViewportSize({ width: 1240, height: 1000 })+ await bootIntoCloudCreate(page)+ await expect(picker(page)).toBeVisible({ timeout: 15_000 })+ await picker(page).click()++ const m = await measure(page)+ expectInsideWindow(m)+ expectOnTrigger(m)+})++test('the open list follows when the window gets shorter', async ({ page }) => {+ await page.setViewportSize({ width: 1000, height: 800 })+ await bootIntoCloudCreate(page)+ await expect(picker(page)).toBeVisible({ timeout: 15_000 })+ await picker(page).click()+ expectInsideWindow(await measure(page))++ // A tiling window manager opens a second window: ours is half as tall now.+ await page.setViewportSize({ width: 1000, height: 400 })+ await expect.poll(async () => {+ const m = await measure(page)+ const gap = Math.min(Math.abs(m.trigger.top - m.menu.bottom), Math.abs(m.menu.top - m.trigger.bottom))+ return m.menu.top >= 0 && m.menu.bottom <= m.height && gap <= 8+ }).toBe(true)+ const m = await measure(page)+ expectInsideWindow(m)+ expectOnTrigger(m)++ // Escape still closes it.+ await page.keyboard.press('Escape')+ await expect(page.getByRole('listbox')).toHaveCount(0)+})diff --git a/e2e/kontextfenster-wird-nicht-abgeschnitten.spec.ts b/e2e/kontextfenster-wird-nicht-abgeschnitten.spec.tsindex e6ed55eb..e0f9b4ed 100644--- a/e2e/kontextfenster-wird-nicht-abgeschnitten.spec.ts+++ b/e2e/kontextfenster-wird-nicht-abgeschnitten.spec.ts@@ -118,3 +118,56 @@ test('im flachen Fenster scrollt sie, statt aus der Flaeche zu laufen', async ({// Gedeckelt, also gescrollt, und nicht ueber die Kante gewachsen.expect(m.inhalt, 'die Liste haette hier scrollen muessen').toBeGreaterThan(m.sichtbar)})++/**+ * GitHub #149, 03.10.2026: seit dem Befund in Create gehen alle Aufklappmenues+ * ueber dieselbe Platzlogik (`usePopoverPlatz`). Hier die beiden, die neben der+ * Kontextliste in der Eingabezeile sitzen, im 400 px hohen Fenster eines+ * Tiling-Fenstermanagers: beide bleiben ganz in der Flaeche, die sie+ * abschneiden koennte, und was nicht passt, scrollt.+ */+async function inSeinerFlaeche(page: Page, testId: string) {+ const el = page.getByTestId(testId)+ await expect(el).toBeVisible()+ // Erst messen, wenn die Einblendung steht: sie skaliert und verschiebt.+ await expect.poll(() => el.evaluate((e) => getComputedStyle(e).opacity)).toBe('1')+ return el.evaluate((e) => {+ let oben = 0+ let unten = window.innerHeight+ for (let p = e.parentElement; p; p = p.parentElement) {+ const cs = getComputedStyle(p)+ if (cs.overflowY !== 'visible' || cs.overflowX !== 'visible') {+ const b = p.getBoundingClientRect()+ oben = Math.max(oben, b.top)+ unten = Math.min(unten, b.bottom)+ }+ }+ const r = e.getBoundingClientRect()+ return { top: r.top, bottom: r.bottom, left: r.left, right: r.right, oben, unten, breite: window.innerWidth }+ })+}++test('Modellauswahl und Sampling-Popup bleiben im 400 px hohen Fenster in ihrer Flaeche', async ({ page }) => {+ await page.setViewportSize({ width: 1280, height: 800 })+ await completeBuiltinOnboarding(page)+ await openNewChat(page)+ await page.setViewportSize({ width: 1280, height: 400 })++ await page.getByRole('button', { name: 'Select chat model' }).click()+ const menue = await inSeinerFlaeche(page, 'model-picker-menu')+ expect(menue.top, 'die Modellauswahl ragt oben hinaus').toBeGreaterThanOrEqual(menue.oben)+ expect(menue.bottom, 'die Modellauswahl ragt unten hinaus').toBeLessThanOrEqual(menue.unten)+ expect(menue.left).toBeGreaterThanOrEqual(0)+ expect(menue.right).toBeLessThanOrEqual(menue.breite)+ await page.keyboard.press('Escape')+ await expect(page.getByTestId('model-picker-menu')).toHaveCount(0)++ await page.getByTestId('sampling-trigger').click()+ const popup = await inSeinerFlaeche(page, 'sampling-panel')+ expect(popup.top, 'das Sampling-Popup ragt oben hinaus').toBeGreaterThanOrEqual(popup.oben)+ expect(popup.bottom, 'das Sampling-Popup ragt unten hinaus').toBeLessThanOrEqual(popup.unten)+ // Hausregel: ein Popup mit X, und Escape schliesst es auch.+ await expect(page.getByTestId('sampling-close')).toBeVisible()+ await page.keyboard.press('Escape')+ await expect(page.getByTestId('sampling-panel')).toHaveCount(0)+})diff --git a/e2e/memory-sync.spec.ts b/e2e/memory-sync.spec.tsindex fdee0561..f6827b11 100644--- a/e2e/memory-sync.spec.ts+++ b/e2e/memory-sync.spec.ts@@ -17,11 +17,11 @@ async function accountFixture(page: Page) {await page.getByRole('button', { name: 'Use account memories', exact: true }).click()}-test('foreground cancellation stops a held pull and leaving the collection cancels the next run', async ({ page }) => {+test('foreground cancellation stops a held pull and leaving the collection cancels the next run', async ({ page, baseURL }) => {let finish: (() => Promise<void>) | undefinedlet hold = truelet reads = 0- await page.route('**/*', route => new URL(route.request().url()).port === '5273' ? route.continue() : route.abort())+ await page.route('**/*', route => new URL(route.request().url()).port === new URL(baseURL ?? 'http://localhost:5273').port ? route.continue() : route.abort())await page.route('**/api/memory/sync**', async route => {expect(route.request().method()).toBe('GET')reads++@@ -66,10 +66,10 @@ test('foreground cancellation stops a held pull and leaving the collection canceawait expect(page.getByRole('button', { name: 'Cancel synchronization', exact: true })).toHaveCount(0)})-test('explicit UI sync uploads, downloads, preserves conflicts and persists shared deletion', async ({ page }, testInfo) => {+test('explicit UI sync uploads, downloads, preserves conflicts and persists shared deletion', async ({ page, baseURL }, testInfo) => {let records: SyncedMemoryRecord[] = []let writes = 0- await page.route('**/*', route => new URL(route.request().url()).port === '5273' ? route.continue() : route.abort())+ await page.route('**/*', route => new URL(route.request().url()).port === new URL(baseURL ?? 'http://localhost:5273').port ? route.continue() : route.abort())await page.route('**/api/memory/sync**', async route => {expect(route.request().headers().authorization).toBe('Bearer synthetic-proof-token')if (route.request().method() === 'POST') {@@ -183,11 +183,11 @@ test('explicit UI sync uploads, downloads, preserves conflicts and persists shar})for (const responseMode of ['lost', 'cancelled'] as const) {-test(`a ${responseMode} first-upload response cannot revive a locally deleted memory after reload`, async ({ page }) => {+test(`a ${responseMode} first-upload response cannot revive a locally deleted memory after reload`, async ({ page, baseURL }) => {let records: SyncedMemoryRecord[] = []let lostResponse = falselet finish: (() => Promise<void>) | undefined- await page.route('**/*', route => new URL(route.request().url()).port === '5273' ? route.continue() : route.abort())+ await page.route('**/*', route => new URL(route.request().url()).port === new URL(baseURL ?? 'http://localhost:5273').port ? route.continue() : route.abort())await page.route('**/api/memory/sync**', async route => {if (route.request().method() === 'GET') return route.fulfill({ json: { ownerId: 'owner-a', records, next: null } })const body: unknown = route.request().postDataJSON()diff --git a/e2e/memory-write-fence.spec.ts b/e2e/memory-write-fence.spec.tsindex e83f845f..6adb17ff 100644--- a/e2e/memory-write-fence.spec.ts+++ b/e2e/memory-write-fence.spec.ts@@ -1,8 +1,8 @@import { expect, test } from '@playwright/test'import { DEFAULT_MODEL_NAME } from './support/tauri-mock'-test('deleting through Memory Settings survives a late automatic extraction and reload', async ({ page }) => {- await page.route('**/*', route => new URL(route.request().url()).port === '5273' ? route.continue() : route.abort())+test('deleting through Memory Settings survives a late automatic extraction and reload', async ({ page, baseURL }) => {+ await page.route('**/*', route => new URL(route.request().url()).port === new URL(baseURL ?? 'http://localhost:5273').port ? route.continue() : route.abort())await page.goto('/e2e/memory-sensitive-proof.html')await page.evaluate(async (modelName) => {const memoryPath = '/src/stores/memoryStore.ts'diff --git a/src/api/__tests__/der-fehlstart-bleibt-stehen.test.ts b/src/api/__tests__/der-fehlstart-bleibt-stehen.test.tsindex 98d0b699..bb198187 100644--- a/src/api/__tests__/der-fehlstart-bleibt-stehen.test.ts+++ b/src/api/__tests__/der-fehlstart-bleibt-stehen.test.ts@@ -86,9 +86,10 @@ describe('das Aufklappmenue bleibt im Fenster', () => {it('es misst, wie viel Platz ueber dem Ausloeser wirklich ist', () => {// Ein festes max-h in vh weiss nichts davon, wo der Ausloeser sitzt.- expect(src).toContain('const frei = openUpward ? r.top : window.innerHeight - r.bottom')- expect(src).toContain('setMenuePlatz(')- expect(src).toContain('style={menuePlatz === null ? undefined : { maxHeight: menuePlatz }}')+ // Seit GitHub #149 misst das der gemeinsame Haken, gegen die Flaeche, die+ // wirklich abschneidet, und ohne Mindesthoehe.+ expect(src).toContain("usePopoverPlatz(menueRef, open, { bevorzugt: openUpward ? 'oben' : 'unten'")+ expect(src).toContain('style={menue.style}')})it('und was nicht mehr hineinpasst, laesst sich scrollen', () => {diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsxindex c17922dd..b25b5fce 100644--- a/src/components/chat/ChatInput.tsx+++ b/src/components/chat/ChatInput.tsx@@ -1,4 +1,5 @@import { useState, useRef, useEffect, useLayoutEffect, useCallback, type ReactNode } from 'react'+import { usePopoverPlatz } from '../../hooks/usePopoverPlatz'import { SamplingControls } from './SamplingControls'import { Send, Square, Paperclip, X, Brain, Gauge, Terminal } from 'lucide-react'import { matchAgentCommands, type AgentCommand, type CommandScope } from '../../lib/agent-commands'@@ -97,6 +98,8 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p// Slash-command autocomplete (v2.5.3). When the input is a lone "/token", show// the matching agent commands; ↑/↓ to move, Enter/Tab to pick, Esc to dismiss.const [cmdMenu, setCmdMenu] = useState<AgentCommand[]>([])+ const cmdMenuRef = useRef<HTMLDivElement>(null)+ const cmdMenuPlatz = usePopoverPlatz(cmdMenuRef, cmdMenu.length > 0, { bevorzugt: 'oben', abstand: 6, deckel: 256 })const [cmdIndex, setCmdIndex] = useState(0)/*** Ein Entwurf gehoert dem Gespraech, in dem er getippt wurde.@@ -477,7 +480,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p>{/* Slash-command autocomplete, floats above the composer */}{cmdMenu.length > 0 && (- <div className="absolute bottom-full left-0 right-0 mb-1.5 z-50 max-h-64 overflow-y-auto scrollbar-thin rounded-lg lu-elevated py-1">+ <div ref={cmdMenuRef} style={cmdMenuPlatz.style} className={`absolute left-0 right-0 z-50 overflow-y-auto scrollbar-thin rounded-lg lu-elevated py-1 ${cmdMenuPlatz.nachOben ? 'bottom-full mb-1.5' : 'top-full mt-1.5'}`}><div className="px-2.5 py-1 flex items-center gap-1 text-[0.5rem] uppercase tracking-widest text-gray-400 dark:text-gray-600"><Terminal size={9} /> Agent commands</div>diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsxindex 3d210a1c..5b442598 100644--- a/src/components/chat/ChatView.tsx+++ b/src/components/chat/ChatView.tsx@@ -1,4 +1,5 @@-import { useState, useEffect } from 'react'+import { useState, useEffect, useRef } from 'react'+import { usePopoverPlatz } from '../../hooks/usePopoverPlatz'import { motion, AnimatePresence } from 'framer-motion'import { useChat } from '../../hooks/useChat'import { useChatStore } from '../../stores/chatStore'@@ -108,6 +109,10 @@ export function ChatView() {const [exportOpen, setExportOpen] = useState(false)const [exportToast, setExportToast] = useState<string>('')const [toolsDropdownOpen, setToolsDropdownOpen] = useState(false)+ const exportMenuRef = useRef<HTMLDivElement>(null)+ const exportMenu = usePopoverPlatz(exportMenuRef, exportOpen)+ const toolsMenuRef = useRef<HTMLDivElement>(null)+ const toolsMenu = usePopoverPlatz(toolsMenuRef, toolsDropdownOpen, { bevorzugt: 'oben', abstand: 2 })// Beide Aufklapplisten dieser Datei legen eine volle `fixed inset-0`-Flaeche// ueber die App, und beide hatten Escape nie bekommen. Der Datei-Waechter// hat es uebersehen, weil weiter unten der Genehmigungsdialog auf 'Escape'@@ -653,7 +658,7 @@ export function ChatView() {{exportOpen && (<><div className="fixed inset-0 z-40" onClick={() => setExportOpen(false)} />- <div className="absolute right-0 top-full mt-1 z-50 w-32 rounded-lg bg-white dark:bg-[#1a1a1a] border border-gray-200 dark:border-white/10 shadow-xl py-1">+ <div ref={exportMenuRef} style={exportMenu.style} className={`absolute right-0 z-50 w-32 rounded-lg bg-white dark:bg-[#1a1a1a] border border-gray-200 dark:border-white/10 shadow-xl py-1 overflow-y-auto scrollbar-thin ${exportMenu.nachOben ? 'bottom-full mb-1' : 'top-full mt-1'}`}>{(['markdown', 'json'] as const).map(fmt => (<buttonkey={fmt}@@ -843,7 +848,7 @@ export function ChatView() {{toolsDropdownOpen && (<><div className="fixed inset-0 z-40" onClick={() => setToolsDropdownOpen(false)} />- <div className="absolute left-0 bottom-full mb-0.5 z-50 w-28 rounded-md bg-white dark:bg-[#1a1a1a] border border-gray-200 dark:border-white/10 shadow-xl py-0.5 px-0.5">+ <div ref={toolsMenuRef} style={toolsMenu.style} className={`absolute left-0 z-50 w-28 rounded-md bg-white dark:bg-[#1a1a1a] border border-gray-200 dark:border-white/10 shadow-xl py-0.5 px-0.5 overflow-y-auto scrollbar-thin ${toolsMenu.nachOben ? 'bottom-full mb-0.5' : 'top-full mt-0.5'}`}><PermissionOverrideBar /></div></>diff --git a/src/components/chat/CodexModeDropdown.tsx b/src/components/chat/CodexModeDropdown.tsxindex c5e58a16..083bdddf 100644--- a/src/components/chat/CodexModeDropdown.tsx+++ b/src/components/chat/CodexModeDropdown.tsx@@ -1,4 +1,5 @@-import { useState } from 'react'+import { useRef, useState } from 'react'+import { usePopoverPlatz } from '../../hooks/usePopoverPlatz'import { useDismissOnEscape } from '../../hooks/useDismissOnEscape'import { ChevronDown, ShieldCheck, Zap, ClipboardList } from 'lucide-react'import { useChatStore } from '../../stores/chatStore'@@ -57,6 +58,8 @@ const MODE_ACTIVE_ROW: Record<CodexMode, string> = {export function CodexModeDropdown({ openUpward = false }: { openUpward?: boolean } = {}) {const [open, setOpen] = useState(false)useDismissOnEscape(open, () => setOpen(false))+ const menuRef = useRef<HTMLDivElement>(null)+ const menu = usePopoverPlatz(menuRef, open, { bevorzugt: openUpward ? 'oben' : 'unten' })const activeConvId = useChatStore((s) => s.activeConversationId)const defaultMode = useSettingsStore((s) => s.settings.codexDefaultMode)const modeByConversation = useCodexStore((s) => s.modeByConversation)@@ -124,7 +127,7 @@ export function CodexModeDropdown({ openUpward = false }: { openUpward?: booleanmenu hung off its right edge ran 240px to the left and the panelcut off the first letters ("ypass permissions", Gegenprobe01.10.2026). The room is to the right. */}- <div className={`absolute left-0 z-50 w-60 rounded-lg lu-elevated py-1.5 ${openUpward ? 'bottom-full mb-1' : 'top-full mt-1'}`}>+ <div ref={menuRef} style={menu.style} className={`absolute left-0 z-50 w-60 rounded-lg lu-elevated py-1.5 overflow-y-auto scrollbar-thin ${menu.nachOben ? 'bottom-full mb-1' : 'top-full mt-1'}`}>{!activeConvId ? (<p className="px-3 py-1.5 text-[0.5rem] text-gray-400">Open a coding chat first, the mode lives on the conversation.diff --git a/src/components/chat/ContextDropdown.tsx b/src/components/chat/ContextDropdown.tsxindex 8adfaa02..f84cbc90 100644--- a/src/components/chat/ContextDropdown.tsx+++ b/src/components/chat/ContextDropdown.tsx@@ -1,4 +1,4 @@-import { useId, useLayoutEffect, useRef, useState, type ReactNode } from 'react'+import { useId, useRef, useState, type ReactNode } from 'react'import { useDismissOnEscape } from '../../hooks/useDismissOnEscape'import { ChevronDown, Check, Loader2, AlertTriangle } from 'lucide-react'import { useModelStore } from '../../stores/modelStore'@@ -17,35 +17,10 @@ import { formatContextWindow } from '../../lib/formatters'import { DEFAULT_SEND_WINDOW_TOKENS } from '../../lib/send-window'import { ENGINE_DEFAULT_CTX } from '../../lib/builtin-ctx'import { SOURCE_LABEL, withStoredWindow } from '../../lib/context-source'-import { platzFuerPopover, type PopoverPlatz } from '../../lib/popover-placement'+import { usePopoverPlatz } from '../../hooks/usePopoverPlatz'const PRESETS = [4096, 8192, 16384, 32768, 65536, 131072]-/** `mt-1` / `mb-1` in Zahlen, damit die Rechnung dasselbe kennt wie die Klasse. */-const ABSTAND = 4-/** Luft zur Kante der abschneidenden Flaeche. */-const LUFT = 8--/**- * Die Flaeche, die dieses Popover wirklich abschneidet.- *- * Nicht das Fenster: im Chat liegt darueber ein `<main>` mit `overflow-hidden`- * (die abgerundete Pane), und dessen Unterkante liegt gemessen 9 px hoeher.- * Wer gegen `window.innerHeight` rechnet, landet in genau diesen 9 px, also im- * Geschnittenen. Gesucht ist der erste Vorfahr, der nicht `visible` ist; gibt- * es keinen, ist es das Fenster.- */-function abschneidendeFlaeche(el: Element): { oben: number; unten: number } {- for (let p = el.parentElement; p; p = p.parentElement) {- const cs = getComputedStyle(p)- if (cs.overflowY !== 'visible' || cs.overflowX !== 'visible') {- const r = p.getBoundingClientRect()- return { oben: r.top, unten: r.bottom }- }- }- return { oben: 0, unten: window.innerHeight }-}-/*** Context-window picker for the active LOCAL model. Sets `contextWindowOverride`* and AUTO-RELOADS the model so the change takes effect immediately:@@ -103,52 +78,12 @@ export function ContextDropdown({ children }: { children?: ReactNode }) {* Fest nach oben zu kippen waere der falsche Ausgang. Derselbe Knopf steht* im Code-Bereich (`CodexView`) in einer Kopfzeile, dort ist oben kein Platz* und unten reichlich. Deshalb wird gemessen, und zwar gegen die Flaeche,- * die tatsaechlich schneidet. Die Entscheidung selbst steht in- * `lib/popover-placement` und hat dort ihre eigenen Tests, denn in der- * Testumgebung dieses Hauses (`environment: 'node'`) gibt es kein Layout.- *- * `useLayoutEffect` und nicht `useEffect`: die Messung braucht die gerenderte- * Liste, und die Korrektur muss vor dem Bild sitzen, sonst blitzt die Liste- * einmal an der falschen Stelle auf.+ * die tatsaechlich schneidet. Seit GitHub #149 misst das nicht mehr dieses+ * Bauteil selbst, sondern `usePopoverPlatz`, derselbe Haken wie fuer jedes+ * andere Aufklappmenue der App.*/- const ankerRef = useRef<HTMLDivElement>(null)const listeRef = useRef<HTMLDivElement>(null)- const [platz, setPlatz] = useState<PopoverPlatz | null>(null)- useLayoutEffect(() => {- if (!open) { setPlatz(null); return }- const messen = () => {- const anker = ankerRef.current- const liste = listeRef.current- if (!anker || !liste) return- const r = anker.getBoundingClientRect()- const grenze = abschneidendeFlaeche(anker)- /* Die App liegt unter einem `zoom: var(--ui-scale)` (index.css:518), und- * die beiden Messwege zaehlen darunter verschieden:- * `getBoundingClientRect` liefert SICHTBARE Pixel, `offsetHeight` und- * `scrollHeight` die CSS-Pixel des Elements. Gemessen bei --ui-scale- * 1,15: dieselbe Liste 111,5 gegen 97. Wer beides mischt, deckelt 15- * Prozent zu grosszuegig, und die Liste ragt wieder heraus, nur weniger.- * Also alles in die CSS-Pixel der Liste umrechnen; `maxHoehe` faellt- * damit in der Einheit an, in der es gleich als `max-height` steht.- */- const skala = liste.offsetHeight > 0 ? liste.getBoundingClientRect().height / liste.offsetHeight : 1- setPlatz(platzFuerPopover({- ankerOben: r.top / skala,- ankerUnten: r.bottom / skala,- grenzeOben: grenze.oben / skala,- grenzeUnten: grenze.unten / skala,- // `scrollHeight` und nicht `offsetHeight`: sobald eine Hoehe gesetzt- // ist, misst `offsetHeight` die Deckelung und nicht den Inhalt, und- // die naechste Messung schriebe den Deckel fest.- inhaltHoehe: liste.scrollHeight,- abstand: ABSTAND,- luft: LUFT,- }))- }- messen()- window.addEventListener('resize', messen)- return () => window.removeEventListener('resize', messen)- }, [open])+ const platz = usePopoverPlatz(listeRef, open)const [busy, setBusy] = useState(false)// Reload failure, surfaced instead of swallowed: the engine's start error// (out of memory for the new ctx, port held by a stranger) is actionable,@@ -306,7 +241,7 @@ export function ContextDropdown({ children }: { children?: ReactNode }) {}`return (- <div ref={ankerRef} className="relative">+ <div className="relative"><buttononClick={() => setOpen((o) => !o)}disabled={busy}@@ -378,9 +313,9 @@ export function ContextDropdown({ children }: { children?: ReactNode }) {laufen. */}<divref={listeRef}- style={platz ? { maxHeight: platz.maxHoehe } : undefined}+ style={platz.style}className={`absolute right-0 z-50 min-w-[140px] rounded-lg lu-elevated p-1 flex flex-col gap-0.5 overflow-y-auto scrollbar-thin ${- platz?.nachOben ? 'bottom-full mb-1' : 'top-full mt-1'+ platz.nachOben ? 'bottom-full mb-1' : 'top-full mt-1'}`}><button onClick={() => apply(0)} className={rowCls(selectedNow === 0)}>diff --git a/src/components/chat/PluginsDropdown.tsx b/src/components/chat/PluginsDropdown.tsxindex 3243a78b..7ce70eab 100644--- a/src/components/chat/PluginsDropdown.tsx+++ b/src/components/chat/PluginsDropdown.tsx@@ -1,4 +1,5 @@-import { useState } from 'react'+import { useRef, useState } from 'react'+import { usePopoverPlatz } from '../../hooks/usePopoverPlatz'import { useDismissOnEscape } from '../../hooks/useDismissOnEscape'import { Plug, ChevronDown, Bone, User, Users, Wrench } from 'lucide-react'import { useSettingsStore } from '../../stores/settingsStore'@@ -32,6 +33,8 @@ export function PluginsDropdown({}: { openUpward?: boolean; iconOnly?: boolean } = {}) {const [open, setOpen] = useState(false)useDismissOnEscape(open, () => setOpen(false))+ const menuRef = useRef<HTMLDivElement>(null)+ const menu = usePopoverPlatz(menuRef, open, { bevorzugt: openUpward ? 'oben' : 'unten' })const [cavemanOpen, setCavemanOpen] = useState(false)const [personaOpen, setPersonaOpen] = useState(false)const [groupOpen, setGroupOpen] = useState(false)@@ -127,7 +130,7 @@ export function PluginsDropdown({{open && (<><div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />- <div className={`absolute right-0 z-50 w-56 rounded-lg lu-elevated py-1.5 ${openUpward ? 'bottom-full mb-1' : 'top-full mt-1'}`}>+ <div ref={menuRef} style={menu.style} className={`absolute right-0 z-50 w-56 rounded-lg lu-elevated py-1.5 overflow-y-auto scrollbar-thin ${menu.nachOben ? 'bottom-full mb-1' : 'top-full mt-1'}`}>{/* ── Chat Tools toggle (v2.5.3) ──────────────── */}<div className="px-2.5">diff --git a/src/components/chat/SamplingControls.tsx b/src/components/chat/SamplingControls.tsxindex aa072182..fa91b8f1 100644--- a/src/components/chat/SamplingControls.tsx+++ b/src/components/chat/SamplingControls.tsx@@ -1,4 +1,5 @@import { useCallback, useEffect, useId, useRef, useState } from 'react'+import { usePopoverPlatz } from '../../hooks/usePopoverPlatz'import { X, SlidersHorizontal } from 'lucide-react'import { useSettingsStore } from '../../stores/settingsStore'import { useChatStore } from '../../stores/chatStore'@@ -104,6 +105,7 @@ export function SamplingControls() {const [draft, setDraft] = useState<string | null>(null)const wrapRef = useRef<HTMLDivElement>(null)const panelRef = useRef<HTMLDivElement>(null)+ const lage = usePopoverPlatz(panelRef, open, { bevorzugt: 'oben', abstand: 6 })const panelId = useId()const settings = useSettingsStore((s) => s.settings)const activeId = useChatStore((s) => s.activeConversationId)@@ -224,14 +226,17 @@ export function SamplingControls() {// Placed with an inline style rather than utility classes, for the// same reason the web app does: `position` is then a fact a test can// read, instead of a class name a test would have to believe.+ // Above the trigger while it fits there; in a short window it takes+ // the side with room and scrolls instead of leaving the window.style={{position: 'absolute',right: 0,- bottom: '100%',- marginBottom: 6,+ ...(lage.nachOben ? { bottom: '100%', marginBottom: 6 } : { top: '100%', marginTop: 6 }),width: PANEL_WIDTH,+ overflowY: 'auto',+ ...lage.style,}}- className="z-50 space-y-2 rounded-lg p-2.5 lu-elevated"+ className="z-50 space-y-2 rounded-lg p-2.5 lu-elevated scrollbar-thin"><div className="flex justify-end"><buttondiff --git a/src/components/create/experimental/PromptHistory.tsx b/src/components/create/experimental/PromptHistory.tsxindex 27895cd3..0fddddb8 100644--- a/src/components/create/experimental/PromptHistory.tsx+++ b/src/components/create/experimental/PromptHistory.tsx@@ -1,4 +1,5 @@import { useEffect, useRef, useState } from 'react'+import { usePopoverPlatz } from '../../../hooks/usePopoverPlatz'import { motion, AnimatePresence } from 'framer-motion'import { History, Trash2, X } from 'lucide-react'import { useCreateStore } from '../../../stores/createStore'@@ -25,6 +26,8 @@ export function PromptHistory({ onPick }: { onPick: (p: string) => void }) {const clearPromptHistory = useCreateStore((s) => s.clearPromptHistory)const removeFromPromptHistory = useCreateStore((s) => s.removeFromPromptHistory)const [open, setOpen] = useState(false)+ const panelRef = useRef<HTMLDivElement>(null)+ const panel = usePopoverPlatz(panelRef, open, { bevorzugt: 'oben', abstand: 6 })const [armed, setArmed] = useState(false)const ref = useRef<HTMLDivElement>(null)const armTimer = useRef<ReturnType<typeof setTimeout> | null>(null)@@ -63,11 +66,13 @@ export function PromptHistory({ onPick }: { onPick: (p: string) => void }) {<AnimatePresence>{open && (<motion.div- initial={{ opacity: 0, y: 4 }}+ ref={panelRef}+ style={panel.style}+ initial={{ opacity: 0, y: panel.nachOben ? 4 : -4 }}animate={{ opacity: 1, y: 0 }}- exit={{ opacity: 0, y: 4 }}+ exit={{ opacity: 0, y: panel.nachOben ? 4 : -4 }}transition={{ duration: 0.12 }}- className="lu-elevated absolute bottom-full mb-1.5 left-0 z-50 w-72 rounded-lg p-1"+ className={cn('lu-elevated absolute left-0 z-50 w-72 rounded-lg p-1 overflow-y-auto scrollbar-thin', panel.nachOben ? 'bottom-full mb-1.5' : 'top-full mt-1.5')}><div className="flex items-center justify-between gap-2 px-1.5 pb-1 mb-1 border-b border-white/[0.06]"><span className="t-label text-gray-500">Prompt history</span>diff --git a/src/components/create/experimental/SpecialIntentControls.tsx b/src/components/create/experimental/SpecialIntentControls.tsxindex d1a73529..456a1fbe 100644--- a/src/components/create/experimental/SpecialIntentControls.tsx+++ b/src/components/create/experimental/SpecialIntentControls.tsx@@ -7,6 +7,7 @@// genuinely differ (extend's source pick, the cloud voice maker).import { useCallback, useEffect, useRef, useState } from 'react'+import { usePopoverPlatz } from '../../../hooks/usePopoverPlatz'import { AnimatePresence, motion } from 'framer-motion'import {AudioLines, Download, Film, ImagePlus, Info, Mic, Music2, Trash2, Upload, Wand2, X,@@ -736,6 +737,8 @@ function VoiceChip({const inputRef = useRef<HTMLInputElement>(null)const ref = useRef<HTMLDivElement>(null)useClickAway(ref, () => { setOpen(false); setMakerOpen(false) }, open || makerOpen)+ const panelRef = useRef<HTMLDivElement>(null)+ const panel = usePopoverPlatz(panelRef, open, { bevorzugt: 'oben', abstand: 6 })const { makeVoice } = useCreateExp()const isGenerating = useCreateStore((s) => s.isGenerating)// The AI voice maker + "your generated audio" picks are cloud runs (hosted@@ -778,11 +781,13 @@ function VoiceChip({<AnimatePresence>{open && (<motion.div- initial={{ opacity: 0, y: 4 }}+ ref={panelRef}+ style={panel.style}+ initial={{ opacity: 0, y: panel.nachOben ? 4 : -4 }}animate={{ opacity: 1, y: 0 }}- exit={{ opacity: 0, y: 4 }}+ exit={{ opacity: 0, y: panel.nachOben ? 4 : -4 }}transition={{ duration: 0.12 }}- className="lu-elevated absolute bottom-full mb-1.5 left-0 z-50 w-72 rounded-lg p-1.5 space-y-1"+ className={cn('lu-elevated absolute left-0 z-50 w-72 rounded-lg p-1.5 space-y-1 overflow-y-auto scrollbar-thin', panel.nachOben ? 'bottom-full mb-1.5' : 'top-full mt-1.5')}>{!makerOpen ? (<>@@ -1049,6 +1054,8 @@ function LocalExtendControls() {const inputRef = useRef<HTMLInputElement>(null)const ref = useRef<HTMLDivElement>(null)useClickAway(ref, () => setOpen(false), open)+ const panelRef = useRef<HTMLDivElement>(null)+ const panel = usePopoverPlatz(panelRef, open, { bevorzugt: 'oben', abstand: 6, deckel: 256 })const adopt = async (getUrl: () => Promise<{ url: string; revoke?: () => void }>, label: string) => {setBusy(true)@@ -1124,11 +1131,13 @@ function LocalExtendControls() {<AnimatePresence>{open && (<motion.div- initial={{ opacity: 0, y: 4 }}+ ref={panelRef}+ style={panel.style}+ initial={{ opacity: 0, y: panel.nachOben ? 4 : -4 }}animate={{ opacity: 1, y: 0 }}- exit={{ opacity: 0, y: 4 }}+ exit={{ opacity: 0, y: panel.nachOben ? 4 : -4 }}transition={{ duration: 0.12 }}- className="lu-elevated absolute bottom-full mb-1.5 left-1/2 -translate-x-1/2 z-50 w-72 rounded-lg p-1 max-h-64 overflow-y-auto scrollbar-thin"+ className={cn('lu-elevated absolute left-1/2 -translate-x-1/2 z-50 w-72 rounded-lg p-1 overflow-y-auto scrollbar-thin', panel.nachOben ? 'bottom-full mb-1.5' : 'top-full mt-1.5')}><buttononClick={() => inputRef.current?.click()}@@ -1162,6 +1171,8 @@ function CloudExtendControls() {const [open, setOpen] = useState(false)const ref = useRef<HTMLDivElement>(null)useClickAway(ref, () => setOpen(false), open)+ const panelRef = useRef<HTMLDivElement>(null)+ const panel = usePopoverPlatz(panelRef, open, { bevorzugt: 'oben', abstand: 6, deckel: 256 })return (<div className="flex items-center justify-center">@@ -1188,11 +1199,13 @@ function CloudExtendControls() {<AnimatePresence>{open && (<motion.div- initial={{ opacity: 0, y: 4 }}+ ref={panelRef}+ style={panel.style}+ initial={{ opacity: 0, y: panel.nachOben ? 4 : -4 }}animate={{ opacity: 1, y: 0 }}- exit={{ opacity: 0, y: 4 }}+ exit={{ opacity: 0, y: panel.nachOben ? 4 : -4 }}transition={{ duration: 0.12 }}- className="lu-elevated absolute bottom-full mb-1.5 left-1/2 -translate-x-1/2 z-50 w-72 rounded-lg p-1 max-h-64 overflow-y-auto scrollbar-thin"+ className={cn('lu-elevated absolute left-1/2 -translate-x-1/2 z-50 w-72 rounded-lg p-1 overflow-y-auto scrollbar-thin', panel.nachOben ? 'bottom-full mb-1.5' : 'top-full mt-1.5')}>{clips.length === 0 && (<div className="t-control text-gray-500 px-2.5 py-2">diff --git a/src/components/create/ui/Select.tsx b/src/components/create/ui/Select.tsxindex 756dad13..7dba6948 100644--- a/src/components/create/ui/Select.tsx+++ b/src/components/create/ui/Select.tsx@@ -1,13 +1,8 @@-import {- useEffect,- useLayoutEffect,- useMemo,- useRef,- useState,-} from 'react'+import { useEffect, useMemo, useRef, useState } from 'react'import { createPortal } from 'react-dom'import { motion, AnimatePresence } from 'framer-motion'import { ChevronDown, Check, Search } from 'lucide-react'+import { usePopoverPlatz } from '../../../hooks/usePopoverPlatz'import { cn } from './cn'export interface SelectOption {@@ -30,22 +25,12 @@ interface Props {size?: 'sm' | 'md'align?: 'left' | 'right'className?: string+ /** Hoeher wird die Liste nie, auch im grossen Fenster nicht. */maxHeight?: number/** Beschriftung fuer Bedienhilfen, wo kein sichtbarer Text danebensteht. */ariaLabel?: string}-interface MenuPosition {- top?: number- bottom?: number- left?: number- right?: number- width: number- maxWidth: number- maxHeight: number- dropUp: boolean-}-export function Select({options,value,@@ -60,11 +45,19 @@ export function Select({}: Props) {const [open, setOpen] = useState(false)const [query, setQuery] = useState('')- const [menuPosition, setMenuPosition] =- useState<MenuPosition | null>(null)const triggerRef = useRef<HTMLDivElement>(null)const menuRef = useRef<HTMLDivElement>(null)+ const listRef = useRef<HTMLDivElement>(null)+ // GitHub #149: the menu used to do its own sums against the window height+ // and kept a minimum height, so in a short or zoomed window it ended up+ // under the window edge. Placement is the app-wide rule now: the side with+ // room, capped to that room, the list scrolls.+ const menu = usePopoverPlatz(menuRef, open, {+ anker: triggerRef,+ rolle: listRef,+ fest: align === 'right' ? 'rechts' : 'links',+ })const current = options.find((option) => option.value === value)@@ -83,7 +76,6 @@ export function Select({const closeMenu = () => {setOpen(false)setQuery('')- setMenuPosition(null)}const toggle = () => {@@ -123,116 +115,11 @@ export function Select({}}, [open])- useLayoutEffect(() => {- if (!open || !triggerRef.current) return-- const updatePosition = () => {- const trigger = triggerRef.current- if (!trigger) return-- const rect = trigger.getBoundingClientRect()- const viewportPadding = 8- const gap = 4-- const spaceBelow =- window.innerHeight - rect.bottom - viewportPadding - gap- const spaceAbove =- rect.top - viewportPadding - gap-- const searchHeight = searchable ? 48 : 0- const menuChromeHeight = searchHeight + 8- const estimatedRowsHeight =- Math.max(filtered.length, 1) * 32-- const desiredHeight = Math.min(- maxHeight + menuChromeHeight,- estimatedRowsHeight + menuChromeHeight,- )-- // Prefer opening downward whenever there is enough usable space.- // The menu can scroll internally when all options do not fit.- const minimumUsefulHeight = Math.min(desiredHeight, 160)- const dropUp =- spaceBelow < minimumUsefulHeight &&- spaceAbove > spaceBelow-- const availableSpace = Math.max(- 80,- dropUp ? spaceAbove : spaceBelow,- )-- // The trigger width is the menu's MINIMUM: options with sublabels- // (model prices) may need more room, so the menu grows with its- // content. Right-aligned menus anchor their right edge and grow- // leftward; both stay clamped inside the viewport via maxWidth.- const width = rect.width- const maxWidth =- window.innerWidth - viewportPadding * 2-- const left =- align === 'right'- ? undefined- : Math.min(- Math.max(viewportPadding, rect.left),- Math.max(- viewportPadding,- window.innerWidth - width - viewportPadding,- ),- )- const right =- align === 'right'- ? Math.max(- viewportPadding,- window.innerWidth - rect.right,- )- : undefined-- setMenuPosition({- top: dropUp ? undefined : rect.bottom + gap,- bottom: dropUp- ? window.innerHeight - rect.top + gap- : undefined,- left,- right,- width,- maxWidth,- maxHeight: Math.min(desiredHeight, availableSpace),- dropUp,- })- }-- updatePosition()-- window.addEventListener('resize', updatePosition)- window.addEventListener('scroll', updatePosition, true)-- const resizeObserver = new ResizeObserver(updatePosition)- resizeObserver.observe(triggerRef.current)-- return () => {- window.removeEventListener('resize', updatePosition)- window.removeEventListener('scroll', updatePosition, true)- resizeObserver.disconnect()- }- }, [- align,- filtered.length,- maxHeight,- open,- searchable,- ])-const controlHeight =size === 'sm'? 'h-[var(--control-h-sm)]': 'h-[var(--control-h-md)]'- const optionsMaxHeight = Math.max(- 64,- (menuPosition?.maxHeight ?? maxHeight) -- (searchable ? 48 : 8),- )-return (<><div@@ -284,7 +171,7 @@ export function Select({ref={menuRef}initial={{opacity: 0,- y: menuPosition?.dropUp ? 4 : -4,+ y: menu.nachOben ? 4 : -4,scale: 0.98,}}animate={{@@ -294,31 +181,19 @@ export function Select({}}exit={{opacity: 0,- y: menuPosition?.dropUp ? 4 : -4,+ y: menu.nachOben ? 4 : -4,scale: 0.98,}}transition={{ duration: 0.12 }}- style={{- top: menuPosition?.top,- bottom: menuPosition?.bottom,- left: menuPosition?.left,- right: menuPosition?.right,- minWidth: menuPosition?.width,- maxWidth: menuPosition?.maxWidth,- maxHeight:- menuPosition?.maxHeight ?? maxHeight,- visibility: menuPosition- ? 'visible'- : 'hidden',- }}+ style={menu.style}className={cn('lu-elevated fixed z-[100] min-w-0','rounded-[var(--radius-panel)]',- 'p-1 overflow-hidden',+ 'flex flex-col p-1 overflow-hidden',)}>{searchable && (- <div className="mb-1 flex items-center gap-1.5 border-b border-white/[0.06] px-2 py-1.5">+ <div className="mb-1 flex shrink-0 items-center gap-1.5 border-b border-white/[0.06] px-2 py-1.5"><Searchsize={13}className="text-gray-500"@@ -337,9 +212,10 @@ export function Select({)}<div+ ref={listRef}role="listbox"- className="overflow-y-auto overscroll-contain scrollbar-thin"- style={{ maxHeight: optionsMaxHeight }}+ className="min-h-0 overflow-y-auto overscroll-contain scrollbar-thin"+ style={{ maxHeight }}onWheel={(event) => event.stopPropagation()}>{filtered.length === 0 && (diff --git a/src/components/create/ui/Tooltip.tsx b/src/components/create/ui/Tooltip.tsxindex f975d1e1..01943a2b 100644--- a/src/components/create/ui/Tooltip.tsx+++ b/src/components/create/ui/Tooltip.tsx@@ -4,6 +4,8 @@ import { createPortal } from 'react-dom'import { motion, AnimatePresence } from 'framer-motion'import { cn } from './cn'import { tooltipPosition, type TooltipPlacement } from './tooltip-position'+import { massstab } from '../../../hooks/usePopoverPlatz'+import { lokaleMasse } from '../../../lib/popover-placement'interface Props {content: React.ReactNode@@ -62,13 +64,20 @@ const handleFocus = (useLayoutEffect(() => {if (!show) returnconst measure = () => {- const a = anchor.current?.getBoundingClientRect()- const b = bubble.current?.getBoundingClientRect()- if (!a || !b) return+ const el = anchor.current+ const b = bubble.current+ if (!el || !b) return+ // One unit for everything: the bubble's own CSS pixels. The app sits+ // under a zoom, and depending on the engine a rect comes back in+ // visible or in zoomed pixels while `top` and `left` always count in+ // the latter (GitHub #149).+ const { kasten, fenster } = lokaleMasse(massstab(el))+ const a = kasten(el.getBoundingClientRect())setPlace(tooltipPosition(- { top: a.top, left: a.left, width: a.width, height: a.height },- { width: b.width, height: b.height },- { width: window.innerWidth, height: window.innerHeight },+ { top: a.top, left: a.left, width: a.right - a.left, height: a.bottom - a.top },+ // offsetWidth/Height, not the rect: untouched by the fade-in transform.+ { width: b.offsetWidth, height: b.offsetHeight },+ { width: fenster.right, height: fenster.bottom },side,))}diff --git a/src/components/create/ui/__tests__/Select-fits-the-window.test.tsx b/src/components/create/ui/__tests__/Select-fits-the-window.test.tsxnew file mode 100644index 00000000..5cc998dd--- /dev/null+++ b/src/components/create/ui/__tests__/Select-fits-the-window.test.tsx@@ -0,0 +1,132 @@+// @vitest-environment jsdom+/**+ * GitHub #149: the Create model list ended up under the bottom edge of the+ * window. The arithmetic has its own tests (lib/__tests__/+ * das-popover-bleibt-in-der-flaeche.test.ts); this one checks that the+ * component really hands its measurements to it and wears the result, and+ * that picking, Escape and resizing still work.+ *+ * jsdom has no layout, so the three things the hook reads are given here:+ * the trigger's box, the window size and the height of the list's content.+ *+ * Run: npx vitest run src/components/create/ui/__tests__/Select-fits-the-window.test.tsx+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'+import { Select } from '../Select'++const OPTIONS = Array.from({ length: 12 }, (_, i) => ({ value: `m${i}`, label: `Model ${i}` }))++/** Where the trigger sits, in window pixels. Set per test. */+let trigger = { top: 0, bottom: 0, left: 0, right: 0 }++function setWindow(width: number, height: number) {+ Object.defineProperty(window, 'innerWidth', { value: width, configurable: true })+ Object.defineProperty(window, 'innerHeight', { value: height, configurable: true })+}++const restore: Array<() => void> = []+function stub<K extends keyof HTMLElement>(key: K, get: (this: HTMLElement) => HTMLElement[K]) {+ const before = Object.getOwnPropertyDescriptor(HTMLElement.prototype, key)+ Object.defineProperty(HTMLElement.prototype, key, { get, configurable: true })+ restore.push(() => {+ if (before) Object.defineProperty(HTMLElement.prototype, key, before)+ else delete (HTMLElement.prototype as unknown as Record<string, unknown>)[key]+ })+}++beforeEach(() => {+ setWindow(900, 400)+ const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {+ const t = this.classList.contains('trigger-under-test') ? trigger : { top: 0, bottom: 0, left: 0, right: 0 }+ return { ...t, x: t.left, y: t.top, width: t.right - t.left, height: t.bottom - t.top, toJSON: () => t }+ })+ restore.push(() => rect.mockRestore())+ // Twelve rows of 32 px in a list the menu has squeezed to 44 px; the menu+ // itself (search field, padding, squeezed list) stands at 100 px.+ stub('scrollHeight', function () { return this.getAttribute('role') === 'listbox' ? 384 : 100 })+ stub('clientHeight', function () { return this.getAttribute('role') === 'listbox' ? 44 : 100 })+ stub('offsetHeight', function () { return 100 })+ stub('offsetWidth', function () { return 220 })+})++afterEach(() => {+ cleanup()+ while (restore.length) restore.pop()?.()+})++function open(onChange = vi.fn()) {+ render(<Select className="trigger-under-test" ariaLabel="Model" searchable align="right" options={OPTIONS} value="m0" onChange={onChange} />)+ fireEvent.click(screen.getByRole('button', { name: 'Model' }))+ return { menu: screen.getByRole('listbox').parentElement as HTMLElement, onChange }+}++describe('the Create model list takes the room there is', () => {+ it('room below: opens downward at the trigger', () => {+ trigger = { top: 20, bottom: 50, left: 500, right: 720 }+ const { menu } = open()+ expect(menu.style.position).toBe('fixed')+ expect(menu.style.top).toBe('54px')+ expect(menu.style.bottom).toBe('')+ // 400 - 50 - 4 gap - 8 margin. The content (100 + 280 - 44 = 336) fits.+ expect(menu.style.maxHeight).toBe('338px')+ })++ it('no room below, room above: opens upward (the reported case)', () => {+ trigger = { top: 340, bottom: 370, left: 500, right: 720 }+ const { menu } = open()+ expect(menu.style.top).toBe('')+ expect(menu.style.bottom).toBe('64px')+ expect(menu.style.maxHeight).toBe('328px')+ // Right-aligned to its trigger, and no wider than the window allows.+ expect(menu.style.right).toBe('180px')+ expect(menu.style.minWidth).toBe('220px')+ expect(menu.style.maxWidth).toBe('712px')+ })++ it('neither side is enough: the larger one, capped, and the list scrolls', () => {+ trigger = { top: 150, bottom: 180, left: 500, right: 720 }+ const { menu } = open()+ expect(menu.style.top).toBe('184px')+ expect(menu.style.maxHeight).toBe('208px')+ expect(screen.getByRole('listbox').className).toContain('overflow-y-auto')+ expect(screen.getByRole('listbox').className).toContain('min-h-0')+ })++ it('follows the window when it gets shorter', () => {+ trigger = { top: 20, bottom: 50, left: 500, right: 720 }+ const { menu } = open()+ expect(menu.style.maxHeight).toBe('338px')+ act(() => {+ setWindow(900, 200)+ window.dispatchEvent(new Event('resize'))+ })+ expect(menu.style.maxHeight).toBe('138px')+ })+})++describe('and is still the same control', () => {+ beforeEach(() => { trigger = { top: 340, bottom: 370, left: 500, right: 720 } })++ it('a click picks the model and closes the list', () => {+ const { onChange } = open()+ fireEvent.click(screen.getByRole('option', { name: 'Model 11' }))+ expect(onChange).toHaveBeenCalledWith('m11')+ expect(screen.getByRole('button', { name: 'Model' }).getAttribute('aria-expanded')).toBe('false')+ })++ it('Escape closes it without picking', () => {+ const { onChange } = open()+ fireEvent.keyDown(window, { key: 'Escape' })+ expect(onChange).not.toHaveBeenCalled()+ expect(screen.getByRole('button', { name: 'Model' }).getAttribute('aria-expanded')).toBe('false')+ })++ it('the search field has the keyboard and narrows the list', () => {+ open()+ const search = screen.getByPlaceholderText('Search...')+ expect(document.activeElement).toBe(search)+ fireEvent.change(search, { target: { value: 'Model 7' } })+ expect(screen.getAllByRole('option')).toHaveLength(1)+ })+})diff --git a/src/components/layout/DownloadBadge.tsx b/src/components/layout/DownloadBadge.tsxindex df4bfb9c..763d3c09 100644--- a/src/components/layout/DownloadBadge.tsx+++ b/src/components/layout/DownloadBadge.tsx@@ -1,4 +1,5 @@import { useState, useRef, useEffect } from 'react'+import { usePopoverPlatz } from '../../hooks/usePopoverPlatz'import { withInstallerOutput } from '../../lib/error-text'import { motion, AnimatePresence } from 'framer-motion'import { ArrowDownToLine, Pause, Play, X, CheckCircle, RotateCcw } from 'lucide-react'@@ -30,6 +31,8 @@ export function DownloadBadge() {const [tray, setTray] = useState(TRAY_CLOSED)const open = tray.openconst ref = useRef<HTMLDivElement>(null)+ const panelRef = useRef<HTMLDivElement>(null)+ const panel = usePopoverPlatz(panelRef, open, { abstand: 6 })// Text model entriesconst textEntries = Object.entries(activePulls)@@ -132,10 +135,12 @@ export function DownloadBadge() {<AnimatePresence>{open && (<motion.div- className="absolute right-0 top-full mt-1.5 w-72 rounded-lg overflow-hidden z-50 bg-white dark:bg-[#363636] border border-gray-200 dark:border-white/[0.08] shadow-2xl shadow-black/50"- initial={{ opacity: 0, y: -6, scale: 0.98 }}+ ref={panelRef}+ style={panel.style}+ className={`absolute right-0 w-72 rounded-lg overflow-x-hidden overflow-y-auto scrollbar-thin z-50 bg-white dark:bg-[#363636] border border-gray-200 dark:border-white/[0.08] shadow-2xl shadow-black/50 ${panel.nachOben ? 'bottom-full mb-1.5' : 'top-full mt-1.5'}`}+ initial={{ opacity: 0, y: panel.nachOben ? 6 : -6, scale: 0.98 }}animate={{ opacity: 1, y: 0, scale: 1 }}- exit={{ opacity: 0, y: -6, scale: 0.98 }}+ exit={{ opacity: 0, y: panel.nachOben ? 6 : -6, scale: 0.98 }}transition={{ duration: 0.12, ease: 'easeOut' }}>{/* Header */}diff --git a/src/components/layout/Header.tsx b/src/components/layout/Header.tsxindex 63409c39..cc42e721 100644--- a/src/components/layout/Header.tsx+++ b/src/components/layout/Header.tsx@@ -1,4 +1,5 @@import { useEffect, useId, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react'+import { usePopoverPlatz } from '../../hooks/usePopoverPlatz'import { Menu, Loader2, Sun, Moon, RefreshCw, X, MoreVertical } from 'lucide-react'import { useUIStore } from '../../stores/uiStore'import { useSettingsStore } from '../../stores/settingsStore'@@ -259,6 +260,8 @@ export function Header() {──────────────────────────────────────────────────────────────────────── */const menuId = useId()const menuTriggerRef = useRef<HTMLButtonElement>(null)+ const moreMenuRef = useRef<HTMLDivElement>(null)+ const moreMenu = usePopoverPlatz(moreMenuRef, showMoreMenu, { abstand: 8 })const menuItemRefs = useRef<(HTMLButtonElement | null)[]>([])const [menuActive, setMenuActive] = useState(0)@@ -460,7 +463,9 @@ export function Header() {aria-label="Main navigation"onPointerDown={(e) => e.stopPropagation()}onKeyDown={onMenuKeyDown}- className="absolute left-1/2 -translate-x-1/2 top-full mt-2 w-40 rounded-lg border border-gray-200 dark:border-white/10 bg-white dark:bg-[#1a1a1a] shadow-xl z-50 flex flex-col gap-0.5 p-1.5"+ ref={moreMenuRef}+ style={moreMenu.style}+ className={`absolute left-1/2 -translate-x-1/2 w-40 rounded-lg border border-gray-200 dark:border-white/10 bg-white dark:bg-[#1a1a1a] shadow-xl z-50 flex flex-col gap-0.5 p-1.5 overflow-y-auto scrollbar-thin ${moreMenu.nachOben ? 'bottom-full mb-2' : 'top-full mt-2'}`}>{navTargets.map((t, i) => (<buttondiff --git a/src/components/layout/UpdateBadge.tsx b/src/components/layout/UpdateBadge.tsxindex 645bea25..293c9b28 100644--- a/src/components/layout/UpdateBadge.tsx+++ b/src/components/layout/UpdateBadge.tsx@@ -1,4 +1,5 @@import { useState, useRef, useEffect } from 'react'+import { usePopoverPlatz } from '../../hooks/usePopoverPlatz'import { motion, AnimatePresence } from 'framer-motion'import { ArrowUpCircle, Download, RefreshCw, RotateCcw, X, Loader2 } from 'lucide-react'import { useUpdateStore, initUpdateChecker } from '../../stores/updateStore'@@ -26,6 +27,8 @@ export function UpdateBadge() {const [open, setOpen] = useState(false)const ref = useRef<HTMLDivElement>(null)+ const panelRef = useRef<HTMLDivElement>(null)+ const panel = usePopoverPlatz(panelRef, open, { abstand: 6 })useEffect(() => { initUpdateChecker() }, [])@@ -119,10 +122,12 @@ export function UpdateBadge() {<AnimatePresence>{open && (<motion.div- className="absolute right-0 top-full mt-1.5 w-72 rounded-lg overflow-hidden z-50 bg-white dark:bg-lu-overlay border border-gray-200 dark:border-white/[0.08] shadow-2xl shadow-black/10 dark:shadow-black/50"- initial={{ opacity: 0, y: -6, scale: 0.98 }}+ ref={panelRef}+ style={panel.style}+ className={`absolute right-0 w-72 rounded-lg overflow-x-hidden overflow-y-auto scrollbar-thin z-50 bg-white dark:bg-lu-overlay border border-gray-200 dark:border-white/[0.08] shadow-2xl shadow-black/10 dark:shadow-black/50 ${panel.nachOben ? 'bottom-full mb-1.5' : 'top-full mt-1.5'}`}+ initial={{ opacity: 0, y: panel.nachOben ? 6 : -6, scale: 0.98 }}animate={{ opacity: 1, y: 0, scale: 1 }}- exit={{ opacity: 0, y: -6, scale: 0.98 }}+ exit={{ opacity: 0, y: panel.nachOben ? 6 : -6, scale: 0.98 }}transition={{ duration: 0.12, ease: 'easeOut' }}>{/* Header */}diff --git a/src/components/models/ModelSelector.tsx b/src/components/models/ModelSelector.tsxindex acc7c857..60499c3f 100644--- a/src/components/models/ModelSelector.tsx+++ b/src/components/models/ModelSelector.tsx@@ -1,4 +1,5 @@-import { useState, useRef, useEffect, useLayoutEffect } from 'react'+import { useState, useRef, useEffect } from 'react'+import { usePopoverPlatz } from '../../hooks/usePopoverPlatz'import { useDismissOnEscape } from '../../hooks/useDismissOnEscape'import { motion, AnimatePresence } from 'framer-motion'import { AlertTriangle, Ban, ChevronDown, Loader2, Power, PlayCircle, Settings as SettingsIcon, Wrench, X, Cloud } from 'lucide-react'@@ -797,12 +798,13 @@ export function ModelSelector({ openUpward = false, surface = 'chat', answeredBy* rohe Maschinenprotokoll, der Satz mit dem Namen des Modells und dem* Handlungsvorschlag war unerreichbar.*- * Ein festes `max-h` in vh reicht dafuer nicht: das Menue haengt mit- * `bottom-full` am Ausloeser, und wie viel Platz DARUEBER ist, weiss nur- * der Ausloeser selbst. Also gemessen, bei jedem Oeffnen und bei jeder- * Groessenaenderung des Fensters.+ * Ein festes `max-h` in vh reicht dafuer nicht: wie viel Platz ueber oder+ * unter dem Ausloeser ist, weiss nur der Ausloeser selbst. Also gemessen,+ * seit GitHub #149 mit `usePopoverPlatz` wie jedes Aufklappmenue der App:+ * die Seite, die reicht, die Hoehe, die bleibt, keine Mindesthoehe mehr.*/- const [menuePlatz, setMenuePlatz] = useState<number | null>(null)+ const menueRef = useRef<HTMLDivElement>(null)+ const menue = usePopoverPlatz(menueRef, open, { bevorzugt: openUpward ? 'oben' : 'unten', abstand: 6, luft: 12 })// Keep the per-row On/Off LOAD state LIVE while the dropdown is open// (David 2026-06-12: "on und offload button sehr delayed und nicht immer@@ -1266,24 +1268,6 @@ export function ModelSelector({ openUpward = false, surface = 'chat', answeredByconst hasOllamaModels = textModels.some(m => ('provider' in m && m.provider === 'ollama') || !('provider' in m))textModelsEmptyRef.current = textModels.length === 0- // Messen, wie viel Fenster ueber (bzw. unter) dem Ausloeser noch frei ist.- // 18 px Abzug: 6 px Abstand des Menues zum Ausloeser plus 12 px Luft zum- // Fensterrand. Die Untergrenze von 200 px ist die Notbremse fuer ein sehr- // flaches Fenster, in dem sonst ein Menue ohne Inhalt herauskaeme.- useLayoutEffect(() => {- if (!open) return- const messen = () => {- const el = ref.current- if (!el) return- const r = el.getBoundingClientRect()- const frei = openUpward ? r.top : window.innerHeight - r.bottom- setMenuePlatz(Math.max(200, Math.round(frei - 18)))- }- messen()- window.addEventListener('resize', messen)- return () => window.removeEventListener('resize', messen)- }, [open, openUpward])-return (<div ref={ref} className="relative">{/* ── Trigger Button ── */}@@ -1366,13 +1350,14 @@ export function ModelSelector({ openUpward = false, surface = 'chat', answeredBy{open && (<motion.divdata-testid="model-picker-menu"- style={menuePlatz === null ? undefined : { maxHeight: menuePlatz }}+ ref={menueRef}+ style={menue.style}className={`absolute w-72 rounded-lg overflow-x-hidden overflow-y-auto scrollbar-thin z-50 lu-elevated ${- openUpward ? 'bottom-full mb-1.5 right-0' : 'top-full mt-1.5 left-1/2 -translate-x-1/2'- }`}- initial={{ opacity: 0, y: openUpward ? 6 : -6, scale: 0.98 }}+ menue.nachOben ? 'bottom-full mb-1.5' : 'top-full mt-1.5'+ } ${openUpward ? 'right-0' : 'left-1/2 -translate-x-1/2'}`}+ initial={{ opacity: 0, y: menue.nachOben ? 6 : -6, scale: 0.98 }}animate={{ opacity: 1, y: 0, scale: 1 }}- exit={{ opacity: 0, y: openUpward ? 6 : -6, scale: 0.98 }}+ exit={{ opacity: 0, y: menue.nachOben ? 6 : -6, scale: 0.98 }}transition={{ duration: MOTION_S.fast, ease: 'easeOut' }}>{/* Noch vor der Engine-Zeile: was sich am Modell selbst geaendertdiff --git a/src/components/models/ModelTiles.tsx b/src/components/models/ModelTiles.tsxindex 69a034a4..9602d923 100644--- a/src/components/models/ModelTiles.tsx+++ b/src/components/models/ModelTiles.tsx@@ -4,6 +4,7 @@// handlers (Ollama routing, sharded confirm, bundle retry/clear, …) keep// working unchanged behind a new surface.import { useEffect, useRef, useState } from 'react'+import { usePopoverPlatz } from '../../hooks/usePopoverPlatz'import { isBelowChatMinimum, SMALL_CHAT_MODEL_WARNING } from '../../lib/chat-model-minimum'import {Download, ExternalLink, Info, Check, ChevronDown, Loader2, RefreshCw,@@ -346,6 +347,8 @@ export function ModelTile({ variants, vramGb, isInstalled, dlState, onDownload,const [pickerOpen, setPickerOpen] = useState(false)const [chosen, setChosen] = useState<string | null>(null)const pickerRef = useRef<HTMLDivElement>(null)+ const variantListRef = useRef<HTMLDivElement>(null)+ const variantList = usePopoverPlatz(variantListRef, pickerOpen)const def = pickDefaultVariant(variants, vramGb, isInstalled, dlState)const sel = variants.find(v => v.name === chosen) ?? def@@ -434,7 +437,9 @@ export function ModelTile({ variants, vramGb, isInstalled, dlState, onDownload,<divrole="listbox"aria-label={`Size and quality for ${groupTitle}`}- className="absolute z-30 left-0 top-full mt-1 w-56 rounded-lg lu-elevated p-1"+ ref={variantListRef}+ style={variantList.style}+ className={`absolute z-30 left-0 w-56 rounded-lg lu-elevated p-1 overflow-y-auto scrollbar-thin ${variantList.nachOben ? 'bottom-full mb-1' : 'top-full mt-1'}`}>{variants.map(v => {const vFit = computeFit(v.sizeGB, vramGb)diff --git a/src/components/settings/ProviderConfig.tsx b/src/components/settings/ProviderConfig.tsxindex 5b9f8c1c..845124f8 100644--- a/src/components/settings/ProviderConfig.tsx+++ b/src/components/settings/ProviderConfig.tsx@@ -1,4 +1,5 @@import { useState, useEffect, useRef } from 'react'+import { usePopoverPlatz } from '../../hooks/usePopoverPlatz'import { Wifi, WifiOff, Loader2, Eye, EyeOff, ChevronDown, Plus, Power, Play, Trash2, X, AlertTriangle } from 'lucide-react'import { useProviderStore, deobfuscate } from '../../stores/providerStore'import { providerRowIds, isReturnableRow } from '../../lib/provider-visibility'@@ -111,6 +112,8 @@ type LmStudioServerInfo = { lms_present: boolean; running: boolean }export function ProviderSettings() {const { providers, setProviderConfig, setProviderApiKey, getProviderApiKey, engineOptedOut } = useProviderStore()const [dropdownOpen, setDropdownOpen] = useState(false)+ const dropdownRef = useRef<HTMLDivElement>(null)+ const dropdown = usePopoverPlatz(dropdownRef, dropdownOpen, { deckel: 224 })const [testing, setTesting] = useState<ProviderId | null>(null)const [statuses, setStatuses] = useState<Record<string, SlotStatus>>({})// Der laufende Zustand unserer eigenen Engine, dieselbe Schleife, die der@@ -859,7 +862,7 @@ export function ProviderSettings() {„Active" stand auf Weiss bei 1,74:1 und traegt jetzt green-700mit 5,02:1. */}{dropdownOpen && (- <div className="absolute z-50 top-full mt-1 w-full bg-white dark:bg-lu-overlay border border-gray-200 dark:border-white/10 rounded-lg shadow-xl max-h-56 overflow-y-auto scrollbar-thin">+ <div ref={dropdownRef} style={dropdown.style} className={`absolute z-50 w-full bg-white dark:bg-lu-overlay border border-gray-200 dark:border-white/10 rounded-lg shadow-xl overflow-y-auto scrollbar-thin ${dropdown.nachOben ? 'bottom-full mb-1' : 'top-full mt-1'}`}>{/* Local group */}<div className="px-2.5 py-1 text-[0.5rem] uppercase tracking-wider text-gray-600 font-semibold">Local</div>{localPresets.map(preset => {diff --git a/src/hooks/usePopoverPlatz.ts b/src/hooks/usePopoverPlatz.tsnew file mode 100644index 00000000..d9b8182c--- /dev/null+++ b/src/hooks/usePopoverPlatz.ts@@ -0,0 +1,209 @@+import { useLayoutEffect, useState, type CSSProperties, type RefObject } from 'react'+import {+ festeLage,+ lokaleMasse,+ platzFuerPopover,+ schubInDieFlaeche,+ type Kasten,+ type Massstab,+} from '../lib/popover-placement'++/**+ * Die EINE Platzlogik fuer alles, was in dieser App aufklappt.+ *+ * GitHub #149 (nexd3v, Hyprland, AppImage): die Modellauswahl in Create lag+ * unter dem Fensterrand, kein Modell war waehlbar. Jedes Aufklappmenue hatte+ * bis dahin seine eigene Vorstellung vom Platz: eine feste Richtung, eine+ * Mindesthoehe, das Fenster statt der abschneidenden Flaeche, oder gar keine.+ * Dieser Haken misst fuer alle gleich: Platz unter und ueber dem Ausloeser,+ * die Seite, die reicht, die Hoehe, die bleibt, und die seitliche Kante. Die+ * Entscheidung selbst steht rein in `lib/popover-placement`; hier steht nur+ * das Ablesen.+ *+ * Zwei Bauarten:+ * - im Baum (`absolute` in einem `relative`-Ausloeser): der Haken liefert+ * `nachOben` fuer die Klasse und `style` mit `max-height` und, wenn das+ * Popover seitlich hinausragt, dem Schub zurueck in die Flaeche.+ * - herausgehoben (`fest`, Portal auf `body`): `style` traegt zusaetzlich+ * die Koordinaten.+ *+ * Das Popover scrollt selbst (`overflow-y-auto`) oder nennt mit `rolle` die+ * innere Liste, die es tut.+ */+export interface PopoverOptionen {+ /** Die Seite, auf der es aufgeht, solange es dort passt. Ohne Angabe unten. */+ bevorzugt?: 'unten' | 'oben'+ /** Abstand zum Ausloeser in px, passend zur Klasse (`mt-1` = 4). */+ abstand?: number+ /** Luft zur Kante der abschneidenden Flaeche in px. */+ luft?: number+ /** Hoeher wird es nie (ersetzt ein festes `max-h-*`). */+ deckel?: number+ /** Der Ausloeser. Ohne Angabe der `offsetParent` des Popovers. */+ anker?: RefObject<HTMLElement | null>+ /** Die innere Liste, falls sie scrollt und nicht das Popover selbst. */+ rolle?: RefObject<HTMLElement | null>+ /** Herausgehoben mit `position: fixed`, an dieser Kante des Ausloesers ausgerichtet. */+ fest?: 'links' | 'rechts'+}++export interface PopoverLage {+ nachOben: boolean+ style: CSSProperties+}++const KEIN_STIL: CSSProperties = {}++/** Was die Engine ueber Zoom und Kastenmass verraet, an der App-Wurzel des Elements abgelesen. */+export function massstab(el: Element): Massstab {+ let wurzel = el+ while (wurzel.parentElement && wurzel.parentElement !== document.body) wurzel = wurzel.parentElement+ const zoom = parseFloat(getComputedStyle(wurzel).zoom) || 1+ const r = wurzel.getBoundingClientRect()+ const css = wurzel instanceof HTMLElement ? wurzel.offsetWidth + wurzel.offsetHeight : 0+ return {+ zoom,+ verhaeltnis: css > 0 ? (r.width + r.height) / css : zoom,+ fensterBreite: window.innerWidth,+ fensterHoehe: window.innerHeight,+ }+}++/**+ * Die Flaeche, die ein Popover im Baum wirklich abschneidet: das Fenster,+ * geschnitten mit jedem Vorfahren, der nicht `visible` ist. Im Chat ist das+ * der `<main>` mit `overflow-hidden`, dessen Unterkante 9 px ueber der des+ * Fensters liegt.+ */+function abschneidendeFlaeche(anker: Element, fenster: Kasten, kasten: (k: Kasten) => Kasten): Kasten {+ let g = fenster+ for (let p = anker.parentElement; p && p !== document.body; p = p.parentElement) {+ const cs = getComputedStyle(p)+ if (cs.overflowY === 'visible' && cs.overflowX === 'visible') continue+ const r = kasten(p.getBoundingClientRect())+ g = {+ top: Math.max(g.top, r.top),+ bottom: Math.min(g.bottom, r.bottom),+ left: Math.max(g.left, r.left),+ right: Math.min(g.right, r.right),+ }+ }+ return g+}++function gleich(a: PopoverLage | null, b: PopoverLage): boolean {+ return a !== null && a.nachOben === b.nachOben && JSON.stringify(a.style) === JSON.stringify(b.style)+}++export function usePopoverPlatz(+ popRef: RefObject<HTMLElement | null>,+ open: boolean,+ optionen: PopoverOptionen = {},+): PopoverLage {+ const { bevorzugt = 'unten', abstand = 4, luft = 8, deckel, anker: ankerRef, rolle: rolleRef, fest } = optionen+ const [lage, setLage] = useState<PopoverLage | null>(null)++ /* `useLayoutEffect` und nicht `useEffect`: die Messung braucht das+ * gerenderte Popover, und die Korrektur muss vor dem Bild sitzen, sonst+ * blitzt es einmal an der falschen Stelle auf. Die Lage des letzten+ * Aufklappens bleibt stehen, bis neu gemessen ist; so behaelt auch die+ * Ausblendung ihren Platz. */+ useLayoutEffect(() => {+ if (!open) return+ const messen = () => {+ const pop = popRef.current+ const anker = ankerRef?.current ?? (pop?.offsetParent as HTMLElement | null | undefined)+ if (!pop || !anker) return+ const roh = anker.getBoundingClientRect()+ // Ein Ausloeser ohne Flaeche hat kein Layout (oder ist gerade+ // ausgeblendet); daraus laesst sich nichts schliessen.+ if (roh.width === 0 && roh.height === 0) return+ const masse = lokaleMasse(massstab(anker))+ const a = masse.kasten(roh)+ const rolle = rolleRef?.current+ // `scrollHeight` und nicht `offsetHeight`: sobald eine Hoehe gesetzt+ // ist, misst `offsetHeight` nur noch den Deckel und nicht den Inhalt.+ // Eine innere Liste, die das Popover gerade zusammendrueckt, zaehlt mit+ // dem, was sie ungedrueckt haette, hoechstens aber ihrem eigenen Deckel.+ const rolleDeckel = rolle ? parseFloat(getComputedStyle(rolle).maxHeight) || Infinity : 0+ const gedrueckt = rolle ? Math.max(0, Math.min(rolle.scrollHeight, rolleDeckel) - rolle.clientHeight) : 0+ const inhaltHoehe = pop.scrollHeight + (pop.offsetHeight - pop.clientHeight) + gedrueckt++ let neu: PopoverLage+ if (fest) {+ const l = festeLage({+ anker: a, fenster: masse.fenster, breite: pop.offsetWidth, inhaltHoehe,+ ausrichtung: fest, abstand, luft, bevorzugt, deckel,+ })+ neu = {+ nachOben: l.nachOben,+ style: {+ position: 'fixed', top: l.top, bottom: l.bottom, left: l.left, right: l.right,+ width: 'max-content', minWidth: l.minWidth, maxWidth: l.maxWidth, maxHeight: l.maxHoehe,+ },+ }+ } else {+ const grenze = abschneidendeFlaeche(anker, masse.fenster, masse.kasten)+ const platz = platzFuerPopover({+ ankerOben: a.top, ankerUnten: a.bottom, grenzeOben: grenze.top, grenzeUnten: grenze.bottom,+ inhaltHoehe, abstand, luft, bevorzugt, deckel,+ })+ // Der natuerliche Platz ist der ohne den Schub von eben.+ const p = masse.kasten(pop.getBoundingClientRect())+ const alt = parseFloat(pop.style.marginLeft) || 0+ const schub = schubInDieFlaeche({+ links: p.left - alt, rechts: p.right - alt,+ grenzeLinks: grenze.left, grenzeRechts: grenze.right, luft,+ })+ neu = {+ nachOben: platz.nachOben,+ // Beide Raender, weil das Popover links ODER rechts verankert sein+ // kann: der Rand an der freien Seite bleibt ohne Wirkung.+ style: schub === 0+ ? { maxHeight: platz.maxHoehe }+ : { maxHeight: platz.maxHoehe, marginLeft: schub, marginRight: -schub },+ }+ }+ setLage((vorher) => (gleich(vorher, neu) ? vorher : neu))+ }+ messen()++ // Capture, weil die abschneidende Flaeche meist selbst der Scroller ist.+ // Das eigene Scrollen der Liste aendert am Platz nichts.+ const beimScrollen = (e: Event) => {+ if (e.target instanceof Node && popRef.current?.contains(e.target)) return+ messen()+ }+ window.addEventListener('resize', messen)+ window.addEventListener('scroll', beimScrollen, true)+ // Inhalt, der spaeter kommt (Suche, nachgeladene Zeilen), aendert die Hoehe.+ const beobachter = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(messen)+ for (const el of [popRef.current, ankerRef?.current ?? popRef.current?.offsetParent, rolleRef?.current]) {+ if (el) beobachter?.observe(el)+ }+ // Ein Ausloeser kann wandern, ohne dass eines der Ereignisse oben davon+ // erzaehlt: das Layout setzt sich nach einer Groessenaenderung erst einen+ // Frame spaeter (gemessen in WebKit, die Liste blieb 79 px vom Ausloeser+ // entfernt stehen). Solange das Popover offen ist, wird deshalb je Frame+ // ein Kasten gelesen und nur bei einer Aenderung neu gemessen.+ let zuletzt = ''+ let frame = requestAnimationFrame(function wache() {+ const anker = ankerRef?.current ?? popRef.current?.offsetParent+ if (anker) {+ const r = anker.getBoundingClientRect()+ const jetzt = `${r.top}|${r.left}|${r.width}|${r.height}|${window.innerWidth}|${window.innerHeight}`+ if (zuletzt !== '' && jetzt !== zuletzt) messen()+ zuletzt = jetzt+ }+ frame = requestAnimationFrame(wache)+ })+ return () => {+ cancelAnimationFrame(frame)+ window.removeEventListener('resize', messen)+ window.removeEventListener('scroll', beimScrollen, true)+ beobachter?.disconnect()+ }+ }, [open, popRef, ankerRef, rolleRef, bevorzugt, abstand, luft, deckel, fest])++ return lage ?? { nachOben: bevorzugt === 'oben', style: KEIN_STIL }+}diff --git a/src/lib/__tests__/das-popover-bleibt-in-der-flaeche.test.ts b/src/lib/__tests__/das-popover-bleibt-in-der-flaeche.test.tsindex eb28fb29..8e511950 100644--- a/src/lib/__tests__/das-popover-bleibt-in-der-flaeche.test.ts+++ b/src/lib/__tests__/das-popover-bleibt-in-der-flaeche.test.ts@@ -1,7 +1,7 @@import { describe, it, expect } from 'vitest'import { readFileSync } from 'node:fs'import { resolve } from 'node:path'-import { platzFuerPopover } from '../popover-placement'+import { festeLage, kastenFaktor, lokaleMasse, platzFuerPopover, schubInDieFlaeche } from '../popover-placement'/*** Der Befund vom 07.09.2026: das Kontextfenster im Chat war abgeschnitten.@@ -79,29 +79,204 @@ describe('die Hoehe ist gedeckelt, und der Deckel luegt nicht', () => {})})-describe('der Kontextwaehler benutzt diese Rechnung wirklich', () => {- const SRC = readFileSync(- resolve(__dirname, '..', '..', 'components', 'chat', 'ContextDropdown.tsx'),- 'utf8',- )+describe('GitHub #149: unten Platz, oben Platz, keiner reicht', () => {+ /** Ein 30 px hoher Ausloeser in einem 400 px hohen Fenster, die Liste will 300. */+ const LISTE = { grenzeOben: 0, grenzeUnten: 400, inhaltHoehe: 300, abstand: 4, luft: 8 }- it('die Richtung steht nicht mehr fest im Klassennamen', () => {- // DER Fehler, buchstaeblich: `top-full` ohne Alternative. Steht er wieder- // allein da, ist der Befund zurueck.- expect(SRC).toContain('platzFuerPopover')- expect(SRC).toMatch(/nachOben \? 'bottom-full mb-1' : 'top-full mt-1'/)+ it('unten ist Platz: sie geht nach unten auf und wird nicht gekuerzt', () => {+ const p = platzFuerPopover({ ...LISTE, ankerOben: 20, ankerUnten: 50 })+ expect(p.nachOben).toBe(false)+ expect(p.maxHoehe).toBe(338)+ })++ it('unten ist keiner, oben schon: sie geht nach oben auf', () => {+ const p = platzFuerPopover({ ...LISTE, ankerOben: 350, ankerUnten: 380 })+ expect(p.nachOben).toBe(true)+ expect(p.maxHoehe).toBe(338)+ })++ it('keiner reicht: die groessere Seite, gekuerzt auf das, was da ist', () => {+ // Ausloeser in der Mitte: oben 138, unten 188. Die Liste scrollt in 188.+ const p = platzFuerPopover({ ...LISTE, ankerOben: 150, ankerUnten: 200 })+ expect(p.nachOben).toBe(false)+ expect(p.maxHoehe).toBe(188)+ expect(p.maxHoehe).toBeLessThan(LISTE.inhaltHoehe)+ })++ it('ein Popover, das oben zu Hause ist, bleibt oben, solange es passt', () => {+ const p = platzFuerPopover({ ...LISTE, inhaltHoehe: 100, ankerOben: 150, ankerUnten: 200, bevorzugt: 'oben' })+ expect(p.nachOben).toBe(true)+ expect(p.maxHoehe).toBe(138)+ })++ it('und kippt nach unten, wenn oben zu wenig und unten mehr ist', () => {+ const p = platzFuerPopover({ ...LISTE, ankerOben: 40, ankerUnten: 70, bevorzugt: 'oben' })+ expect(p.nachOben).toBe(false)+ expect(p.maxHoehe).toBe(318)+ })++ it('der Deckel haelt die Liste klein, auch wenn mehr Platz waere', () => {+ const p = platzFuerPopover({ ...LISTE, grenzeUnten: 2000, ankerOben: 20, ankerUnten: 50, deckel: 256 })+ expect(p.maxHoehe).toBe(256)+ // Und er entscheidet mit: 300 px Inhalt, die auf 256 gedeckelt sind,+ // passen in 260 px und muessen nicht kippen.+ const knapp = platzFuerPopover({ ...LISTE, grenzeUnten: 800, ankerOben: 500, ankerUnten: 528, deckel: 256 })+ expect(knapp.nachOben).toBe(false)+ })+})++describe('seitlich bleibt das Popover in der Flaeche', () => {+ const FLAECHE = { grenzeLinks: 0, grenzeRechts: 900, luft: 8 }++ it('passt es, rueckt es nicht', () => {+ expect(schubInDieFlaeche({ ...FLAECHE, links: 100, rechts: 340 })).toBe(0)})- it('und die Liste darf scrollen, sonst nuetzt der Deckel nichts', () => {- expect(SRC).toContain('overflow-y-auto')- expect(SRC).toContain('maxHeight: platz.maxHoehe')+ it('ragt es rechts hinaus, rueckt es nach links', () => {+ expect(schubInDieFlaeche({ ...FLAECHE, links: 700, rechts: 940 })).toBe(-48)+ })++ it('ragt es links hinaus, rueckt es nach rechts', () => {+ // Der Befund vom 01.10.2026 ("ypass permissions"): 240 px nach links+ // gehaengt, die ersten Buchstaben abgeschnitten.+ expect(schubInDieFlaeche({ ...FLAECHE, links: -30, rechts: 210 })).toBe(38)+ })++ it('ist es breiter als die Flaeche, gewinnt die linke Kante', () => {+ expect(schubInDieFlaeche({ grenzeLinks: 0, grenzeRechts: 200, luft: 8, links: 50, rechts: 350 })).toBe(-42)+ })+})++describe('GitHub #149: eine Einheit, egal wie die Engine misst', () => {+ /* Die Bilder von nexd3v, nachgerechnet. Fenster 1242x1410 sichtbare Pixel,+ * App unter zoom 1,15, der Ausloeser der Modellauswahl sichtbar von+ * y=1333 bis y=1363 und x=592 bis x=840.+ *+ * Sein WebKitGTK liefert den Kasten in den Pixeln des gezoomten Elements+ * (sichtbar durch 1,15), Chromium und neues WebKit in sichtbaren Pixeln.+ * `window.innerHeight` ist in beiden sichtbar. */+ const FENSTER = { fensterBreite: 1242, fensterHoehe: 1410 }+ const SICHTBAR = { top: 1333, bottom: 1363, left: 592, right: 840 }+ const ALT = { zoom: 1.15, verhaeltnis: 1, ...FENSTER }+ const NEU = { zoom: 1.15, verhaeltnis: 1.1494, ...FENSTER }+ const durch = (k: typeof SICHTBAR, f: number) => ({ top: k.top / f, bottom: k.bottom / f, left: k.left / f, right: k.right / f })++ const lage = (m: typeof ALT, roh: typeof SICHTBAR) => {+ const { kasten, fenster } = lokaleMasse(m)+ return festeLage({+ anker: kasten(roh), fenster, breite: 220, inhaltHoehe: 152,+ ausrichtung: 'rechts', abstand: 4, luft: 8,+ })+ }++ it('der Faktor ist der Zoom oder 1, nichts dazwischen', () => {+ expect(kastenFaktor(1.15, 1.1494)).toBe(1.15)+ expect(kastenFaktor(1.15, 1.127)).toBe(1.15)+ expect(kastenFaktor(1.15, 1)).toBe(1)+ expect(kastenFaktor(1, 1)).toBe(1)+ })++ it('DER FEHLER: im hohen Fenster geht die Liste nach oben auf, nicht unter den Rand', () => {+ // Vorher: 1410 - 1185 - 12 = 213 "freie" Pixel unter dem Ausloeser, wo+ // in Wahrheit (1410 - 1363) / 1,15 - 12 = 28 waren. Die Liste ging nach+ // unten auf und lag unter dem Fensterrand.+ const l = lage(ALT, durch(SICHTBAR, 1.15))+ expect(l.nachOben).toBe(true)+ expect(l.top).toBeUndefined()+ // Unterkante 4 px ueber dem Ausloeser: (1410 - 1333) / 1,15 + 4.+ expect(l.bottom).toBeCloseTo(77 / 1.15 + 4, 5)+ expect(l.maxHoehe).toBe(Math.floor(1333 / 1.15 - 12))+ })++ it('und beide Messarten kommen auf dieselbe Lage', () => {+ const alt = lage(ALT, durch(SICHTBAR, 1.15))+ const neu = lage(NEU, SICHTBAR)+ expect(neu.nachOben).toBe(alt.nachOben)+ expect(neu.bottom).toBeCloseTo(alt.bottom ?? NaN, 5)+ expect(neu.right).toBeCloseTo(alt.right ?? NaN, 5)+ expect(neu.minWidth).toBeCloseTo(alt.minWidth, 5)+ expect(neu.maxHoehe).toBe(alt.maxHoehe)+ })++ it('rechts ausgerichtet haengt sie an der rechten Kante des Ausloesers', () => {+ // Vorher stand sie 183 px zu weit links (rechte Kante bei 657 statt 840).+ const l = lage(NEU, SICHTBAR)+ expect(l.right).toBeCloseTo((1242 - 840) / 1.15, 5)+ expect(l.left).toBeUndefined()+ expect(l.maxWidth).toBeCloseTo(1242 / 1.15 - (1242 - 840) / 1.15 - 8, 5)+ })++ it('im 400 px hohen Fenster bleibt sie bedienbar: oben, gekuerzt, im Fenster', () => {+ // Ausloeser unten im Fenster, die Liste will mit "Older models" und+ // Marken 336 px. Ueber dem Ausloeser sind 330 / 1,15 - 12 = 274.+ const { kasten, fenster } = lokaleMasse({ zoom: 1.15, verhaeltnis: 1.15, fensterBreite: 900, fensterHoehe: 400 })+ const l = festeLage({+ anker: kasten({ top: 330, bottom: 360, left: 500, right: 720 }), fenster,+ breite: 220, inhaltHoehe: 336, ausrichtung: 'rechts', abstand: 4, luft: 8,+ })+ expect(l.nachOben).toBe(true)+ expect(l.maxHoehe).toBe(274)+ // Oberkante in sichtbaren Pixeln: nie ueber dem Fenster.+ const oberkante = 400 - ((l.bottom ?? 0) + l.maxHoehe) * 1.15+ expect(oberkante).toBeGreaterThanOrEqual(8)+ })++ it('links ausgerichtet rueckt sie ins Fenster, wenn sie rechts hinausragte', () => {+ const { kasten, fenster } = lokaleMasse({ zoom: 1, verhaeltnis: 1, fensterBreite: 900, fensterHoehe: 600 })+ const l = festeLage({+ anker: kasten({ top: 100, bottom: 130, left: 780, right: 880 }), fenster,+ breite: 260, inhaltHoehe: 100, ausrichtung: 'links', abstand: 4, luft: 8,+ })+ expect(l.left).toBe(900 - 8 - 260)+ expect(l.top).toBe(134)+ expect(l.nachOben).toBe(false)+ })+})++describe('die Aufklappmenues der App benutzen diese Rechnung wirklich', () => {+ const lies = (...teile: string[]) => readFileSync(resolve(__dirname, '..', '..', ...teile), 'utf8')+ const HAKEN = lies('hooks', 'usePopoverPlatz.ts')++ it('der Haken misst gegen die abschneidende Flaeche, nicht nur gegen das Fenster', () => {+ // `window.innerHeight` liegt im Chat 9 px unter der Kante, die wirklich+ // schneidet (`<main>` mit overflow-hidden). Wer dagegen rechnet, laesst+ // genau diese 9 px durchgehen.+ expect(HAKEN).toContain('abschneidendeFlaeche')+ expect(HAKEN).toMatch(/overflowY === 'visible'/)+ expect(HAKEN).toContain('platzFuerPopover')+ expect(HAKEN).toContain('lokaleMasse')+ })++ it('keine eigene Rechnung mehr neben dem Haken', () => {+ // Jedes dieser Bauteile hatte seine eigene Vorstellung vom Platz. Steht+ // `window.innerHeight` wieder in einem davon, ist die zweite Rechnung+ // zurueck, und mit ihr die zweite Masseinheit.+ for (const datei of [+ ['components', 'create', 'ui', 'Select.tsx'],+ ['components', 'create', 'ui', 'Tooltip.tsx'],+ ['components', 'chat', 'ContextDropdown.tsx'],+ ['components', 'models', 'ModelSelector.tsx'],+ ['components', 'chat', 'CodexModeDropdown.tsx'],+ ['components', 'chat', 'PluginsDropdown.tsx'],+ ['components', 'chat', 'SamplingControls.tsx'],+ ]) {+ const src = lies(...datei)+ expect(src, datei.join('/')).toContain('usePopoverPlatz')+ expect(src, datei.join('/')).not.toContain('window.innerHeight')+ }+ })++ it('die Richtung steht nicht mehr fest im Klassennamen', () => {+ // DER Fehler vom 07.09., buchstaeblich: `top-full` ohne Alternative.+ expect(lies('components', 'chat', 'ContextDropdown.tsx'))+ .toMatch(/nachOben \? 'bottom-full mb-1' : 'top-full mt-1'/)+ expect(lies('components', 'chat', 'ContextDropdown.tsx')).toContain('overflow-y-auto')})- it('gemessen wird gegen die abschneidende Flaeche, nicht gegen das Fenster', () => {- // `window.innerHeight` liegt in dieser App 9 px unter der Kante, die- // wirklich schneidet (`<main>` mit overflow-hidden). Wer dagegen rechnet,- // laesst genau diese 9 px durchgehen.- expect(SRC).toContain('abschneidendeFlaeche')- expect(SRC).toMatch(/overflowY !== 'visible'/)+ it('KEINE Mindesthoehe in der Modellauswahl, weder im Chat noch in Create', () => {+ // Create hielt 80 px fest, der Chat 200. Beides ist die Zusage, bei+ // genug Enge ueber die Kante zu laufen.+ expect(lies('components', 'create', 'ui', 'Select.tsx')).not.toMatch(/Math\.max\(\s*(64|80)/)+ expect(lies('components', 'models', 'ModelSelector.tsx')).not.toContain('Math.max(200')})})diff --git a/src/lib/popover-placement.ts b/src/lib/popover-placement.tsindex e5325918..2161bcd9 100644--- a/src/lib/popover-placement.ts+++ b/src/lib/popover-placement.ts@@ -31,9 +31,25 @@* kommt an einer Stelle heraus, die schon geschnitten wird, und der Fehler* kaeme in kleinerer Form zurueck. Deshalb bekommt diese Rechnung die* abschneidende Flaeche gesagt, nicht das Fenster.+ *+ * ── GitHub #149, 03.10.2026: zwei Masseinheiten in einer Rechnung ──+ *+ * nexd3v, CachyOS mit Hyprland, AppImage: die Modellauswahl in Create ging im+ * hohen Fenster nach unten auf und lag unter dem Fensterrand, im halbhohen+ * stand sie 110 px ueber ihrem Ausloeser. Aus seinen Bildern nachgerechnet:+ * die App liegt unter `zoom: 1.15`, und das WebKitGTK des AppImage liefert+ * `getBoundingClientRect` in den Pixeln des gezoomten Elements (sichtbar durch+ * 1,15), `window.innerHeight` aber in sichtbaren Pixeln. Der Waehler zog das+ * eine vom anderen ab und sah unter dem Ausloeser 213 px Platz, wo 35 waren.+ * Chromium und neues WebKit liefern beides in sichtbaren Pixeln, dort stimmte+ * die Richtung, aber das Menue sass um den Zoomfaktor daneben, weil `top` an+ * einem gezoomten Element mitskaliert.+ *+ * Deshalb rechnet hier alles in EINER Einheit, den CSS-Pixeln des Popovers+ * (`lokaleMasse`), und jedes Popover der App geht ueber `usePopoverPlatz`.*/-/** Die vier Zahlen, die das Bauteil misst. Alle in Fensterkoordinaten. */+/** Die Zahlen, die das Bauteil misst. Alle in den CSS-Pixeln des Popovers. */export interface PopoverRaum {/** Oberkante des Ausloesers. */readonly ankerOben: number@@ -49,6 +65,10 @@ export interface PopoverRaum {readonly abstand: number/** Luft zwischen Popover und Kante der abschneidenden Flaeche. */readonly luft: number+ /** Die Seite, auf der das Popover aufgeht, solange es dort passt. Ohne Angabe unten. */+ readonly bevorzugt?: 'unten' | 'oben'+ /** Hoeher wird das Popover nie, auch wenn mehr Platz waere. */+ readonly deckel?: number}export interface PopoverPlatz {@@ -59,11 +79,12 @@ export interface PopoverPlatz {}/**- * Die Seite mit mehr Platz gewinnt, aber nur, wenn die andere nicht reicht.+ * Die Seite mit mehr Platz gewinnt, aber nur, wenn die bevorzugte nicht reicht.*- * Kein "immer die groessere Seite": das Menue soll dort aufgehen, wo Menues in- * dieser App aufgehen, naemlich unter ihrem Ausloeser. Nach oben zu kippen ist- * die Ausnahme, und sie hat einen Grund, den man messen kann.+ * Kein "immer die groessere Seite": das Menue soll dort aufgehen, wo man es+ * erwartet, unter seinem Ausloeser, oder darueber, wenn der Ausloeser am+ * unteren Rand sitzt (`bevorzugt: 'oben'`). Zu kippen ist die Ausnahme, und+ * sie hat einen Grund, den man messen kann.** Und ausdruecklich KEINE Mindesthoehe. Eine Mindesthoehe waere die Zusage,* bei genug Enge doch wieder ueber die Kante zu laufen, also genau der Fehler,@@ -73,9 +94,147 @@ export interface PopoverPlatz {* ist sichtbar wenig und nicht heimlich abgeschnitten.*/export function platzFuerPopover(raum: PopoverRaum): PopoverPlatz {+ const deckel = raum.deckel ?? Infinity+ const inhalt = Math.min(raum.inhaltHoehe, deckel)const unten = raum.grenzeUnten - raum.ankerUnten - raum.abstand - raum.luftconst oben = raum.ankerOben - raum.grenzeOben - raum.abstand - raum.luft- const nachOben = raum.inhaltHoehe > unten && oben > unten- const frei = nachOben ? oben : unten+ const nachOben = raum.bevorzugt === 'oben'+ ? !(inhalt > oben && unten > oben)+ : inhalt > unten && oben > unten+ const frei = Math.min(nachOben ? oben : unten, deckel)return { nachOben, maxHoehe: Math.max(0, Math.floor(frei)) }}++/** Die waagerechte Lage eines Popovers und die Flaeche, in der es bleiben soll. */+export interface PopoverBreite {+ /** Linke Kante des Popovers an seinem natuerlichen Platz. */+ readonly links: number+ /** Rechte Kante ebenda. */+ readonly rechts: number+ readonly grenzeLinks: number+ readonly grenzeRechts: number+ readonly luft: number+}++/**+ * Um wie viel das Popover seitlich ruecken muss, damit es in der Flaeche bleibt.+ * Positiv heisst nach rechts. Ist es breiter als die Flaeche, gewinnt die linke+ * Kante: dort faengt der Text an.+ */+export function schubInDieFlaeche(b: PopoverBreite): number {+ const zuWeitRechts = b.rechts - (b.grenzeRechts - b.luft)+ const schub = zuWeitRechts > 0 ? -zuWeitRechts : 0+ const zuWeitLinks = b.grenzeLinks + b.luft - (b.links + schub)+ return Math.round(zuWeitLinks > 0 ? schub + zuWeitLinks : schub)+}++/** Ein Kasten, wie ihn `getBoundingClientRect` liefert. */+export interface Kasten {+ readonly top: number+ readonly bottom: number+ readonly left: number+ readonly right: number+}++/** Was die Engine ueber den Massstab verraet, roh abgelesen. */+export interface Massstab {+ /** Der `zoom` der App-Wurzel, unter der der Ausloeser liegt (1 = keiner). */+ readonly zoom: number+ /**+ * `getBoundingClientRect` geteilt durch `offsetWidth`/`offsetHeight` an+ * dieser Wurzel. Chromium und neues WebKit: gleich dem Zoom, denn der Kasten+ * kommt in sichtbaren Pixeln. Aelteres WebKit (das WebKitGTK aus #149): 1,+ * der Kasten kommt schon in den Pixeln des gezoomten Elements.+ */+ readonly verhaeltnis: number+ /** `window.innerWidth`, in jeder Engine sichtbare Pixel. */+ readonly fensterBreite: number+ /** `window.innerHeight`, ebenso. */+ readonly fensterHoehe: number+}++/**+ * Mit welchem Faktor die Kaesten dieser Engine auf CSS-Pixel des gezoomten+ * Baums zurueckgehen. Es gibt nur die zwei Antworten "Zoom" und "1"; das+ * gemessene Verhaeltnis wird auf die naehere gerundet, weil `offsetHeight`+ * ganze Pixel liefert und der Quotient deshalb nie genau stimmt.+ */+export function kastenFaktor(zoom: number, verhaeltnis: number): number {+ return Math.abs(verhaeltnis - zoom) <= Math.abs(verhaeltnis - 1) ? zoom : 1+}++/**+ * Bringt Kaesten und Fenster in dieselbe Einheit: die CSS-Pixel des gezoomten+ * Baums, also die Einheit, in der `top`, `left` und `max-height` eines+ * Popovers gleich wieder gesetzt werden.+ */+export function lokaleMasse(m: Massstab): { kasten: (k: Kasten) => Kasten; fenster: Kasten } {+ const zoom = m.zoom > 0 ? m.zoom : 1+ const f = kastenFaktor(zoom, m.verhaeltnis)+ return {+ kasten: (k) => ({ top: k.top / f, bottom: k.bottom / f, left: k.left / f, right: k.right / f }),+ fenster: { top: 0, left: 0, right: m.fensterBreite / zoom, bottom: m.fensterHoehe / zoom },+ }+}++/** Die Lage eines Popovers, das mit `position: fixed` aus dem Baum herausgehoben ist. */+export interface FestePopoverLage extends PopoverPlatz {+ /** Abstand zur Fensteroberkante; gesetzt, wenn es nach unten aufgeht. */+ readonly top?: number+ /** Abstand zur Fensterunterkante; gesetzt, wenn es nach oben aufgeht. */+ readonly bottom?: number+ /** Gesetzt bei Ausrichtung links. */+ readonly left?: number+ /** Gesetzt bei Ausrichtung rechts: das Popover waechst von dort nach links. */+ readonly right?: number+ /** Der Ausloeser ist die Mindestbreite. */+ readonly minWidth: number+ readonly maxWidth: number+}++/**+ * Wo ein herausgehobenes Popover (Portal auf `body`, `position: fixed`) steht.+ * Abschneiden kann es nur das Fenster. Alle Zahlen in lokalen CSS-Pixeln.+ */+export function festeLage(e: {+ anker: Kasten+ fenster: Kasten+ /** Breite des Popovers, wie es gerade dasteht. */+ breite: number+ inhaltHoehe: number+ ausrichtung: 'links' | 'rechts'+ abstand: number+ luft: number+ bevorzugt?: 'unten' | 'oben'+ deckel?: number+}): FestePopoverLage {+ const platz = platzFuerPopover({+ ankerOben: e.anker.top,+ ankerUnten: e.anker.bottom,+ grenzeOben: e.fenster.top,+ grenzeUnten: e.fenster.bottom,+ inhaltHoehe: e.inhaltHoehe,+ abstand: e.abstand,+ luft: e.luft,+ bevorzugt: e.bevorzugt,+ deckel: e.deckel,+ })+ const senkrecht = platz.nachOben+ ? { bottom: e.fenster.bottom - e.anker.top + e.abstand }+ : { top: e.anker.bottom + e.abstand }+ const minWidth = e.anker.right - e.anker.left+ const fensterBreite = e.fenster.right - e.fenster.left+ if (e.ausrichtung === 'rechts') {+ const right = Math.max(e.luft, e.fenster.right - e.anker.right)+ return { ...platz, ...senkrecht, right, minWidth, maxWidth: Math.max(0, fensterBreite - right - e.luft) }+ }+ const breite = Math.max(e.breite, minWidth)+ const left = e.anker.left + schubInDieFlaeche({+ links: e.anker.left,+ rechts: e.anker.left + breite,+ grenzeLinks: e.fenster.left,+ grenzeRechts: e.fenster.right,+ luft: e.luft,+ })+ return { ...platz, ...senkrecht, left, minWidth, maxWidth: Math.max(0, fensterBreite - 2 * e.luft) }+}