Skip to content

Commit

Permalink
improve demo code:
Browse files Browse the repository at this point in the history
* load htmx and hyperscript after mock-request, so you can use `init` and `load` correctly
* disable all disableable elements while the demo environment is loading
* support a `delay` attribute on templates to specify a delay
* merged @dz4k's excellent simplification to the eval code
  • Loading branch information
carson committed Feb 19, 2022
1 parent f7a51bd commit 3d93251
Show file tree
Hide file tree
Showing 2 changed files with 109 additions and 40 deletions.
131 changes: 93 additions & 38 deletions www/js/demo/it.js
Original file line number Diff line number Diff line change
@@ -1,42 +1,97 @@
function addScript(url) {
var myScript = document.createElement('script');
myScript.setAttribute('src', url);
document.head.appendChild(myScript);
}

function interpolate(str, params) {
try {
return eval(
`env => { with (env) { return \`${str.replace(/`/, '\\`'}\` } }`
)(params)
} catch (e) {
return e.message;
(function(){

function addScript(url) {
var myScript = document.createElement('script');
myScript.setAttribute('src', url);
document.head.appendChild(myScript);
}

function interpolate(str, params) {
try {
var escapedCode = str.replace(/`/, '\\`');
return eval(
`env => { with (env) { return \`${escapedCode}\` } }`
)(params)
} catch (e) {
log('demo:response-error', "An error occured during a mock response", e);
return e.message;
}
}

function log(name, message) {
console.log("@ " + new Date().valueOf() + " - ", ...arguments);
var event = new Event(name, {name:name, info:arguments});
if (document.body) {
document.body.dispatchEvent(event);
}
}

function initHtmxAndHyperscript() {
if (typeof htmx === "undefined" || typeof _hyperscript === "undefined") {
setTimeout(initHtmxAndHyperscript, 20);
} else {
enableThings();
log('demo:ready', "the demo environment is ready");
}
}
}

function initMockRequests() {
if(typeof MockRequests === "undefined" ||
typeof htmx === "undefined" ||
typeof _hyperscript === "undefined") {
// console.log("Not defined yet");
setTimeout(initMockRequests, 20);
} else {
// console.log("defining");
htmx.findAll("template").forEach(function(elt){
if(elt.getAttribute("url")){
MockRequests.setDynamicMockUrlResponse(elt.getAttribute("url"),
{dynamicResponseModFn:
function(request, response, parameters) {
console.log(request, response, parameters)
return interpolate(elt.innerHTML, { ...parameters, ...Object.fromEntries(new URLSearchParams(request)) });
},
usePathnameForAllQueries: true});

var DISABLEABLE_ELTS = "button, command, fieldset, keygen, optgroup, option, select, textarea, input";
function disableThings() {
log('demo:disabling-elts', "disabling elements");
document.querySelectorAll(DISABLEABLE_ELTS).forEach(function(elt){
elt.setAttribute("data-was-disabled", elt.hasAttribute('disabled'));
elt.setAttribute("disabled", "true");
})
}

function enableThings() {
log('demo:enabling-elts', "enabling elements");
document.querySelectorAll(DISABLEABLE_ELTS).forEach(function(elt){
if (elt.getAttribute("data-was-disabled") == "false") {
elt.removeAttribute("disabled");
}
});
})
}

function initMockRequests() {
if(typeof MockRequests === "undefined") {
// console.log("Not defined yet");
setTimeout(initMockRequests, 20);
} else {

log('demo:mock-request-loaded', "mock-request library loaded, mocking requests and loading htmx & hyperscript")

//-----------------------------------------------------------------
// mock requests based on template tags
//-----------------------------------------------------------------
document.querySelectorAll("template").forEach(function(elt){
if(elt.getAttribute("url")){
var configDelay = elt.getAttribute("delay");
if (configDelay) {
var delay = Number.parseInt(configDelay);
}
MockRequests.setDynamicMockUrlResponse(elt.getAttribute("url"),
{dynamicResponseModFn:
function(request, response, parameters) {
log("demo:request", "A mock request was made: ", request, response, parameters)
return interpolate(elt.innerHTML, { ...parameters, ...Object.fromEntries(new URLSearchParams(request)) });
},
delay: delay,
usePathnameForAllQueries: true});
}
});

log('demo:htmx-loading', "loading htmx & hyperscript...")
addScript("https://unpkg.com/htmx.org");
addScript("https://unpkg.com/hyperscript.org");
initHtmxAndHyperscript();
}
}
}

addScript("https://unpkg.com/htmx.org");
addScript("https://unpkg.com/hyperscript.org");
addScript("https://unpkg.com/[email protected]/index.js");
initMockRequests();
document.addEventListener('DOMContentLoaded', function () {
disableThings();
log('demo:mock-request-loading', "loading mock-request library...")
addScript("https://unpkg.com/[email protected]/index.js");
initMockRequests();
}, false);
})();
18 changes: 16 additions & 2 deletions www/js/demo/scratch.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,27 @@
</head>
<body>
<!-- post to /foo -->
<button hx-get="/foo?bar=10" hx-target="#result">Count Up</button> <output id="result"></output>
<button hx-get="/foo" hx-target="#result">Count Up</button> <output id="result"></output>
<!-- respond to /foo -->
<script>
globalInt = 0;
</script>

<button _="init log 'inited from hyperscript!'">
Init From Hyperscript
</button>

<div hx-get="/bar" hx-trigger="load">
Foo
</div>


<template url="/foo">
${bar + 5}
${hurr++}
</template>

<template url="/bar" delay="3000">
bar
</template>

</body>
Expand Down

0 comments on commit 3d93251

Please sign in to comment.