Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

non-capturama requests notify iframe parent via postMessage; prettify #36

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
151 changes: 95 additions & 56 deletions src/cropduster.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const DEPRECATION_MSG = 'callbacks are deprecated in cropduster, prefer using promises for asynchronous operations';
const DEPRECATION_MESSAGE =
'callbacks are deprecated in cropduster, prefer using promises for asynchronous operations';

const CD = {
CORS_PROXY_SERVER: 'http://cors.movableink.com',
Expand Down Expand Up @@ -57,17 +58,27 @@ const CD = {
}
},

throwError(msg) {
throwError(message) {
CD.miCaptureFallback(
() => { MICapture.error(msg); },
() => { CD.log('Capturama error: ' + msg) }
() => {
MICapture.error(message);
},
() => {
CD.log('Capturama error: ' + message);
CD.notify('error', { message });
}
);
},

cancelRequest(msg) {
cancelRequest(message) {
CD.miCaptureFallback(
() => { MICapture.cancel(msg); },
() => { CD.log(`Request canceled: ${msg}`); }
() => {
MICapture.cancel(message);
},
() => {
CD.log(`Request canceled: ${message}`);
CD.notify('canceled', { message });
}
);
},

Expand All @@ -79,6 +90,7 @@ const CD = {
a.style.display = 'none';

document.body.appendChild(a);
CD.notify('imageRedirect', { url: imageUrl });

return a;
},
Expand All @@ -91,6 +103,7 @@ const CD = {
a.style.display = 'none';

document.body.appendChild(a);
CD.notify('clickthrough', { url });

return a;
},
Expand All @@ -117,6 +130,7 @@ const CD = {

el.setAttribute('data-mi-data', JSON.stringify(existingData));
document.body.appendChild(el);
CD.notify('extraData', { data: existingData });

return el;
},
Expand All @@ -143,25 +157,35 @@ const CD = {
CD._readyToCapture = true;
},

pause(maxSuspension, msg = 'manual suspension') {
pause(maxSuspension, message = 'manual suspension') {
if (maxSuspension) {
msg += `, will end in ${maxSuspension}ms`;
message += `, will end in ${maxSuspension}ms`;

setTimeout(() => {
CD.resume(msg);
CD.resume(message);
}, maxSuspension);
}

CD.miCaptureFallback(
() => { MICapture.pause(msg) },
() => { CD.log(`paused: ${msg}`) }
() => {
MICapture.pause(message);
},
() => {
CD.log(`paused: ${message}`);
CD.notify('pause', { message });
}
);
},

resume(msg) {
resume(message) {
CD.miCaptureFallback(
() => { MICapture.resume(msg) },
() => { CD.log(`resuming paused capture: ${msg}`)}
() => {
MICapture.resume(message);
},
() => {
CD.log(`resuming paused capture: ${message}`);
CD.notify('resume', { message });
}
);
},

Expand Down Expand Up @@ -189,39 +213,44 @@ const CD = {
options = {};
}

const msg = `xhr: ${url}`;
const message = `xhr: ${url}`;
const deprecatedCallback = function() {
if (callback && typeof callback === 'function') {
CD.log(DEPRECATION_MSG);
CD.log(DEPRECATION_MESSAGE);
return callback(...arguments);
}
};

CD.pause(options.maxSuspension || 0, msg);

return ajaxPromise(url, options).then(response => {
const contentType = response.getResponseHeader('content-type');
const { status, responseText: data } = response;

deprecatedCallback(data, status, contentType);

return {
data,
status,
contentType,
response
};
}).then(response => {
CD.resume(msg);
return response;
}, (error) => {
CD.log(`Error encountered in CD.get for ${url}: ${error}`);
CD.resume(msg);

deprecatedCallback(null);

throw error;
});
CD.pause(options.maxSuspension || 0, message);

return ajaxPromise(url, options)
.then(response => {
const contentType = response.getResponseHeader('content-type');
const { status, responseText: data } = response;

deprecatedCallback(data, status, contentType);

return {
data,
status,
contentType,
response
};
})
.then(
response => {
CD.resume(message);
return response;
},
error => {
CD.log(`Error encountered in CD.get for ${url}: ${error}`);
CD.resume(message);

deprecatedCallback(null);

throw error;
}
);
},

getImage(url, options = {}, callback) {
Expand All @@ -232,34 +261,34 @@ const CD = {

const deprecatedCallback = function() {
if (callback && typeof callback === 'function') {
CD.log(DEPRECATION_MSG);
CD.log(DEPRECATION_MESSAGE);

return callback(...arguments);
}
};

const msg = `getImage: ${url}`;
const message = `getImage: ${url}`;

return new Promise(function(resolve, reject) {
const img = new Image();

img.onload = function() {
CD.resume(msg);
CD.resume(message);

deprecatedCallback(img);

resolve(img);
};

img.onerror = function(event) {
CD.resume(msg);
CD.resume(message);

deprecatedCallback(null);

reject(event);
};

CD.pause(options.maxSuspension, msg);
CD.pause(options.maxSuspension, message);
img.src = url;
});
},
Expand All @@ -276,8 +305,8 @@ const CD = {
* If any image fails to load, the Promise will reject.
*/
getImages(urls, options = {}, afterEach, afterAll) {
const msg = 'getImages:';
CD.pause(options.maxSuspension, msg);
const message = 'getImages:';
CD.pause(options.maxSuspension, message);

if (typeof options === 'function') {
afterAll = afterEach;
Expand All @@ -298,30 +327,40 @@ const CD = {
return Promise.all(promises).then(
images => {
if (afterAll) {
CD.log(DEPRECATION_MSG);
CD.log(DEPRECATION_MESSAGE);
afterAll(images);
}

CD.resume(msg);
CD.resume(message);
return images;
},
_ => {
CD.resume(msg);
CD.resume(message);
throw new Error('Not all images loaded successfully');
});
}
);
},

waitForAsset(assetUrl) {
CD.miCaptureFallback(
() => { MICapture.waitForAsset(assetUrl); },
() => { CD.log(`Wait for asset: ${assetUrl}`); }
() => {
MICapture.waitForAsset(assetUrl);
},
() => {
CD.log(`Wait for asset: ${assetUrl}`);
CD.notify('waitForAsset', { url: assetUrl });
}
);
},

log(message) {
console.log(message);
},

notify(type, attrs = {}) {
window.parent && window.parent.postMessage({ type, attrs }, '*');
},

miCaptureFallback(ifCapturama, ifBrowser) {
const loadedInCapturama = !!window.MICapture && typeof window.MICapture === 'object';
return loadedInCapturama ? ifCapturama() : ifBrowser();
Expand Down Expand Up @@ -361,7 +400,7 @@ function ajaxPromise(url, options) {

if (options.headers) {
const { headers } = options;
Object.keys(headers).forEach((header) => {
Object.keys(headers).forEach(header => {
req.setRequestHeader(header, headers[header]);
});
}
Expand Down