Skip to content

Commit

Permalink
Use media query event instead of beforeprint to detect printing
Browse files Browse the repository at this point in the history
FIX: Re-measure the document when print settings are changed on Chrome.

Closes codemirror/dev#1354
  • Loading branch information
marijnh committed Mar 14, 2024
1 parent 1ecb5f1 commit 0989e20
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/domobserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export class DOMObserver {
intersecting: boolean = false
gapIntersection: IntersectionObserver | null = null
gaps: readonly HTMLElement[] = []
printQuery: MediaQueryList | null = null

// Timeout for scheduling check of the parents that need scroll handlers
parentCheck = -1
Expand Down Expand Up @@ -88,6 +89,7 @@ export class DOMObserver {
this.onPrint = this.onPrint.bind(this)
this.onScroll = this.onScroll.bind(this)

if (window.matchMedia) this.printQuery = window.matchMedia("print")
if (typeof ResizeObserver == "function") {
this.resizeScroll = new ResizeObserver(() => {
if (this.view.docView?.lastUpdate < Date.now() - 75) this.onResize()
Expand Down Expand Up @@ -134,7 +136,8 @@ export class DOMObserver {
}, 50)
}

onPrint() {
onPrint(event: Event) {
if (event.type == "change" && !(event as MediaQueryListEvent).matches) return
this.view.viewState.printing = true
this.view.measure()
setTimeout(() => {
Expand Down Expand Up @@ -407,15 +410,17 @@ export class DOMObserver {

addWindowListeners(win: Window) {
win.addEventListener("resize", this.onResize)
win.addEventListener("beforeprint", this.onPrint)
if (this.printQuery) this.printQuery.addEventListener("change", this.onPrint)
else win.addEventListener("beforeprint", this.onPrint)
win.addEventListener("scroll", this.onScroll)
win.document.addEventListener("selectionchange", this.onSelectionChange)
}

removeWindowListeners(win: Window) {
win.removeEventListener("scroll", this.onScroll)
win.removeEventListener("resize", this.onResize)
win.removeEventListener("beforeprint", this.onPrint)
if (this.printQuery) this.printQuery.removeEventListener("change", this.onPrint)
else win.removeEventListener("beforeprint", this.onPrint)
win.document.removeEventListener("selectionchange", this.onSelectionChange)
}

Expand Down

0 comments on commit 0989e20

Please sign in to comment.