-
-
Save kevinweber/364247b67cefd086c37cea9ab6d13f89 to your computer and use it in GitHub Desktop.
AEM: Server-side JS / Use class - snippet collection - debugging
This file contains 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
'use strict'; | |
use(function () { | |
function filterAnchorName(anchorName) { | |
var anchor = anchorName; | |
// Remove whitespace | |
anchor = anchor.trim(); | |
// Filter non-word characters | |
anchor = anchor.replace(/\W/g, '_'); | |
// Remove duplicate underscores | |
anchor = anchor.replace(/_{2,}/g, '_'); | |
// Remove underscores from end of anchor | |
anchor = anchor.replace(/_$/, ''); | |
// Ensure lower case words | |
anchor = anchor.toLowerCase(); | |
return anchor; | |
} | |
return { | |
filtered: this.anchorName ? filterAnchorName(this.anchorName) : false | |
}; | |
}); |
This file contains 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
use(function () { | |
// - Messages get logged in error.log. | |
// - When testing this, make sure the component is on the page you're loading, otherwise this file doesn't load and trigger debugging messages, of course. | |
// - You can't concatenate variables using a comma (`,`) like you can do in client-side JS. | |
var variable = 'Yes'; | |
log.debug('Does it work? ' + variable); | |
log.error('Does it work? ' + variable); | |
log.info('Does it work? ' + variable); | |
log.warn('Does it work? ' + variable); | |
// Throw an error while right on page when it's requested | |
throw new Error('Does it work? ' + variable); | |
}); |
This file contains 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
'use strict'; | |
use(function () { | |
function isExternal(absoluteUrlDomain) { | |
var currentServer = request.getServerName() + ''; | |
var serverMainDomain; | |
if (currentServer.indexOf('.') > -1) { | |
serverMainDomain = currentServer.split('.'); | |
if (serverMainDomain.length > 1) { | |
serverMainDomain = serverMainDomain[serverMainDomain.length - 2] + '.' + serverMainDomain[serverMainDomain.length - 1]; | |
} else { | |
serverMainDomain = serverMainDomain[serverMainDomain.length - 1]; | |
} | |
} else { | |
serverMainDomain = currentServer; | |
} | |
if (absoluteUrlDomain.indexOf(serverMainDomain) > -1) { | |
return false; | |
} | |
return true; | |
} | |
return { | |
target: isExternal(this.absoluteUrl) ? '_blank' : false | |
}; | |
}); |
This file contains 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
'use strict'; | |
use(function () { | |
// var currentUrl = currentPage.getPath(); | |
// var currentDomain = request.getServerName(); | |
// WOW! We can use any Java package like this: | |
var package = Packages.com.day.cq.commons.Externalizer; | |
// And we can adopt a resource to it: | |
var externalizer = resource.resourceResolver.adaptTo(package); | |
var targetUrl = getAbsoluteUrl(this.path); | |
function getAbsoluteUrl(url) { | |
return externalizer.absoluteLink(request, request.getScheme(), url); | |
} | |
return { | |
targetUrl: targetUrl | |
}; | |
}); |
This file contains 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
/* | |
* Usage: | |
* Pass a list of all interesting get parameters, then access an individual value using the same parameter name. | |
<sly data-sly-use.params="${'./server.get.js' @ params=['msg','msgType']}" /> | |
${params.msgType} | |
*/ | |
'use strict'; | |
use(function () { | |
var collectedParams = {}; | |
var parameterArr = this.params; | |
var paramName; | |
var paramValue; | |
var i; | |
for (i = 0; i < parameterArr.length; i++) { | |
paramName = parameterArr[i]; | |
paramValue = request.getParameter(paramName); | |
collectedParams[paramName] = paramValue; | |
} | |
return collectedParams; | |
}); |
This file contains 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
... | |
var children = resource.resourceResolver.listChildren(resource); | |
... |
This file contains 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
// Usage example: | |
// <meta charset="utf-8" data-sly-use.head="head.js"> | |
// <meta name="keywords" content="${head.keywords}"/> | |
use(function () { | |
var WCMUtils = Packages.com.day.cq.wcm.commons.WCMUtils; | |
return { | |
keywords: WCMUtils.getKeywords(currentPage, false) | |
}; | |
}); |
This file contains 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
// Request page property of another page using its path | |
'use strict'; | |
use(function () { | |
// Example path: `/content/about-project/en_us/company/brand-resources` | |
var resource = request.resourceResolver.getResource(this.path + '/jcr:content'); | |
var ValueMap = Packages.org.apache.sling.api.resource.ValueMap; | |
function doesRedirect(resource) { | |
var properties = resource.adaptTo(ValueMap); | |
// NOTE We can't compare the property using `=== undefined` because it is neither `undefined` nor a string `'undefined'` (it is an object) | |
return properties.get('redirectTarget', String.class) != 'undefined'; | |
} | |
return { | |
target: doesRedirect(resource) ? '_blank' : false | |
}; | |
}); |
This file contains 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
//... | |
// Get JSON file from JCR | |
var jsonURL = '/etc/designs/core-twitter/json/typography.json/jcr:content/jcr:data'; | |
var resource = request.resourceResolver.getResource(jsonURL); | |
var json = JSON.parse(resource.adaptTo(java.lang.String)); | |
/... |
This file contains 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
use(function () { | |
var that = this; | |
that.properties = resource.properties || {}; | |
var themes = { | |
green: { | |
fallback: '#f7f9fa', | |
from: '#F7FBFF', | |
to: '#034D3A' | |
}, | |
purple: { | |
fallback: '#f7f9fa', | |
from: '#FFF6EC', | |
to: '#4B1E5D' | |
}, | |
}; | |
themes.default = themes.green; | |
return { | |
theme: themes[that.properties.theme] || themes.default | |
} | |
}); | |
This file contains 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
// ... | |
// Path to current page resource, e.g. `/content/tesla-configurator/language-masters/en/jcr:content` | |
currentPage.getContentResource(); | |
// Path to current page, e.g. `/content/tesla-configurator/language-masters/en` | |
currentPage.getPath(); | |
// Get property within page hierarchy | |
// See also: http://labs.6dglobal.com/blog/2012-07-23/good-know-inheritancevaluemap/ | |
// https://docs.adobe.com/docs/en/aem/6-0/develop/ref/javadoc/com/day/cq/commons/inherit/InheritanceValueMap.html | |
var HierarchyNodeInheritanceValueMap = Packages.com.day.cq.commons.inherit.HierarchyNodeInheritanceValueMap | |
var hierarchyNodeInheritanceValueMap = new HierarchyNodeInheritanceValueMap(resource); | |
var inheritedProperty = hierarchyNodeInheritanceValueMap.getInherited(fieldName, String.class); | |
throw new Error(inheritedProperty); // E.g. `{"text":"test","link":"/tmp"}` | |
throw new Error(JSON.stringify(JSON.parse(inheritedProperty))); // E.g. `{"text":"test","link":"/tmp"}` | |
// ... |
This file contains 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
// page.js | |
use(['./page.props.js'], function (props) { | |
var template = granite.resource.properties['cq:template']; | |
var templateName = ''; | |
if (template) { | |
templateName = template.split('/')[template.length - 1]; | |
} | |
var headerClasses = { | |
default: 'tsla-header-main', | |
semitransparent: 'tsla-header-semitransparent', | |
transparent: 'tsla-header-transparent' | |
}; | |
return { | |
className: props.className || headerClasses[headerStyle] || headerClasses['default'], | |
templateName: templateName | |
}; | |
}); | |
// page.props.js | |
use(function () { | |
// Copy this file into an inheriting template to override default properties | |
return { | |
className: '' | |
}; | |
}); |
This file contains 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
use(function () { | |
var Calendar = Packages.java.util.Calendar; | |
var currentYear = Calendar.getInstance().get(Calendar.YEAR); | |
return { | |
year: currentYear | |
}; | |
}); |
This file contains 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
/******************************************************************************* | |
* Copyright 2016 Adobe Systems Incorporated | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
******************************************************************************/ | |
"use strict"; | |
/** | |
* Helper JS object having convenience methods to retrieve image properties | |
* | |
* @constructor | |
*/ | |
use(["../ResourceUtils.js", "/libs/sightly/js/3rd-party/q.js"], function (ResourceUtils, Q) { | |
var that; | |
var Image = function (resource) { | |
that = this; | |
that.resource = resource; | |
that.properties = resource.properties || {}; | |
that.timestamp = (new Date()).getTime(); | |
}; | |
var CONST = { | |
PROP_FILE_REFERENCE: "fileReference", | |
PROP_ALT: "alt", | |
PROP_IS_DECORATIVE: "isDecorative", | |
PROP_TITLE: "jcr:title", | |
PROP_WIDTH: "width", | |
PROP_HEIGHT: "height", | |
PROP_LINK_URL: "linkURL", | |
PROP_IMAGE_MAP: "imageMap", | |
PROP_JCR_CONTENT: "jcr:content", | |
PROP_JCR_MIME_TYPE: "jcr:mimeType", | |
PROP_JCR_CREATED: "jcr:created", | |
PROP_JCR_LAST_MODIFIED: "jcr:lastModified", | |
RENDITIONS_PATH: "renditions", | |
WEB_RENDITION_SELECTOR: "img", | |
WEB_RENDITION_PREFIX: "cq5dam.web.", | |
DEFAULT_MIME_TYPE: "image/png", | |
MIME_TYPES: { | |
"image/png": "png", | |
"image/jpg": "jpg", | |
"image/jpeg": "jpg", | |
"image/gif": "gif" | |
} | |
}; | |
// Adding the constants to the exposed API | |
Image.CONST = CONST; | |
Image.prototype.forcedMimeType = function (mimeType) { | |
if(mimeType) { | |
that._forcedMimeType = mimeType; | |
} | |
return that._forcedMimeType; | |
}; | |
Image.prototype.fileReference = function () { | |
return that.properties[CONST.PROP_FILE_REFERENCE]; | |
}; | |
Image.prototype.fileName = function () { | |
var filePath = that.fileReference() || that.resource.path; | |
var lastIndex = filePath.lastIndexOf("/"); | |
return (lastIndex >= 0) ? filePath.substring(lastIndex + 1) : filePath; | |
}; | |
Image.prototype.src = function () { | |
return that.resource.path + "." + CONST.WEB_RENDITION_SELECTOR + "." + getExtension() + getCachingSuffix(); | |
}; | |
Image.prototype.alt = function () { | |
if (that.isDecorative()) { | |
// declared decorative image: null alt attribute | |
return true; | |
} else { | |
// use alt or remove the alt attribute completely (latter allows accessibility checking tools to | |
// report missing alt attributes) | |
return that.properties[CONST.PROP_ALT] || false; | |
} | |
}; | |
Image.prototype.isDecorative = function () { | |
return that.properties[CONST.PROP_IS_DECORATIVE]; | |
}; | |
Image.prototype.title = function () { | |
return that.properties[CONST.PROP_TITLE]; | |
}; | |
Image.prototype.width = function () { | |
return that.properties[CONST.PROP_WIDTH]; | |
}; | |
Image.prototype.height = function () { | |
return that.properties[CONST.PROP_HEIGHT]; | |
}; | |
Image.prototype.linkUrl = function () { | |
return that.properties[CONST.PROP_LINK_URL]; | |
}; | |
Image.prototype.imageMaps = function () { | |
var imgMaps = null; | |
var mapInfo = that.properties[CONST.PROP_IMAGE_MAP]; | |
if (mapInfo) { | |
var name = "map-" + that.timestamp; | |
imgMaps = { | |
name: name, | |
hash: "#" + name, | |
maps: [] | |
}; | |
var mapInfoRegex = /\[([^(]*)\(([^)]*)\)([^|]*)\|([^|]*)\|([^\]]*)\]/g; | |
while (match = mapInfoRegex.exec(mapInfo)) { | |
imgMaps.maps.push({ | |
type: match[1], | |
coords: match[2], | |
href: match[3].replace(/\"([^\"]*)\"/g, "$1"), | |
target: match[4].replace(/\"([^\"]*)\"/g, "$1"), | |
text: match[5].replace(/\"([^\"]*)\"/g, "$1") | |
}); | |
} | |
} | |
return imgMaps; | |
}; | |
function getExtension() { | |
var extensionPromise = Q.defer(); | |
var fileReference = that.fileReference(); | |
var defaultMimeType = that.forcedMimeType() ? that.forcedMimeType() : CONST.DEFAULT_MIME_TYPE; | |
if (fileReference) { | |
ResourceUtils.getResource(fileReference + "/" + CONST.PROP_JCR_CONTENT + "/" + CONST.RENDITIONS_PATH) | |
.then(function (fileRefRenditions) { | |
log.debug("Returning rendition children promise"); | |
return fileRefRenditions.getChildren(); | |
}, function (error) { | |
log.error(error); | |
}) | |
.then(function (imgRenditions) { | |
log.debug("Searching rendition children for the web rendition " + imgRenditions.length); | |
searchWebRendition(imgRenditions, 0, extensionPromise); | |
}, function (error) { | |
log.error(error); | |
}); | |
} else { | |
log.debug("Using default mime type for image " + fileReference + " : " + defaultMimeType); | |
extensionPromise.resolve(CONST.MIME_TYPES[defaultMimeType]); | |
} | |
return extensionPromise.promise; | |
} | |
function getCachingSuffix() { | |
var cachingSuffixPromise = Q.defer(); | |
var fileReference = that.fileReference(); | |
var resourceLastModif = that.properties["jcr:lastModified"] || that.properties["jcr:created"], | |
suffix; | |
if (typeof resourceLastModif === 'undefined') { | |
suffix = 0 | |
} else { | |
suffix = resourceLastModif.getTimeInMillis(); | |
} | |
if (fileReference) { | |
ResourceUtils.getResource(fileReference + "/" + CONST.PROP_JCR_CONTENT) | |
.then(function (fileResourceContent) { | |
var fileLastModif = fileResourceContent.properties[CONST.PROP_JCR_LAST_MODIFIED] | |
|| fileResourceContent.properties[CONST.PROP_JCR_CREATED]; | |
if (fileLastModif && fileLastModif > resourceLastModif) { | |
resourceLastModif = fileLastModif; | |
} | |
if (typeof resourceLastModif !== 'undefined') { | |
suffix = resourceLastModif.getTimeInMillis(); | |
} | |
if (suffix) { | |
getExtension().then(function (extension) { | |
suffix = "/" + suffix + "." + extension; | |
log.debug("Computed image caching suffix: " + suffix); | |
cachingSuffixPromise.resolve(suffix); | |
}); | |
} else { | |
log.debug("Using empty image caching suffix"); | |
cachingSuffixPromise.resolve(""); | |
} | |
}); | |
} else { | |
log.debug("Using local image caching suffix"); | |
getExtension().then(function (extension) { | |
suffix = "/" + suffix + "." + extension; | |
log.debug("Computed image caching suffix: " + suffix); | |
cachingSuffixPromise.resolve(suffix); | |
}); | |
} | |
return cachingSuffixPromise.promise; | |
} | |
function searchWebRendition(renditions, currentIndex, promise) { | |
var defaultMimeType = that.forcedMimeType() ? that.forcedMimeType() : CONST.DEFAULT_MIME_TYPE; | |
if (currentIndex >= renditions.length) { | |
log.debug("No web rendition found, using default mime type " + defaultMimeType); | |
promise.resolve(CONST.MIME_TYPES[defaultMimeType]); | |
return; | |
} | |
var currentRendition = renditions[currentIndex]; | |
if (currentRendition.name.indexOf(CONST.WEB_RENDITION_PREFIX) >= 0) { | |
ResourceUtils.getResource(currentRendition.path + "/" + CONST.PROP_JCR_CONTENT) | |
.then(function (renditionContentResource) { | |
log.debug("Found image information resource: " + renditionContentResource.path); | |
mimeType = that.forcedMimeType() ? that.forcedMimeType() : (renditionContentResource.properties[CONST.PROP_JCR_MIME_TYPE] || defaultMimeType); | |
log.debug("Found mime type for image " + that.fileReference() + " : " + mimeType); | |
promise.resolve(CONST.MIME_TYPES[mimeType]); | |
}); | |
} else { | |
log.debug("Not a web rendition " + currentRendition.path); | |
searchWebRendition(renditions, currentIndex + 1, promise); | |
} | |
} | |
return Image; | |
}); |
This file contains 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
use(['./page.props.js'], function (props) { | |
var headerStyle = granite.resource.properties['headerStyle']; | |
var headerClasses = { | |
default: 'header-main', | |
semitransparent: 'header-semitransparent', | |
transparent: 'header-transparent' | |
}; | |
return { | |
className: props.className || headerClasses[headerStyle] || headerClasses['default'] | |
}; | |
}); |
This file contains 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
use(function () { | |
// Copy this file into an inheriting template to override default properties | |
return { | |
className: '' | |
}; | |
}); |
This file contains 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
// Source: /libs/wcm/foundation/components/iparsys/par/par.js | |
/******************************************************************************* | |
* Copyright 2016 Adobe Systems Incorporated | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
******************************************************************************/ | |
/** | |
* iParsys paragraph sightly foundation component JS backing script | |
*/ | |
"use strict"; | |
use(["../../utils/ResourceUtils.js", "../../utils/ParagraphSystem.js", "/libs/sightly/js/3rd-party/q.js"], function (ResourceUtils, ParagraphSystem, Q) { | |
var isParentCanceled = false; | |
var CONST = { | |
PROP_INHERITANCE: "inheritance", | |
INHERITANCE_CANCELED: "cancel", | |
INHERITANCE_PAR_SUFFIX: "/iparsys/par" | |
} | |
/** | |
* Compute the paragraphs that need rendering | |
* Will include parent's content recursively when encountering resource types having the INHERITANCE_PAR_SUFFIX suffix | |
*/ | |
var _getParagraphs = function (parentResource, parSysPath, allParagraphsPromise, collector) { | |
if (!collector) { | |
collector = []; | |
} | |
var parPath = parentResource.path + "/jcr:content/" + parSysPath; | |
log.debug("Trying to resolve resource " + parPath); | |
parentResource.resolve(parPath).then(function (parResource) { | |
try { | |
log.debug("Reading paragraphs under resource " + parResource.path); | |
var isCanceled = parResource.properties[CONST.PROP_INHERITANCE] == CONST.INHERITANCE_CANCELED; | |
isParentCanceled = isParentCanceled || isCanceled; | |
if (isCanceled) { | |
log.debug("iParsys: Inheritance cancelled, not collecting paragraphs"); | |
allParagraphsPromise.resolve(collector); | |
return; | |
} | |
log.debug("iParsys: Building paragraph system under " + parResource.path); | |
var parsys = new ParagraphSystem(parResource, undefined, false); | |
log.debug("iParsys: Built paragraph system under " + parResource.path); | |
parsys.getParagraphs().then(function (paragraphs) { | |
log.debug("iParsys: Found " + paragraphs.length + " paragraphs"); | |
for (var parIdx = 0 ; parIdx < paragraphs.length ; parIdx++) { | |
var currentPar = paragraphs[parIdx]; | |
log.debug("iParsys: Found paragraph " + currentPar.resourcePath); | |
var resourceType = currentPar.resourceType; | |
isCanceled = currentPar[CONST.PROP_INHERITANCE] == CONST.INHERITANCE_CANCELED; | |
if (resourceType && resourceType.indexOf(CONST.INHERITANCE_PAR_SUFFIX) >= 0) { | |
// do recursive call to determine parent's content if not cancelled | |
if (!isCanceled) { | |
log.debug("Recursing into paragraphs of resource " + parResource.path); | |
parentResource.getParent().then(function (newParent) { | |
_getParagraphs(newParent, parSysPath, allParagraphsPromise, collector); | |
}); | |
} else { | |
log.debug("iParsys: Inheritance cancelled, not collecting paragraphs"); | |
} | |
} else { | |
collector.push(currentPar); | |
} | |
} | |
allParagraphsPromise.resolve(collector); | |
}); | |
} catch (e) { | |
log.error(e); | |
} | |
}, function() { | |
log.debug("Can't resolve " + parPath + " trying parent "); | |
parentResource.getParent().then(function (newParent) { | |
_getParagraphs(newParent, parSysPath, allParagraphsPromise, collector); | |
}, function() { | |
log.debug("No parent for " + parentResource.path + " found!"); | |
allParagraphsPromise.resolve(collector); | |
}); | |
}); | |
}; | |
var parentResource = undefined; | |
var inheritanceDisabled = granite.resource.properties[CONST.PROP_INHERITANCE] == CONST.INHERITANCE_CANCELED; | |
var allParagraphsPromise = Q.defer(); | |
ResourceUtils.getContainingPage(granite.resource).then(function (containingPage) { | |
containingPage.getParent().then(function (parentResource) { | |
log.debug("Found iParsys parent Resource/Page: " + parentResource.path); | |
// get page content relative path to the parsys | |
var parSysPath = ResourceUtils.getRelativeParent(granite.resource.path, 1); | |
var contentPrefix = containingPage.path + "/jcr:content"; | |
parSysPath = parSysPath.substring(contentPrefix.length + 1); | |
log.debug("Using parsys path: " + parSysPath); | |
if (!inheritanceDisabled) { | |
_getParagraphs(parentResource, parSysPath, allParagraphsPromise); | |
} else { | |
allParagraphsPromise.resolve([]); | |
} | |
}); | |
}); | |
return { | |
inheritanceDisabled: inheritanceDisabled, | |
parentInheritanceDisabled: isParentCanceled, | |
renderInfo: allParagraphsPromise.promise | |
}; | |
}); |
This file contains 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
/******************************************************************************* | |
* Copyright 2016 Adobe Systems Incorporated | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
******************************************************************************/ | |
"use strict"; | |
use(["/libs/sightly/js/3rd-party/q.js"], function (Q) { | |
var ResourceUtils = {}; | |
ResourceUtils.getAbsoluteParent = function (path, level) { | |
var idx = 0; | |
var length = path.length; | |
if (isNaN(length)) { | |
length = path.length(); | |
} | |
while (level >= 0 && idx < length) { | |
idx = path.indexOf("/", idx + 1); | |
if (idx < 0) { | |
idx = length; | |
} | |
level--; | |
} | |
return level >= 0 ? "" : path.substring(0, idx); | |
}; | |
ResourceUtils.getRelativeParent = function (path, level) { | |
var idx = path.length; | |
if (isNaN(idx)) { | |
idx = path.length(); | |
} | |
while (level > 0) { | |
idx = path.lastIndexOf("/",idx-1); | |
if (idx < 0) { | |
return ""; | |
} | |
level--; | |
} | |
return path.substring(0,idx); | |
}; | |
/** | |
* Returns a promise | |
*/ | |
ResourceUtils.getContainingPage = function (childResource, containingPagePromise) { | |
if (!containingPagePromise) { | |
containingPagePromise = Q.defer(); | |
} | |
log.debug("Resolving containing page for resource " + childResource.path); | |
if (childResource.name == "jcr:content") { | |
log.debug("Resource " + childResource.path + " is a page content node"); | |
childResource.getParent().then(function (parentRes) { | |
log.debug("Found " + parentRes.path + " as containing page of " + childResource.path); | |
containingPagePromise.resolve(parentRes); | |
return; | |
}); | |
} else { | |
log.debug("Searching through all children of " + childResource.path + " for a jcr:content node "); | |
childResource.getChildren().then(function (childItems) { | |
log.debug("Found " + childItems.length + " children of " + childResource.path); | |
for (var childItemIdx = 0 ; childItemIdx < childItems.length ; childItemIdx++) { | |
if (childItems[childItemIdx].name == "jcr:content") { | |
log.debug("Found child jcr:content node, " + childResource.path + " is a page "); | |
containingPagePromise.resolve(childResource); | |
return; | |
} | |
} | |
var parentPromise = childResource.getParent(); | |
if (parentPromise) { | |
log.debug(" No child jcr:content found, moving to parent "); | |
parentPromise.then(function (parentRes) { | |
log.debug(" Recursing into getContainingPage() for parent " + parentRes.path); | |
ResourceUtils.getContainingPage(parentRes, containingPagePromise); | |
}); | |
} else { | |
log.debug("No parent available, could not determine a containing page"); | |
containingPagePromise.resolve(null); | |
} | |
}); | |
} | |
return containingPagePromise.promise; | |
}; | |
/** | |
* Returns a promise | |
*/ | |
ResourceUtils.getPageProperties = function (pageResource) { | |
var pagePropertiesPromise = Q.defer(); | |
pageResource.resolve(pageResource.path + "/jcr:content") | |
.then(function (pageContentResource) { | |
pagePropertiesPromise.resolve(pageContentResource.properties); | |
}, function () { | |
pagePropertiesPromise.reject(); | |
}); | |
return pagePropertiesPromise.promise; | |
}; | |
ResourceUtils.getInheritedPageProperty = function (pageResource, propName, inheritedPropertyPromise) { | |
if (!inheritedPropertyPromise) { | |
log.debug("Fetching inherited property " + propName + " of page " + pageResource.path); | |
inheritedPropertyPromise = Q.defer(); | |
} | |
var failPromise = function (inheritedPropertyPromise) { | |
log.debug("Did not find inherited property " + propName + ", returning 'undefined'"); | |
inheritedPropertyPromise.resolve(undefined); | |
} | |
ResourceUtils.getResource(pageResource.path + "/jcr:content").then(function (pageContentResource) { | |
var propValue = pageContentResource.properties[propName]; | |
if (propValue) { | |
log.debug("Found inherited property " + propName + " = " + propValue); | |
inheritedPropertyPromise.resolve(propValue); | |
} else { | |
var parentPromise = pageResource.getParent(); | |
if (parentPromise) { | |
parentPromise.then(function (parentResource) { | |
log.debug("parent res " + parentResource); | |
if (parentResource) { | |
log.debug("Searching inherited property " + propName + " on parent page " + parentResource.path); | |
ResourceUtils.getInheritedPageProperty(parentResource, propName, inheritedPropertyPromise); | |
} else { | |
failPromise(inheritedPropertyPromise); | |
} | |
}, function () { | |
failPromise(inheritedPropertyPromise); | |
}); | |
} else { | |
failPromise(inheritedPropertyPromise); | |
} | |
} | |
}, function() { | |
failPromise(inheritedPropertyPromise); | |
}); | |
return inheritedPropertyPromise.promise; | |
}; | |
/** | |
* Resolves a resource | |
* | |
* @returns promise as returned by the granite.resource.resolve or undefined if | |
* the 'granite' cross-platform API is not available | |
*/ | |
ResourceUtils.getResource = function (resourcePath) { | |
var resolvedResource = undefined; | |
if (typeof granite != "undefined") { | |
// resolve based on cross platform API | |
log.debug("Found 'granite' cross-platform namespace, using it to resolve " + resourcePath + " path"); | |
resolvedResource = granite.resource.resolve(resourcePath); | |
log.debug("Resolved resource " + resourcePath); | |
} else { | |
log.error("Can't find 'granite' cross-platform namespace!"); | |
} | |
return resolvedResource; | |
} | |
return ResourceUtils; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment