diff --git a/.agents/skills/simple-words-design/README.md b/.agents/skills/simple-words-design/README.md index 9bcd88a..aa95e1e 100644 --- a/.agents/skills/simple-words-design/README.md +++ b/.agents/skills/simple-words-design/README.md @@ -180,7 +180,7 @@ The options page is fully opaque. ### Layout rules -- **Floating button** is `position: fixed`, `z-index: 2147483647` (max), and positioned near the active editable field's lower-right edge. +- **Floating button** is `position: fixed`, `z-index: 2147483647` (max), starts near the active editable field's lower-right edge, and can move to avoid button-like page controls. This is non-negotiable — it must clear every host page, including ones with their own floating UI. Use a compact 24px `sw` glyph button for normal editors and a 20px version for short inputs. The injected button and panel are visible only while the current domain is enabled and the active editor is connected, focused, and visible, including empty editors. diff --git a/.agents/skills/simple-words-design/ui_kits/extension/README.md b/.agents/skills/simple-words-design/ui_kits/extension/README.md index 66abc24..5dde15e 100644 --- a/.agents/skills/simple-words-design/ui_kits/extension/README.md +++ b/.agents/skills/simple-words-design/ui_kits/extension/README.md @@ -6,7 +6,7 @@ Check the production extension files before treating this kit as pixel-faithful. ## Surfaces 1. **Floating button** (`FloatingButton.jsx`) - a prototype pill button with the older sparkles icon and label. - Production now uses a compact `sw` glyph button near the lower-right edge of focused editable fields, so check the extension files before treating this component as pixel-faithful. + Production now uses a compact `sw` glyph button that starts near the lower-right edge of focused editable fields and can move to avoid button-like page controls, so check the extension files before treating this component as pixel-faithful. 2. **Refine panel** (`RefinePanel.jsx`) - the floating panel that shows loading, setup or provider error guidance, rewritten draft states, and Open settings/Replace/Dismiss actions. 3. **Options page** (`OptionsPage.jsx`) - the settings page prototype with provider config, enabled domains, name field, and advanced system prompt. 4. **Host page** (`HostPage.jsx`) - a faked Gmail-like compose window, just so the floating button has something to attach to in `index.html`. @@ -33,7 +33,7 @@ Preserve that visibility contract in production-facing work. ## Demo `index.html` boots a fake Gmail compose window with a draft typed in. -The prototype still positions its legacy pill below the textarea; production positions the compact `sw` button near the editor's lower-right edge. +The prototype still positions its legacy pill below the textarea; production starts the compact `sw` button near the editor's lower-right edge and can move it to avoid button-like page controls. Clicking the button opens the refine panel with a 1-second simulated "Refining..." state, then a rewritten draft. Click "Replace draft" to swap the textarea content; click "Dismiss" to close. There's also a tab switch at the top to jump to the **Options page** view. diff --git a/e2e/button-overlap.spec.ts b/e2e/button-overlap.spec.ts new file mode 100644 index 0000000..fbdd582 --- /dev/null +++ b/e2e/button-overlap.spec.ts @@ -0,0 +1,231 @@ +import { test, expect, chromium, type BrowserContext } from '@playwright/test' +import { createServer, type Server } from 'node:http' +import { mkdir, writeFile } from 'node:fs/promises' +import { mkdtemp } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import path from 'node:path' + +const evidenceDir = path.join(process.cwd(), 'test-results', 'button-overlap') + +test('places the Simple Words button away from page buttons but not broad tabindex containers', async () => { + const app = await startFixtureServer() + const extensionPath = path.join(process.cwd(), 'extension') + const userDataDir = await mkdtemp( + path.join(tmpdir(), 'simplewords-overlap-e2e-') + ) + let context: BrowserContext | undefined + + try { + context = await chromium.launchPersistentContext(userDataDir, { + headless: false, + args: [ + `--disable-extensions-except=${extensionPath}`, + `--load-extension=${extensionPath}` + ] + }) + + await configureSiteEnablementOnly(context) + await mkdir(evidenceDir, { recursive: true }) + + const page = await context.newPage() + await page.setViewportSize({ width: 640, height: 480 }) + + await page.goto(`${app.baseURL}/button-overlap`) + await page.locator('#editor').click() + await expect(page.locator('#simplewords-button')).toBeVisible() + const buttonControlEvidence = await page.evaluate(measurePlacement) + expect(buttonControlEvidence.overlapsAvoidTarget).toBe(false) + expect(buttonControlEvidence.simpleWordsButton.top).toBeLessThan( + buttonControlEvidence.editor.bottom - 30 + ) + await page.screenshot({ + path: path.join(evidenceDir, 'button-control-avoided.png'), + fullPage: true + }) + + await page.goto(`${app.baseURL}/tabindex-nearby`) + await page.locator('#editor').click() + await expect(page.locator('#simplewords-button')).toBeVisible() + const tabindexEvidence = await page.evaluate(measurePlacement) + expect(tabindexEvidence.overlapsAvoidTarget).toBe(true) + expect(tabindexEvidence.simpleWordsButton.top).toBeGreaterThan( + tabindexEvidence.editor.bottom - 40 + ) + await page.screenshot({ + path: path.join(evidenceDir, 'tabindex-container-not-avoided.png'), + fullPage: true + }) + + await writeFile( + path.join(evidenceDir, 'placement-evidence.json'), + `${JSON.stringify({ buttonControlEvidence, tabindexEvidence }, null, 2)}\n` + ) + } finally { + await context?.close() + await app.close() + } +}) + +async function configureSiteEnablementOnly( + context: BrowserContext +): Promise { + const serviceWorker = + context.serviceWorkers()[0] ?? (await context.waitForEvent('serviceworker')) + + await serviceWorker.evaluate(() => { + return chrome.storage.local.set({ + enabledDomains: ['127.0.0.1'] + }) + }) +} + +async function startFixtureServer(): Promise<{ + baseURL: string + close: () => Promise +}> { + const server: Server = createServer((request, response) => { + if (request.url === '/button-overlap') { + response.writeHead(200, { 'content-type': 'text/html' }) + response.end( + fixturePage('') + ) + return + } + + if (request.url === '/tabindex-nearby') { + response.writeHead(200, { 'content-type': 'text/html' }) + response.end( + fixturePage( + '
Focusable wrapper
' + ) + ) + return + } + + response.writeHead(404, { 'content-type': 'text/plain' }) + response.end('not found') + }) + + await new Promise((resolve) => { + server.listen(0, '127.0.0.1', resolve) + }) + + const address = server.address() + if (!address || typeof address === 'string') { + throw new Error('Unable to start E2E fixture server') + } + + return { + baseURL: `http://127.0.0.1:${address.port}`, + close: () => + new Promise((resolve, reject) => { + server.close((error) => { + if (error) { + reject(error) + return + } + + resolve() + }) + }) + } +} + +function fixturePage(avoidTarget: string): string { + return ` + + + Simple Words button overlap fixture + + + +
+

Reply composer

+
+ + ${avoidTarget} +
+
+ +` +} + +function measurePlacement(): { + editor: PlainRect + avoidTarget: PlainRect + simpleWordsButton: PlainRect + overlapsAvoidTarget: boolean +} { + const plainRect = (element: HTMLElement | null): PlainRect => { + if (!element) { + throw new Error('Expected element to exist') + } + + const rect = element.getBoundingClientRect() + return { + top: Math.round(rect.top), + left: Math.round(rect.left), + right: Math.round(rect.right), + bottom: Math.round(rect.bottom), + width: Math.round(rect.width), + height: Math.round(rect.height) + } + } + const rectsOverlap = (a: PlainRect, b: PlainRect): boolean => { + return ( + a.left < b.right && + a.right > b.left && + a.top < b.bottom && + a.bottom > b.top + ) + } + + const editor = plainRect(document.getElementById('editor')) + const avoidTarget = plainRect(document.getElementById('avoid-target')) + const simpleWordsButton = plainRect( + document.getElementById('simplewords-button') + ) + + return { + editor, + avoidTarget, + simpleWordsButton, + overlapsAvoidTarget: rectsOverlap(simpleWordsButton, avoidTarget) + } +} + +interface PlainRect { + top: number + left: number + right: number + bottom: number + width: number + height: number +} diff --git a/src/content.ts b/src/content.ts index b78f42e..6ecd13a 100644 --- a/src/content.ts +++ b/src/content.ts @@ -16,9 +16,10 @@ import { type SimpleWordsSettings } from './settings' import { - buttonPositionNearEditor, + buttonCandidateRectsNearEditor, panelPositionAboveButton } from './uiPosition' +import type { RectLike } from './uiPosition' const BUTTON_ID = 'simplewords-button' const PANEL_ID = 'simplewords-panel' @@ -27,6 +28,19 @@ const MAX_CONTEXT_CHARS = 30_000 const BUTTON_SIZE = 24 const SMALL_BUTTON_SIZE = 20 const SMALL_EDITOR_HEIGHT = 34 +const CLICKABLE_AVOID_SELECTOR = [ + 'button', + 'a[href]', + '[role="button"]', + '[role="menuitem"]', + '[role="option"]', + 'input[type="button"]', + 'input[type="submit"]', + 'input[type="reset"]', + 'summary' +].join(',') +const CLICKABLE_AVOID_PROXIMITY = 80 +const CLICKABLE_AVOID_INTERIOR_SAMPLE_STEP = 4 const BRAND_GLYPH_SVG = `` @@ -543,15 +557,158 @@ function positionButton(editor: HTMLElement): void { const rect = editor.getBoundingClientRect() const size = buttonSizeForEditor(rect) button.dataset.size = size === SMALL_BUTTON_SIZE ? 'small' : 'normal' - const position = buttonPositionNearEditor({ + const position = collisionAwareButtonPositionNearEditor({ editorRect: rect, buttonSize: { width: size, height: size }, - viewportSize: { width: window.innerWidth, height: window.innerHeight } + viewportSize: { width: window.innerWidth, height: window.innerHeight }, + editor }) button.style.top = `${position.top}px` button.style.left = `${position.left}px` } +function collisionAwareButtonPositionNearEditor(options: { + editor: HTMLElement + editorRect: DOMRect + buttonSize: { width: number; height: number } + viewportSize: { width: number; height: number } +}): RectLike { + const { editor, ...positionOptions } = options + const candidateRects = buttonCandidateRectsNearEditor(positionOptions) + + for (const candidateRect of candidateRects) { + const avoidRects = clickableAvoidRectsForCandidate(editor, candidateRect) + if (!avoidRects.some((rect) => rectsOverlap(rect, candidateRect))) { + return candidateRect + } + } + + return candidateRects[0] +} + +function clickableAvoidRectsForCandidate( + editor: HTMLElement, + candidateRect: RectLike +): DOMRect[] { + const elementsFromPoint = document.elementsFromPoint?.bind(document) + + if (elementsFromPoint) { + const seenElements = new Set() + + for (const element of elementsFromCandidateRect( + candidateRect, + elementsFromPoint + )) { + const clickableElement = element.closest( + CLICKABLE_AVOID_SELECTOR + ) + + if (!clickableElement || seenElements.has(clickableElement)) { + continue + } + + seenElements.add(clickableElement) + + if (clickableElement === editor) { + continue + } + + if (clickableElement.contains(editor)) { + continue + } + + if (isInjectedUITarget(clickableElement)) { + continue + } + + const visibility = getComputedStyle(clickableElement).visibility + if (visibility === 'hidden' || visibility === 'collapse') { + continue + } + + const rect = clickableElement.getBoundingClientRect() + if ( + rect.width > 0 && + rect.height > 0 && + rectsOverlap(rect, candidateRect) + ) { + return [rect] + } + } + + return [] + } + + const proximityRect = expandedRect(candidateRect, CLICKABLE_AVOID_PROXIMITY) + + return Array.from( + document.querySelectorAll(CLICKABLE_AVOID_SELECTOR) + ) + .filter((element) => element !== editor) + .filter((element) => !element.contains(editor)) + .filter((element) => !isInjectedUITarget(element)) + .filter((element) => { + const visibility = getComputedStyle(element).visibility + return visibility !== 'hidden' && visibility !== 'collapse' + }) + .map((element) => element.getBoundingClientRect()) + .filter((rect) => rect.width > 0 && rect.height > 0) + .filter((rect) => rectsOverlap(rect, proximityRect)) +} + +function* elementsFromCandidateRect( + rect: RectLike, + elementsFromPoint: (x: number, y: number) => Element[] +): Iterable { + const right = rect.right - 1 + const bottom = rect.bottom - 1 + const centerX = Math.floor(rect.left + rect.width / 2) + + for (let x = rect.left; x < rect.right; x += 1) { + yield* elementsFromPoint(x, rect.top) + yield* elementsFromPoint(x, bottom) + } + + for (let y = rect.top + 1; y < bottom; y += 1) { + yield* elementsFromPoint(rect.left, y) + yield* elementsFromPoint(right, y) + yield* elementsFromPoint(centerX, y) + } + + for ( + let x = rect.left + CLICKABLE_AVOID_INTERIOR_SAMPLE_STEP; + x < right; + x += CLICKABLE_AVOID_INTERIOR_SAMPLE_STEP + ) { + if (x === centerX) { + continue + } + + for ( + let y = rect.top + CLICKABLE_AVOID_INTERIOR_SAMPLE_STEP; + y < bottom; + y += CLICKABLE_AVOID_INTERIOR_SAMPLE_STEP + ) { + yield* elementsFromPoint(x, y) + } + } +} + +function expandedRect(rect: RectLike, amount: number): DOMRect { + return new DOMRect( + rect.left - amount, + rect.top - amount, + rect.width + amount * 2, + rect.height + amount * 2 + ) +} + +function rectsOverlap(a: RectLike, b: RectLike): boolean { + return ( + a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top + ) +} + function buttonSizeForEditor(rect: DOMRect): number { return rect.height <= SMALL_EDITOR_HEIGHT ? SMALL_BUTTON_SIZE : BUTTON_SIZE } diff --git a/src/uiPosition.ts b/src/uiPosition.ts index ff480f8..f2496e1 100644 --- a/src/uiPosition.ts +++ b/src/uiPosition.ts @@ -39,19 +39,65 @@ export function buttonPositionNearEditor(options: { editorRect: RectLike buttonSize: Size viewportSize: Size + avoidRects?: RectLike[] }): { top: number; left: number } { + const { avoidRects = [] } = options + const candidates = buttonCandidateRectsNearEditor(options) + + const nonOverlappingCandidate = candidates.find( + (candidate) => !rectOverlapsAny(candidate, avoidRects) + ) + + return nonOverlappingCandidate ?? candidates[0] +} + +export function buttonCandidateRectsNearEditor(options: { + editorRect: RectLike + buttonSize: Size + viewportSize: Size +}): RectLike[] { const { editorRect, buttonSize, viewportSize } = options const fitsInsideEditor = editorRect.height >= buttonSize.height + BUTTON_GAP * 2 - const unclampedTop = fitsInsideEditor + const lowerRightTop = fitsInsideEditor ? editorRect.bottom - buttonSize.height - BUTTON_GAP : editorRect.top + editorRect.height / 2 - buttonSize.height / 2 - const unclampedLeft = editorRect.right - buttonSize.width - BUTTON_GAP + const rightAlignedLeft = editorRect.right - buttonSize.width - BUTTON_GAP const maxTop = viewportSize.height - buttonSize.height - VIEWPORT_GUTTER const maxLeft = viewportSize.width - buttonSize.width - VIEWPORT_GUTTER + return [ + { top: lowerRightTop, left: rightAlignedLeft }, + { top: editorRect.top + BUTTON_GAP, left: rightAlignedLeft }, + { top: editorRect.bottom + BUTTON_GAP, left: rightAlignedLeft }, + { + top: editorRect.top - buttonSize.height - BUTTON_GAP, + left: rightAlignedLeft + }, + { top: lowerRightTop, left: editorRect.right + BUTTON_GAP }, + { + top: lowerRightTop, + left: editorRect.left - buttonSize.width - BUTTON_GAP + } + ].map((candidate) => { + const top = Math.max(VIEWPORT_GUTTER, Math.min(maxTop, candidate.top)) + const left = Math.max(VIEWPORT_GUTTER, Math.min(maxLeft, candidate.left)) + return { + top, + left, + right: left + buttonSize.width, + bottom: top + buttonSize.height, + width: buttonSize.width, + height: buttonSize.height + } + }) +} - return { - top: Math.max(VIEWPORT_GUTTER, Math.min(maxTop, unclampedTop)), - left: Math.max(VIEWPORT_GUTTER, Math.min(maxLeft, unclampedLeft)) - } +function rectOverlapsAny(rect: RectLike, avoidRects: RectLike[]): boolean { + return avoidRects.some((avoidRect) => rectsOverlap(rect, avoidRect)) +} + +function rectsOverlap(a: RectLike, b: RectLike): boolean { + return ( + a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top + ) } diff --git a/test/content.test.ts b/test/content.test.ts index 215c2fc..30897d3 100644 --- a/test/content.test.ts +++ b/test/content.test.ts @@ -8,6 +8,7 @@ describe('content script button visibility', () => { document.getElementById('simplewords-button')?.remove() document.getElementById('simplewords-panel')?.remove() vi.restoreAllMocks() + Reflect.deleteProperty(document, 'elementsFromPoint') Reflect.deleteProperty(globalThis, 'chrome') resetExtensionContextForTests() }) @@ -85,6 +86,420 @@ describe('content script button visibility', () => { expect(button.innerHTML).toContain('font-size="48"') }) + test('moves the Simple Words button away from overlapping page buttons', () => { + document.body.innerHTML = + '' + + const editor = document.querySelector('textarea') as HTMLTextAreaElement + const sendButton = document.querySelector('button') as HTMLButtonElement + vi.spyOn(editor, 'getBoundingClientRect').mockReturnValue({ + top: 100, + left: 100, + right: 300, + bottom: 200, + width: 200, + height: 100, + x: 100, + y: 100, + toJSON: () => null + }) + vi.spyOn(sendButton, 'getBoundingClientRect').mockReturnValue({ + top: 160, + left: 260, + right: 310, + bottom: 210, + width: 50, + height: 50, + x: 260, + y: 160, + toJSON: () => null + }) + + editor.dispatchEvent(new FocusEvent('focusin', { bubbles: true })) + + const button = document.getElementById( + 'simplewords-button' + ) as HTMLButtonElement + expect(button.style.top).toBe('108px') + expect(button.style.left).toBe('268px') + }) + + test('does not avoid invisible page buttons near the editor', () => { + document.body.innerHTML = + '' + + const editor = document.querySelector('textarea') as HTMLTextAreaElement + const sendButton = document.querySelector('button') as HTMLButtonElement + vi.spyOn(editor, 'getBoundingClientRect').mockReturnValue({ + top: 100, + left: 100, + right: 300, + bottom: 200, + width: 200, + height: 100, + x: 100, + y: 100, + toJSON: () => null + }) + vi.spyOn(sendButton, 'getBoundingClientRect').mockReturnValue({ + top: 160, + left: 260, + right: 310, + bottom: 210, + width: 50, + height: 50, + x: 260, + y: 160, + toJSON: () => null + }) + + editor.dispatchEvent(new FocusEvent('focusin', { bubbles: true })) + + const button = document.getElementById( + 'simplewords-button' + ) as HTMLButtonElement + expect(button.style.top).toBe('168px') + expect(button.style.left).toBe('268px') + }) + + test('does not measure distant page buttons while positioning', () => { + document.body.innerHTML = + '' + + const editor = document.querySelector('textarea') as HTMLTextAreaElement + const nearButton = document.querySelector( + '[data-near]' + ) as HTMLButtonElement + const farButton = document.querySelector('[data-far]') as HTMLButtonElement + vi.spyOn(editor, 'getBoundingClientRect').mockReturnValue({ + top: 100, + left: 100, + right: 300, + bottom: 200, + width: 200, + height: 100, + x: 100, + y: 100, + toJSON: () => null + }) + const nearRect = { + top: 160, + left: 260, + right: 310, + bottom: 210, + width: 50, + height: 50, + x: 260, + y: 160, + toJSON: () => null + } + vi.spyOn(nearButton, 'getBoundingClientRect').mockReturnValue(nearRect) + const farRectSpy = vi.spyOn(farButton, 'getBoundingClientRect') + Object.defineProperty(document, 'elementsFromPoint', { + configurable: true, + value: () => [] + }) + vi.spyOn(document, 'elementsFromPoint').mockReturnValue([nearButton]) + + editor.dispatchEvent(new FocusEvent('focusin', { bubbles: true })) + + expect(farRectSpy).not.toHaveBeenCalled() + const button = document.getElementById( + 'simplewords-button' + ) as HTMLButtonElement + expect(button.style.top).toBe('108px') + expect(button.style.left).toBe('268px') + }) + + test('avoids page buttons that partially overlap a candidate between sampled points', () => { + document.body.innerHTML = + '' + + const editor = document.querySelector('textarea') as HTMLTextAreaElement + const sendButton = document.querySelector('button') as HTMLButtonElement + vi.spyOn(editor, 'getBoundingClientRect').mockReturnValue({ + top: 100, + left: 100, + right: 300, + bottom: 200, + width: 200, + height: 100, + x: 100, + y: 100, + toJSON: () => null + }) + const sendRect = { + top: 170, + left: 282, + right: 302, + bottom: 178, + width: 20, + height: 8, + x: 282, + y: 170, + toJSON: () => null + } + vi.spyOn(sendButton, 'getBoundingClientRect').mockReturnValue(sendRect) + Object.defineProperty(document, 'elementsFromPoint', { + configurable: true, + value: (x: number, y: number) => + x >= sendRect.left && + x < sendRect.right && + y >= sendRect.top && + y < sendRect.bottom + ? [sendButton] + : [] + }) + + editor.dispatchEvent(new FocusEvent('focusin', { bubbles: true })) + + const button = document.getElementById( + 'simplewords-button' + ) as HTMLButtonElement + expect(button.style.top).toBe('108px') + expect(button.style.left).toBe('268px') + }) + + test('stops overlap hit testing after finding a clear button position', () => { + document.body.innerHTML = + '' + + const editor = document.querySelector('textarea') as HTMLTextAreaElement + const sendButton = document.querySelector('button') as HTMLButtonElement + vi.spyOn(editor, 'getBoundingClientRect').mockReturnValue({ + top: 100, + left: 100, + right: 300, + bottom: 200, + width: 200, + height: 100, + x: 100, + y: 100, + toJSON: () => null + }) + const sendRect = { + top: 170, + left: 282, + right: 302, + bottom: 178, + width: 20, + height: 8, + x: 282, + y: 170, + toJSON: () => null + } + vi.spyOn(sendButton, 'getBoundingClientRect').mockReturnValue(sendRect) + const elementsFromPoint = vi.fn((x: number, y: number) => + x >= sendRect.left && + x < sendRect.right && + y >= sendRect.top && + y < sendRect.bottom + ? [sendButton] + : [] + ) + Object.defineProperty(document, 'elementsFromPoint', { + configurable: true, + value: elementsFromPoint + }) + + editor.dispatchEvent(new FocusEvent('focusin', { bubbles: true })) + + expect(elementsFromPoint).toHaveBeenCalledTimes(187) + const button = document.getElementById( + 'simplewords-button' + ) as HTMLButtonElement + expect(button.style.top).toBe('108px') + expect(button.style.left).toBe('268px') + }) + + test('short-circuits overlap hit testing for blocked button positions', () => { + document.body.innerHTML = + '' + + const editor = document.querySelector('textarea') as HTMLTextAreaElement + const sendButton = document.querySelector('button') as HTMLButtonElement + vi.spyOn(editor, 'getBoundingClientRect').mockReturnValue({ + top: 100, + left: 100, + right: 300, + bottom: 200, + width: 200, + height: 100, + x: 100, + y: 100, + toJSON: () => null + }) + const sendRect = { + top: 168, + left: 268, + right: 292, + bottom: 192, + width: 24, + height: 24, + x: 268, + y: 168, + toJSON: () => null + } + vi.spyOn(sendButton, 'getBoundingClientRect').mockReturnValue(sendRect) + const elementsFromPoint = vi.fn((x: number, y: number) => + x >= sendRect.left && + x < sendRect.right && + y >= sendRect.top && + y < sendRect.bottom + ? [sendButton] + : [] + ) + Object.defineProperty(document, 'elementsFromPoint', { + configurable: true, + value: elementsFromPoint + }) + + editor.dispatchEvent(new FocusEvent('focusin', { bubbles: true })) + + expect(elementsFromPoint).toHaveBeenCalledTimes(135) + const button = document.getElementById( + 'simplewords-button' + ) as HTMLButtonElement + expect(button.style.top).toBe('108px') + expect(button.style.left).toBe('268px') + }) + + test('avoids small page buttons that overlap between sampled rows and columns', () => { + document.body.innerHTML = + '' + + const editor = document.querySelector('textarea') as HTMLTextAreaElement + const sendButton = document.querySelector('button') as HTMLButtonElement + vi.spyOn(editor, 'getBoundingClientRect').mockReturnValue({ + top: 100, + left: 100, + right: 300, + bottom: 200, + width: 200, + height: 100, + x: 100, + y: 100, + toJSON: () => null + }) + const sendRect = { + top: 170, + left: 278, + right: 282, + bottom: 174, + width: 4, + height: 4, + x: 278, + y: 170, + toJSON: () => null + } + vi.spyOn(sendButton, 'getBoundingClientRect').mockReturnValue(sendRect) + Object.defineProperty(document, 'elementsFromPoint', { + configurable: true, + value: (x: number, y: number) => + x >= sendRect.left && + x < sendRect.right && + y >= sendRect.top && + y < sendRect.bottom + ? [sendButton] + : [] + }) + + editor.dispatchEvent(new FocusEvent('focusin', { bubbles: true })) + + const button = document.getElementById( + 'simplewords-button' + ) as HTMLButtonElement + expect(button.style.top).toBe('108px') + expect(button.style.left).toBe('268px') + }) + + test('avoids small page buttons fully inside a candidate away from sampled lines', () => { + document.body.innerHTML = + '' + + const editor = document.querySelector('textarea') as HTMLTextAreaElement + const sendButton = document.querySelector('button') as HTMLButtonElement + vi.spyOn(editor, 'getBoundingClientRect').mockReturnValue({ + top: 100, + left: 100, + right: 300, + bottom: 200, + width: 200, + height: 100, + x: 100, + y: 100, + toJSON: () => null + }) + const sendRect = { + top: 176, + left: 276, + right: 280, + bottom: 180, + width: 4, + height: 4, + x: 276, + y: 176, + toJSON: () => null + } + vi.spyOn(sendButton, 'getBoundingClientRect').mockReturnValue(sendRect) + Object.defineProperty(document, 'elementsFromPoint', { + configurable: true, + value: (x: number, y: number) => + x >= sendRect.left && + x < sendRect.right && + y >= sendRect.top && + y < sendRect.bottom + ? [sendButton] + : [] + }) + + editor.dispatchEvent(new FocusEvent('focusin', { bubbles: true })) + + const button = document.getElementById( + 'simplewords-button' + ) as HTMLButtonElement + expect(button.style.top).toBe('108px') + expect(button.style.left).toBe('268px') + }) + + test('does not avoid broad tabindex containers near the editor', () => { + document.body.innerHTML = + '
Focusable wrapper
' + + const editor = document.querySelector('textarea') as HTMLTextAreaElement + const focusableWrapper = document.querySelector('div') as HTMLDivElement + vi.spyOn(editor, 'getBoundingClientRect').mockReturnValue({ + top: 100, + left: 100, + right: 300, + bottom: 200, + width: 200, + height: 100, + x: 100, + y: 100, + toJSON: () => null + }) + vi.spyOn(focusableWrapper, 'getBoundingClientRect').mockReturnValue({ + top: 160, + left: 260, + right: 310, + bottom: 210, + width: 50, + height: 50, + x: 260, + y: 160, + toJSON: () => null + }) + + editor.dispatchEvent(new FocusEvent('focusin', { bubbles: true })) + + const button = document.getElementById( + 'simplewords-button' + ) as HTMLButtonElement + expect(button.style.top).toBe('168px') + expect(button.style.left).toBe('268px') + }) + test('uses the editable root when input events come from a contenteditable child', () => { document.body.innerHTML = '
rough reply
' diff --git a/test/uiPosition.test.ts b/test/uiPosition.test.ts index 2167690..a7f952a 100644 --- a/test/uiPosition.test.ts +++ b/test/uiPosition.test.ts @@ -78,4 +78,32 @@ describe('buttonPositionNearEditor', () => { expect(position.top).toBe(40) expect(position.left).toBe(192) }) + + test('uses the upper-right of the editor when the lower-right overlaps an avoided control', () => { + const position = buttonPositionNearEditor({ + editorRect: { + top: 100, + left: 100, + right: 300, + bottom: 200, + width: 200, + height: 100 + }, + buttonSize: { width: 24, height: 24 }, + viewportSize: { width: 500, height: 500 }, + avoidRects: [ + { + top: 160, + left: 260, + right: 310, + bottom: 210, + width: 50, + height: 50 + } + ] + }) + + expect(position.top).toBe(108) + expect(position.left).toBe(268) + }) })