<template>
    <div class="zoom" :class="{'zoom--ready': backgroundLoaded}" @mousemove="onMouseMove" :style="background">
        <img v-if="activated && !backgroundLoaded" :src="zoom" @load="onImageLoad" class="preloader" />
        <slot></slot>
    </div>
</template>

<script>
/**
 * Image Zoom Vue Component
 * 
 * This will zoom into an image on hover.
 * This works by loading a background image behind the image
 * and then moving that background as the mouse cursor moves.
 * 
 * The background image is not loaded until the first time
 * the mouse rolls over the image.
 * 
 * Wrap your normal image tag with this component and pass
 * in a large version of the image in the `zoom` prop.
 */
export default {
    data: function() {
        return {
            activated: false,
            backgroundLoaded: false
        }
    },
    props: {
        zoom: {
            type: String,
            default: null
        }
    },
    computed: {
        background: function() {
            if (!this.zoom || !this.backgroundLoaded) return;
            
            return 'background-image: url('+this.zoom+')';
        }
    },
    methods: {
        /**
         * On mouse move, adjust the background positions
         */
        onMouseMove: function(e) {
            if (!this.zoom) return;
            
            this.activated = true;
            
            var zoomer = e.currentTarget;
            // var offsetX = e.offsetX ? e.offsetX : e.touches[0].pageX;
            // var offsetY = e.offsetY ? e.offsetY : e.touches[0].pageY;
            var offsetX = e.offsetX;
            var offsetY = e.offsetY;
            var x = offsetX/zoomer.offsetWidth*100;
            var y = offsetY/zoomer.offsetHeight*100;
            zoomer.style.backgroundPosition = x + '% ' + y + '%';
        },
        /**
         * When image has loaded enable the background image
         */
        onImageLoad: function() {
            this.backgroundLoaded = true;
        }
    }
}
</script>

<style lang="scss" scoped>
.zoom {
    background-position: 50% 50%;
    position: relative;
    overflow: hidden;
    
    &--ready {
        cursor: zoom-in;
    }
    
    &--ready picture:hover {
        opacity: 0;
    }
    
    &--ready img:hover {
        opacity: 0;
    }
    
    img, picture {
        transition: opacity .5s;
        display: block;
        width: 100%;
    }
    
    .preloader {
        visibility: hidden;  
        position: absolute;
        top: 0;
        z-index: -1;
    }
}
</style>