Repository: kylewetton/image-compare-viewer Branch: master Commit: dfa79a3cbd88 Files: 16 Total size: 25.6 KB Directory structure: gitextract_tiwp983s/ ├── .babelrc ├── .dependabot/ │ └── config.yml ├── .eslintrc ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── __.browserslistrc ├── package.json ├── src/ │ ├── index.html │ ├── scripts/ │ │ └── index.js │ └── styles/ │ └── index.scss ├── webpack/ │ ├── webpack.common.js │ ├── webpack.config.dev.js │ └── webpack.config.prod.js └── webpack.config.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .babelrc ================================================ { "presets": [ [ "@babel/preset-env", { "useBuiltIns": "usage", "corejs": "3.0.0" } ] ], "plugins": [ "@babel/plugin-syntax-dynamic-import", "@babel/plugin-proposal-class-properties" ] } ================================================ FILE: .dependabot/config.yml ================================================ version: 1 update_configs: - package_manager: "javascript" directory: "/" update_schedule: "daily" automerged_updates: - match: dependency_type: "all" update_type: "semver:minor" ================================================ FILE: .eslintrc ================================================ { "env": { "browser": true, "node": true }, "parserOptions": { "ecmaVersion": 6, "sourceType": "module" }, "rules": { "semi": 2 } } ================================================ FILE: .gitignore ================================================ # dependencies node_modules # production build public # misc .DS_Store npm-debug.log yarn-error.log yarn.lock .yarnclean .vscode ================================================ FILE: .travis.yml ================================================ language: node_js node_js: - "lts/*" - "node" script: npm run build ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2020 Kyle Wetton Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ ![](screenshots/logo.jpg) A fully responsive slider to compare before and after images for grading, retouching and all else. Mobile and fluid container friendly! [Check out live examples](https://image-compare-viewer.netlify.app/) ![](screenshots/eg-1.jpg) ![](screenshots/eg-2.jpg) ### Installation ``` npm install image-compare-viewer --save ``` Stylesheet is available at "node_modules/image-compare-viewer/src/styles/index.scss" or "node_modules/image-compare-viewer/dist/image-compare-viewer.min.css" ### CDN #### Javascript ``` ``` #### CSS ``` ``` ### Documentation [Installation, usage, options and examples](https://image-compare-viewer.netlify.app/) ================================================ FILE: __.browserslistrc ================================================ [production staging] >5% last 2 versions Firefox ESR not ie < 11 [development] last 1 chrome version last 1 firefox version last 1 edge version ================================================ FILE: package.json ================================================ { "name": "image-compare-viewer", "version": "1.7.0", "description": "A fully responsive slider to compare before and after images for grading, retouching and all else. Mobile and fluid container friendly!", "scripts": { "build": "webpack --mode production --config webpack/webpack.config.prod.js", "start": "webpack-dev-server --host 127.0.0.1 --open --config webpack/webpack.config.dev.js", "pack": "webpack --mode production --config webpack.config.js" }, "main": "src/scripts/index.js", "unpkg": "dist/image-compare-viewer.min.js", "repository": { "type": "git", "url": "git+https://github.com/kylewetton/image-compare-viewer" }, "keywords": [ "before", "after", "compare", "grading", "images", "frontend", "es6", "javascript", "vanilla" ], "author": "Kyle Wetton", "license": "MIT", "bugs": { "url": "https://github.com/kylewetton/image-compare-viewer" }, "browserslist": [ "> 1%", "last 2 versions" ], "devDependencies": { "@babel/core": "^7.6.4", "@babel/plugin-proposal-class-properties": "^7.5.5", "@babel/plugin-syntax-dynamic-import": "^7.2.0", "@babel/preset-env": "^7.6.3", "babel-loader": "^8.0.6", "clean-webpack-plugin": "^4.0.0", "copy-webpack-plugin": "^11.0.0", "css-loader": "^6.7.1", "eslint": "^8.18.0", "eslint-webpack-plugin": "^3.2.0", "file-loader": "^6.2.0", "html-webpack-plugin": "^5.5.0", "mini-css-extract-plugin": "^2.6.1", "node-sass": "^9.0.0", "sass-loader": "^13.0.0", "style-loader": "^3.3.1", "webpack": "^5.73.0", "webpack-cli": "^4.10.0", "webpack-dev-server": "^4.9.2", "webpack-merge": "^5.8.0" }, "dependencies": { "@babel/polyfill": "^7.6.0", "autoprefixer": "^10.4.7", "body-scroll-lock-upgrade": "^1.1.0", "core-js": "^3.3.2", "postcss-loader": "^7.0.0" } } ================================================ FILE: src/index.html ================================================ Image Compare Viewer
================================================ FILE: src/scripts/index.js ================================================ // uncomment for packing // import "../styles/index.scss"; import { disableBodyScroll, enableBodyScroll } from "body-scroll-lock-upgrade"; class ImageCompare { constructor(el, settings = {}) { const defaults = { controlColor: "#FFFFFF", controlShadow: true, addCircle: false, addCircleBlur: true, showLabels: false, labelOptions: { before: "Before", after: "After", onHover: false, }, smoothing: true, smoothingAmount: 100, hoverStart: false, verticalMode: false, startingPoint: 50, fluidMode: false, }; this.settings = Object.assign(defaults, settings); this.safariAgent = navigator.userAgent.indexOf("Safari") != -1 && navigator.userAgent.indexOf("Chrome") == -1; this.el = el; this.images = {}; this.wrapper = null; this.control = null; this.arrowContainer = null; this.arrowAnimator = []; this.active = false; this.slideWidth = 50; this.lineWidth = 2; this.arrowCoordinates = { circle: [5, 3], standard: [8, 0], }; } mount() { // Temporarily disable Safari smoothing if (this.safariAgent) { this.settings.smoothing = false; } this._shapeContainer(); this._getImages(); this._buildControl(); this._events(); } _events() { let bodyStyles = ``; // Desktop events this.el.addEventListener("mousedown", (ev) => { this._activate(true); document.body.classList.add("icv__body"); disableBodyScroll(this.el, {reserveScrollBarGap: true}); this._slideCompare(ev); }); this.el.addEventListener( "mousemove", (ev) => this.active && this._slideCompare(ev) ); this.el.addEventListener("mouseup", () => this._activate(false)); document.body.addEventListener("mouseup", () => { document.body.classList.remove("icv__body"); enableBodyScroll(this.el); this._activate(false); }); // Mobile events this.control.addEventListener("touchstart", (e) => { this._activate(true); document.body.classList.add("icv__body"); disableBodyScroll(this.el, {reserveScrollBarGap: true}); }); this.el.addEventListener("touchmove", (ev) => { this.active && this._slideCompare(ev); }); this.el.addEventListener("touchend", () => { this._activate(false); document.body.classList.remove("icv__body"); enableBodyScroll(this.el); }); // hover this.el.addEventListener("mouseenter", () => { this.settings.hoverStart && this._activate(true); let coord = this.settings.addCircle ? this.arrowCoordinates.circle : this.arrowCoordinates.standard; this.arrowAnimator.forEach((anim, i) => { anim.style.cssText = ` ${ this.settings.verticalMode ? `transform: translateY(${coord[1] * (i === 0 ? 1 : -1)}px);` : `transform: translateX(${coord[1] * (i === 0 ? 1 : -1)}px);` } `; }); }); this.el.addEventListener("mouseleave", () => { let coord = this.settings.addCircle ? this.arrowCoordinates.circle : this.arrowCoordinates.standard; this.arrowAnimator.forEach((anim, i) => { anim.style.cssText = ` ${ this.settings.verticalMode ? `transform: translateY(${ i === 0 ? `${coord[0]}px` : `-${coord[0]}px` });` : `transform: translateX(${ i === 0 ? `${coord[0]}px` : `-${coord[0]}px` });` } `; }); }); } _slideCompare(ev) { let bounds = this.el.getBoundingClientRect(); let x = ev.touches !== undefined ? ev.touches[0].clientX - bounds.left : ev.clientX - bounds.left; let y = ev.touches !== undefined ? ev.touches[0].clientY - bounds.top : ev.clientY - bounds.top; let position = this.settings.verticalMode ? (y / bounds.height) * 100 : (x / bounds.width) * 100; if (position >= 0 && position <= 100) { this.settings.verticalMode ? (this.control.style.top = `calc(${position}% - ${ this.slideWidth / 2 }px)`) : (this.control.style.left = `calc(${position}% - ${ this.slideWidth / 2 }px)`); if (this.settings.fluidMode) { this.settings.verticalMode ? (this.wrapper.style.clipPath = `inset(0 0 ${100 - position}% 0)`) : (this.wrapper.style.clipPath = `inset(0 0 0 ${position}%)`); } else { this.settings.verticalMode ? (this.wrapper.style.height = `calc(${position}%)`) : (this.wrapper.style.width = `calc(${100 - position}%)`); } } } _activate(state) { this.active = state; } _shapeContainer() { let imposter = document.createElement("div"); let label_l = document.createElement("span"); let label_r = document.createElement("span"); label_l.classList.add("icv__label", "icv__label-before", "keep"); label_r.classList.add("icv__label", "icv__label-after", "keep"); if (this.settings.labelOptions.onHover) { label_l.classList.add("on-hover"); label_r.classList.add("on-hover"); } if (this.settings.verticalMode) { label_l.classList.add("vertical"); label_r.classList.add("vertical"); } label_l.innerHTML = this.settings.labelOptions.before || "Before"; label_r.innerHTML = this.settings.labelOptions.after || "After"; if (this.settings.showLabels) { this.el.appendChild(label_l); this.el.appendChild(label_r); } this.el.classList.add( `icv`, this.settings.verticalMode ? `icv__icv--vertical` : `icv__icv--horizontal`, this.settings.fluidMode ? `icv__is--fluid` : `standard` ); imposter.classList.add("icv__imposter"); this.el.appendChild(imposter); } _buildControl() { let control = document.createElement("div"); let uiLine = document.createElement("div"); let arrows = document.createElement("div"); let circle = document.createElement("div"); const arrowSize = "20"; arrows.classList.add("icv__theme-wrapper"); for (var idx = 0; idx <= 1; idx++) { let animator = document.createElement(`div`); let arrow = ` `; animator.innerHTML += arrow; this.arrowAnimator.push(animator); arrows.appendChild(animator); } let coord = this.settings.addCircle ? this.arrowCoordinates.circle : this.arrowCoordinates.standard; this.arrowAnimator.forEach((anim, i) => { anim.classList.add("icv__arrow-wrapper"); anim.style.cssText = ` ${ this.settings.verticalMode ? `transform: translateY(${ i === 0 ? `${coord[0]}px` : `-${coord[0]}px` });` : `transform: translateX(${ i === 0 ? `${coord[0]}px` : `-${coord[0]}px` });` } `; }); control.classList.add("icv__control"); control.style.cssText = ` ${this.settings.verticalMode ? `height` : `width `}: ${this.slideWidth}px; ${this.settings.verticalMode ? `top` : `left `}: calc(${ this.settings.startingPoint }% - ${this.slideWidth / 2}px); ${ "ontouchstart" in document.documentElement ? `` : this.settings.smoothing ? `transition: ${this.settings.smoothingAmount}ms ease-out;` : `` } `; uiLine.classList.add("icv__control-line"); uiLine.style.cssText = ` ${this.settings.verticalMode ? `height` : `width `}: ${this.lineWidth}px; background: ${this.settings.controlColor}; ${ this.settings.controlShadow ? `box-shadow: 0px 0px 15px rgba(0,0,0,0.33);` : `` } `; let uiLine2 = uiLine.cloneNode(true); circle.classList.add("icv__circle"); circle.style.cssText = ` ${ this.settings.addCircleBlur && `-webkit-backdrop-filter: blur(5px); backdrop-filter: blur(5px)` }; border: ${this.lineWidth}px solid ${this.settings.controlColor}; ${ this.settings.controlShadow && `box-shadow: 0px 0px 15px rgba(0,0,0,0.33)` }; `; control.appendChild(uiLine); this.settings.addCircle && control.appendChild(circle); control.appendChild(arrows); control.appendChild(uiLine2); this.arrowContainer = arrows; this.control = control; this.el.appendChild(control); } _getImages() { let children = this.el.querySelectorAll("img, video, .keep"); this.el.innerHTML = ""; children.forEach((img) => { this.el.appendChild(img); }); let childrenImages = [...children].filter( (element) => ["img", "video"].includes(element.nodeName.toLowerCase()) ); // this.settings.verticalMode && [...children].reverse(); this.settings.verticalMode && childrenImages.reverse(); for (let idx = 0; idx <= 1; idx++) { let child = childrenImages[idx]; child.classList.add("icv__img"); child.classList.add(idx === 0 ? `icv__img-a` : `icv__img-b`); if (idx === 1) { let wrapper = document.createElement("div"); let afterUrl = childrenImages[1].src; wrapper.classList.add("icv__wrapper"); wrapper.style.cssText = ` width: ${100 - this.settings.startingPoint}%; height: ${this.settings.startingPoint}%; ${ "ontouchstart" in document.documentElement ? `` : this.settings.smoothing ? `transition: ${this.settings.smoothingAmount}ms ease-out;` : `` } ${ this.settings.fluidMode && `background-image: url(${afterUrl}); clip-path: inset(${ this.settings.verticalMode ? ` 0 0 ${100 - this.settings.startingPoint}% 0` : `0 0 0 ${this.settings.startingPoint}%` })` } `; wrapper.appendChild(child); this.wrapper = wrapper; this.el.appendChild(this.wrapper); } } if (this.settings.fluidMode) { let url = childrenImages[0].src; let fluidWrapper = document.createElement("div"); fluidWrapper.classList.add("icv__fluidwrapper"); fluidWrapper.style.cssText = ` background-image: url(${url}); `; this.el.appendChild(fluidWrapper); } } } // const el = document.querySelectorAll(".image-compare"); // el.forEach((viewer) => { // let v = new ImageCompare(viewer, { // controlShadow: false, // addCircle: true, // addCircleBlur: true, // fluidMode: false, // showLabels: true, // labelOptions: { // onHover: true, // before: "Draft", // after: "Final", // }, // }).mount(); // }); export default ImageCompare; ================================================ FILE: src/styles/index.scss ================================================ .icv { position: relative; overflow: hidden; cursor: row-resize; &__icv--vertical { cursor: row-resize; } &__icv--horizontal { cursor: col-resize; } &__img { pointer-events: none; -khtml-user-select: none; -o-user-select: none; -moz-user-select: none; -webkit-user-select: none; user-select: none; max-width: none; width: 100%; margin: 0 !important; padding: 0 !important; border: 0 !important; border-radius: 0 !important; top: 0; display: block; } &__is--fluid &__img { display: none; } &__img-a { height: auto; position: static; z-index: 1; left: 0px; } &__img-b { height: 100%; position: absolute; z-index: 2; left: auto; right: 0px; width: auto; } &__icv--vertical &__img-b { width: 100%; height: auto; } &__imposter { z-index: 4; position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; } &__wrapper { position: absolute; width: 100%; height: 100%; right: 0px; top: 0px; overflow: hidden; background-size: cover; background-position: center center; z-index: 3; } &__is--fluid &__wrapper, &__icv--vertical &__wrapper { width: 100% !important; } &__is--fluid &__wrapper, &__icv--horizontal &__wrapper { height: 100% !important; } &__fluidwrapper { background-size: cover; background-position: center; position: absolute; top: 0; left: 0; width: 100%; height: 100%; } &__control { position: absolute; display: flex; flex-direction: column; justify-content: center; align-items: center; box-sizing: border-box; height: 100%; top: 0px; z-index: 5; } &__icv--vertical &__control { flex-direction: row; left: 0; width: 100%; } &__control-line { height: 50%; width: 2px; z-index: 6; } &__icv--vertical &__control-line { width: 50%; } &__theme-wrapper { width: 100%; height: 100%; display: flex; justify-content: space-between; align-items: center; position: absolute; transition: all 0.1s ease-out 0s; z-index: 5; } &__icv--vertical &__theme-wrapper { flex-direction: column; } &__arrow-wrapper { display: flex; justify-content: center; align-items: center; transition: all 0.1s ease-out 0s; } &__arrow-a { transform: scale(1.5) rotateZ(180deg); height: 20px; width: 20px; -webkit-filter: drop-shadow(0px 3px 5px rgba(0, 0, 0, 0.33)); filter: drop-shadow(0px -3px 5px rgba(0, 0, 0, 0.33)); } &__arrow-b { transform: scale(1.5) rotateZ(0deg); height: 20px; width: 20px; -webkit-filter: drop-shadow(0px 3px 5px rgba(0, 0, 0, 0.33)); filter: drop-shadow(0px 3px 5px rgba(0, 0, 0, 0.33)); } &__circle { width: 50px; height: 50px; box-sizing: border-box; flex-shrink: 0; border-radius: 999px; } &__label { position: absolute; bottom: 1rem; z-index: 12; background: rgba(0, 0, 0, 0.33); color: white; border-radius: 3px; padding: 0.5rem 0.75rem; font-size: 0.85rem; user-select: none; } &__label.vertical { bottom: auto; left: 1rem; } &__label.on-hover { transform: scale(0); transition: 0.25s cubic-bezier(0.68, 0.26, 0.58, 1.22); } &:hover &__label.on-hover { transform: scale(1); } &__label-before { left: 1rem; } &__label-after { right: 1rem; } &__label-before.vertical { top: 1rem; } &__label-after.vertical { bottom: 1rem; right: auto; } &__body { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } } ================================================ FILE: webpack/webpack.common.js ================================================ const Path = require('path'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { app: Path.resolve(__dirname, '../src/scripts/index.js') }, output: { path: Path.join(__dirname, '../build'), filename: 'js/[name].js' }, optimization: { splitChunks: { chunks: 'all', name: false } }, plugins: [ new CleanWebpackPlugin(), new CopyWebpackPlugin({ patterns: [ { from: Path.resolve(__dirname, '../public'), to: 'public' } ] }), new HtmlWebpackPlugin({ template: Path.resolve(__dirname, '../src/index.html') }) ], resolve: { alias: { '~': Path.resolve(__dirname, '../src') } }, module: { rules: [ { test: /\.mjs$/, include: /node_modules/, type: 'javascript/auto' }, { test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/, use: { loader: 'file-loader', options: { name: '[path][name].[ext]' } } }, ] } }; ================================================ FILE: webpack/webpack.config.dev.js ================================================ const ESLintPlugin = require('eslint-webpack-plugin'); const Path = require('path'); const Webpack = require('webpack'); const { merge } = require('webpack-merge'); const common = require('./webpack.common.js'); module.exports = merge(common, { mode: 'development', devtool: 'eval-cheap-source-map', output: { chunkFilename: 'js/[name].chunk.js' }, plugins: [ new Webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('development') }), new ESLintPlugin({ files: '../src/**/*.js', emitWarning: true }) ], module: { rules: [ { test: /\.js$/, include: Path.resolve(__dirname, '../src'), loader: 'babel-loader' }, { test: /\.s?css$/i, use: [ 'style-loader', { loader: 'css-loader', options: { sourceMap: true } }, 'sass-loader' ] } ] } }); ================================================ FILE: webpack/webpack.config.prod.js ================================================ const Webpack = require("webpack"); const { merge } = require("webpack-merge"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const common = require("./webpack.common.js"); module.exports = merge(common, { mode: "production", devtool: "source-map", stats: "errors-only", bail: true, output: { filename: "js/.[chunkhash:8].js", chunkFilename: "js/[name].[chunkhash:8].chunk.js", }, plugins: [ new Webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("production"), }), new Webpack.optimize.ModuleConcatenationPlugin(), new MiniCssExtractPlugin({ filename: "bundle.css", }), ], module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: "babel-loader", }, { test: /\.s?css/i, use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"], }, ], }, }); ================================================ FILE: webpack.config.js ================================================ const path = require("path"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const Webpack = require("webpack"); const autoprefixer = require("autoprefixer"); module.exports = ["source-map"].map((devtool) => ({ mode: "production", entry: "./src/scripts/index.js", output: { path: path.resolve(__dirname, "dist"), filename: "image-compare-viewer.min.js", library: "ImageCompare", libraryTarget: "umd", libraryExport: "default", umdNamedDefine: true, }, devtool, optimization: { runtimeChunk: false, }, plugins: [ new Webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("production"), }), new Webpack.optimize.ModuleConcatenationPlugin(), new MiniCssExtractPlugin({ filename: "image-compare-viewer.min.css", }), ], module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: "babel-loader", }, { test: /\.s?css/i, use: [ MiniCssExtractPlugin.loader, "css-loader", { loader: "postcss-loader", options: { postcssOptions: { plugins: [[autoprefixer()]], }, }, }, "sass-loader", ], }, ], }, }));