Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
13 changes: 11 additions & 2 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ interface SnuggleProps {
>
}

export const SnuggleChild: React.FC<{ span?: number }> = ({ children }) => (
<>{children}</>
)

/**
* Helpers
*/
Expand Down Expand Up @@ -69,21 +73,26 @@ const Snuggle: React.FC<SnuggleProps> = ({

// Methods
const settle = useCallback(() => {
elementsRef.current?.forEach((item: HTMLElement) => {
const childrenArr = Array.isArray(children) ? children : [children]

elementsRef.current?.forEach((item, index) => {
const { span } = childrenArr?.[index]?.props

if (item && item.firstElementChild) {
const firstElement = item.firstElementChild
const itemHeight = firstElement.getBoundingClientRect().height
const rowSpan = Math.ceil((itemHeight + rowGap) / rowGap)

item.style.gridRowEnd = `span ${rowSpan}`
item.style.gridColumn = `span ${span}`
}
})

if (!reposition.current) {
window.requestAnimationFrame(settle)
reposition.current = true
}
}, [rowGap])
}, [children, rowGap])

// Effects
useEffect(() => {
Expand Down
27 changes: 16 additions & 11 deletions stories/index.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React, { useRef, createElement } from 'react'
import { storiesOf } from '@storybook/react'

import './style.css'
import Snuggle from '../src'
import Snuggle, { SnuggleChild } from '../src'
import {
ItemStyled,
listElements,
Expand All @@ -14,21 +14,26 @@ storiesOf('Snuggle', module)
.add('default', () => (
<div className="wrap">
<Snuggle>
<img
style={{ width: '100%' }}
alt="Placeholder"
src="https://picsum.photos/500/200"
/>
<SnuggleChild span={2}>
<img
style={{ width: '100%' }}
alt="Placeholder"
src="https://picsum.photos/500/200"
/>
</SnuggleChild>

<SnuggleChild span={2}>
<img
style={{ width: '100%' }}
alt="Placeholder"
src="https://picsum.photos/300/200"
/>
</SnuggleChild>
<img
style={{ width: '100%' }}
alt="Placeholder"
src="https://picsum.photos/300/300"
/>
<img
style={{ width: '100%' }}
alt="Placeholder"
src="https://picsum.photos/300/200"
/>
<img
style={{ width: '100%' }}
alt="Placeholder"
Expand Down