Created
March 13, 2024 06:04
-
-
Save ilsubyeega/e454f4ac285d9c7e2f1885dfc149595d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script lang="ts"> | |
import { onMount } from 'svelte'; | |
let observer: ResizeObserver | undefined = undefined; | |
let topElement: HTMLDivElement; | |
let slotElement: HTMLDivElement; | |
onMount(() => { | |
console.log(slotElement.getBoundingClientRect()); | |
observer = new ResizeObserver((_) => updateStyle()); | |
observer.observe(slotElement); | |
}); | |
let width: number | undefined = undefined; | |
let height: number | undefined = undefined; | |
// the parent element's max-width, max-height | |
let parentMaxWidth: string | undefined = undefined; | |
let parentMaxHeight: string | undefined = undefined; | |
const updateStyle = () => { | |
if (!slotElement || !topElement) return; | |
const rect = slotElement.getBoundingClientRect(); | |
// FIXME: transform property affects these value, need to fix this | |
// https://stackoverflow.com/questions/27745438/how-to-compute-getboundingclientrect-without-considering-transforms | |
width = rect.width; | |
height = rect.height; | |
// FIXME: This doesn't mean that the parent's max-width, max-height from layout-calculated value | |
// Maybe loop to parent and then get widths? also minus: padding, margin, etc... | |
if (topElement.parentElement) { | |
const computedParentStyle = window.getComputedStyle(topElement.parentElement); | |
parentMaxWidth = | |
computedParentStyle.maxWidth === 'none' ? 'max-content' : computedParentStyle.maxWidth; | |
parentMaxHeight = | |
computedParentStyle.maxHeight === 'none' ? 'max-content' : computedParentStyle.maxHeight; | |
} | |
}; | |
</script> | |
<div | |
class="lazy-box" | |
style:width={`${width}px`} | |
style:height={`${height}px`} | |
bind:this={topElement} | |
> | |
<div class="lazy-box-inner" style:width={parentMaxWidth} style:height={parentMaxHeight}> | |
<div class="lazy-box-slot" bind:this={slotElement}> | |
<slot /> | |
</div> | |
</div> | |
</div> | |
<style lang="sass"> | |
.lazy-box | |
position: relative | |
background: pink | |
transition: width 0.2s, height 0.2s | |
.lazy-box-inner | |
position: absolute | |
top: 0 | |
left: 0 | |
width: 3000px | |
height: 1000px | |
.lazy-box-slot | |
display: block | |
width: fit-content | |
height: fit-content | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment