Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add resize plugin: x-resize #4304

Merged
merged 2 commits into from
Jul 15, 2024
Merged

Add resize plugin: x-resize #4304

merged 2 commits into from
Jul 15, 2024

Conversation

calebporzio
Copy link
Collaborator

This PR adds a new Alpine plugin called "Resize" with the following API:

CleanShot 2024-07-15 at 12 22 37@2x

@calebporzio calebporzio merged commit 10997a7 into main Jul 15, 2024
2 checks passed
@ekwoka
Copy link
Contributor

ekwoka commented Jul 15, 2024

Damn, I just made this plugin myself a few days ago.

I think you can safely use a similar strategy for the event delegation on the element as well with a weakmap.

The code I made

import type { PluginCallback } from 'alpinejs'

export const Resize: PluginCallback = (Alpine) => {
  const observerMap = new WeakMap<Element, (width: number) => void>()
  const observer = new ResizeObserver((entries) =>
    entries.forEach((entry) =>
      observerMap.get(entry.target)?.(entry.contentRect.width),
    ),
  )
  Alpine.directive(
    'resize',
    (el, { expression }, { evaluateLater, cleanup }) => {
      let evaluate = evaluateLater(expression)
      observerMap.set(el, (width: number) =>
        // biome-ignore lint/suspicious/noEmptyBlockStatements: Does not need to do anything
        evaluate(() => {}, { scope: { $width: width }, params: [width] }),
      )
      observer.observe(el)
      cleanup(() => {
        observerMap.delete(el)
        observer.unobserve(el)
      })
    },
  )
}

export default Resize

Seems like the contentRect is a better choice than the border box.

Would the border box sizes and height stay consistent if the element is in a flex column?

@joshhanley joshhanley deleted the x-resize branch July 18, 2024 22:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants