File size: 2,320 Bytes
bf88397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
(id, action) => {
    const image = document.getElementById(id)?.querySelector(".image-frame img");
    if (!image?.naturalWidth) return;
    const viewport = image.closest("button");
    const fresh = !image.octZoom;
    const state = image.octZoom ??= { scale: 1, x: 0, y: 0, drag: null };
    const paint = () => {
        const bounds = viewport.getBoundingClientRect();
        if (!bounds.width || !bounds.height) return;
        const fit = Math.min(
            image.clientWidth / image.naturalWidth,
            image.clientHeight / image.naturalHeight,
            1
        );
        const limitX = Math.max(0, (image.naturalWidth * fit * state.scale - bounds.width) / 2);
        const limitY = Math.max(0, (image.naturalHeight * fit * state.scale - bounds.height) / 2);
        state.x = Math.max(-limitX, Math.min(limitX, state.x));
        state.y = Math.max(-limitY, Math.min(limitY, state.y));
        image.style.transformOrigin = "center";
        image.style.transform = `translate(${state.x}px, ${state.y}px) scale(${state.scale})`;
        viewport.style.overflow = "hidden";
        viewport.style.cursor = state.scale > 1 ? "grab" : "";
        viewport.style.touchAction = state.scale > 1 ? "none" : "";
    };
    if (fresh) {
        image.draggable = false;
        viewport.addEventListener("pointerdown", (event) => {
            if (state.scale === 1 || event.button !== 0) return;
            event.preventDefault();
            viewport.setPointerCapture(event.pointerId);
            state.drag = { id: event.pointerId, x: event.clientX, y: event.clientY };
        });
        viewport.addEventListener("pointermove", (event) => {
            if (state.drag?.id !== event.pointerId) return;
            state.x += event.clientX - state.drag.x;
            state.y += event.clientY - state.drag.y;
            state.drag.x = event.clientX;
            state.drag.y = event.clientY;
            paint();
        });
        for (const event of ["pointerup", "pointercancel", "lostpointercapture"]) {
            viewport.addEventListener(event, () => { state.drag = null; });
        }
        image.addEventListener("load", paint);
    }
    state.scale = action === "fit" ? 1 : Math.max(
        1, Math.min(16, state.scale * (action === "in" ? 1.5 : 1 / 1.5))
    );
    paint();
}