generated from adobe/aem-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Co-authored-by: piyushjindal <[email protected]> Co-authored-by: Bryan Stopp <[email protected]>
- Loading branch information
1 parent
47a33b1
commit 2361c70
Showing
2 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
/* stylelint-disable-next-line no-empty-source */ |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
/* | ||
* Fragment Block | ||
* Include content on a page as a fragment. | ||
* https://www.aem.live/developer/block-collection/fragment | ||
*/ | ||
|
||
import { | ||
decorateMain, | ||
} from '../../scripts/scripts.js'; | ||
|
||
import { | ||
loadBlocks, | ||
} from '../../scripts/aem.js'; | ||
|
||
/** | ||
* Loads a fragment. | ||
* @param {string} path The path to the fragment | ||
* @returns {HTMLElement} The root element of the fragment | ||
*/ | ||
export async function loadFragment(path) { | ||
if (path?.startsWith('/')) { | ||
const resp = await fetch(`${path}.plain.html`); | ||
if (resp.ok) { | ||
const main = document.createElement('main'); | ||
main.innerHTML = await resp.text(); | ||
|
||
// reset base path for media to fragment base | ||
const resetAttributeBase = (tag, attr) => { | ||
main.querySelectorAll(`${tag}[${attr}^="./media_"]`).forEach((elem) => { | ||
elem[attr] = new URL(elem.getAttribute(attr), new URL(path, window.location)).href; | ||
}); | ||
}; | ||
resetAttributeBase('img', 'src'); | ||
resetAttributeBase('source', 'srcset'); | ||
|
||
decorateMain(main); | ||
await loadBlocks(main); | ||
return main; | ||
} | ||
} | ||
return null; | ||
} | ||
|
||
export default async function decorate(block) { | ||
const link = block.querySelector('a'); | ||
const path = link ? link.getAttribute('href') : block.textContent.trim(); | ||
const fragment = await loadFragment(path); | ||
|
||
if (fragment) { | ||
const fragmentSection = fragment.querySelector(':scope .section'); | ||
|
||
if (fragmentSection) { | ||
block.closest('.section').classList.add(...fragmentSection.classList); | ||
block.closest('.fragment').replaceWith(...fragment.childNodes); | ||
} | ||
} | ||
} |