Last active
March 28, 2018 04:22
-
-
Save Danetag/323c8684a4eceee2deb9a995fb4c911f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Update the path of the assets in the animation data to use CMS assets instead (optmized) | |
const updateAnimationData = (assets, animationData, maxAssetWidth) => { | |
const refIdDictionary = []; | |
animationData.assets.forEach((asset, i) => { | |
if (!asset.u || !asset.id) return; | |
// replace id | |
const newId = asset.p.split('.')[0]; | |
const prevId = asset.id !== newId ? asset.id : `image_${i}`; | |
const refIdReplaceObject = [prevId, newId]; | |
refIdDictionary.push(refIdReplaceObject); | |
asset.id = newId; | |
// find the assets in the CMS list using the id as a key | |
const assetsCMS = assets.filter((ast) => ast.get('key') === asset.id); | |
if (!assetsCMS.size) return; | |
const assetCMS = assetsCMS.get(0); | |
if (!assetCMS || !assetCMS.get('asset')) return; | |
const assetCMSUrl = assetCMS.getIn(['asset', 'file', 'url']).split('/'); | |
// Update asset path and filename | |
asset.u = assetCMSUrl.map((seg, i) => i < assetCMSUrl.length - 1 ? seg : '').join('/'); | |
asset.p = assetCMSUrl[assetCMSUrl.length - 1]; | |
// Update the last part of asset.p with the correct query | |
let width = asset.w > maxAssetWidth ? maxAssetWidth : asset.w; | |
// Returns the correct format(webp/png) depending of the current browser. | |
asset.query = getQuery(asset.url, `w=${width}`); | |
asset.p += '?' + asset.query; | |
}); | |
// Parsing the JSON to string so we can easily search and replace | |
animationData = JSON.stringify(animationData); | |
// Update the refId as well, brute forcing style | |
refIdDictionary.forEach( ([prevId, newId], index) => { | |
var regexId = RegExp('("refId":"'+prevId+'")','g'); | |
animationData = animationData.replace(regexId, `"refId":"${newId}"`); | |
}); | |
// Back to JSON | |
animationData = JSON.parse(animationData); | |
return animationData; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment