diff --git a/src/components/Output/custom-els/TwoUp/index.ts b/src/components/Output/custom-els/TwoUp/index.ts index 53966c0a..0c76a5d2 100644 --- a/src/components/Output/custom-els/TwoUp/index.ts +++ b/src/components/Output/custom-els/TwoUp/index.ts @@ -18,6 +18,10 @@ export default class TwoUp extends HTMLElement { * The position of the split in pixels. */ private _position = 0; + /** + * The position of the split in %. + */ + private _relativePosition = 0.5; /** * The value of _position when the pointer went down. */ @@ -37,6 +41,14 @@ export default class TwoUp extends HTMLElement { new MutationObserver(() => this._childrenChange()) .observe(this, { childList: true }); + // Watch for element size changes. + if ('ResizeObserver' in window) { + new ResizeObserver(() => this._resetPosition()) + .observe(this); + } else { + window.addEventListener('resize', () => this._resetPosition()); + } + // Watch for pointers on the handle. const pointerTracker: PointerTracker = new PointerTracker(this._handle, { start: (_, event) => { @@ -57,7 +69,7 @@ export default class TwoUp extends HTMLElement { connectedCallback() { this._handle.innerHTML = `
${ - `` + '' }
`; this._childrenChange(); @@ -77,7 +89,8 @@ export default class TwoUp extends HTMLElement { // Set the initial position of the handle. requestAnimationFrame(() => { const bounds = this.getBoundingClientRect(); - this._position = (this.orientation === 'vertical' ? bounds.height : bounds.width) / 2; + const dimensionAxis = this.orientation === 'vertical' ? 'height' : 'width'; + this._position = bounds[dimensionAxis] * this._relativePosition; this._setPosition(); }); } @@ -138,6 +151,7 @@ export default class TwoUp extends HTMLElement { // Clamp position to element bounds. this._position = Math.max(0, Math.min(this._position, bounds[dimensionAxis])); + this._relativePosition = this._position / bounds[dimensionAxis]; this._setPosition(); } diff --git a/src/components/Output/custom-els/TwoUp/missing-types.d.ts b/src/components/Output/custom-els/TwoUp/missing-types.d.ts index fde547bd..b3c129d5 100644 --- a/src/components/Output/custom-els/TwoUp/missing-types.d.ts +++ b/src/components/Output/custom-els/TwoUp/missing-types.d.ts @@ -19,3 +19,34 @@ declare namespace JSX { 'two-up': TwoUpAttributes; } } + +interface DOMRectReadOnly { + readonly x: number; + readonly y: number; + readonly width: number; + readonly height: number; + readonly top: number; + readonly right: number; + readonly bottom: number; + readonly left: number; +} + +interface ResizeObserverCallback { + (entries: ResizeObserverEntry[], observer: ResizeObserver): void; +} + +interface ResizeObserverEntry { + readonly target: Element; + readonly contentRect: DOMRectReadOnly; +} + +interface ResizeObserver { + observe(target: Element): void; + unobserve(target: Element): void; + disconnect(): void; +} + +declare var ResizeObserver: { + prototype: ResizeObserver; + new(callback: ResizeObserverCallback): ResizeObserver; +};