useCanvasViewport

 
 
 
 

Overview

Editor hooks that tell a block which Method breakpoint tier the canvas is in — mobile, tablet, desktop or wide — by running media queries against the canvas iframe’s own window rather than the admin window.

Block editor scripts run in the top admin window, so window.matchMedia there only ever describes the browser. The editor renders the post in an iframe whose width is the device preview or the resized canvas, and only that window’s media queries follow it. These hooks do what core’s block visibility does: useMediaQuery( query, view ) with the canvas window as view.


Signature

JavaScript
import useCanvasViewport, { useCanvasWindow, getMethodBreakpoints } from '../../hooks/useCanvasViewport';

const [ref, canvasWindow] = useCanvasWindow();
const blockProps = useBlockProps({ ref });
const tier = useCanvasViewport(canvasWindow); // 'mobile' | 'tablet' | 'desktop' | 'wide' | undefined

Parameters

useCanvasWindow()

  • Returns: [ref, canvasWindow] — a callback ref to attach to the block wrapper (through useBlockProps({ ref })) and the Window that element is rendered in, undefined until the ref is attached.

useCanvasViewport( view )

  • view: The window from useCanvasWindow().
  • Returns: "wide" when the canvas is at least wide_min wide, else "desktop" above tablet_max, else "tablet" from tablet_min, else "mobile"; undefined while view is unknown.
  • Queries: Range syntax — (width >= 768px), (width > 1199px), (width >= 1600px) — so the theme’s unit is used as is, with no +1 arithmetic.

getMethodBreakpoints()

  • Returns: { mobile_max, tablet_min, tablet_max, wide_min } — methodGlobalData.breakpoints over the defaults (767px, 768px, 1199px, 1600px).

Behavior

  • The tier updates live: resizing the canvas or switching the device preview re-evaluates the queries, and the block re-renders.
  • The tiers are the same four the frontend CSS uses, so a preview that reads the tier can show the value the page will use — the Swiper blocks initialise their preview with the tier’s per-view, spacing or width instead of Swiper’s own breakpoints option, which would evaluate against the admin window.
  • The Modal block compares the tier with its fullscreenBelow setting so the preview goes full screen at the same canvas widths as the page.

Usage by Blocks

BlockNotes
SwiperResolves the tier for the live preview’s per-view / spacing / slide width.
Swiper GalleryAs above, since the beta23 rebuild.
ModalFull-screen-below-a-tier preview.
Mapbox MapuseCanvasWindow() only — the preview needs the canvas window to load Mapbox GL JS into.

Changelog

VersionDescription
2.0.0-beta18Introduced, for the Swiper block’s canvas-aware preview (3064cd9).