1/* 2 * Fragment Block 3 * Include content on a page as a fragment. 4 * https://www.aem.live/developer/block-collection/fragment 5 */ 6 7import { 8 decorateMain, 9 loadBlocks, 10} from '../../scripts/scripts.js'; 11 12/** 13 * Loads a fragment. 14 * @param {string} path The path to the fragment 15 * @returns {HTMLElement} The root element of the fragment 16 */ 17export async function loadFragment(path) { 18 if (path && path.startsWith('/')) { 19 const resp = await fetch(`${path}.plain.html`); 20 if (resp.ok) { 21 const main = document.createElement('main'); 22 main.innerHTML = await resp.text(); 23 24 // reset base path for media to fragment base 25 const resetAttributeBase = (tag, attr) => { 26 main.querySelectorAll(`${tag}[${attr}^="./media_"]`).forEach((elem) => { 27 elem[attr] = new URL( 28 elem.getAttribute(attr), 29 new URL(path, window.location), 30 ).href; 31 }); 32 }; 33 resetAttributeBase('img', 'src'); 34 resetAttributeBase('source', 'srcset'); 35 36 decorateMain(main); 37 await loadBlocks(main); 38 return main; 39 } 40 } 41 return null; 42} 43 44export default async function decorate(block) { 45 const link = block.querySelector('a'); 46 const path = link ? link.getAttribute('href') : block.textContent.trim(); 47 const fragment = await loadFragment(path); 48 if (fragment) { 49 const fragmentSection = fragment.querySelector(':scope .section'); 50 if (fragmentSection) { 51 block.closest('.section').classList.add(...fragmentSection.classList); 52 block.closest('.fragment').replaceWith(...fragment.childNodes); 53 } 54 } 55}
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.