Skip to content
Draft
Show file tree
Hide file tree
Changes from 6 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
23 changes: 23 additions & 0 deletions e2e/tests/shared/parent-methods.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,29 @@ export function parentMethodTests(baseUrl, { hasDisconnect = true } = {}) {
)
})

test('connectResizer re-binding sends update without breaking the iframe', async ({
page,
}) => {
await page.goto(baseUrl)
await page.waitForLoadState('networkidle')
await waitForResizer(page)

// Skip frameworks that don't expose the imperative factory globally.
const hasFactory = await page.evaluate(
() => typeof window.iframeResize === 'function',
)
test.skip(!hasFactory, 'iframeResize factory not exposed globally')

// Re-bind with new options on an already-connected iframe.
// The update flow should fire (no throw) and iframeResizer stays attached.
const result = await page.evaluate(() => {
const iframe = document.querySelector('iframe')
window.iframeResize({ license: 'GPLv3', log: true }, iframe)
return iframe.iframeResizer ? 'attached' : 'detached'
})
expect(result).toBe('attached')
})

if (hasDisconnect) {
test('disconnect removes iframeResizer from iframe', async ({ page }) => {
await page.goto(baseUrl)
Expand Down
38 changes: 27 additions & 11 deletions packages/angular/directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
EventEmitter,
Input,
Output,
type SimpleChanges,
} from '@angular/core'
import { esModuleInterop } from '@iframe-resizer/common'
import type {
Expand Down Expand Up @@ -63,16 +64,8 @@ export class IframeResizerDirective {

constructor(private elementRef: ElementRef) {}

ngAfterViewInit(): void {
const id = this.elementRef.nativeElement?.id

this.consoleGroup.label(`angular(${id})`)
this.consoleGroup.event('setup')
this.consoleGroup.expand(this.options.logExpand)

if (this.debug) this.consoleGroup.log('ngAfterViewInit')

this.resizer = connectResizer({
private buildOptions(): IFrameOptions {
return {
...this.options,

onBeforeClose: () => {
Expand All @@ -98,7 +91,30 @@ export class IframeResizerDirective {
top: number
left: number
}) => this.onScroll.next(event),
})(this.elementRef.nativeElement)
} as IFrameOptions
}

ngAfterViewInit(): void {
const id = this.elementRef.nativeElement?.id

this.consoleGroup.label(`angular(${id})`)
this.consoleGroup.event('setup')
this.consoleGroup.expand(this.options.logExpand)

if (this.debug) this.consoleGroup.log('ngAfterViewInit')

this.resizer = connectResizer(this.buildOptions())(
this.elementRef.nativeElement,
)
}

ngOnChanges(changes: SimpleChanges): void {
// Re-bind when @Input options change. Skip the first call: the binding
// hasn't been established yet at that point — ngAfterViewInit handles it.
if (!this.resizer) return
if (!changes.options) return
if (this.debug) this.consoleGroup.log('ngOnChanges: options updated')
connectResizer(this.buildOptions())(this.elementRef.nativeElement)
}

ngOnDestroy(): void {
Expand Down
12 changes: 12 additions & 0 deletions packages/child/events/mouse.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'

import sendMessage from '../send/message'
import settings from '../values/settings'
import setupMouseEvents from './mouse'

vi.mock('../send/message', () => ({ default: vi.fn() }))

describe('child/events/mouse', () => {
let addSpy
beforeEach(() => {
settings.mouseEvents = true
addSpy = vi.spyOn(document, 'addEventListener')
})

Expand Down Expand Up @@ -37,4 +39,14 @@ describe('child/events/mouse', () => {
expect(sendMessage).toHaveBeenCalledWith(0, 0, 'mouseenter', '10:20')
expect(sendMessage).toHaveBeenCalledWith(0, 0, 'mouseleave', '30:40')
})

test('does not forward events when settings.mouseEvents is false', () => {
setupMouseEvents({ mouseEvents: true })

settings.mouseEvents = false
const [, fn1] = addSpy.mock.calls[0].slice(0, 2)
fn1({ type: 'mouseenter', screenY: 10, screenX: 20 })

expect(sendMessage).not.toHaveBeenCalled()
})
})
5 changes: 4 additions & 1 deletion packages/child/events/mouse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ import { HIGHLIGHT } from 'auto-console-group'

import { log } from '../console'
import sendMessage from '../send/message'
import settings from '../values/settings'
import { addEventListener } from './listeners'

const sendMouse = (evt: MouseEvent): void =>
const sendMouse = (evt: MouseEvent): void => {
if (settings.mouseEvents !== true) return
sendMessage(0, 0, evt.type, `${evt.screenY}:${evt.screenX}`)
}

function addMouseListener(evt: string, name: string): void {
log(`Add event listener: %c${name}`, HIGHLIGHT)
Expand Down
14 changes: 5 additions & 9 deletions packages/child/methods/move-to-anchor.test.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,26 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'

vi.mock('../console', () => ({ advise: vi.fn() }))

const { advise } = await import('../console')
const state = (await import('../values/state')).default
const moveToAnchor = (await import('./move-to-anchor')).default

describe('child/methods/move-to-anchor', () => {
beforeEach(() => {
vi.restoreAllMocks()
state.inPageLinks = { findTarget: vi.fn() }
state.findInPageLinkTarget = vi.fn()
})

it('calls findTarget with the provided anchor', () => {
moveToAnchor('section-1')
expect(state.inPageLinks.findTarget).toHaveBeenCalledWith('section-1')
expect(state.findInPageLinkTarget).toHaveBeenCalledWith('section-1')
})

it('throws TypeError when anchor is not a string', () => {
// @ts-expect-error testing runtime type check with wrong type
expect(() => moveToAnchor(123)).toThrowError(TypeError)
})

it('advises when inPageLinks is not enabled', () => {
state.inPageLinks = undefined
moveToAnchor('section-1')
expect(advise).toHaveBeenCalledWith(expect.stringContaining('inPageLinks'))
it('is a no-op when inPageLinks is not enabled', () => {
state.findInPageLinkTarget = null
expect(() => moveToAnchor('section-1')).not.toThrow()
})
})
11 changes: 1 addition & 10 deletions packages/child/methods/move-to-anchor.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,9 @@
import { typeAssert } from '@iframe-resizer/common'
import { STRING } from '@iframe-resizer/common/consts'

import { advise } from '../console'
import state from '../values/state'

export default function moveToAnchor(anchor: string): void {
typeAssert(anchor, STRING, 'parentIframe.moveToAnchor(anchor) anchor')

if (!state.inPageLinks?.findTarget) {
advise(
'<rb>Move to Anchor</><br><br>moveToAnchor() requires <b>inPageLinks</> to be enabled',
)
return
}

state.inPageLinks.findTarget(anchor)
state.findInPageLinkTarget?.(anchor)
}
15 changes: 8 additions & 7 deletions packages/child/page/links.branches.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,16 @@ describe('child/page/links branches', () => {
beforeEach(() => {
vi.restoreAllMocks()
document.body.innerHTML = ''
state.inPageLinks = undefined
state.findInPageLinkTarget = null
settings.mode = 0
settings.inPageLinks = true
sendMessage.mockClear()
})

it('enabled=false logs and does not set up handlers', () => {
setupInPageLinks(false)

expect(state.inPageLinks).toBeUndefined()
expect(state.findInPageLinkTarget).toBeNull()
expect(sendMessage).not.toHaveBeenCalled()
})

Expand All @@ -34,7 +35,7 @@ describe('child/page/links branches', () => {
setupInPageLinks(true)

expect(consoleMod.advise).toHaveBeenCalled()
expect(state.inPageLinks).toBeUndefined()
expect(state.findInPageLinkTarget).toBeNull()
expect(sendMessage).not.toHaveBeenCalled()
})

Expand Down Expand Up @@ -69,15 +70,15 @@ describe('child/page/links branches', () => {
})

it('findTarget jumps when element exists', () => {
// Enable and use state.inPageLinks.findTarget
// Enable and use state.findInPageLinkTarget
const target = document.createElement('div')
target.id = 'found'
target.getBoundingClientRect = () => ({ left: 7, top: 11 })
document.body.append(target)

setupInPageLinks(true)

state.inPageLinks.findTarget('#found')
state.findInPageLinkTarget('#found')

expect(sendMessage).toHaveBeenCalledWith(11, 7, SCROLL_TO_OFFSET)
})
Expand All @@ -91,7 +92,7 @@ describe('child/page/links branches', () => {
setupInPageLinks(true)

// Pass location without # prefix
state.inPageLinks.findTarget('nohash')
state.findInPageLinkTarget('nohash')

expect(sendMessage).toHaveBeenCalledWith(15, 5, SCROLL_TO_OFFSET)
})
Expand All @@ -104,7 +105,7 @@ describe('child/page/links branches', () => {

setupInPageLinks(true)

state.inPageLinks.findTarget('#byname')
state.findInPageLinkTarget('#byname')

expect(sendMessage).toHaveBeenCalledWith(9, 3, SCROLL_TO_OFFSET)
})
Expand Down
13 changes: 11 additions & 2 deletions packages/child/page/links.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { beforeEach, describe, expect, test, vi } from 'vitest'
import sendMessage from '../send/message'
import settings from '../values/settings'
import state from '../values/state'
import setupInPageLinks from './links'
import setupInPageLinks, { findTarget } from './links'

vi.mock('../console', () => ({ log: vi.fn(), advise: vi.fn() }))
vi.mock('../send/message', () => ({ __esModule: true, default: vi.fn() }))
Expand All @@ -13,6 +13,8 @@ describe('child/page/links', () => {
vi.clearAllMocks()
document.body.innerHTML = ''
settings.mode = 0
settings.inPageLinks = true
state.findInPageLinkTarget = null
})

test('setup and findTarget sends message for existing id', () => {
Expand All @@ -26,8 +28,15 @@ describe('child/page/links', () => {

setupInPageLinks(true)
// use the registered finder directly
state.inPageLinks.findTarget('#t1')
state.findInPageLinkTarget('#t1')

expect(sendMessage).toHaveBeenCalled()
})

test('findTarget no-op when inPageLinks setting becomes false', () => {
settings.inPageLinks = false
findTarget('#nope')

expect(sendMessage).not.toHaveBeenCalled()
})
})
54 changes: 33 additions & 21 deletions packages/child/page/links.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ function jumpToTarget(hash: string, target: Element): void {
}

export function findTarget(location: string): void {
if (settings.inPageLinks !== true) return

const hash = location.split('#')[1] || location // Remove # if present
const hashData = decodeURIComponent(hash)
const target =
Expand All @@ -65,17 +67,25 @@ export function checkLocationHash(): void {
}
}

export function handleAnchorClick(e: Event): void {
if (settings.inPageLinks !== true) return

const target = e.target as Element | null
const link = target?.closest?.('a[href^="#"]')
Comment on lines +73 to +74
if (!link) return

const href = link.getAttribute('href')
if (!href || href === '#') return

e.preventDefault()
findTarget(href)
}

export function bindAnchors(): void {
for (const link of document.querySelectorAll('a[href^="#"]')) {
const href = link.getAttribute('href')

if (href && href !== '#') {
addEventListener(link, 'click', (e) => {
e.preventDefault()
findTarget(href)
})
}
}
// Delegated listener: catches anchors added after init, and lets disable
// (settings.inPageLinks = false) restore native anchor behaviour because
// preventDefault() is gated inside the handler.
addEventListener(document, 'click', handleAnchorClick)
}

function bindLocationHash(): void {
Expand All @@ -93,21 +103,23 @@ function enableInPageLinks(): void {
bindLocationHash()
initCheck()

state.inPageLinks = {
findTarget,
}
state.findInPageLinkTarget = findTarget
}

export default function setupInPageLinks(enabled: boolean): void {
export default function setupInPageLinks(requested: boolean): void {
const { mode } = settings

if (enabled) {
if (checkMode(mode)) {
advise(getModeData(5))
} else {
enableInPageLinks()
}
} else {
if (!requested) {
log('In page linking not enabled')
return
}

if (state.findInPageLinkTarget) return // Already wired up

if (checkMode(mode)) {
advise(getModeData(5))
return
}

enableInPageLinks()
}
Loading