import { Element } from '@core/element' import scrollbarStyles from '@core/scrollbars.css?inline' import { html, nothing } from 'lit' import { consume } from '@lit/context' import { snapshotStyles } from './snapshot-styles.js' import { compactSelectStyles } from '../shared-styles.js' import { renderBrowserChrome } from './browser-chrome.js' import { deviceFrameSize, edgeInset, renderDeviceChrome } from './device-frame.js' import { drawElementOverlay, clearElementOverlay, resolveTestSelector } from './element-overlay.js' import { commandPageUrl } from './url-at-timestamp.js' import { mutationForCommand } from './mutation-at-command.js' import { booleanAttributeOn, isBooleanAttribute } from './boolean-attribute.js' import { render } from 'preact' import { customElement, query } from 'lit/decorators.js' import { replayDocument, transform } from './vnode-transform.js' import { archivedResources } from './archived-resources.js' import { PlayerFrames } from './player-frame.js' import { isUnsafeReplayAttribute } from './replay-safety.js' import type { SimplifiedVNode } from '@wdio/devtools-script/types' // Type-only, like the `script/types` import above: the collector owns the // characterData wire shape (parent ref + child index), so the replay reads it // from the same declaration that produces it. import type { TextMutation } from '@wdio/devtools-script/mutations.js' import { imageDimensions, imageMime, type CommandLog, type ImageSize, type TracePlayerFrame } from '@wdio/devtools-shared' import { mutationContext, metadataContext, metadataBySessionContext, commandContext, framesContext, playerArchiveContext, type PlayerArchive } from '../../controller/context.js' import { OPEN_DOCK_TAB_EVENT } from '../../controller/constants.js' import type { DeviceInfo, Metadata, MetadataBySession } from '@wdio/devtools-shared' import '../placeholder.js' import './screencast-player.js' import '~icons/mdi/cursor-default-click-outline.js' const MUTATION_SELECTOR = '__mutation-highlight__' /** A characterData mutation the collector could address. Older traces (and any * producer that only sets `target`) carry no `childIndex`, and there is no * child to patch without one — patching the parent instead would delete its * element children. */ function isAddressedText(mutation: TraceMutation): mutation is TextMutation { return ( typeof mutation.target === 'string' && typeof mutation.childIndex === 'number' ) } const textChildren = (el: Node) => Array.from(el.childNodes).filter( (node): node is Text => node.nodeType === Node.TEXT_NODE ) declare global { interface WindowEventMap { 'screencast-ready': CustomEvent<{ sessionId: string startTime?: number duration?: number }> } } const COMPONENT = 'wdio-devtools-browser' @customElement(COMPONENT) export class DevtoolsBrowser extends Element { #vdom = document.createDocumentFragment() /** Fields a field-state record has written the `value` PROPERTY of, which is * what separates a dirty replayed field from a pristine one. Weak, and every * replay rebuilds the document, so entries die with the elements they key. */ #fieldStateApplied = new WeakSet() #activeUrl?: string /** Base64 PNG of the screenshot for the currently selected command, or null. */ #screenshotData: string | null = null /** A player trace's frame for the selected command, read from its zip. */ #playerFrames = new PlayerFrames(() => this.requestUpdate()) /** * All recorded videos received from the backend, in arrival order. A new * entry is pushed for every browser session (initial + after every * reloadSession() call). `startTime`/`duration` (recording first-frame * timestamp and total span in ms) drive the scrubber's action markers. */ #videos: Array<{ sessionId: string url: string startTime?: number duration?: number }> = [] /** Index into #videos of the currently displayed video. */ #activeVideoIdx = 0 /** * Which view is active in the browser panel. * 'video' — always show the screencast player (default when a recording exists) * 'snapshot' — show DOM mutations replay and per-command screenshots */ #viewMode: 'snapshot' | 'video' = 'snapshot' /** When on, outline the elements the test interacted with (their command * target selectors) on the replayed page; click a box to copy its locator. */ #overlayOn = false @consume({ context: metadataContext, subscribe: true }) metadata: Metadata | undefined = undefined @consume({ context: metadataBySessionContext, subscribe: true }) metadataBySession: MetadataBySession | undefined = undefined @consume({ context: mutationContext, subscribe: true }) mutations: TraceMutation[] = [] @consume({ context: commandContext, subscribe: true }) commands: CommandLog[] = [] @consume({ context: framesContext, subscribe: true }) frames: TracePlayerFrame[] = [] @consume({ context: playerArchiveContext, subscribe: true }) archive: PlayerArchive | undefined = undefined static styles = [...Element.styles, compactSelectStyles, snapshotStyles] @query('iframe') iframe?: HTMLIFrameElement @query('header') header?: HTMLIFrameElement @query('section') section?: HTMLElement /** * Watches the player's OWN box rather than the window. Re-fitting used to * hang off `resize` and `window-drag`, so it depended on whoever changed the * layout announcing it — and the dock divider, the sidebar collapsing and * browser zoom announce nothing. Every one of those moves this box. */ #boxObserver?: ResizeObserver /** The window events the player handles while connected, as one table so its * registration and its teardown cannot drift. Every handler is a per-instance * arrow field, so the reference removeEventListener gets is the one that was * added — a bound method would produce a new function per call and never * detach. Sizing is not among them: that is the ResizeObserver's job. */ #windowListeners(): ReadonlyArray { return [ ['app-mutation-highlight', this.#highlightMutation], ['app-mutation-select', this.#handleMutationSelect], ['a11y-highlight', this.#highlightBySelector], ['show-command', this.#handleShowCommand], ['screencast-ready', this.#handleScreencastReady] ] } async connectedCallback() { super.connectedCallback() for (const [type, handler] of this.#windowListeners()) { window.addEventListener(type, handler) } // Safe against the observer loop: this watches the host, and the sizing it // triggers writes to a descendant. The host is laid out by its parent // (width/height 100%), so nothing it writes can feed back into this box. this.#boxObserver = new ResizeObserver(() => this.#handleResize()) this.#boxObserver.observe(this) await this.updateComplete } // Lit calls connectedCallback again on every re-connect, so a listener left // behind keeps a discarded player working — it still replays into its detached // iframe and collects arriving recordings — and makes the re-connected one // handle every event twice. disconnectedCallback() { super.disconnectedCallback() for (const [type, handler] of this.#windowListeners()) { window.removeEventListener(type, handler) } this.#boxObserver?.disconnect() this.#boxObserver = undefined this.#playerFrames.release(this.archive) } #captureShape?: { screenshot: string; size: ImageSize | null } /** Shape of the capture on screen, from its own decoded pixels. Memoized on * the frame it was read from, because this is read per render and per rAF. */ get #captureSize(): ImageSize | null { const screenshot = this.#screenshotData ?? this.#latestAutoScreenshot if (!screenshot) { // A REPLAYED capture keeps its images in its zip: the shown frame's size // once read, the first frame's (which the reader measured) until then. const frameSize = this.#playerFrames.size ?? this.archive?.frameSize if (frameSize) { return frameSize } // A trace with no frame has no screenshot to measure at all. Without a // fallback no native trace could ever draw device chrome, because the // shape was undecidable, and the player framed a phone as a desktop // browser. // // Only a PORTRAIT viewport is trusted for it. The reader substitutes a // synthetic 1280x720 for a trace that recorded no viewport, and that // shape is indistinguishable from a real one here — so a capture whose // geometry was never measured would be drawn as a landscape, // desktop-proportioned "device". Landscape costs nothing to refuse: // `#deviceLayout` already sends that shape to the stacked layout, so a // frame is not wanted there either. // // Still a fallback, not the primary: a native screenshot's pixels and // its window size genuinely differ (a Pixel reports 1080x2219 for a // 1080x2400 shot), so the image is the truer answer when there is one. const viewport = this.metadata?.viewport const portrait = Boolean( viewport?.width && viewport?.height && viewport.height > viewport.width ) return portrait ? { width: viewport!.width, height: viewport!.height } : null } if (this.#captureShape?.screenshot !== screenshot) { this.#captureShape = { screenshot, size: imageDimensions(screenshot) } } return this.#captureShape.size } /** * The device a capture was recorded on, once there is an image to shape the * frame around — a mobile BROWSER session (Appium driving Chrome on Android) * reports a device too, and must keep the browser frame. Two conditions * separate them, because either alone is decidable too late: * * - no DOM. That replay is an iframe laid out at its own captured viewport, * so shaping the frame to a screenshot would fight * `#sizeSnapshotToViewport` for the same box. It is the same signal * `#renderViewport` branches on, so the frame can never disagree with what * is inside it — but mutations arrive in batches, so early in a live run a * browser session has none yet. * - no url ON THE METADATA. A native session never issues a navigation, so * it never reports one, while a browser session reports one from its first * navigation — which lands before any DOM batch and closes that window. * Deliberately not `#displayUrl`: that is a display concern, resolved from * the selected command and empty until one is selected. */ get #deviceCapture(): { device: DeviceInfo; size: ImageSize } | null { if (this.mutations?.length || this.metadata?.url) { return null } const device = this.metadata?.device const size = device ? this.#captureSize : null return device && size ? { device, size } : null } #setIframeSize() { if (!this.section || !this.header) { return } // Screencast: let the device frame fill the pane and the video object-fit // inside it, so the frame spans the column like the mockup regardless of // the captured window's aspect ratio. Snapshot mode keeps its aspect-lock // (the DOM-replay iframe is scaled to the captured viewport). if (this.#viewMode === 'video') { this.section.style.width = '100%' this.section.style.height = '100%' return } if (this.#deviceCapture) { this.#sizeSectionToDevice() return } this.#sizeSnapshotToViewport() } /** Shape the frame to the device rather than to the pane. A native capture * reaches the screenshot branch, which fills whatever box it is given — so * in a landscape frame a portrait capture was a narrow strip with ~60% of * the frame backdrop, wrapped in window furniture describing nothing. */ #sizeSectionToDevice() { requestAnimationFrame(() => { const capture = this.#deviceCapture // The mode can flip between scheduling and firing: `updated()` re-sizes // on every view-mode change and the video branch is synchronous, so an // unguarded callback lands AFTER it and pins the screencast inside a // phone-shaped box until the next resize. if ( !this.section || !this.header || !capture || this.#viewMode === 'video' ) { return } const hostStyle = getComputedStyle(this) const rect = this.getBoundingClientRect() const padX = parseFloat(hostStyle.paddingLeft || '0') + parseFloat(hostStyle.paddingRight || '0') const padY = parseFloat(hostStyle.paddingTop || '0') + parseFloat(hostStyle.paddingBottom || '0') const sectionStyle = getComputedStyle(this.section) const frame = deviceFrameSize( { width: Math.max(0, rect.width - padX), height: Math.max(0, rect.height - padY) }, capture.size, { headerHeight: this.header.getBoundingClientRect().height, // Padding AND border: the section is border-box, so both come out of // the width and height set on it. Omitting the 2px border left the // capture area 4px short per axis and letterboxed it inside a frame // that was supposed to be its shape. insetX: edgeInset(sectionStyle, 'Left', 'Right'), insetY: edgeInset(sectionStyle, 'Top', 'Bottom') } ) this.section.style.width = `${frame.width}px` this.section.style.height = `${frame.height}px` }) } #sizeSnapshotToViewport() { const metadata = this.metadata if (!this.section || !this.header || !metadata) { return } // viewport may not be serialized yet (race between metadata message and // first resize event), or may arrive without dimensions — fall back to // sensible defaults so we never throw. const viewport = metadata.viewport as { width?: number; height?: number } | undefined const viewportWidth = viewport?.width || 1280 const viewportHeight = viewport?.height || 800 if (!viewportWidth || !viewportHeight) { return } // Defer to next frame so we read post-reflow dimensions on resize events. // NB: we deliberately do NOT clear the iframe's inline style first — the rAF // below overwrites every property it sets, so the iframe keeps its prior // (correct) transform until then. Clearing synchronously here made it paint // one frame un-scaled → a zoom flicker on every replayed frame during // playback, and let the overlay measure a collapsed/narrow layout. requestAnimationFrame(() => { if (!this.section || !this.header) { return } const frameSize = this.getBoundingClientRect() const headerSize = this.header.getBoundingClientRect() const hostStyle = getComputedStyle(this) // getBoundingClientRect returns the padding-box; subtract host padding // so a height-limited scale doesn't push section.width past the edge. const padX = parseFloat(hostStyle.paddingLeft || '0') + parseFloat(hostStyle.paddingRight || '0') const padY = parseFloat(hostStyle.paddingTop || '0') + parseFloat(hostStyle.paddingBottom || '0') const effectiveViewportH = viewportHeight const availW = Math.max(0, frameSize.width - padX) const availH = Math.max(0, frameSize.height - padY - headerSize.height) const scale = Math.max( 0, Math.min(availW / viewportWidth, availH / effectiveViewportH) ) // Keep the frame at full pane size (same as screencast) so toggling // between the two modes never resizes it; the replay iframe is scaled to // fit and centred horizontally inside the stable frame. this.section.style.width = '100%' this.section.style.height = '100%' // Iframe absent in screenshot/video modes — section sizing above still runs. this.#scaleReplayIframe(viewportWidth, viewportHeight, scale) // Layout is now settled — the one moment element rects are reliable, so // the overlay boxes track the replayed DOM after every step and resize. this.#redrawOverlay() }) } /** Scale the DOM-replay iframe to the captured viewport. Content taller than * the viewport scrolls INSIDE the iframe — a native page scrollbar at the * page's own edge, like a real browser window — so the player adds no outer * scroll surface and no gutter can appear beside the page. Centering is the * wrapper's job (align-items), so the iframe sits at 0,0 inside the sizer. */ #scaleReplayIframe( viewportWidth: number, viewportHeight: number, scale: number ) { if (!this.iframe) { return } this.iframe.style.width = `${viewportWidth}px` this.iframe.style.height = `${viewportHeight}px` this.iframe.style.transformOrigin = '0 0' this.iframe.style.transform = `scale(${scale})` this.iframe.style.left = '0px' this.iframe.style.top = '0px' const sizer = this.iframe.parentElement if (sizer) { sizer.style.width = `${viewportWidth * scale}px` sizer.style.height = `${viewportHeight * scale}px` } } #handleResize = () => this.#setIframeSize() #handleMutationSelect = (event: Event) => this.#renderBrowserState((event as CustomEvent).detail) #handleShowCommand = (event: Event) => this.#renderCommandScreenshot( (event as CustomEvent<{ command?: CommandLog }>).detail?.command ) #handleScreencastReady = (event: Event) => { const { sessionId, startTime, duration } = ( event as CustomEvent<{ sessionId: string startTime?: number duration?: number }> ).detail this.#videos.push({ sessionId, url: `/api/video/${sessionId}`, startTime, duration }) // Always show the latest video and switch to video mode automatically this.#activeVideoIdx = this.#videos.length - 1 this.#viewMode = 'video' this.requestUpdate() } #setViewMode(mode: 'snapshot' | 'video') { this.#viewMode = mode this.requestUpdate() } #setActiveVideo(idx: number) { this.#activeVideoIdx = idx this.requestUpdate() } /** URL of the currently selected video, or null when no videos exist. */ get #activeVideoUrl(): string | null { return this.#videos[this.#activeVideoIdx]?.url ?? null } /** Recording window of the active video — feeds the scrubber's markers. */ get #activeRecording(): { startTime?: number; duration?: number } { const v = this.#videos[this.#activeVideoIdx] return { startTime: v?.startTime, duration: v?.duration } } /** URL for the address bar: in video mode the selected recording's page URL * (looked up by its sessionId), else the snapshot's resolved URL. */ get #displayUrl(): string | undefined { if (this.#viewMode === 'video') { const sessionId = this.#videos[this.#activeVideoIdx]?.sessionId const sessionUrl = sessionId ? this.metadataBySession?.[sessionId]?.url : undefined return sessionUrl ?? this.#activeUrl ?? this.metadata?.url } return this.#activeUrl } async #renderCommandScreenshot(command?: CommandLog) { this.#screenshotData = this.#screenshotForCommand(command) void this.#playerFrames.show( this.frames ?? [], this.archive, this.#screenshotData ? undefined : command ) // Follow the selected command's page in the address bar — commands carry no // URL, so resolve it from the navigation active at the command's time. if (command) { this.#activeUrl = commandPageUrl(command, this.commands ?? [], this.mutations ?? []) ?? this.#activeUrl } // Switch to snapshot mode so the command snapshot is visible instead of the // video, and let that render LAND before replaying into it. In video mode // `#renderViewport` renders the player and no iframe at all, so a replay // issued here targeted an element that did not exist yet: the pane stayed // blank until the row was clicked a second time, by which point the render // this method requested had finally created the iframe. A recording arriving // switches the view on its own (`#handleScreencastReady`), so the very first // row clicked after any run with a screencast hit it. this.#viewMode = 'snapshot' this.requestUpdate() await this.updateComplete // DOM time-travel: rebuild the iframe DOM to the command's RESULT state (see // #mutationForCommand). The await above has already rendered the screenshot // fallback, so only the replay is left to do. const target = mutationForCommand( command, this.commands ?? [], this.mutations ?? [] ) if (target) { await this.#renderBrowserState(target) } } // View-mode flips swap the iframe with /