francoischalifour / medium-zoom

🔎🖼 A JavaScript library for zooming images like Medium
https://medium-zoom.francoischalifour.com
MIT License
3.64k stars 165 forks source link

feat: introduce pure bundle (JS and CSS separated) #206

Closed francoischalifour closed 10 months ago

francoischalifour commented 10 months ago

This is work on top of #204 and closes #203.

Description

This introduces a pure bundle where the JavaScript and CSS styles are separated. This brings support for Page Transitions in Astro.

Usage

import mediumZoom from 'medium-zoom/dist/pure'
import 'medium-zoom/dist/style.css'

(Or import the CSS with a <link> tag.)

francoischalifour commented 10 months ago

@Nomango I reused your branch to:

Can you please let me know if that works as expected in your Astro setup?

Nomango commented 10 months ago

@francoischalifour Thanks for handling this!

I can't import medium-zoom/pure neither medium-zoom/style.css. But medium-zoom/dist/pure is working.

And this is what I did.

  1. checkout to pure-bundle branch
  2. pnpm i && pnpm build
  3. pnpm link ../medium-zoom in my project

There is another issue, when using page transition, multiple calls to mediumZoom will cause problems. Seems like the background is overlaid on the image.

// instead of...
mediumZoom(imgs, { background: "rgba(0, 0, 0, 0.8)" });

// using...
if (window.zoom === undefined) {
  window.zoom = mediumZoom({ background: "rgba(0, 0, 0, 0.8)" });
}
const zoom = window.zoom;
zoom.detach();
zoom.attach(imgs);

Is there something I missed?

francoischalifour commented 10 months ago

Indeed, the imports should use the /dist path, I'll update the documentation.

import mediumZoom from 'medium-zoom/dist/pure'
import 'medium-zoom/dist/style.css'

In Page Transitions in Astro, you might need to capture when the page changes with astro:after-swap and call zoom.destroy(). Then, you should be able to re-initialize the zoom on the new page. See Script behavior during page navigation.

Let me know if that works!

Nomango commented 10 months ago

Yes, it works!

Here are my test codes

// src/utils/mediumZoom.ts
import mediumZoom from "medium-zoom/dist/pure";
import "medium-zoom/dist/style.css";

const zoom = mediumZoom({
  background: "rgba(0, 0, 0, 0.8)",
});

document.addEventListener("astro:page-load", () => zoom.detach());

export default zoom;
---
// ...
---

<script>
  import zoom from "@utils/mediumZoom";

  // listen to astro:page-load event to handle the first loading
  document.addEventListener("astro:page-load", () => zoom.attach("main img"));
</script>
francoischalifour commented 10 months ago

Perfect, I'll merge this PR then, and release right after. Thanks a lot for your contributions @Nomango!

francoischalifour commented 10 months ago

🎉 Released in 1.1.0.