Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions common/styles/_widget.scss
Original file line number Diff line number Diff line change
Expand Up @@ -567,12 +567,12 @@
&[position='anchor'] .c7-panel {
bottom: auto;
left: var(--c7-anchor-left, 20px);
max-height: calc(100vh - 24px);
max-height: calc(100dvh - 24px);
max-width: calc(100vw - 24px);
max-height: var(--c7-anchor-max-height, calc(100vh - 24px));
max-height: var(--c7-anchor-max-height, calc(100dvh - 24px));
max-width: var(--c7-anchor-max-width, calc(100vw - 24px));
right: auto;
top: var(--c7-anchor-top, 20px);
transform: translateY(8px) scale(0.98);
transform: translateY(var(--c7-anchor-translate-y, 8px)) scale(0.98);
transform-origin: var(--c7-anchor-origin, top right);
}

Expand Down Expand Up @@ -1024,8 +1024,10 @@

&[position='anchor'] .c7-panel {
left: var(--c7-anchor-left, 12px);
max-height: var(--c7-anchor-max-height, calc(100dvh - 28px));
max-width: var(--c7-anchor-max-width, calc(100vw - 24px));
top: var(--c7-anchor-top, 12px);
transform: translateY(8px) scale(0.98);
transform: translateY(var(--c7-anchor-translate-y, 8px)) scale(0.98);
transform-origin: var(--c7-anchor-origin, top right);
}

Expand Down
11 changes: 11 additions & 0 deletions common/tests/unit/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,17 @@ export function setViewportSize(width: number, height: number): void {
});
}

export function setDocumentClientSize(width: number, height: number): void {
Object.defineProperty(document.documentElement, 'clientWidth', {
configurable: true,
value: width
});
Object.defineProperty(document.documentElement, 'clientHeight', {
configurable: true,
value: height
});
}

export function setElementSize(element: HTMLElement | null | undefined, width: number, height: number): void {
if (!element) throw new Error('Expected element to exist.');

Expand Down
10 changes: 5 additions & 5 deletions demo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@
"dependencies": {
"@desource/context7-widget": "workspace:*",
"@desource/context7-widget-vue": "workspace:*",
"@lucide/vue": "^1.27.0",
"nuxt": "^4.5.1",
"@lucide/vue": "^1.28.0",
"nuxt": "^4.5.2",
"postprocessing": "^6.39.4",
"three": "^0.185.1",
"vue": "^3.5.40"
"vue": "^3.5.41"
},
"devDependencies": {
"@types/three": "^0.185.1",
"vue-tsc": "^3.3.8"
"@types/three": "^0.185.4",
"vue-tsc": "^3.3.9"
}
}
10 changes: 5 additions & 5 deletions demo/public/widget.js

Large diffs are not rendered by default.

7 changes: 5 additions & 2 deletions docs/INTEGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,11 @@ menu, help item, or navigation action.
></script>
```

With `position="anchor"`, the panel opens above the trigger when there is enough
space and below it otherwise.
With `position="anchor"`, the panel opens above the trigger by default and flips
below when the upper side cannot fit it. When neither side can fit the requested
height, it uses the roomier side. The panel's height and width are constrained
to the visible viewport, including mobile browser and on-screen-keyboard
viewport changes.

## Centered Help Dialog

Expand Down
20 changes: 10 additions & 10 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,31 +58,31 @@
"@changesets/cli": "^2.31.1",
"@eslint/js": "^10.0.1",
"@microsoft/api-extractor": "^7.58.12",
"@playwright/test": "^1.62.0",
"@playwright/test": "^1.62.1",
"@types/node": "^26.1.2",
"@typescript-eslint/eslint-plugin": "^8.65.0",
"@typescript-eslint/parser": "^8.65.0",
"@typescript-eslint/eslint-plugin": "^8.66.0",
"@typescript-eslint/parser": "^8.66.0",
"@vitest/coverage-v8": "^4.1.10",
"esbuild": "^0.28.1",
"eslint": "^10.8.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-svelte": "^3.22.0",
"eslint-plugin-vue": "^10.10.0",
"esbuild": "^0.28.1",
"globals": "^17.8.0",
"globals": "^17.9.0",
"husky": "^9.1.7",
"jsdom": "^29.1.1",
"lint-staged": "^17.2.0",
"jsdom": "^30.0.1",
"lint-staged": "^17.3.0",
"prettier": "^3.9.6",
"prettier-plugin-svelte": "^4.1.1",
"publint": "^0.3.22",
"publint": "^0.3.23",
"rimraf": "^6.1.3",
"sass": "^1.102.0",
"svelte-eslint-parser": "^1.8.0",
"typescript": "~5.9.3",
"vite": "^8.1.4",
"vitest": "^4.1.10",
"vite": "^8.2.0",
"vite-plugin-dts": "^5.0.3",
"vitest": "^4.1.10",
"vue-eslint-parser": "^10.4.1"
},
"lint-staged": {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ Events: `c7:ready`, `c7:open`, `c7:close`, `c7:question`, `c7:first-token`,
The root and `/kit` are ESM-only and preserve internal module boundaries.
Downstream bundlers can therefore remove the custom-element runtime when an
application imports only a helper such as `renderMarkdown` or
`resolveContext7AnchorLayout`. The `widget.js` subpath is the classic browser
`updateAnchorPosition`. The `widget.js` subpath is the classic browser
script and intentionally has side effects.

The custom element shares one constructable stylesheet across instances when
Expand Down
80 changes: 69 additions & 11 deletions packages/core/src/dom.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Context7TriggerA11yState, Context7WidgetTarget } from './types.js';
import type { Context7Position, Context7TriggerA11yState, Context7WidgetTarget } from './types.js';

export interface Context7AnchorRect {
readonly bottom: number;
Expand All @@ -14,42 +14,100 @@ export interface Context7AnchorLayoutOptions {
readonly panelHeight: number;
readonly panelWidth: number;
readonly viewportHeight: number;
readonly viewportLeft?: number;
readonly viewportTop?: number;
readonly viewportWidth: number;
}

export interface Context7AnchorLayout {
readonly left: number;
readonly maxHeight: number;
readonly maxWidth: number;
readonly origin: string;
readonly placement: 'bottom' | 'top';
readonly top: number;
}

/** Resolve an end-aligned floating panel within the visible viewport. */
/** Resolve an end-aligned floating panel within the visible visual viewport. */
export function resolveContext7AnchorLayout({
anchor,
gap = 12,
margin = 12,
panelHeight,
panelWidth,
viewportHeight,
viewportLeft = 0,
viewportTop = 0,
viewportWidth
}: Context7AnchorLayoutOptions): Context7AnchorLayout {
const above = anchor.top - panelHeight - gap;
const below = anchor.bottom + gap;
const spaceAbove = anchor.top - margin - gap;
const spaceBelow = viewportHeight - anchor.bottom - margin - gap;
const hasSpaceAbove = above >= margin;
const hasSpaceBelow = below + panelHeight <= viewportHeight - margin;
const opensAbove = hasSpaceAbove || (!hasSpaceBelow && spaceAbove >= spaceBelow);
const left = clamp(anchor.right - panelWidth, margin, Math.max(margin, viewportWidth - panelWidth - margin));
const top = clamp(opensAbove ? above : below, margin, Math.max(margin, viewportHeight - panelHeight - margin));
const viewportBottom = viewportTop + Math.max(0, viewportHeight);
const viewportRight = viewportLeft + Math.max(0, viewportWidth);
const topBoundary = viewportTop + margin;
const leftBoundary = viewportLeft + margin;
const maxHeight = Math.max(0, viewportHeight - margin * 2);
const maxWidth = Math.max(0, viewportWidth - margin * 2);
const renderedWidth = Math.min(Math.max(0, panelWidth), maxWidth);
const spaceAbove = Math.max(0, anchor.top - gap - topBoundary);
const spaceBelow = Math.max(0, viewportBottom - margin - anchor.bottom - gap);

// Prefer the top placement. Flip when it cannot fit there, or choose the
// roomier side when neither side can fit the requested height.
const opensAbove = spaceAbove >= panelHeight || (spaceBelow < panelHeight && spaceAbove >= spaceBelow);
const placement = opensAbove ? 'top' : 'bottom';
const availableHeight = Math.min(opensAbove ? spaceAbove : spaceBelow, maxHeight);
const renderedHeight = Math.min(Math.max(0, panelHeight), availableHeight);
const left = clamp(
anchor.right - renderedWidth,
leftBoundary,
Math.max(leftBoundary, viewportRight - margin - renderedWidth)
);
const naturalTop = opensAbove ? anchor.top - gap - renderedHeight : anchor.bottom + gap;
const top = clamp(naturalTop, topBoundary, Math.max(topBoundary, viewportBottom - margin - renderedHeight));

return {
left,
maxHeight: availableHeight,
maxWidth,
origin: `${opensAbove ? 'bottom' : 'top'} right`,
placement,
top
};
}

/** Update the CSS custom properties for an anchored floating panel. */
export function updateAnchorPosition(
position: Context7Position,
anchor: Element | null,
panel?: HTMLElement | null,
rootStyle?: CSSStyleDeclaration
): void {
if (position !== 'anchor' || !anchor || !panel || !rootStyle) return;

const rect = anchor.getBoundingClientRect();
rootStyle.removeProperty('--c7-anchor-max-height');
rootStyle.removeProperty('--c7-anchor-max-width');
const panelWidth = panel.offsetWidth || 400;
const panelHeight = panel.offsetHeight || 600;
const viewport = window.visualViewport;
const viewportWidth = viewport?.width || window.innerWidth || document.documentElement.clientWidth || panelWidth;
const viewportHeight = viewport?.height || window.innerHeight || document.documentElement.clientHeight || panelHeight;
const { left, maxHeight, maxWidth, origin, placement, top } = resolveContext7AnchorLayout({
anchor: rect,
panelHeight,
panelWidth,
viewportHeight,
viewportLeft: viewport?.offsetLeft,
viewportTop: viewport?.offsetTop,
viewportWidth
});
rootStyle.setProperty('--c7-anchor-left', `${left}px`);
rootStyle.setProperty('--c7-anchor-max-height', `${maxHeight}px`);
rootStyle.setProperty('--c7-anchor-max-width', `${maxWidth}px`);
rootStyle.setProperty('--c7-anchor-top', `${top}px`);
rootStyle.setProperty('--c7-anchor-origin', origin);
rootStyle.setProperty('--c7-anchor-translate-y', placement === 'top' ? '8px' : '-8px');
}

export function requestRenderFrame(callback: (timestamp: number) => void): number {
if (typeof requestAnimationFrame === 'function') return requestAnimationFrame(callback);
return window.setTimeout(() => callback(performance.now()), 16);
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export {
isContext7WidgetEventName
} from './kit.js';
export { mountContext7WidgetFromScript } from './loader.js';
export { resolveContext7AnchorLayout } from './dom.js';
export { resolveContext7AnchorLayout, updateAnchorPosition } from './dom.js';
export { renderMarkdown } from './markdown.js';
export { streamContext7Response, Context7TransportError } from './transport.js';
export { Context7WidgetElement, defineContext7Widget } from './widget-element.js';
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/kit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ export {
resolveContext7AnchorLayout,
resolveTarget,
restoreTriggerAccessibility,
trapFocus
trapFocus,
updateAnchorPosition
} from './dom.js';
export { escapeHtml, renderMarkdown } from './markdown.js';
export { buildContext7ErrorHtml, DEFAULT_CONTEXT7_INITIAL_MESSAGE, isAbortError } from './runtime.js';
Expand Down
59 changes: 34 additions & 25 deletions packages/core/src/widget-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import {
captureTriggerAccessibility,
querySelectorSafely,
requestRenderFrame,
resolveContext7AnchorLayout,
restoreTriggerAccessibility,
trapFocus
trapFocus,
updateAnchorPosition
} from './dom.js';
import { escapeHtml, renderMarkdown } from './markdown.js';
import { buildContext7ErrorHtml, isAbortError } from './runtime.js';
Expand Down Expand Up @@ -94,6 +94,9 @@ export class Context7WidgetElement extends BaseHTMLElement {
private config: Context7WidgetConfig = readConfig(this);
private conversationInitialized = false;
private readonly elements: WidgetElements;
private floatingLayoutFrame: number | null = null;
private floatingResizeObserver: ResizeObserver | null = null;
private floatingViewport: VisualViewport | null = null;
private lastFocus: Element | null = null;
private messageCounter = 0;
private messages: Context7Message[] = [];
Expand Down Expand Up @@ -131,8 +134,9 @@ export class Context7WidgetElement extends BaseHTMLElement {
this.close();
};

private readonly onFloatingLayout = () => {
if (this.isOpen()) this.updateAnchorPosition();
private readonly onFloatingLayout = (event: Event) => {
if (event.type === 'scroll' && event.composedPath().includes(this)) return;
this.scheduleAnchorPositionUpdate();
};

private readonly onKeyDown = (event: KeyboardEvent) => {
Expand Down Expand Up @@ -650,38 +654,43 @@ export class Context7WidgetElement extends BaseHTMLElement {
if (this.config.position === 'anchor') {
window.addEventListener('resize', this.onFloatingLayout);
window.addEventListener('scroll', this.onFloatingLayout, true);
this.floatingViewport = window.visualViewport;
this.floatingViewport?.addEventListener('resize', this.onFloatingLayout);
this.floatingViewport?.addEventListener('scroll', this.onFloatingLayout);

if (typeof ResizeObserver === 'function') {
this.floatingResizeObserver = new ResizeObserver(() => this.scheduleAnchorPositionUpdate());
const anchor = this.getAnchorElement();
if (anchor) this.floatingResizeObserver.observe(anchor);
this.floatingResizeObserver.observe(this.panel);
}
}
}

private unbindFloatingListeners(): void {
document.removeEventListener('pointerdown', this.onDocumentPointerDown, true);
window.removeEventListener('resize', this.onFloatingLayout);
window.removeEventListener('scroll', this.onFloatingLayout, true);
this.floatingViewport?.removeEventListener('resize', this.onFloatingLayout);
this.floatingViewport?.removeEventListener('scroll', this.onFloatingLayout);
this.floatingViewport = null;
this.floatingResizeObserver?.disconnect();
this.floatingResizeObserver = null;
cancelRenderFrame(this.floatingLayoutFrame);
this.floatingLayoutFrame = null;
}

private updateAnchorPosition(): void {
if (this.config.position !== 'anchor') return;

const anchor = this.getAnchorElement();
const panel = this.panel;
if (!anchor || !panel) return;

const rect = anchor.getBoundingClientRect();
const panelWidth = panel.offsetWidth || 400;
const panelHeight = panel.offsetHeight || 600;
const viewportWidth = window.innerWidth || document.documentElement.clientWidth || panelWidth;
const viewportHeight = window.innerHeight || document.documentElement.clientHeight || panelHeight;
const { left, origin, top } = resolveContext7AnchorLayout({
anchor: rect,
panelHeight,
panelWidth,
viewportHeight,
viewportWidth
private scheduleAnchorPositionUpdate(): void {
if (!this.isOpen() || this.floatingLayoutFrame !== null) return;

this.floatingLayoutFrame = requestRenderFrame(() => {
this.floatingLayoutFrame = null;
if (this.isOpen()) this.updateAnchorPosition();
});
}

this.style.setProperty('--c7-anchor-left', `${left}px`);
this.style.setProperty('--c7-anchor-top', `${top}px`);
this.style.setProperty('--c7-anchor-origin', origin);
private updateAnchorPosition(): void {
updateAnchorPosition(this.config.position, this.getAnchorElement(), this.panel, this.style);
}

private getAnchorElement(): Element | null {
Expand Down
Loading