Skip to content

Commit

Permalink
Switch to ResizeObserver from window onresize
Browse files Browse the repository at this point in the history
  • Loading branch information
abagshaw committed Dec 5, 2017
1 parent 15d061a commit d9af819
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@
"devDependencies": {
"browserify": "^14.5.0",
"cropcalc-js": "^0.9.3",
"debounce": "^1.1.0",
"mkdirp": "^0.5.1",
"pixelmatch": "^4.0.2",
"pngjs": "^3.3.1",
"puppeteer": "^0.13.0",
"resize-observer-polyfill": "^1.5.0",
"tap-spec": "^4.1.1",
"tape": "^4.8.0",
"uglify-js": "^3.2.1"
Expand Down
29 changes: 22 additions & 7 deletions src/salieo.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
var cropcalcJS = require("cropcalc-js");
var debounce = require("debounce");
var ResizeObserverPolyfill = require("resize-observer-polyfill");

var ResizeObserver = ResizeObserver ? ResizeObserver : ResizeObserverPolyfill;

function salieo(userOptions) {
var loadedImages = [];
var salieoDataCache = {};
var ro;

var options = {
img_class: "salieo",
Expand All @@ -18,15 +23,13 @@ function salieo(userOptions) {
window.addEventListener("message", triggerEditMode);
}

setOpts(options, userOptions);
refresh();

if(options.watch_resize) {
window.addEventListener('resize', function(event) {
refresh();
});
ro = new ResizeObserver(debounce(refresh, 10));
}

setOpts(options, userOptions);
refresh();

//Handy to use functions
function setOpts(standard, user) {
if (typeof user === 'object') {
Expand Down Expand Up @@ -264,13 +267,21 @@ function salieo(userOptions) {
}

function refresh() {
if(ro) {
ro.disconnect();
}

var rawElements = document.getElementsByClassName(options.img_class);
var newSalieoDataCache = {};
var tmpImgInfo, currentImage;

loadedImages = [];

for(var i = 0; i < rawElements.length; i++) {
if(ro) {
ro.observe(rawElements[i]);
}

tmpImgInfo = getElementURL(rawElements[i]);
if(!tmpImgInfo) {
continue; //Error getting image URL
Expand Down Expand Up @@ -298,11 +309,15 @@ function salieo(userOptions) {
var avoidElements = document.getElementsByClassName(options.avoid_class);
var avoidAreas = [];
for(var i = 0; i < avoidElements.length; i++) {
if(ro) {
ro.observe(avoidElements[i]);
}

avoidAreas.push({elementRect: avoidElements[i].getBoundingClientRect(), dataset: avoidElements[i].dataset});
}

var tmpElementRect;
for(var i = 0; i < loadedImages.length; i++) {
for(var i = 0; i < loadedImages.length; i++) {
loadedImages[i].elementRect = loadedImages[i].element.getBoundingClientRect();
loadedImages[i].cropOptions = Object.create(options.crop_options);

Expand Down

0 comments on commit d9af819

Please sign in to comment.