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

Ajax children #7

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
42 changes: 42 additions & 0 deletions xajax/sandbox/test-content-with-children.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>X-Ajax</title>
<script type="module">
import AJAX from '../src/index.js';
import Alpine from 'https://esm.sh/alpinejs';

Alpine.plugin(AJAX);

window.Alpine = Alpine;
Alpine.start();
</script>
</head>
<body>

// This is a page of content to test x-ajax with children
<div>
<div class="empty-div"></div>
<div class="text-element">This is a div with plain text.</div>
<div class="nested-div">
<div class="inner-div">
<p>Paragraph inside inner div.</p>
</div>
</div>
<div class="multiple-divs">
<div>
First child div.
<span>Child of first child div.</span>
</div>
<div>
Second child div.
<span>Child of second child div.</span>
</div>
</div>
</div>

</body>
</html>
54 changes: 54 additions & 0 deletions xajax/sandbox/test-x-ajax-with-children.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>X-Ajax</title>
<script type="module">
import AJAX from '../src/index.js';
import Alpine from 'https://esm.sh/alpinejs';

Alpine.plugin(AJAX);

window.Alpine = Alpine;
Alpine.start();
</script>
</head>
<body>

<div x-data="{url: 'https://your-url-with-the-content-to-fetch-goes-here'}">

<!-- 1. Basic Case: Empty div -->
<div x-ajax-mod.query.class.empty-div="url">...loading</div>

<!-- 2. Basic Text Element: Fetch a div with plain text inside -->
<div x-ajax-mod.query.class.text-element="url">...loading</div>

<!-- 3. Nested Div: Fetch an element that has a child element -->
<div x-ajax-mod.query.class.nested-div.children="url">...loading</div>

<!-- 4. Nested Div: Fetch a nested div including the parent wrapper -->
<div x-ajax-mod.query.class.nested-div="url">...loading</div>

<!-- 5. Multiple Divs: Fetch multiple sibling divs without replacement -->
<div x-ajax-mod.query.class.multiple-divs.children="url">...loading</div>

<!-- 6. Multiple Divs: Fetch all divs inside .multiple-divs and replace existing content with all of them -->
<div x-ajax-mod.query.class.multiple-divs.all.children="url">...loading</div>

<!-- 7. Entire Content: Fetch the entire content without the body tag -->
<div x-ajax-mod="url">...loading</div>

<!-- 8. Edge Case: Combining 'all', 'replace' and 'children' (not a common use, but for testing). Note: May return nothing if no children -->
<div x-ajax-mod.query.class.multiple-divs.all.replace.children="url">...loading</div>

<!-- 9. Edge Case with Children: Combining 'all', 'replace' and 'children' on an element with children. -->
<div class="parent-div">
<div x-ajax-mod.query.class.multiple-divs.all.replace.children="url">...loading</div>
</div>

</div>

</body>
</html>
100 changes: 69 additions & 31 deletions xajax/src/index.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,76 @@
const xParser = new DOMParser();

export default function (Alpine) {
Alpine.directive('ajax', async (el, { expression, modifiers }, { effect, evaluateLater }) => {
const target = evaluateLater(expression);
let query;

if (modifiers.includes('query')) query = modifiers[modifiers.indexOf(modifiers.includes('class') ? 'class' : 'query') + 1];
if (modifiers.includes('class')) query = '.' + query;

effect(() => {
target(async (target) => {
if (!target) return el.dispatchEvent(new CustomEvent('halted', { detail: 'Target is not defined', ...eventDefaults }));
try {
const response = await fetch(target, { mode: 'no-cors' });
if (!response.ok) throw new Error(response.statusText);
const content = await response.text();
const doc = xParser.parseFromString(content, 'text/html');
const selector = query ? (modifiers.includes('all') ? doc.body.querySelectorAll(query) : doc.body.querySelector(query)) : doc.body;
if (!selector) throw new Error('Selected element not found');

el.dispatchEvent(new Event('load', eventDefaults));
if (modifiers.includes('replace')) return el.replaceWith(selector);
if (modifiers.includes('all')) return el.replaceChildren(...selector);
if (selector.tagName == 'BODY') return el.replaceChildren(...selector.children);
return el.replaceChildren(selector);
} catch (e) {
console.error(e);
el.dispatchEvent(new Event('error', { detail: e, ...eventDefaults }));
}
});
});
});
Alpine.directive('ajax', async (el, { expression, modifiers }, { effect, evaluateLater }) => {

const target = evaluateLater(expression);
let query;

if (modifiers.includes('query')) query = modifiers[modifiers.indexOf(modifiers.includes('class') ? 'class' : 'query') + 1];
if (modifiers.includes('class')) query = '.' + query;

effect(() => {
target(async (target) => {
if (!target) return el.dispatchEvent(new CustomEvent('halted', { detail: 'Target is not defined', ...eventDefaults }));
try {
const response = await fetch(target, { mode: 'no-cors' });
if (!response.ok) throw new Error(response.statusText);
const content = await response.text();
const doc = xParser.parseFromString(content, 'text/html');

// If both 'all' and 'children' modifiers, append '>*' to the query to select all children of the selected element.
const updatedQuery = modifiers.includes('all') ?
doc.body.querySelectorAll(modifiers.includes('children') ? query + '>*' : query) :
doc.body.querySelector(query);

const selector = query ? updatedQuery : doc.body;
if (!selector) throw new Error('Selected element not found');

el.dispatchEvent(new Event('load', eventDefaults));

// Handles edge case where combination of all, replace, and children modifiers are used
if (modifiers.includes('replace') && modifiers.includes('all') && modifiers.includes('children')) {
if (selector instanceof NodeList) {
console.log('xajax: Fetched NodeList:', selector);
let fragment = document.createDocumentFragment();
selector.forEach(node => {
console.log('xajax: Node children:', node.children);
Array.from(node.children).forEach(child => fragment.appendChild(child.cloneNode(true)));
});
console.log('xajax: Final fragment:', fragment);
el.replaceWith(fragment);
return;
}
}

// Added Conditon for 'replace' and 'children' modifiers
if (modifiers.includes('replace') && modifiers.includes('children')) return el.replaceWith(...selector.children);

// Handle 'replace' modifier for NodeList case - spreads the NodeList and replaces the current element with all nodes from the list
// Corrects behavior for the scenario where fetching all instances of an element and replacing them, but the element is not a direct child of the parent
if (modifiers.includes('replace')) {
if (selector instanceof NodeList) {
el.replaceWith(...selector);
} else {
el.replaceWith(selector);
}
return;
}

if (modifiers.includes('all')) return el.replaceChildren(...selector);

// Include a check for 'children' modifier
if (selector.tagName == 'BODY' || modifiers.includes('children')) return el.replaceChildren(...selector.children);
return el.replaceChildren(selector);
} catch (e) {
console.error(e);
el.dispatchEvent(new Event('error', { detail: e, ...eventDefaults }));
}
});
});
});
}

const eventDefaults = {
bubbles: false
bubbles: false
};