mirror of
https://github.com/angular/angular.git
synced 2026-11-22 22:55:25 -05:00
refactor(devtools): improve canvas highlighter by reducing memory usage (#71046)
Previously, the canvas highlighter spanned across the whole document. That resulted in a high memory usage since empty canvases still take memory. This refactor converts the canvas to a `fixed` one, which covers only the viewport/visible part of the screen. PR Close #71046
This commit is contained in:
@@ -98,6 +98,8 @@ describe('HighlightImpl', () => {
|
||||
describe('updateLabel', () => {
|
||||
it('should update the label props and re-render', () => {
|
||||
const highlight = createHighlight();
|
||||
highlight.display();
|
||||
renderer.renderHighlight.calls.reset();
|
||||
|
||||
highlight.updateLabel('title', 'Bar');
|
||||
|
||||
|
||||
@@ -51,9 +51,16 @@ export class HighlightImpl<
|
||||
}
|
||||
|
||||
updateLabel(labelId: keyof T, ...props: Parameters<T[keyof T]>) {
|
||||
if (this.destroyed) {
|
||||
debugLog.warn('Cannot display a destroyed highlight.');
|
||||
return;
|
||||
}
|
||||
|
||||
this.props[labelId] = props;
|
||||
|
||||
this.renderer.renderHighlight(this);
|
||||
if (this.displayed) {
|
||||
this.renderer.renderHighlight(this);
|
||||
}
|
||||
}
|
||||
|
||||
destroy() {
|
||||
@@ -76,13 +83,13 @@ export class HighlightImpl<
|
||||
}
|
||||
|
||||
display() {
|
||||
if (this.displayed) {
|
||||
return;
|
||||
}
|
||||
if (this.destroyed) {
|
||||
debugLog.warn('Cannot display a destroyed highlight.');
|
||||
return;
|
||||
}
|
||||
if (this.displayed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.renderer.renderHighlight(this);
|
||||
this.displayed = true;
|
||||
|
||||
+47
-12
@@ -12,11 +12,21 @@ import {
|
||||
OVERLAY_FADE_OUT_DUR,
|
||||
StaticHighlightRenderOp,
|
||||
} from './operations';
|
||||
import {Rect, ViewportData} from './utils';
|
||||
import {RectWithScroll, ViewportData} from './utils';
|
||||
|
||||
const VIEWPORT: ViewportData = {width: 640, height: 480, scrollX: 0, scrollY: 0};
|
||||
const VISIBLE_RECT: Rect = {x: 100, y: 50, width: 200, height: 80};
|
||||
const OFFSCREEN_RECT: Rect = {x: 1000, y: 1000, width: 200, height: 80};
|
||||
const VISIBLE_RECT: RectWithScroll = {
|
||||
x: 100,
|
||||
y: 50,
|
||||
width: 200,
|
||||
height: 80,
|
||||
scrollX: 0,
|
||||
scrollY: 0,
|
||||
};
|
||||
|
||||
// The `IntersectionObserver` sets a `null` rect when
|
||||
// the target is outside of the viewport.
|
||||
const OFFSCREEN_RECT = null;
|
||||
|
||||
const TTL = 1000;
|
||||
|
||||
@@ -32,7 +42,7 @@ describe('Highlighter render operations', () => {
|
||||
});
|
||||
|
||||
describe('StaticHighlightRenderOp', () => {
|
||||
function createOp(rect: Rect) {
|
||||
function createOp(rect: RectWithScroll | null) {
|
||||
return new StaticHighlightRenderOp(createMockHighlight(), ctx, rect, VIEWPORT);
|
||||
}
|
||||
|
||||
@@ -52,7 +62,7 @@ describe('Highlighter render operations', () => {
|
||||
|
||||
op.render(0);
|
||||
|
||||
expect(op.isVisible).toBeFalse();
|
||||
expect(op.isVisible()).toBeFalse();
|
||||
expect(fillRect).not.toHaveBeenCalled();
|
||||
expect(op.state).toBe('standby');
|
||||
});
|
||||
@@ -63,23 +73,38 @@ describe('Highlighter render operations', () => {
|
||||
op.update({rect: VISIBLE_RECT});
|
||||
op.render(0);
|
||||
|
||||
expect(op.isVisible).toBeTrue();
|
||||
expect(op.isVisible()).toBeTrue();
|
||||
expect(fillRect).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should become visible when the viewport is scrolled to the highlight', () => {
|
||||
const op = createOp(OFFSCREEN_RECT);
|
||||
it('should draw relative to the scroll position of the updated viewport', () => {
|
||||
const op = createOp(VISIBLE_RECT);
|
||||
|
||||
expect(op.isVisible).toBeFalse();
|
||||
op.update({viewport: {...VIEWPORT, scrollX: 30, scrollY: 20}});
|
||||
op.render(0);
|
||||
|
||||
op.update({viewport: {...VIEWPORT, scrollX: 900, scrollY: 900}});
|
||||
// The first `fillRect` call is the overlay.
|
||||
expect(fillRect.calls.first().args).toEqual([
|
||||
VISIBLE_RECT.x - 30,
|
||||
VISIBLE_RECT.y - 20,
|
||||
VISIBLE_RECT.width,
|
||||
VISIBLE_RECT.height,
|
||||
]);
|
||||
});
|
||||
|
||||
expect(op.isVisible).toBeTrue();
|
||||
it('should hide the highlight when the rect is cleared', () => {
|
||||
const op = createOp(VISIBLE_RECT);
|
||||
|
||||
op.update({rect: null});
|
||||
op.render(0);
|
||||
|
||||
expect(op.isVisible()).toBeFalse();
|
||||
expect(fillRect).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('DynamicTtlBoundHighlightRenderOp', () => {
|
||||
function createOp(rect: Rect) {
|
||||
function createOp(rect: RectWithScroll | null) {
|
||||
const highlight = createMockHighlight(createTemplate({ttl: TTL}));
|
||||
return new DynamicTtlBoundHighlightRenderOp(highlight, ctx, rect, VIEWPORT);
|
||||
}
|
||||
@@ -119,5 +144,15 @@ describe('Highlighter render operations', () => {
|
||||
expect(fillRect).not.toHaveBeenCalled();
|
||||
expect(op.state).toBe('completed');
|
||||
});
|
||||
|
||||
it('should hide the highlight when the rect is cleared', () => {
|
||||
const op = createOp(VISIBLE_RECT);
|
||||
|
||||
op.update({rect: null});
|
||||
op.render(0);
|
||||
|
||||
expect(op.isVisible()).toBeFalse();
|
||||
expect(fillRect).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+27
-21
@@ -7,7 +7,15 @@
|
||||
*/
|
||||
|
||||
import {Highlight} from '../types';
|
||||
import {drawLabels, drawOverlay, Rect, setCanvasOpacity, ViewportData} from './utils';
|
||||
import {
|
||||
drawLabels,
|
||||
drawOverlay,
|
||||
normalizeRect,
|
||||
Rect,
|
||||
RectWithScroll,
|
||||
setCanvasOpacity,
|
||||
ViewportData,
|
||||
} from './utils';
|
||||
|
||||
export const OVERLAY_FADE_OUT_DUR = 300;
|
||||
|
||||
@@ -24,7 +32,7 @@ export const OVERLAY_FADE_OUT_DUR = 300;
|
||||
type RenderOpState = 'non-executed' | 'in-progress' | 'standby' | 'completed';
|
||||
|
||||
interface RenderOpUpdate {
|
||||
rect?: Rect;
|
||||
rect?: RectWithScroll | null;
|
||||
viewport?: ViewportData;
|
||||
}
|
||||
|
||||
@@ -48,7 +56,7 @@ export abstract class RenderOp {
|
||||
constructor(
|
||||
public readonly highlight: Highlight,
|
||||
protected readonly ctx: CanvasRenderingContext2D,
|
||||
protected rect: Rect,
|
||||
protected rect: RectWithScroll | null,
|
||||
protected viewport: ViewportData,
|
||||
) {}
|
||||
|
||||
@@ -56,17 +64,13 @@ export abstract class RenderOp {
|
||||
return this.stateInternal;
|
||||
}
|
||||
|
||||
get currentRect(): RectWithScroll | null {
|
||||
return this.rect;
|
||||
}
|
||||
|
||||
/** Tells whether the highlight is visible in the viewport. */
|
||||
get isVisible() {
|
||||
const rect = this.rect;
|
||||
const viewport = this.viewport;
|
||||
|
||||
const xAxis =
|
||||
viewport.scrollX - rect.width < rect.x && rect.x < viewport.width + viewport.scrollX;
|
||||
const yAxis =
|
||||
viewport.scrollY - rect.height < rect.y && rect.y < viewport.height + viewport.scrollY;
|
||||
|
||||
return xAxis && yAxis;
|
||||
isVisible(): this is {rect: Rect} {
|
||||
return !!this.rect;
|
||||
}
|
||||
|
||||
protected get template() {
|
||||
@@ -79,10 +83,10 @@ export abstract class RenderOp {
|
||||
|
||||
/** Update the highlight rect and/or the viewport data. */
|
||||
update({rect, viewport}: RenderOpUpdate) {
|
||||
if (rect) {
|
||||
if (rect !== undefined) {
|
||||
this.rect = rect;
|
||||
}
|
||||
if (viewport) {
|
||||
if (viewport !== undefined) {
|
||||
this.viewport = viewport;
|
||||
}
|
||||
}
|
||||
@@ -93,10 +97,11 @@ export class StaticHighlightRenderOp extends RenderOp {
|
||||
override render(timestamp: number) {
|
||||
this.start = timestamp;
|
||||
|
||||
if (this.isVisible) {
|
||||
if (this.isVisible()) {
|
||||
const normRect = normalizeRect(this.rect, this.viewport);
|
||||
setCanvasOpacity(this.ctx, 1);
|
||||
drawOverlay(this.ctx, this.template, this.rect);
|
||||
drawLabels(this.ctx, this.template, this.props, this.rect, this.viewport);
|
||||
drawOverlay(this.ctx, this.template, normRect);
|
||||
drawLabels(this.ctx, this.template, this.props, normRect, this.viewport);
|
||||
}
|
||||
|
||||
// Static highlights are directly marked as `standby`
|
||||
@@ -118,7 +123,7 @@ export class DynamicTtlBoundHighlightRenderOp extends RenderOp {
|
||||
|
||||
const timePassed = timestamp - this.start;
|
||||
|
||||
if (this.isVisible) {
|
||||
if (this.isVisible()) {
|
||||
// Calculate the diff between the fade out start timestamp and the passed time.
|
||||
const fadeOutTimePassDiff = timePassed - this.fadeOutStart;
|
||||
let opacity: number;
|
||||
@@ -131,9 +136,10 @@ export class DynamicTtlBoundHighlightRenderOp extends RenderOp {
|
||||
opacity = 1 - progress;
|
||||
}
|
||||
|
||||
const normRect = normalizeRect(this.rect, this.viewport);
|
||||
setCanvasOpacity(this.ctx, opacity);
|
||||
drawOverlay(this.ctx, this.template, this.rect);
|
||||
drawLabels(this.ctx, this.template, this.props, this.rect, this.viewport);
|
||||
drawOverlay(this.ctx, this.template, normRect);
|
||||
drawLabels(this.ctx, this.template, this.props, normRect, this.viewport);
|
||||
}
|
||||
|
||||
if (timePassed >= this.template.ttl!) {
|
||||
|
||||
+33
-25
@@ -39,11 +39,10 @@ function nextFrame(): Promise<void> {
|
||||
return new Promise((resolve) => requestAnimationFrame(() => resolve()));
|
||||
}
|
||||
|
||||
async function waitFor(predicate: () => boolean): Promise<void> {
|
||||
// Giving super tight timeout since rAF is not mocked.
|
||||
// Adjust the tests so that they fit within it.
|
||||
async function waitFor(predicate: () => boolean, timeout = 100): Promise<void> {
|
||||
const start = performance.now();
|
||||
// Giving super tight timeout since rAF is not mocked.
|
||||
// Adjust the tests so that they fit within it.
|
||||
const timeout = 30;
|
||||
|
||||
while (!predicate()) {
|
||||
if (performance.now() - start > timeout) {
|
||||
@@ -56,24 +55,30 @@ async function waitFor(predicate: () => boolean): Promise<void> {
|
||||
describe('Renderer', () => {
|
||||
let renderer: Renderer;
|
||||
|
||||
function createTarget(rect = DEF_TARGET_RECT): HTMLElement {
|
||||
function createTarget({x, y, width, height} = DEF_TARGET_RECT): HTMLElement {
|
||||
const el = document.createElement('div');
|
||||
el.style.position = 'absolute';
|
||||
el.style.top = '0';
|
||||
el.style.left = '0';
|
||||
el.style.left = `${x}px`;
|
||||
el.style.top = `${y}px`;
|
||||
el.style.width = `${width}px`;
|
||||
el.style.height = `${height}px`;
|
||||
|
||||
document.body.appendChild(el);
|
||||
spyOn(el, 'getBoundingClientRect').and.returnValue(rect);
|
||||
targets.push(el);
|
||||
|
||||
return el;
|
||||
}
|
||||
|
||||
let targets: HTMLElement[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
renderer = new Renderer();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
renderer.destroy();
|
||||
targets.forEach((t) => t.remove());
|
||||
targets = [];
|
||||
});
|
||||
|
||||
it('should append a transparent canvas to the body', () => {
|
||||
@@ -94,9 +99,9 @@ describe('Renderer', () => {
|
||||
const highlight = createMockHighlight(createTemplate(), {name: ['Foo']}, createTarget());
|
||||
|
||||
renderer.renderHighlight(highlight);
|
||||
await nextFrame();
|
||||
// Firefox needs a slightly longer timeout
|
||||
await waitFor(() => isPixelRenderedAt(INSIDE_DEF_RECT_PX), 200);
|
||||
|
||||
expect(isPixelRenderedAt(INSIDE_DEF_RECT_PX)).toBeTrue();
|
||||
expect(isPixelRenderedAt(OUTSIDE_DEF_RECT_PX)).toBeFalse();
|
||||
});
|
||||
|
||||
@@ -104,9 +109,7 @@ describe('Renderer', () => {
|
||||
const highlight = createMockHighlight(createTemplate(), {name: ['Foo']}, createTarget());
|
||||
|
||||
renderer.renderHighlight(highlight);
|
||||
await nextFrame();
|
||||
|
||||
expect(isPixelRenderedAt(INSIDE_DEF_RECT_PX)).toBeTrue();
|
||||
await waitFor(() => isPixelRenderedAt(INSIDE_DEF_RECT_PX));
|
||||
|
||||
renderer.removeHighlight(highlight);
|
||||
await nextFrame();
|
||||
@@ -127,10 +130,7 @@ describe('Renderer', () => {
|
||||
// 1st: The two highlights must be visible
|
||||
renderer.renderHighlight(foo);
|
||||
renderer.renderHighlight(bar);
|
||||
await nextFrame();
|
||||
|
||||
expect(isPixelRenderedAt(fooPixel)).toBeTrue();
|
||||
expect(isPixelRenderedAt(barPixel)).toBeTrue();
|
||||
await waitFor(() => isPixelRenderedAt(fooPixel) && isPixelRenderedAt(barPixel));
|
||||
|
||||
// 2nd. Foo removed. Only bar should be visible
|
||||
renderer.removeHighlight(foo);
|
||||
@@ -144,20 +144,28 @@ describe('Renderer', () => {
|
||||
});
|
||||
|
||||
it('should remove a TTL-bound highlight once it has faded out', async () => {
|
||||
const highlight = createMockHighlight(
|
||||
createTemplate({ttl: 10}),
|
||||
{name: ['Foo']},
|
||||
createTarget(),
|
||||
);
|
||||
// The TTL should be long enough for the `IntersectionObserver`
|
||||
// to provide the rect before the highlight expires.
|
||||
const ttl = 100;
|
||||
const highlight = createMockHighlight(createTemplate({ttl}), {name: ['Foo']}, createTarget());
|
||||
|
||||
renderer.renderHighlight(highlight);
|
||||
await nextFrame();
|
||||
await waitFor(() => isPixelRenderedAt(INSIDE_DEF_RECT_PX));
|
||||
|
||||
expect(isPixelRenderedAt(INSIDE_DEF_RECT_PX)).toBeTrue();
|
||||
expect(highlight.destroy).not.toHaveBeenCalled();
|
||||
|
||||
await waitFor(() => highlight.destroy.calls.any());
|
||||
await waitFor(() => highlight.destroy.calls.any(), ttl * 2);
|
||||
|
||||
expect(isPixelRenderedAt(INSIDE_DEF_RECT_PX)).toBeFalse();
|
||||
});
|
||||
|
||||
it('should disconnect the observers on destroy', () => {
|
||||
const ioDisconnect = spyOn(IntersectionObserver.prototype, 'disconnect').and.callThrough();
|
||||
const roDisconnect = spyOn(ResizeObserver.prototype, 'disconnect').and.callThrough();
|
||||
|
||||
renderer.destroy();
|
||||
|
||||
expect(ioDisconnect).toHaveBeenCalled();
|
||||
expect(roDisconnect).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
+108
-104
@@ -9,10 +9,15 @@
|
||||
import {runOutsideAngular} from '../../utils/general';
|
||||
import {Highlight} from '../types';
|
||||
import {DynamicTtlBoundHighlightRenderOp, RenderOp, StaticHighlightRenderOp} from './operations';
|
||||
import {createCanvas, getAbsoluteBoundingClientRect, getViewportData, ViewportData} from './utils';
|
||||
import {
|
||||
createCanvas,
|
||||
createRectWithScroll,
|
||||
getViewportData,
|
||||
RectWithScroll,
|
||||
ViewportData,
|
||||
} from './utils';
|
||||
|
||||
export const CANVAS_ID = 'ng-devtools-highlighter-canvas';
|
||||
const WINDOW_RESIZE_DEBOUNCE = 100;
|
||||
|
||||
/**
|
||||
* Provides HTML5 Canvas rendering medium for highlights.
|
||||
@@ -30,6 +35,7 @@ export class Renderer {
|
||||
private readonly targets = new WeakMap<Element, Set<Highlight>>();
|
||||
private viewportData: ViewportData = getViewportData();
|
||||
private elementResizeObserver!: ResizeObserver;
|
||||
private elementIntersectionObserver!: IntersectionObserver;
|
||||
private cleanUpFn?: () => void;
|
||||
private lastFrame?: ReturnType<typeof requestAnimationFrame>;
|
||||
|
||||
@@ -54,28 +60,46 @@ export class Renderer {
|
||||
return;
|
||||
}
|
||||
|
||||
const rect = getAbsoluteBoundingClientRect(targetEl);
|
||||
let op: RenderOp;
|
||||
|
||||
if (!highlight.template.ttl) {
|
||||
op = new StaticHighlightRenderOp(highlight, this.ctx, rect, this.viewportData);
|
||||
} else {
|
||||
op = new DynamicTtlBoundHighlightRenderOp(highlight, this.ctx, rect, this.viewportData);
|
||||
}
|
||||
|
||||
this.operations.set(highlight, op);
|
||||
let currentRect: RectWithScroll | null = null;
|
||||
|
||||
// Since an element might have multiple highlights,
|
||||
// we keep track of them to know when to observe or
|
||||
// unobserve from the `ResizeObserver`.
|
||||
// unobserve from our Observers.
|
||||
let highlights = this.targets.get(targetEl);
|
||||
if (!highlights) {
|
||||
highlights = new Set();
|
||||
this.targets.set(targetEl, highlights);
|
||||
|
||||
// Attaching the object to the intersection observer
|
||||
// will determine whether the rect is withing the viewport
|
||||
// and will render the highlight, if true.
|
||||
this.elementIntersectionObserver.observe(targetEl);
|
||||
this.elementResizeObserver.observe(targetEl);
|
||||
} else {
|
||||
// If the target is already observed, we can
|
||||
// use one of the existing rects for the new op.
|
||||
const [arbitraryHighlight] = highlights;
|
||||
const arbitraryOp = this.operations.get(arbitraryHighlight);
|
||||
currentRect = arbitraryOp?.currentRect ?? null;
|
||||
}
|
||||
|
||||
highlights.add(highlight);
|
||||
|
||||
let op: RenderOp;
|
||||
|
||||
if (!highlight.template.ttl) {
|
||||
op = new StaticHighlightRenderOp(highlight, this.ctx, currentRect, this.viewportData);
|
||||
} else {
|
||||
op = new DynamicTtlBoundHighlightRenderOp(
|
||||
highlight,
|
||||
this.ctx,
|
||||
currentRect,
|
||||
this.viewportData,
|
||||
);
|
||||
}
|
||||
|
||||
this.operations.set(highlight, op);
|
||||
|
||||
this.render();
|
||||
}
|
||||
|
||||
@@ -99,136 +123,115 @@ export class Renderer {
|
||||
* @returns A clean up function that unlistens all events.
|
||||
*/
|
||||
private initEvents(): () => void {
|
||||
const root = document.documentElement;
|
||||
let rootResizeObserver: ResizeObserver;
|
||||
let rootMutationObserver: MutationObserver;
|
||||
let elementFrame: ReturnType<typeof requestAnimationFrame> = 0;
|
||||
let rootFrame: ReturnType<typeof requestAnimationFrame> = 0;
|
||||
let scrollTimeout: ReturnType<typeof setTimeout>;
|
||||
let lastSize: {width: number; height: number} = {
|
||||
width: 0,
|
||||
height: 0,
|
||||
};
|
||||
|
||||
// We use this handler for all changes that
|
||||
// happen to the root element.
|
||||
const rootUpdatesHandler = () => {
|
||||
if (rootFrame) {
|
||||
cancelAnimationFrame(rootFrame);
|
||||
}
|
||||
rootFrame = requestAnimationFrame(() => {
|
||||
const width = root.scrollWidth;
|
||||
const height = root.scrollHeight;
|
||||
const {width: lastWidth, height: lastHeight} = lastSize;
|
||||
|
||||
if (width !== lastWidth || height !== lastHeight) {
|
||||
this.updateCanvasSize();
|
||||
this.updateViewportData();
|
||||
this.updateHighlightsData('full');
|
||||
this.render();
|
||||
// Used for updating the viewport data and canvas size and scaling.
|
||||
const windowChangeHandler = (shouldUpdateCanvasSize: boolean) => {
|
||||
let windowChangeScheduled = false;
|
||||
return () => {
|
||||
if (windowChangeScheduled) {
|
||||
return;
|
||||
}
|
||||
windowChangeScheduled = true;
|
||||
|
||||
lastSize = {width, height};
|
||||
});
|
||||
};
|
||||
|
||||
// The scroll handler takes care of viewport data updates.
|
||||
const scrollHandler = () => {
|
||||
if (scrollTimeout) {
|
||||
clearTimeout(scrollTimeout);
|
||||
}
|
||||
scrollTimeout = setTimeout(() => {
|
||||
requestAnimationFrame(() => {
|
||||
this.updateViewportData();
|
||||
this.updateHighlightsData('viewport');
|
||||
if (shouldUpdateCanvasSize) {
|
||||
this.updateCanvasSize();
|
||||
}
|
||||
this.viewportData = getViewportData();
|
||||
this.updateHighlightsViewportData();
|
||||
this.render();
|
||||
|
||||
windowChangeScheduled = false;
|
||||
});
|
||||
}, WINDOW_RESIZE_DEBOUNCE);
|
||||
};
|
||||
};
|
||||
|
||||
const forEachTargetOp = <T extends {target: Element}>(
|
||||
entries: T[],
|
||||
cb: (entry: T, op: RenderOp) => void,
|
||||
) => {
|
||||
for (const e of entries) {
|
||||
const highlights = this.targets.get(e.target);
|
||||
if (!highlights) {
|
||||
continue;
|
||||
}
|
||||
for (const h of highlights) {
|
||||
const op = this.operations.get(h);
|
||||
if (op) {
|
||||
cb(e, op);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const windowScrollHandler = windowChangeHandler(false);
|
||||
const windowResizeHandler = windowChangeHandler(true);
|
||||
|
||||
// Wrap Zone.js monkey-patched code for Zone-based apps.
|
||||
runOutsideAngular(() => {
|
||||
// NOTE: Along with the obvious `ResizeObserver`, we also
|
||||
// `observe` to a `MutationObserver`. It covers some specific
|
||||
// cases where absolutely-positioned content might change page
|
||||
// scroll area without affecting the size of the root element.
|
||||
rootResizeObserver = new ResizeObserver(rootUpdatesHandler);
|
||||
rootMutationObserver = new MutationObserver(rootUpdatesHandler);
|
||||
window.addEventListener('scroll', windowScrollHandler);
|
||||
window.addEventListener('resize', windowResizeHandler);
|
||||
|
||||
rootResizeObserver.observe(root);
|
||||
rootResizeObserver.observe(document.body);
|
||||
rootMutationObserver.observe(root, {childList: true, subtree: true, attributes: true});
|
||||
|
||||
window.addEventListener('scroll', scrollHandler);
|
||||
|
||||
this.elementResizeObserver = new ResizeObserver(() => {
|
||||
if (elementFrame) {
|
||||
return;
|
||||
}
|
||||
|
||||
elementFrame = requestAnimationFrame(() => {
|
||||
elementFrame = 0;
|
||||
this.updateHighlightsData('full');
|
||||
this.render();
|
||||
// Detects when the target is inside the viewport and
|
||||
// provides the available `boundingRectClient`, therefore,
|
||||
// making the highlight visible until the target leaves
|
||||
// of the viewport (=> removing the rect => hiding it).
|
||||
this.elementIntersectionObserver = new IntersectionObserver((entries) => {
|
||||
forEachTargetOp(entries, (e, op) => {
|
||||
op.update({
|
||||
rect: e.isIntersecting ? createRectWithScroll(e.boundingClientRect) : null,
|
||||
});
|
||||
});
|
||||
|
||||
this.render();
|
||||
});
|
||||
|
||||
// Triggered when a target resizes. All affected
|
||||
// targets get their rect updates using standard
|
||||
// `getBoundingClientRect`.
|
||||
this.elementResizeObserver = new ResizeObserver((entries) => {
|
||||
forEachTargetOp(entries, (e, op) => {
|
||||
if (op.isVisible()) {
|
||||
op.update({rect: createRectWithScroll(e.target.getBoundingClientRect())});
|
||||
}
|
||||
});
|
||||
|
||||
this.render();
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
if (scrollTimeout) {
|
||||
clearTimeout(scrollTimeout);
|
||||
}
|
||||
if (rootFrame) {
|
||||
cancelAnimationFrame(rootFrame);
|
||||
}
|
||||
if (elementFrame) {
|
||||
cancelAnimationFrame(elementFrame);
|
||||
}
|
||||
rootResizeObserver.disconnect();
|
||||
rootMutationObserver.disconnect();
|
||||
this.elementResizeObserver.disconnect();
|
||||
window.removeEventListener('scroll', scrollHandler);
|
||||
this.elementIntersectionObserver.disconnect();
|
||||
window.removeEventListener('scroll', windowScrollHandler);
|
||||
window.removeEventListener('resize', windowResizeHandler);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the highlights render ops.
|
||||
* @param config Use `full` for a full update (rect and viewport),
|
||||
* or `viewport` to update only the viewport data.
|
||||
* Update the viewport data of the render ops.
|
||||
*/
|
||||
private updateHighlightsData(config: 'full' | 'viewport') {
|
||||
const fullData = config === 'full';
|
||||
|
||||
private updateHighlightsViewportData() {
|
||||
for (const highlight of this.operations.keys()) {
|
||||
const targetEl = highlight.targetElement.deref();
|
||||
|
||||
// Get the updated positions of all target elements.
|
||||
if (targetEl) {
|
||||
const rect = fullData ? getAbsoluteBoundingClientRect(targetEl) : undefined;
|
||||
const op = this.operations.get(highlight);
|
||||
op!.update({rect, viewport: this.viewportData});
|
||||
op!.update({viewport: this.viewportData});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private updateViewportData() {
|
||||
this.viewportData = getViewportData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update and scale the canvas size based on
|
||||
* the root page element and the screen DPR.
|
||||
*/
|
||||
private updateCanvasSize() {
|
||||
const width = document.documentElement.scrollWidth;
|
||||
const height = document.documentElement.scrollHeight;
|
||||
const width = this.canvas.clientWidth;
|
||||
const height = this.canvas.clientHeight;
|
||||
|
||||
this.canvas.width = width * this.dpr;
|
||||
this.canvas.height = height * this.dpr;
|
||||
|
||||
// Width is set by CSS (100%)
|
||||
this.canvas.style.height = `${height}px`;
|
||||
|
||||
// Normalize the coordinate system to use CSS pixels
|
||||
this.ctx.scale(this.dpr, this.dpr);
|
||||
}
|
||||
@@ -248,6 +251,7 @@ export class Renderer {
|
||||
if (!highlights?.size) {
|
||||
this.targets.delete(targetEl);
|
||||
this.elementResizeObserver.unobserve(targetEl);
|
||||
this.elementIntersectionObserver.unobserve(targetEl);
|
||||
}
|
||||
}
|
||||
this.operations.delete(highlight);
|
||||
|
||||
+21
-21
@@ -12,7 +12,7 @@ import {
|
||||
createCanvas,
|
||||
drawLabels,
|
||||
drawOverlay,
|
||||
getAbsoluteBoundingClientRect,
|
||||
createRectWithScroll,
|
||||
Rect,
|
||||
toCSSColor,
|
||||
ViewportData,
|
||||
@@ -46,33 +46,33 @@ describe('Rendering utils', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAbsoluteBoundingClientRect', () => {
|
||||
describe('createRectWithScroll', () => {
|
||||
it('should truncate the rect values', () => {
|
||||
const el = document.createElement('div');
|
||||
spyOn(el, 'getBoundingClientRect').and.returnValue(new DOMRect(10.7, 20.3, 100.9, 50.6));
|
||||
|
||||
expect(getAbsoluteBoundingClientRect(el)).toEqual({x: 10, y: 20, width: 100, height: 50});
|
||||
});
|
||||
|
||||
it('should offset the rect by the page scroll position', () => {
|
||||
const spacer = document.createElement('div');
|
||||
spacer.style.height = '3000px';
|
||||
document.body.appendChild(spacer);
|
||||
window.scrollTo(0, 200);
|
||||
|
||||
const el = document.createElement('div');
|
||||
spyOn(el, 'getBoundingClientRect').and.returnValue(new DOMRect(10, 20, 100, 50));
|
||||
|
||||
expect(getAbsoluteBoundingClientRect(el)).toEqual({
|
||||
expect(createRectWithScroll(new DOMRect(10.7, 20.3, 100.9, 50.6))).toEqual({
|
||||
x: 10,
|
||||
y: 20 + window.scrollY,
|
||||
y: 20,
|
||||
width: 100,
|
||||
height: 50,
|
||||
scrollX: 0,
|
||||
scrollY: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('should store the rect along with the page scroll position', () => {
|
||||
document.body.style.width = '2000px';
|
||||
document.body.style.height = '2000px';
|
||||
window.scrollTo(30, 200);
|
||||
|
||||
expect(createRectWithScroll(new DOMRect(10, 20, 100, 50))).toEqual({
|
||||
x: 10,
|
||||
y: 20,
|
||||
width: 100,
|
||||
height: 50,
|
||||
scrollX: 30,
|
||||
scrollY: 200,
|
||||
});
|
||||
expect(window.scrollY).toBe(200);
|
||||
|
||||
window.scrollTo(0, 0);
|
||||
spacer.remove();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+48
-26
@@ -30,8 +30,15 @@ export interface ViewportData extends Dimensions {
|
||||
scrollY: number;
|
||||
}
|
||||
|
||||
/** Represents a normalized rect with coordinates relative to viewport. */
|
||||
export type Rect = Coor & Dimensions;
|
||||
|
||||
/** Represents a rect with scroll data collected at the moment of creation. */
|
||||
export type RectWithScroll = Rect & {
|
||||
scrollX: number;
|
||||
scrollY: number;
|
||||
};
|
||||
|
||||
const LABEL_PADDING = 2;
|
||||
const SVG_SIZE = 12;
|
||||
const SVG_VIEWBOX = 24;
|
||||
@@ -48,11 +55,11 @@ export function createCanvas(canvasId: string): {
|
||||
if (!canvas) {
|
||||
canvas = document.createElement('canvas');
|
||||
canvas.id = canvasId;
|
||||
canvas.style.position = 'absolute';
|
||||
canvas.style.position = 'fixed';
|
||||
canvas.style.display = 'block';
|
||||
canvas.style.pointerEvents = 'none';
|
||||
canvas.style.width = '100%';
|
||||
canvas.style.height = 'auto';
|
||||
canvas.style.height = '100%';
|
||||
canvas.style.top = '0';
|
||||
canvas.style.left = '0';
|
||||
canvas.style.zIndex = '2147483647';
|
||||
@@ -81,15 +88,31 @@ export function toCSSColor([red, green, blue]: RgbColor, alpha = 1): string {
|
||||
return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
|
||||
}
|
||||
|
||||
/** Returns a `Rect` based on `getBoundingClientRect` + the scroll positions. */
|
||||
export function getAbsoluteBoundingClientRect(target: Element): Rect {
|
||||
const {width, height, x, y} = target.getBoundingClientRect();
|
||||
|
||||
/** Returns a rect with scroll data collected at the moment of creation. */
|
||||
export function createRectWithScroll({width, height, x, y}: DOMRect): RectWithScroll {
|
||||
return {
|
||||
width: ~~width,
|
||||
height: ~~height,
|
||||
x: ~~(x + window.scrollX),
|
||||
y: ~~(y + window.scrollY),
|
||||
x: ~~x,
|
||||
y: ~~y,
|
||||
scrollX: ~~window.scrollX,
|
||||
scrollY: ~~window.scrollY,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a `RectWithScroll` to a normalized `Rect`
|
||||
* with coordinates relative to the viewport.
|
||||
*/
|
||||
export function normalizeRect(
|
||||
{x, y, scrollX, scrollY, width, height}: RectWithScroll,
|
||||
viewport: ViewportData,
|
||||
): Rect {
|
||||
return {
|
||||
width,
|
||||
height,
|
||||
x: x + (scrollX - viewport.scrollX),
|
||||
y: y + (scrollY - viewport.scrollY),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -254,17 +277,6 @@ function calculateLabelPos(
|
||||
const isInset = labelOffset === 'inset';
|
||||
const isStrictInset = labelOffset === 'strict-inset';
|
||||
|
||||
// If the label type is set to `sticky`, we determine the max X and Y
|
||||
// based on the viewport and current scroll. This way, the labels are kept
|
||||
// always visible.
|
||||
let maxX = Infinity;
|
||||
let maxY = Infinity;
|
||||
|
||||
if (labelType === 'sticky') {
|
||||
maxX = viewport.width + viewport.scrollX - labelSize.width;
|
||||
maxY = viewport.height + viewport.scrollY - labelSize.height;
|
||||
}
|
||||
|
||||
if (isInset || isStrictInset) {
|
||||
const isRectTooSmall = labelSize.width > rect.width || labelSize.height > rect.height;
|
||||
|
||||
@@ -279,24 +291,34 @@ function calculateLabelPos(
|
||||
// the rendering of that label.
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
y = rect.y + rect.height - labelSize.height;
|
||||
}
|
||||
|
||||
const originY = rect.y + rect.height - labelSize.height;
|
||||
y = isInset ? Math.min(originY, maxY) : originY;
|
||||
}
|
||||
|
||||
if (labelOffset === 'outset' || insetFallback) {
|
||||
y = Math.min(rect.y + rect.height, maxY);
|
||||
y = rect.y + rect.height;
|
||||
}
|
||||
|
||||
switch (labelX) {
|
||||
case 'left':
|
||||
x = Math.min(rect.x, maxX);
|
||||
x = rect.x;
|
||||
break;
|
||||
case 'center':
|
||||
x = Math.min(rect.x + (rect.width / 2 - labelSize.width / 2), maxX);
|
||||
x = rect.x + (rect.width / 2 - labelSize.width / 2);
|
||||
break;
|
||||
case 'right':
|
||||
x = Math.min(rect.x + rect.width - labelSize.width, maxX);
|
||||
x = rect.x + rect.width - labelSize.width;
|
||||
}
|
||||
|
||||
// If the label type is set to `sticky`, we determine the max X and Y
|
||||
// based on the viewport. This way, the labels are kept always visible.
|
||||
if (labelType === 'sticky' && !isStrictInset) {
|
||||
const maxX = viewport.width - labelSize.width;
|
||||
const maxY = viewport.height - labelSize.height;
|
||||
|
||||
x = Math.max(Math.min(x, maxX), 0);
|
||||
y = Math.max(Math.min(y, maxY), 0);
|
||||
}
|
||||
|
||||
return {x, y};
|
||||
|
||||
@@ -42,7 +42,8 @@ export interface HighlightLabel<T extends LabelContentFn> {
|
||||
* - `outset` – the label is rendered outside the highlight.
|
||||
* - `inset` – the label is rendered inside the highlight, if there is enough space to fit.
|
||||
* Else, it fall backs to `outset` mode.
|
||||
* - `strict-inset` – the label is rendered always inside the highlight.
|
||||
* - `strict-inset` – the label is rendered always inside the highlight and acts as `static`
|
||||
* irrespective of `labelsType` setting.
|
||||
* If there isn't enough space, the label won't be displayed.
|
||||
*/
|
||||
offset: 'inset' | 'outset' | 'strict-inset';
|
||||
|
||||
Reference in New Issue
Block a user